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/queue/src/main/java/org/killbill/notificationq/api/NotificationEvent.java
queue/src/main/java/org/killbill/notificationq/api/NotificationEvent.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.api; import org.killbill.queue.api.QueueEvent; /** * The interface that needs to be implemented for any notification event * <p/> * <p> The user specific class implementing this interface must also be serializable in json using jackson annotations. * The generated JSON must also fit in the varchar as defined by the schema */ public interface NotificationEvent extends QueueEvent { }
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/api/NotificationEventWithMetadata.java
queue/src/main/java/org/killbill/notificationq/api/NotificationEventWithMetadata.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.api; import java.util.UUID; import org.joda.time.DateTime; import org.killbill.bus.api.BusEventWithMetadata; /** * The NotificationEventWithMetadata return to the user. It encapsulates the de-serialized version of the json event on disk. * * @param <T> The type of event serialized on disk */ public class NotificationEventWithMetadata<T extends NotificationEvent> extends BusEventWithMetadata<T> { private final UUID futureUserToken; private final DateTime effectiveDate; private final String queueName; public NotificationEventWithMetadata(final Long recordId, final UUID userToken, final DateTime createdDate, final Long searchKey1, final Long searchKey2, final T event, final UUID futureUserToken, final DateTime effectiveDate, final String queueName) { super(recordId, userToken, createdDate, searchKey1, searchKey2, event); this.futureUserToken = futureUserToken; this.effectiveDate = effectiveDate; this.queueName = queueName; } public UUID getFutureUserToken() { return futureUserToken; } public DateTime getEffectiveDate() { return effectiveDate; } public String getQueueName() { return queueName; } }
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/api/NotificationQueueConfig.java
queue/src/main/java/org/killbill/notificationq/api/NotificationQueueConfig.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.api; import org.skife.config.Config; import org.skife.config.Default; import org.skife.config.Description; import org.skife.config.TimeSpan; import org.killbill.queue.api.PersistentQueueConfig; public abstract class NotificationQueueConfig implements PersistentQueueConfig { @Override @Config("org.killbill.notificationq.${instanceName}.inMemory") @Default("false") @Description("Set to false, not available for NotificationQueue") public abstract boolean isInMemory(); @Override @Config("org.killbill.notificationq.${instanceName}.max.failure.retry") @Default("3") @Description("Number retry for a given event when an exception occurs") public abstract int getMaxFailureRetries(); @Override @Config("org.killbill.persistent.bus.${instanceName}.inflight.min") @Default("-1") @Description("Min number of bus events to fetch from the database at once (only valid in 'STICKY_EVENTS')") public abstract int getMinInFlightEntries(); @Override @Config("org.killbill.persistent.bus.${instanceName}.inflight.max") @Default("-1") @Description("Max number of bus events to fetch from the database at once (only valid in 'STICKY_EVENTS')") public abstract int getMaxInFlightEntries(); @Override @Config("org.killbill.notificationq.${instanceName}.claimed") @Default("10") @Description("Number of notifications to fetch at once") public abstract int getMaxEntriesClaimed(); @Override @Config("org.killbill.notificationq.${instanceName}.queue.mode") @Default("POLLING") @Description("How entries are put in the queue") public abstract PersistentQueueMode getPersistentQueueMode(); @Override @Config("org.killbill.notificationq.${instanceName}.claim.time") @Default("5m") @Description("Claim time") public abstract TimeSpan getClaimedTime(); @Override @Config("org.killbill.notificationq.${instanceName}.sleep") @Default("3000") @Description("Time in milliseconds to sleep between runs") public abstract long getPollingSleepTimeMs(); @Override @Config("org.killbill.notificationq.${instanceName}.notification.off") @Default("false") @Description("Whether to turn off the notification queue") public abstract boolean isProcessingOff(); @Override @Config("org.killbill.notificationq.${instanceName}.notification.nbThreads") @Default("10") @Description("Number of threads to use") public abstract int geMaxDispatchThreads(); @Override @Config("org.killbill.notificationq.${instanceName}.lifecycle.dispatch.nbThreads") @Default("1") @Description("Max number of lifecycle dispatch threads to use") public abstract int geNbLifecycleDispatchThreads(); @Override @Config("org.killbill.notificationq.${instanceName}.lifecycle.complete.nbThreads") @Default("2") @Description("Max number of lifecycle complete threads to use") public abstract int geNbLifecycleCompleteThreads(); @Override @Config("org.killbill.notificationq.${instanceName}.queue.capacity") @Default("100") @Description("Capacity for the worker queue") public abstract int getEventQueueCapacity(); @Override @Config("org.killbill.notificationq.${instanceName}.tableName") @Default("notifications") @Description("Notifications table name") public abstract String getTableName(); @Override @Config("org.killbill.notificationq.${instanceName}.historyTableName") @Default("notifications_history") @Description("Notifications history table name") public abstract String getHistoryTableName(); @Override @Config("org.killbill.notificationq.${instanceName}.reapThreshold") @Default("10m") @Description("Time span when a notification must be re-dispatched") public abstract TimeSpan getReapThreshold(); @Override @Config("org.killbill.notificationq.${instanceName}.maxReDispatchCount") @Default("10") @Description("Max number of notification to be re-dispatched at a time") public abstract int getMaxReDispatchCount(); @Override @Config("org.killbill.notificationq.${instanceName}.reapSchedule") @Default("3m") @Description("Reaper schedule period") public abstract TimeSpan getReapSchedule(); @Override @Config("org.killbill.notificationq.${instanceName}.shutdownTimeout") @Default("15s") @Description("Shutdown sequence timeout") public abstract TimeSpan getShutdownTimeout(); }
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/api/NotificationQueueService.java
queue/src/main/java/org/killbill/notificationq/api/NotificationQueueService.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.api; import java.util.List; import java.util.UUID; import org.joda.time.DateTime; import org.killbill.queue.api.QueueLifecycle; /** * A service to create and delete NotificationQueue */ public interface NotificationQueueService extends QueueLifecycle { interface NotificationQueueHandler { /** * Called for each notification ready * * @param eventJson the notification key associated to that notification entry * @param userToken user token associated with that notification entry * @param searchKey1 the searchKey1 associated with that notification entry * @param searchKey2 the searchKey2 associated with that notification entry */ void handleReadyNotification(NotificationEvent eventJson, DateTime eventDateTime, UUID userToken, Long searchKey1, Long searchKey2); } final class NotificationQueueAlreadyExists extends Exception { private static final long serialVersionUID = 1541281L; public NotificationQueueAlreadyExists(final String msg) { super(msg); } } final class NoSuchNotificationQueue extends Exception { private static final long serialVersionUID = 1561283L; public NoSuchNotificationQueue(final String msg) { super(msg); } } /** * Creates a new NotificationQueue for a given associated with the given service and queueName * * @param svcName the name of the service using that queue * @param queueName a name for that queue (unique per service) * @param handler the handler required for notifying the caller of state change * @return a new NotificationQueue * @throws NotificationQueueAlreadyExists is the queue associated with that service and name already exits */ NotificationQueue createNotificationQueue(final String svcName, final String queueName, final NotificationQueueHandler handler) throws NotificationQueueAlreadyExists; /** * Retrieves an already created NotificationQueue by service and name if it exists * * @param svcName the name of the service using that queue * @param queueName a name for that queue (unique per service) * @return a new NotificationQueue * @throws NoSuchNotificationQueue if queue does not exist */ NotificationQueue getNotificationQueue(final String svcName, final String queueName) throws NoSuchNotificationQueue; /** * Delete notificationQueue * * @param svcName the name of the service using that queue * @param queueName a name for that queue (unique per service) * @return a new NotificationQueue * @throws NoSuchNotificationQueue if queue does not exist */ void deleteNotificationQueue(final String svcName, final String queueName) throws NoSuchNotificationQueue; /** * Retrieve all the notificationq registered * * @return */ List<NotificationQueue> getNotificationQueues(); }
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/api/NotificationQueue.java
queue/src/main/java/org/killbill/notificationq/api/NotificationQueue.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.api; import java.io.IOException; import java.sql.Connection; import java.util.UUID; import org.joda.time.DateTime; import org.killbill.notificationq.api.NotificationQueueService.NotificationQueueHandler; import org.killbill.queue.api.QueueLifecycle; /** * A NotificationQueue offers a persistent queue with a set of API to record future notifications along with their callbacks. * * When an Iterable is returned, the client must iterate through all results to close the DB connection. */ public interface NotificationQueue extends QueueLifecycle { /** * Record the need to be called back when the notification is ready * * @param futureNotificationTime the time at which the notification is ready * * @param eventJson the key for that notification */ /** * @param futureNotificationTime the time at which the notification is ready * @param eventJson the event to be serailzed on disk * @param userToken a opaque token that can be attached to that event * @param searchKey1 a key that can be used for search * @param searchKey2 a key that can be used for search * @throws IOException if the serialization of the event fails */ void recordFutureNotification(final DateTime futureNotificationTime, final NotificationEvent eventJson, final UUID userToken, final Long searchKey1, final Long searchKey2) throws IOException; /** * @param connection the transaction that should be used to record the event * @param futureNotificationTime the time at which the notification is ready * @param eventJson the event to be serailzed on disk * @param userToken a opaque token that can be attached to that event * @param searchKey1 a key that can be used for search * @param searchKey2 a key that can be used for search * @throws IOException if the serialization of the event fails */ void recordFutureNotificationFromTransaction(final Connection connection, final DateTime futureNotificationTime, final NotificationEvent eventJson, final UUID userToken, final Long searchKey1, final Long searchKey2) throws IOException; void updateFutureNotification(final Long recordId, final NotificationEvent eventJson, final Long searchKey1, final Long searchKey2) throws IOException; void updateFutureNotificationFromTransaction(final Connection connection, final Long recordId, final NotificationEvent eventJson, final Long searchKey1, final Long searchKey2) throws IOException; /** * Retrieve all future notifications associated with that queue and matching that search key * * @param searchKey1 the value for key1 * @param searchKey2 the value for key2 * @return a list of NotificationEventWithMetadata objects matching the search */ <T extends NotificationEvent> Iterable<NotificationEventWithMetadata<T>> getFutureNotificationForSearchKeys(final Long searchKey1, final Long searchKey2); /** * Retrieve all future notifications associated with that queue and matching that search key * * @param searchKey1 the value for key1 * @param searchKey2 the value for key2 * @param connection the transaction that should be used to make that search * @return a list of NotificationEventWithMetadata objects matching the search */ <T extends NotificationEvent> Iterable<NotificationEventWithMetadata<T>> getFutureNotificationFromTransactionForSearchKeys(final Long searchKey1, final Long searchKey2, final Connection connection); /** * Retrieve all future notifications associated with that queue and matching that search key * * @param maxEffectiveDate effective_date cutoff, to limit the search * @param searchKey2 the value for key2 * @return a list of NotificationEventWithMetadata objects matching the search */ <T extends NotificationEvent> Iterable<NotificationEventWithMetadata<T>> getFutureNotificationForSearchKey2(final DateTime maxEffectiveDate, final Long searchKey2); /** * Retrieve all future notifications associated with that queue and matching that search key * * @param maxEffectiveDate effective_date cutoff, to limit the search * @param searchKey2 the value for key2 * @param connection the transaction that should be used to make that search * @return a list of NotificationEventWithMetadata objects matching the search */ <T extends NotificationEvent> Iterable<NotificationEventWithMetadata<T>> getFutureNotificationFromTransactionForSearchKey2(final DateTime maxEffectiveDate, final Long searchKey2, final Connection connection); /** * @return the notifications that have been claimed and are being processed */ <T extends NotificationEvent> Iterable<NotificationEventWithMetadata<T>> getInProcessingNotifications(); /** * Retrieve all future or in processing notifications associated with that queue and matching that search key * * @param searchKey1 the value for key1 * @param searchKey2 the value for key2 * @return a list of NotificationEventWithMetadata objects matching the search */ <T extends NotificationEvent> Iterable<NotificationEventWithMetadata<T>> getFutureOrInProcessingNotificationForSearchKeys(final Long searchKey1, final Long searchKey2); /** * Retrieve all future or in processing notifications associated with that queue and matching that search key * * @param searchKey1 the value for key1 * @param searchKey2 the value for key2 * @param connection the transaction that should be used to make that search * @return a list of NotificationEventWithMetadata objects matching the search */ <T extends NotificationEvent> Iterable<NotificationEventWithMetadata<T>> getFutureOrInProcessingNotificationFromTransactionForSearchKeys(final Long searchKey1, final Long searchKey2, final Connection connection); /** * Retrieve all future or in processing notifications associated with that queue and matching that search key * * @param maxEffectiveDate effective_date cutoff, to limit the search * @param searchKey2 the value for key2 * @return a list of NotificationEventWithMetadata objects matching the search */ <T extends NotificationEvent> Iterable<NotificationEventWithMetadata<T>> getFutureOrInProcessingNotificationForSearchKey2(final DateTime maxEffectiveDate, final Long searchKey2); /** * Retrieve all future or in processing notifications associated with that queue and matching that search key * * @param maxEffectiveDate effective_date cutoff, to limit the search * @param searchKey2 the value for key2 * @param connection the transaction that should be used to make that search * @return a list of NotificationEventWithMetadata objects matching the search */ <T extends NotificationEvent> Iterable<NotificationEventWithMetadata<T>> getFutureOrInProcessingNotificationFromTransactionForSearchKey2(final DateTime maxEffectiveDate, final Long searchKey2, final Connection connection); /** * Retrieve all historical notifications associated with that queue and matching that search key * * @param searchKey1 the value for key1 * @param searchKey2 the value for key2 * @return a list of NotificationEventWithMetadata objects matching the search */ <T extends NotificationEvent> Iterable<NotificationEventWithMetadata<T>> getHistoricalNotificationForSearchKeys(final Long searchKey1, final Long searchKey2); /** * Retrieve all historical notifications associated with that queue and matching that search key * * @param minEffectiveDate effective_date cutoff, to limit the search * @param searchKey2 the value for key2 * @return a list of NotificationEventWithMetadata objects matching the search */ <T extends NotificationEvent> Iterable<NotificationEventWithMetadata<T>> getHistoricalNotificationForSearchKey2(final DateTime minEffectiveDate, final Long searchKey2); /** * Count the number of notifications ready to be processed * * @param maxEffectiveDate effective_date cutoff (typically now()) * @return the number of ready entries */ long getNbReadyEntries(final DateTime maxEffectiveDate); /** * Move the notification to history table and mark it as 'removed' * * @param recordId the recordId */ void removeNotification(final Long recordId); void removeNotificationFromTransaction(final Connection connection, final Long recordId); /** * Remove all future notifications associated with that queue and matching these search keys * * @param searchKey1 the value for key1 * @param searchKey2 the value for key2 */ void removeFutureNotificationsForSearchKeys(final Long searchKey1, final Long searchKey2); /** * @return the name of that queue */ String getFullQName(); /** * @return the service name associated to that queue */ String getServiceName(); /** * @return the queue name associated */ String getQueueName(); /** * @return the handler associated with that notification queue */ NotificationQueueHandler getHandler(); }
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/queue/QueueObjectMapper.java
queue/src/main/java/org/killbill/queue/QueueObjectMapper.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.queue; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.joda.JodaModule; public class QueueObjectMapper { private static final ObjectMapper objectMapper = new ObjectMapper(); static { objectMapper.registerModule(new JodaModule()); objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); } public static ObjectMapper get() { return objectMapper; } }
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/queue/DBBackedQueueWithInflightQueue.java
queue/src/main/java/org/killbill/queue/DBBackedQueueWithInflightQueue.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.queue; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.joda.time.DateTime; import org.killbill.CreatorName; import org.killbill.bus.dao.PersistentBusSqlDao; import org.killbill.clock.Clock; import org.killbill.commons.eventbus.AllowConcurrentEvents; import org.killbill.commons.eventbus.Subscribe; import org.killbill.commons.jdbi.notification.DatabaseTransactionEvent; import org.killbill.commons.jdbi.notification.DatabaseTransactionEventType; import org.killbill.commons.jdbi.notification.DatabaseTransactionNotificationApi; import org.killbill.commons.metrics.api.Gauge; import org.killbill.commons.metrics.api.MetricRegistry; import org.killbill.commons.utils.Preconditions; import org.killbill.commons.utils.annotation.VisibleForTesting; import org.killbill.queue.api.PersistentQueueConfig; import org.killbill.queue.api.PersistentQueueEntryLifecycleState; import org.killbill.queue.dao.EventEntryModelDao; import org.killbill.queue.dao.QueueSqlDao; import org.skife.jdbi.v2.IDBI; import org.skife.jdbi.v2.Transaction; import org.skife.jdbi.v2.TransactionStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DBBackedQueueWithInflightQueue<T extends EventEntryModelDao> extends DBBackedQueue<T> { private static final Logger log = LoggerFactory.getLogger(DBBackedQueueWithInflightQueue.class); // How many recordIds we pull per iteration during init to fill the inflightQ private static final int MAX_FETCHED_RECORDS_ID = 1000; // Drain inflightQ using getMaxInFlightEntries() config at a time and sleep for a maximum of 100 mSec if there is nothing to do private static final long INFLIGHT_POLLING_TIMEOUT_MSEC = 100; private final LinkedBlockingQueue<Long> inflightEvents; private final DatabaseTransactionNotificationApi databaseTransactionNotificationApi; protected final Gauge<Integer> inflightEventsGauge; // // Per thread information to keep track or recordId while it is accessible and right before // transaction gets committed/rollback // private static final AtomicInteger QUEUE_ID_CNT = new AtomicInteger(0); private final int queueId; private final TransientInflightQRowIdCache transientInflightQRowIdCache; public DBBackedQueueWithInflightQueue(final Clock clock, final IDBI dbi, final Class<? extends QueueSqlDao<T>> sqlDaoClass, final PersistentQueueConfig config, final String dbBackedQId, final MetricRegistry metricRegistry, final DatabaseTransactionNotificationApi databaseTransactionNotificationApi) { super(clock, dbi, sqlDaoClass, config, dbBackedQId, metricRegistry); Preconditions.checkArgument(config.getMinInFlightEntries() <= config.getMaxInFlightEntries(), "config.getMinInFlightEntries() >= config.getMaxInFlightEntries()"); this.queueId = QUEUE_ID_CNT.incrementAndGet(); // We use an unboundedQ - the risk of running OUtOfMemory exists for a very large number of entries showing a more systematic problem... this.inflightEvents = new LinkedBlockingQueue<Long>(); this.databaseTransactionNotificationApi = databaseTransactionNotificationApi; databaseTransactionNotificationApi.registerForNotification(this); // Metrics the size of the inflightQ this.inflightEventsGauge = metricRegistry.gauge(String.format("%s.%s.%s.%s", DBBackedQueueWithInflightQueue.class.getName(), dbBackedQId, "inflightQ", "size"), new Gauge<>() { @Override public Integer getValue() { return inflightEvents.size(); } }); this.transientInflightQRowIdCache = new TransientInflightQRowIdCache(queueId); } @Override public void initialize() { initializeInflightQueue(); log.info("{} Initialized with queueId={}, mode={}", DB_QUEUE_LOG_ID, queueId, config.getPersistentQueueMode()); } @Override public void close() { databaseTransactionNotificationApi.unregisterForNotification(this); } @Override public void insertEntryFromTransaction(final QueueSqlDao<T> transactional, final T entry) { final Long lastInsertId = safeInsertEntry(transactional, entry); if (lastInsertId == 0) { log.warn("{} Failed to insert entry, lastInsertedId={}", DB_QUEUE_LOG_ID, lastInsertId); return; } // The current thread is in the middle of a transaction and this is the only times it knows about the recordId for the queue event; // It keeps track of it as a per thread data. Very soon, when the transaction gets committed/rolled back it can then extract the info // and insert the recordId into a blockingQ that is highly optimized to dispatch events. transientInflightQRowIdCache.addRowId(lastInsertId); } private long pollEntriesFromInflightQ(final List<Long> result) { long pollSleepTime = 0; inflightEvents.drainTo(result, config.getMaxInFlightEntries()); if (result.isEmpty()) { try { long beforePollTime = System.nanoTime(); // We block until we see the first entry or reach the timeout (in which case we will rerun the doDispatchEvents() loop and come back here). final Long entryId = inflightEvents.poll(INFLIGHT_POLLING_TIMEOUT_MSEC, TimeUnit.MILLISECONDS); // Maybe there was at least one entry and we did not sleep at all, in which case this time is close to 0. pollSleepTime = System.nanoTime() - beforePollTime; if (entryId != null) { result.add(entryId); } } catch (final InterruptedException e) { Thread.currentThread().interrupt(); log.warn("{} Got interrupted", DB_QUEUE_LOG_ID); return 0; } } return pollSleepTime; } @Override public ReadyEntriesWithMetrics<T> getReadyEntries() { final long ini = System.nanoTime(); long pollSleepTime = 0; final List<Long> recordIds = new ArrayList<Long>(config.getMaxInFlightEntries()); do { pollSleepTime += pollEntriesFromInflightQ(recordIds); } while (recordIds.size() < config.getMinInFlightEntries() && pollSleepTime < INFLIGHT_POLLING_TIMEOUT_MSEC); List<T> entries = Collections.emptyList(); if (!recordIds.isEmpty()) { log.debug("{} fetchReadyEntriesFromIds: {}", DB_QUEUE_LOG_ID, recordIds); entries = executeQuery(new Query<List<T>, QueueSqlDao<T>>() { @Override public List<T> execute(final QueueSqlDao<T> queueSqlDao) { long ini = System.nanoTime(); final List<T> result = queueSqlDao.getEntriesFromIds(recordIds, config.getTableName()); rawGetEntriesTime.update(System.nanoTime() - ini, TimeUnit.NANOSECONDS); return result; } }); } return new ReadyEntriesWithMetrics<T>(entries, (System.nanoTime() - ini) - pollSleepTime); } @Override public void updateOnError(final T entry) { executeTransaction(new Transaction<Void, QueueSqlDao<T>>() { @Override public Void inTransaction(final QueueSqlDao<T> transactional, final TransactionStatus status) throws Exception { transactional.updateOnError(entry.getRecordId(), clock.getUTCNow().toDate(), entry.getErrorCount(), config.getTableName()); transientInflightQRowIdCache.addRowId(entry.getRecordId()); return null; } }); } @Override protected void insertReapedEntriesFromTransaction(final QueueSqlDao<T> transactional, final List<T> entriesLeftBehind, final DateTime now) { for (final T entry : entriesLeftBehind) { entry.setCreatedDate(now); entry.setProcessingState(PersistentQueueEntryLifecycleState.AVAILABLE); entry.setCreatingOwner(CreatorName.get()); entry.setProcessingOwner(null); insertEntryFromTransaction(transactional, entry); } } @AllowConcurrentEvents @Subscribe public void handleDatabaseTransactionEvent(final DatabaseTransactionEvent event) { // Either a transaction we are not interested in, or for the wrong queue; just return. if (transientInflightQRowIdCache == null || !transientInflightQRowIdCache.isValid()) { return; } // This is a ROLLBACK, clear the threadLocal and return if (event.getType() == DatabaseTransactionEventType.ROLLBACK) { transientInflightQRowIdCache.reset(); return; } try { // Add entry in the inflightQ and clear threadlocal final Iterator<Long> entries = transientInflightQRowIdCache.iterator(); while (entries.hasNext()) { final Long entry = entries.next(); final boolean result = inflightEvents.offer(entry); if (result) { log.debug("{} Inserting entry {} into inflightQ", DB_QUEUE_LOG_ID, entry); } else { log.warn("{} Inflight Q overflowed....", DB_QUEUE_LOG_ID, entry); } } } finally { transientInflightQRowIdCache.reset(); } } @VisibleForTesting public int getInflightQSize() { return inflightEvents.size(); } // // Hide the ThreadLocal logic required for inflightQ algorithm in that class and export an easy to use interface. // private static class TransientInflightQRowIdCache { private final ThreadLocal<RowRef> rowRefThreadLocal = new ThreadLocal<RowRef>(); private final int queueId; private TransientInflightQRowIdCache(final int queueId) { this.queueId = queueId; } public boolean isValid() { final RowRef entry = rowRefThreadLocal.get(); return (entry != null && entry.queueId == queueId); } public void addRowId(final Long rowId) { RowRef entry = rowRefThreadLocal.get(); if (entry == null) { entry = new RowRef(queueId); rowRefThreadLocal.set(entry); } entry.addRowId(rowId); } public void reset() { rowRefThreadLocal.remove(); } public Iterator<Long> iterator() { final RowRef entry = rowRefThreadLocal.get(); Preconditions.checkNotNull(entry); return entry.iterator(); } // Internal structure to keep track of recordId per queue private static final class RowRef { private final int queueId; private final List<Long> rowIds; public RowRef(final int queueId) { this.queueId = queueId; this.rowIds = new ArrayList<Long>(); } public void addRowId(final long rowId) { rowIds.add(rowId); } public Iterator<Long> iterator() { return rowIds.iterator(); } } } private void initializeInflightQueue() { inflightEvents.clear(); int totalEntries = 0; long fromRecordId = -1; do { final List<Long> existingIds = ((PersistentBusSqlDao) sqlDao).getReadyEntryIds(clock.getUTCNow().toDate(), fromRecordId, MAX_FETCHED_RECORDS_ID, CreatorName.get(), config.getTableName()); if (existingIds.isEmpty()) { break; } inflightEvents.addAll(existingIds); totalEntries += existingIds.size(); if (existingIds.size() < MAX_FETCHED_RECORDS_ID) { break; } fromRecordId = existingIds.get(existingIds.size() - 1) + 1; } while (true); log.info("{} Inserting {} entries into inflightQ during initialization", DB_QUEUE_LOG_ID, totalEntries); } }
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/queue/DBBackedQueueWithPolling.java
queue/src/main/java/org/killbill/queue/DBBackedQueueWithPolling.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.queue; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.joda.time.DateTime; import org.killbill.CreatorName; import org.killbill.clock.Clock; import org.killbill.commons.metrics.api.MetricRegistry; import org.killbill.queue.api.PersistentQueueConfig; import org.killbill.queue.api.PersistentQueueConfig.PersistentQueueMode; import org.killbill.queue.api.PersistentQueueEntryLifecycleState; import org.killbill.queue.dao.EventEntryModelDao; import org.killbill.queue.dao.QueueSqlDao; import org.skife.jdbi.v2.IDBI; import org.skife.jdbi.v2.Transaction; import org.skife.jdbi.v2.TransactionStatus; public class DBBackedQueueWithPolling<T extends EventEntryModelDao> extends DBBackedQueue<T> { public DBBackedQueueWithPolling(final Clock clock, final IDBI dbi, final Class<? extends QueueSqlDao<T>> sqlDaoClass, final PersistentQueueConfig config, final String dbBackedQId, final MetricRegistry metricRegistry) { super(clock, dbi, sqlDaoClass, config, dbBackedQId, metricRegistry); } @Override public void initialize() { log.info("{} Initialized mode={}", DB_QUEUE_LOG_ID, config.getPersistentQueueMode()); } @Override public void close() { } @Override public void insertEntryFromTransaction(final QueueSqlDao<T> transactional, final T entry) { safeInsertEntry(transactional, entry); } @Override public ReadyEntriesWithMetrics<T> getReadyEntries() { final long ini = System.nanoTime(); final List<T> claimedEntries = executeTransaction(new Transaction<>() { @Override public List<T> inTransaction(final QueueSqlDao<T> queueSqlDao, final TransactionStatus status) throws Exception { final DateTime now = clock.getUTCNow(); final List<T> entriesToClaim = fetchReadyEntries(now, config.getMaxEntriesClaimed(), queueSqlDao); List<T> claimedEntries = Collections.emptyList(); if (!entriesToClaim.isEmpty()) { log.debug("{} Entries to claim: {}", DB_QUEUE_LOG_ID, entriesToClaim); claimedEntries = claimEntries(now, entriesToClaim, queueSqlDao); } return claimedEntries; } }); return new ReadyEntriesWithMetrics<T>(claimedEntries, System.nanoTime() - ini); } @Override public void updateOnError(final T entry) { executeTransaction(new Transaction<Void, QueueSqlDao<T>>() { @Override public Void inTransaction(final QueueSqlDao<T> transactional, final TransactionStatus status) throws Exception { transactional.updateOnError(entry.getRecordId(), clock.getUTCNow().toDate(), entry.getErrorCount(), config.getTableName()); return null; } }); } @Override protected void insertReapedEntriesFromTransaction(final QueueSqlDao<T> transactional, final List<T> entriesLeftBehind, final DateTime now) { for (final T entry : entriesLeftBehind) { entry.setCreatedDate(now); entry.setProcessingState(PersistentQueueEntryLifecycleState.AVAILABLE); entry.setCreatingOwner(CreatorName.get()); entry.setProcessingOwner(null); } transactional.insertEntries(entriesLeftBehind, config.getTableName()); } private List<T> fetchReadyEntries(final DateTime now, final int maxEntries, final QueueSqlDao<T> queueSqlDao) { final String owner = config.getPersistentQueueMode() == PersistentQueueMode.POLLING ? null : CreatorName.get(); final long ini = System.nanoTime(); final List<T> result = queueSqlDao.getReadyEntries(now.toDate(), maxEntries, owner, config.getTableName()); rawGetEntriesTime.update(System.nanoTime() - ini, TimeUnit.NANOSECONDS); return result; } private List<T> claimEntries(final DateTime now, final List<T> candidates, final QueueSqlDao<T> queueSqlDao) { switch (config.getPersistentQueueMode()) { case POLLING: return sequentialClaimEntries(now, candidates, queueSqlDao); case STICKY_POLLING: return batchClaimEntries(now, candidates, queueSqlDao); default: throw new IllegalStateException("Unsupported PersistentQueueMode " + config.getPersistentQueueMode()); } } private List<T> batchClaimEntries(final DateTime utcNow, final List<T> candidates, final QueueSqlDao<T> queueSqlDao) { if (candidates.isEmpty()) { return Collections.emptyList(); } final Date now = utcNow.toDate(); final Date nextAvailable = utcNow.plus(config.getClaimedTime().getMillis()).toDate(); final String owner = CreatorName.get(); final List<Long> recordIds = candidates.stream() .map(input -> input == null ? Long.valueOf( -1L) : input.getRecordId()) .collect(Collectors.toUnmodifiableList()); final long ini = System.nanoTime(); final int resultCount = queueSqlDao.claimEntries(recordIds, owner, nextAvailable, config.getTableName()); rawClaimEntriesTime.update(System.nanoTime() - ini, TimeUnit.NANOSECONDS); // We should ALWAYS see the same number since we are in STICKY_POLLING mode and there is only one thread claiming entries. // We keep the 2 cases below for safety (code was written when this was MT-threaded), and we log with warn (will eventually remove it in the future) if (resultCount == candidates.size()) { log.debug("{} batchClaimEntries claimed (recordIds={}, now={}, nextAvailable={}, owner={}): {}", DB_QUEUE_LOG_ID, recordIds, now, nextAvailable, owner, candidates); return candidates; } else { final List<T> maybeClaimedEntries = queueSqlDao.getEntriesFromIds(recordIds, config.getTableName()); final StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < maybeClaimedEntries.size(); i++) { final T eventEntryModelDao = maybeClaimedEntries.get(i); if (i > 0) { stringBuilder.append(","); } stringBuilder.append("[recordId=").append(eventEntryModelDao.getRecordId()) .append(",processingState=").append(eventEntryModelDao.getProcessingState()) .append(",processingOwner=").append(eventEntryModelDao.getProcessingOwner()) .append(",processingAvailableDate=").append(eventEntryModelDao.getNextAvailableDate()) .append("]"); } log.warn("{} batchClaimEntries only claimed partial entries {}/{} (now={}, nextAvailable={}, owner={}): {}", DB_QUEUE_LOG_ID, resultCount, candidates.size(), now, nextAvailable, owner, stringBuilder.toString()); return maybeClaimedEntries.stream() .filter(input -> input != null && input.getProcessingState() == PersistentQueueEntryLifecycleState.IN_PROCESSING && owner.equals(input.getProcessingOwner())) .collect(Collectors.toUnmodifiableList()); } } // // In non sticky mode, we don't optimize claim update because we can't synchronize easily -- we could rely on global lock, // but we are looking for performance and that does not the right choice. // private List<T> sequentialClaimEntries(final DateTime now, final List<T> candidates, final QueueSqlDao<T> queueSqlDao) { return candidates.stream() .filter(input -> claimEntry(now, input, queueSqlDao)) .collect(Collectors.toUnmodifiableList()); } private boolean claimEntry(final DateTime now, final T entry, final QueueSqlDao<T> queueSqlDao) { final Date nextAvailable = now.plus(config.getClaimedTime().getMillis()).toDate(); final long ini = System.nanoTime(); final int claimEntry = queueSqlDao.claimEntry(entry.getRecordId(), CreatorName.get(), nextAvailable, config.getTableName()); rawClaimEntryTime.update(System.nanoTime() - ini, TimeUnit.NANOSECONDS); final boolean claimed = (claimEntry == 1); if (claimed) { log.debug("{} Claimed entry {}", DB_QUEUE_LOG_ID, entry); } return claimed; } }
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/queue/DefaultReaper.java
queue/src/main/java/org/killbill/queue/DefaultReaper.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.Date; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.killbill.clock.Clock; import org.killbill.commons.concurrent.Executors; import org.killbill.queue.api.PersistentQueueConfig; import org.killbill.queue.api.Reaper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class DefaultReaper implements Reaper { static final long ONE_MINUTES_IN_MSEC = 60000; static final long FIVE_MINUTES_IN_MSEC = 5 * ONE_MINUTES_IN_MSEC; private final DBBackedQueue<?> dao; private final PersistentQueueConfig config; private final Clock clock; private final AtomicBoolean isStarted; private final String threadScheduledExecutorName; private ScheduledFuture<?> reapEntriesHandle; private static final Logger log = LoggerFactory.getLogger(DefaultReaper.class); private ScheduledExecutorService scheduler; public DefaultReaper(final DBBackedQueue<?> dao, final PersistentQueueConfig config, final Clock clock, final String threadScheduledExecutorName) { this.dao = dao; this.config = config; this.clock = clock; this.isStarted = new AtomicBoolean(false); this.threadScheduledExecutorName = threadScheduledExecutorName; } @Override public void start() { if (!isStarted.compareAndSet(false, true)) { return; } final long reapThresholdMillis = getReapThreshold(); final long schedulePeriodMillis = config.getReapSchedule().getMillis(); log.info("{}: Starting... reapThresholdMillis={}, schedulePeriodMillis={}", threadScheduledExecutorName, reapThresholdMillis, schedulePeriodMillis); final Runnable reapEntries = new Runnable() { @Override public void run() { dao.reapEntries(getReapingDate()); } private Date getReapingDate() { return clock.getUTCNow().minusMillis((int) reapThresholdMillis).toDate(); } }; scheduler = Executors.newSingleThreadScheduledExecutor(threadScheduledExecutorName); reapEntriesHandle = scheduler.scheduleWithFixedDelay(reapEntries, schedulePeriodMillis, schedulePeriodMillis, TimeUnit.MILLISECONDS); } @Override public boolean stop() { if (!isStarted.compareAndSet(true, false)) { return true; } log.info("{}: Shutting down reaper", threadScheduledExecutorName); if (!reapEntriesHandle.isCancelled() || !reapEntriesHandle.isDone()) { reapEntriesHandle.cancel(true); } scheduler.shutdown(); try { return scheduler.awaitTermination(config.getShutdownTimeout().getPeriod(), config.getShutdownTimeout().getUnit()); } catch (final InterruptedException e) { log.info("{} stop sequence has been interrupted", threadScheduledExecutorName); Thread.currentThread().interrupt(); return false; } } @Override public boolean isStarted() { return isStarted.get(); } long getReapThreshold() { final long threshold; // if Claim time is greater than reap threshold if (config.getClaimedTime().getMillis() >= config.getReapThreshold().getMillis()) { // override reap threshold using claim time + 5 minutes threshold = config.getClaimedTime().getMillis() + FIVE_MINUTES_IN_MSEC; log.warn("{}: Reap threshold was mis-configured. Claim time [{}] is greater than reap threshold [{}]", threadScheduledExecutorName, config.getClaimedTime().toString(), config.getReapThreshold().toString()); } else { threshold = config.getReapThreshold().getMillis(); } return threshold; } }
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/queue/DefaultQueueLifecycle.java
queue/src/main/java/org/killbill/queue/DefaultQueueLifecycle.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.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.killbill.commons.concurrent.Executors; import org.killbill.commons.metrics.api.Gauge; import org.killbill.commons.metrics.api.Histogram; import org.killbill.commons.metrics.api.MetricRegistry; import org.killbill.commons.metrics.api.Timer; import org.killbill.queue.api.PersistentQueueConfig; import org.killbill.queue.api.QueueLifecycle; import org.killbill.queue.dao.EventEntryModelDao; import org.skife.jdbi.v2.exceptions.DBIException; 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 abstract class DefaultQueueLifecycle implements QueueLifecycle { public static final String QUEUE_NAME = "Queue"; private static final Logger log = LoggerFactory.getLogger(DefaultQueueLifecycle.class); private static final long ONE_MILLION = 1000L * 1000L; private static final long MAX_SLEEP_TIME_MS = 100; // Max size of the batch we allow private static final int MAX_COMPLETED_ENTRIES = 15; protected final String svcQName; protected final ObjectReader objectReader; protected final ObjectWriter objectWriter; protected final PersistentQueueConfig config; private final LinkedBlockingQueue<EventEntryModelDao> completedOrFailedEvents; private final LinkedBlockingQueue<EventEntryModelDao> retriedEvents; // Time to dispatch entries to Dispatcher threads private final Timer dispatchTime; // Time to move entries to history table (or update entry for retry) private final Timer completeTime; // Nb of entries dispatched at each loop private final Histogram dispatchedEntries; // Nb of entries completed at each loop private final Histogram completeEntries; private final boolean isStickyEvent; private volatile boolean isDispatchingEvents; private volatile boolean isCompletingEvents; // Deferred in start sequence to allow for restart, which is not possible after the shutdown (mostly for test purpose) private ExecutorService lifecycleDispatcherExecutor; private ExecutorService lifecycleCompletionExecutor; protected final Gauge<Integer> completedOrFailedEventsGauge; public DefaultQueueLifecycle(final String svcQName, final PersistentQueueConfig config, final MetricRegistry metricRegistry) { this(svcQName, config, metricRegistry, QueueObjectMapper.get()); } private DefaultQueueLifecycle(final String svcQName, final PersistentQueueConfig config, final MetricRegistry metricRegistry, final ObjectMapper objectMapper) { this.svcQName = svcQName; this.config = config; this.isDispatchingEvents = false; this.isCompletingEvents = false; this.objectReader = objectMapper.reader(); this.objectWriter = objectMapper.writer(); this.completedOrFailedEvents = new LinkedBlockingQueue<>(); this.retriedEvents = new LinkedBlockingQueue<>(); this.isStickyEvent = config.getPersistentQueueMode() == PersistentQueueConfig.PersistentQueueMode.STICKY_EVENTS; this.dispatchTime = metricRegistry.timer(String.format("%s.%s.%s", DefaultQueueLifecycle.class.getName(), svcQName, "dispatchTime")); this.completeTime = metricRegistry.timer(String.format("%s.%s.%s", DefaultQueueLifecycle.class.getName(), svcQName, "completeTime")); this.dispatchedEntries = metricRegistry.histogram(String.format("%s.%s.%s", DefaultQueueLifecycle.class.getName(), svcQName, "dispatchedEntries")); this.completeEntries = metricRegistry.histogram(String.format("%s.%s.%s", DefaultQueueLifecycle.class.getName(), svcQName, "completeEntries")); this.completedOrFailedEventsGauge = metricRegistry.gauge(String.format("%s.%s.%s.%s", DefaultQueueLifecycle.class.getName(), svcQName, "completedOrFailedEvents", "size"), new Gauge<Integer>() { @Override public Integer getValue() { return completedOrFailedEvents.size(); } }); } @Override public boolean startQueue() { this.lifecycleDispatcherExecutor = Executors.newFixedThreadPool(config.geNbLifecycleDispatchThreads(), config.getTableName() + "-lifecycle-dispatcher-th"); this.lifecycleCompletionExecutor = Executors.newFixedThreadPool(config.geNbLifecycleCompleteThreads(), config.getTableName() + "-lifecycle-completion-th"); log.info("{}: Starting...", svcQName); // Start the completion threads before the dispatcher ones isCompletingEvents = true; for (int i = 0; i < config.geNbLifecycleCompleteThreads(); i++) { lifecycleCompletionExecutor.execute(new CompletionRunnable()); } isDispatchingEvents = true; for (int i = 0; i < config.geNbLifecycleDispatchThreads(); i++) { lifecycleDispatcherExecutor.execute(new DispatcherRunnable()); } return true; } // Stop the lifecycle dispatcher threads, which fetch available entries and move them into the dispatch queue protected boolean stopLifecycleDispatcher() { isDispatchingEvents = false; lifecycleDispatcherExecutor.shutdown(); try { return lifecycleDispatcherExecutor.awaitTermination(config.getShutdownTimeout().getPeriod(), config.getShutdownTimeout().getUnit()); } catch (final InterruptedException e) { log.info("{}: Lifecycle dispatcher stop sequence has been interrupted", svcQName); return false; } } // Stop the lifecycle completion threads, which move processed and failed entries into the history tables protected boolean stopLifecycleCompletion() { isCompletingEvents = false; lifecycleCompletionExecutor.shutdown(); try { return lifecycleCompletionExecutor.awaitTermination(config.getShutdownTimeout().getPeriod(), config.getShutdownTimeout().getUnit()); } catch (final InterruptedException e) { log.info("{}: Lifecycle completion stop sequence has been interrupted", svcQName); return false; } finally { final int remainingCompleted = completedOrFailedEvents.size(); final int remainingRetried = retriedEvents.size(); if (remainingCompleted > 0 || remainingRetried > 0) { log.warn("{}: Stopped queue with {} event/notifications non completed", svcQName, (remainingCompleted + remainingRetried)); } } } public <M extends EventEntryModelDao> void dispatchCompletedOrFailedEvents(final M event) { completedOrFailedEvents.add(event); } public <M extends EventEntryModelDao> void dispatchRetriedEvents(final M event) { retriedEvents.add(event); } public abstract DispatchResultMetrics doDispatchEvents(); public abstract void doProcessCompletedEvents(final Iterable<? extends EventEntryModelDao> completed); public abstract void doProcessRetriedEvents(final Iterable<? extends EventEntryModelDao> retried); public ObjectReader getObjectReader() { return objectReader; } public ObjectWriter getObjectWriter() { return objectWriter; } public static class DispatchResultMetrics { private final int nbEntries; private final long timeNanoSec; public DispatchResultMetrics(final int nbEntries, final long timeNanoSec) { this.nbEntries = nbEntries; this.timeNanoSec = timeNanoSec; } public int getNbEntries() { return nbEntries; } public long getTimeNanoSec() { return timeNanoSec; } } private final class CompletionRunnable implements Runnable { @Override public void run() { try { log.info("{}: Completion thread {} [{}] starting ", svcQName, Thread.currentThread().getName(), Thread.currentThread().getId()); while (true) { if (!isCompletingEvents) { break; } withHandlingRuntimeException(new RunnableRawCallback() { @Override public void callback() throws InterruptedException { long ini = System.nanoTime(); long pollSleepTime = 0; final List<EventEntryModelDao> completed = new ArrayList<>(MAX_COMPLETED_ENTRIES); completedOrFailedEvents.drainTo(completed, MAX_COMPLETED_ENTRIES); if (completed.isEmpty()) { long beforePollTime = System.nanoTime(); final EventEntryModelDao entry = completedOrFailedEvents.poll(MAX_SLEEP_TIME_MS, TimeUnit.MILLISECONDS); pollSleepTime = System.nanoTime() - beforePollTime; if (entry != null) { completed.add(entry); } } if (!completed.isEmpty()) { doProcessCompletedEvents(completed); } int retried = drainRetriedEvents(); final int completeOrRetried = completed.size() + retried; if (completeOrRetried > 0) { completeEntries.update(completeOrRetried); completeTime.update((System.nanoTime() - ini) - pollSleepTime, TimeUnit.NANOSECONDS); } } }); } } catch (final InterruptedException e) { log.info("{}: Completion thread {} [{}] got interrupted, exiting... ", svcQName, Thread.currentThread().getName(), Thread.currentThread().getId()); } catch (final Error e) { log.error("{}: Completion thread {} [{}] got an exception, exiting...", svcQName, Thread.currentThread().getName(), Thread.currentThread().getId(), e); } finally { log.info("{}: Completion thread {} [{}] has exited", svcQName, Thread.currentThread().getName(), Thread.currentThread().getId()); } } private int drainRetriedEvents() { final int curSize = retriedEvents.size(); if (curSize > 0) { final List<EventEntryModelDao> retried = new ArrayList<>(curSize); retriedEvents.drainTo(retried, curSize); doProcessRetriedEvents(retried); } return curSize; } } private final class DispatcherRunnable implements Runnable { @Override public void run() { try { log.info("{}: Dispatching thread {} [{}] starting ", svcQName, Thread.currentThread().getName(), Thread.currentThread().getId()); while (true) { if (!isDispatchingEvents) { break; } withHandlingRuntimeException(new RunnableRawCallback() { @Override public void callback() throws InterruptedException { final long beforeLoop = System.nanoTime(); dispatchEvents(); final long afterLoop = System.nanoTime(); sleepSporadically((afterLoop - beforeLoop) / ONE_MILLION); } }); } } catch (final InterruptedException e) { log.info("{}: Dispatching thread {} [{}] got interrupted, exiting... ", svcQName, Thread.currentThread().getName(), Thread.currentThread().getId()); } catch (final Error e) { log.error("{}: Dispatching thread {} [{}] got an exception, exiting... ", svcQName, Thread.currentThread().getName(), Thread.currentThread().getId(), e); } finally { log.info("{}: Dispatching thread {} [{}] has exited", svcQName, Thread.currentThread().getName(), Thread.currentThread().getId()); } } private void dispatchEvents() { long ini = System.nanoTime(); final DispatchResultMetrics metricsResult = doDispatchEvents(); dispatchedEntries.update(metricsResult.getNbEntries()); if (isStickyEvent) { dispatchTime.update(metricsResult.getTimeNanoSec(), TimeUnit.NANOSECONDS); } else { dispatchTime.update(System.nanoTime() - ini, TimeUnit.NANOSECONDS); } } private void sleepSporadically(final long loopTimeMsec) throws InterruptedException { if (isStickyEvent) { // In this mode, the main thread does not sleep, but blocks on the inflightQ to minimize latency. return; } long remainingSleepTime = config.getPollingSleepTimeMs() - loopTimeMsec; while (remainingSleepTime > 0) { final long curSleepTime = remainingSleepTime > MAX_SLEEP_TIME_MS ? MAX_SLEEP_TIME_MS : remainingSleepTime; Thread.sleep(curSleepTime); remainingSleepTime -= curSleepTime; } } } private interface RunnableRawCallback { void callback() throws InterruptedException; } private void withHandlingRuntimeException(final RunnableRawCallback cb) throws InterruptedException { try { cb.callback(); } catch (final DBIException e) { log.warn("{}: Thread {} got DBIException exception: ", svcQName, Thread.currentThread().getName(), e); } catch (final RuntimeException e) { log.warn("{}: Thread {} got Runtime exception: ", svcQName, Thread.currentThread().getName(), 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/main/java/org/killbill/queue/InTransaction.java
queue/src/main/java/org/killbill/queue/InTransaction.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.queue; import java.io.PrintWriter; import java.sql.Connection; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import javax.sql.DataSource; import org.killbill.bus.dao.BusEventModelDao; import org.killbill.commons.jdbi.argument.DateTimeArgumentFactory; import org.killbill.commons.jdbi.argument.DateTimeZoneArgumentFactory; import org.killbill.commons.jdbi.argument.LocalDateArgumentFactory; import org.killbill.commons.jdbi.argument.UUIDArgumentFactory; import org.killbill.commons.jdbi.mapper.LowerToCamelBeanMapperFactory; import org.killbill.commons.jdbi.mapper.UUIDMapper; import org.killbill.commons.utils.annotation.VisibleForTesting; import org.killbill.notificationq.dao.NotificationEventModelDao; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.tweak.ConnectionFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class InTransaction { private static final Logger logger = LoggerFactory.getLogger(InTransaction.class); public static <K, R> R execute(final DBI dbi, final Connection connection, final InTransactionHandler<K, R> handler, final Class<K> klass) { // Make sure to NOT recreate a DBI object as all existing caches would be discarded final Handle handle = dbi.open(new ConnectionFactoryWithDelegate(connection)); try { final K transactional = handle.attach(klass); return handler.withSqlDao(transactional); } finally { // We do not release the connection -- client is responsible for closing it // h.close(); } } public static DBI buildDDBI(final Connection connection) { final DataSourceWithDelegate dataSource = new DataSourceWithDelegate(connection); return buildDDBI(dataSource); } public static DBI buildDDBI(final DataSource dataSource) { final DBI dbi = new DBI(dataSource); setupDBI(dbi); return dbi; } @VisibleForTesting public static void setupDBI(final DBI dbi) { dbi.registerArgumentFactory(new UUIDArgumentFactory()); dbi.registerArgumentFactory(new DateTimeZoneArgumentFactory()); dbi.registerArgumentFactory(new DateTimeArgumentFactory()); dbi.registerArgumentFactory(new LocalDateArgumentFactory()); dbi.registerMapper(new UUIDMapper()); dbi.registerMapper(new LowerToCamelBeanMapperFactory(BusEventModelDao.class)); dbi.registerMapper(new LowerToCamelBeanMapperFactory(NotificationEventModelDao.class)); } public static interface InTransactionHandler<K, R> { public R withSqlDao(final K transactional); } private static final class DataSourceWithDelegate implements DataSource { private final Connection connection; public DataSourceWithDelegate(final Connection connection) { this.connection = connection; } public Connection getConnection() throws SQLException { return connection; } public Connection getConnection(final String username, final String password) throws SQLException { return connection; } public PrintWriter getLogWriter() throws SQLException { throw new UnsupportedOperationException(); } public void setLogWriter(final PrintWriter out) throws SQLException { throw new UnsupportedOperationException(); } public void setLoginTimeout(final int seconds) throws SQLException { throw new UnsupportedOperationException(); } public int getLoginTimeout() throws SQLException { throw new UnsupportedOperationException(); } public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException { throw new UnsupportedOperationException(); } public <T> T unwrap(final Class<T> iface) throws SQLException { throw new UnsupportedOperationException(); } public boolean isWrapperFor(final Class<?> iface) throws SQLException { throw new UnsupportedOperationException(); } } private static final class ConnectionFactoryWithDelegate implements ConnectionFactory { private final Connection connection; public ConnectionFactoryWithDelegate(final Connection connection) { this.connection = connection; } @Override public Connection openConnection() throws SQLException { return connection; } } }
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/queue/DBBackedQueue.java
queue/src/main/java/org/killbill/queue/DBBackedQueue.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.queue; import java.sql.SQLException; import java.sql.SQLWarning; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.joda.time.DateTime; import org.killbill.CreatorName; import org.killbill.clock.Clock; import org.killbill.commons.metrics.api.MetricRegistry; import org.killbill.commons.metrics.api.Timer; import org.killbill.commons.profiling.Profiling; import org.killbill.commons.profiling.ProfilingFeature; import org.killbill.commons.utils.collect.Iterables; import org.killbill.queue.api.PersistentQueueConfig; import org.killbill.queue.api.PersistentQueueConfig.PersistentQueueMode; import org.killbill.queue.api.PersistentQueueEntryLifecycleState; import org.killbill.queue.dao.EventEntryModelDao; import org.killbill.queue.dao.QueueSqlDao; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.IDBI; import org.skife.jdbi.v2.Transaction; import org.skife.jdbi.v2.TransactionCallback; import org.skife.jdbi.v2.TransactionStatus; import org.skife.jdbi.v2.tweak.HandleCallback; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class abstract the interaction with the database tables which store the persistent entries for the bus events or * notification events. * <p/> * <p>This can be configured to either cache the recordId for the entries that are ready be fetched so that we avoid expansive * queries to the database. Alternatively, the inflight queue is not used and the search query is always run when we need to retrieve * new entries. * * @param <T> */ public abstract class DBBackedQueue<T extends EventEntryModelDao> { protected static final Logger log = LoggerFactory.getLogger(DBBackedQueue.class); protected final String DB_QUEUE_LOG_ID; protected final IDBI dbi; protected final Class<? extends QueueSqlDao<T>> sqlDaoClass; protected final QueueSqlDao<T> sqlDao; protected final Clock clock; protected final PersistentQueueConfig config; // // All these *raw* time measurement only measure the query time *not* including the transaction and the time to acquire DB connection // // Time to get the ready entries (polling) or all entries from ids (inflight) protected final Timer rawGetEntriesTime; // Time to insert one entry in the DB protected final Timer rawInsertEntryTime; // Time to claim the batch of entries (STICKY_POLLING) protected final Timer rawClaimEntriesTime; // Time to claim one entry (POLLING mode) protected final Timer rawClaimEntryTime; // Time to move a batch of entries (delete from table + insert into history) protected final Timer rawDeleteEntriesTime; // Time to move one entry (delete from table + insert into history) protected final Timer rawDeleteEntryTime; protected final Profiling<Long, RuntimeException> prof; public DBBackedQueue(final Clock clock, final IDBI dbi, final Class<? extends QueueSqlDao<T>> sqlDaoClass, final PersistentQueueConfig config, final String dbBackedQId, final MetricRegistry metricRegistry) { this.dbi = dbi; this.sqlDaoClass = sqlDaoClass; this.sqlDao = dbi.onDemand(sqlDaoClass); this.config = config; this.clock = clock; this.prof = new Profiling<Long, RuntimeException>(); this.rawGetEntriesTime = metricRegistry.timer(String.format("%s.%s.%s", DBBackedQueue.class.getName(), dbBackedQId, "rawGetEntriesTime")); this.rawInsertEntryTime = metricRegistry.timer(String.format("%s.%s.%s", DBBackedQueue.class.getName(), dbBackedQId, "rawInsertEntryTime")); this.rawClaimEntriesTime = metricRegistry.timer(String.format("%s.%s.%s", DBBackedQueue.class.getName(), dbBackedQId, "rawClaimEntriesTime")); this.rawClaimEntryTime = metricRegistry.timer(String.format("%s.%s.%s", DBBackedQueue.class.getName(), dbBackedQId, "rawClaimEntryTime")); this.rawDeleteEntriesTime = metricRegistry.timer(String.format("%s.%s.%s", DBBackedQueue.class.getName(), dbBackedQId, "rawDeleteEntriesTime")); this.rawDeleteEntryTime = metricRegistry.timer(String.format("%s.%s.%s", DBBackedQueue.class.getName(), dbBackedQId, "rawDeleteEntryTime")); this.DB_QUEUE_LOG_ID = "DBBackedQueue-" + dbBackedQId; } public static class ReadyEntriesWithMetrics<T extends EventEntryModelDao> { private final List<T> entries; private final long time; public ReadyEntriesWithMetrics(final List<T> entries, final long time) { this.entries = new ArrayList<>(entries); this.time = time; } public List<T> getEntries() { return entries; } public long getTime() { return time; } } public abstract void initialize(); public abstract void close(); public abstract ReadyEntriesWithMetrics<T> getReadyEntries(); public abstract void insertEntryFromTransaction(final QueueSqlDao<T> transactional, final T entry); public abstract void updateOnError(final T entry); protected abstract void insertReapedEntriesFromTransaction(final QueueSqlDao<T> transactional, final List<T> entriesLeftBehind, final DateTime now); public void insertEntry(final T entry) { executeTransaction(new Transaction<Void, QueueSqlDao<T>>() { @Override public Void inTransaction(final QueueSqlDao<T> transactional, final TransactionStatus status) { insertEntryFromTransaction(transactional, entry); return null; } }); } public void moveEntryToHistory(final T entry) { executeTransaction(new Transaction<Void, QueueSqlDao<T>>() { @Override public Void inTransaction(final QueueSqlDao<T> transactional, final TransactionStatus status) throws Exception { moveEntryToHistoryFromTransaction(transactional, entry); return null; } }); } public void moveEntryToHistoryFromTransaction(final QueueSqlDao<T> transactional, final T entry) { try { switch (entry.getProcessingState()) { case FAILED: case PROCESSED: case REMOVED: case REAPED: break; default: log.warn("{} Unexpected terminal event state={} for record_id={}", DB_QUEUE_LOG_ID, entry.getProcessingState(), entry.getRecordId()); break; } log.debug("{} Moving entry into history: recordId={}, className={}, json={}", DB_QUEUE_LOG_ID, entry.getRecordId(), entry.getClassName(), entry.getEventJson()); long ini = System.nanoTime(); transactional.insertEntry(entry, config.getHistoryTableName()); transactional.removeEntry(entry.getRecordId(), config.getTableName()); rawDeleteEntryTime.update(System.nanoTime() - ini, TimeUnit.NANOSECONDS); } catch (final Exception e) { log.warn("{} Failed to move entry into history: {}", DB_QUEUE_LOG_ID, entry, e); } } public void moveEntriesToHistory(final Iterable<T> entries) { try { executeTransaction(new Transaction<Void, QueueSqlDao<T>>() { @Override public Void inTransaction(final QueueSqlDao<T> transactional, final TransactionStatus status) throws Exception { moveEntriesToHistoryFromTransaction(transactional, entries); return null; } }); } catch (final Exception e) { log.warn("{} Failed to move entries into history: {}", DB_QUEUE_LOG_ID, entries, e); } } public void moveEntriesToHistoryFromTransaction(final QueueSqlDao<T> transactional, final Iterable<T> entries) { if (!entries.iterator().hasNext()) { return; } for (final T cur : entries) { switch (cur.getProcessingState()) { case FAILED: case PROCESSED: case REMOVED: case REAPED: break; default: log.warn("{} Unexpected terminal event state={} for record_id={}", DB_QUEUE_LOG_ID, cur.getProcessingState(), cur.getRecordId()); break; } log.debug("{} Moving entry into history: recordId={}, className={}, json={}", DB_QUEUE_LOG_ID, cur.getRecordId(), cur.getClassName(), cur.getEventJson()); } final Collection<Long> toBeRemovedRecordIds = Iterables.toStream(entries) .map(input -> input == null ? Long.valueOf(-1L) : input.getRecordId()) .collect(Collectors.toUnmodifiableList()); final long ini = System.nanoTime(); transactional.insertEntries(entries, config.getHistoryTableName()); transactional.removeEntries(toBeRemovedRecordIds, config.getTableName()); rawDeleteEntriesTime.update(System.nanoTime() - ini, TimeUnit.NANOSECONDS); } protected long getNbReadyEntries() { final Date now = clock.getUTCNow().toDate(); return getNbReadyEntries(now); } public long getNbReadyEntries(final Date now) { final String owner = config.getPersistentQueueMode() == PersistentQueueMode.POLLING ? null : CreatorName.get(); return executeQuery(new Query<Long, QueueSqlDao<T>>() { @Override public Long execute(final QueueSqlDao<T> queueSqlDao) { return queueSqlDao.getNbReadyEntries(now, owner, config.getTableName()); } }); } protected Long safeInsertEntry(final QueueSqlDao<T> transactional, final T entry) { return prof.executeWithProfiling(ProfilingFeature.ProfilingFeatureType.DAO, "QueueSqlDao:insert", new Profiling.WithProfilingCallback<Long, RuntimeException>() { @Override public Long execute() throws RuntimeException { final long init = System.nanoTime(); final Long lastInsertId = transactional.insertEntry(entry, config.getTableName()); if (lastInsertId > 0) { log.debug("{} Inserting entry: lastInsertId={}, entry={}", DB_QUEUE_LOG_ID, lastInsertId, entry); } else { log.warn("{} Error inserting entry: lastInsertId={}, entry={}", DB_QUEUE_LOG_ID, lastInsertId, entry); } rawInsertEntryTime.update(System.nanoTime() - init, TimeUnit.NANOSECONDS); return lastInsertId; } }); } // It is a good idea to monitor reapEntries in logs as these entries should rarely happen public void reapEntries(final Date reapingDate) { executeTransaction(new Transaction<Void, QueueSqlDao<T>>() { @Override public Void inTransaction(final QueueSqlDao<T> transactional, final TransactionStatus status) throws Exception { final DateTime now = clock.getUTCNow(); final String owner = CreatorName.get(); final List<T> entriesLeftBehind = transactional.getEntriesLeftBehind(config.getMaxReDispatchCount(), now.toDate(), reapingDate, config.getTableName()); if (entriesLeftBehind.isEmpty()) { return null; } final List<T> entriesToReInsert = new ArrayList<T>(entriesLeftBehind.size()); final List<T> lateEntries = new LinkedList<T>(); for (final T entryLeftBehind : entriesLeftBehind) { // entryIsBeingProcessedByThisNode is a sign of a stuck entry on this node // entryCreatedByThisNodeAndNeverProcessed is likely a sign of the queue being late final boolean entryCreatedByThisNodeAndNeverProcessed = owner.equals(entryLeftBehind.getCreatingOwner()) && entryLeftBehind.getProcessingOwner() == null; if (entryCreatedByThisNodeAndNeverProcessed) { lateEntries.add(entryLeftBehind); } else { /* This includes entryIsBeingProcessedByThisNode (owner.equals(entryLeftBehind.getProcessingOwner())). See https://github.com/killbill/killbill-commons/issues/169 */ // Set the status to REAPED in the history table entryLeftBehind.setProcessingState(PersistentQueueEntryLifecycleState.REAPED); entriesToReInsert.add(entryLeftBehind); } } if (!lateEntries.isEmpty()) { log.warn("{} reapEntries: late queue entries {}", DB_QUEUE_LOG_ID, lateEntries); } if (!entriesToReInsert.isEmpty()) { moveEntriesToHistoryFromTransaction(transactional, entriesToReInsert); insertReapedEntriesFromTransaction(transactional, entriesToReInsert, now); log.warn("{} reapEntries: {} entries were reaped by {} {}", DB_QUEUE_LOG_ID, entriesToReInsert.size(), owner, entriesToReInsert.stream().map(input -> input == null ? null : input.getUserToken())); } return null; } }); } protected <U> U executeQuery(final Query<U, QueueSqlDao<T>> query) { return dbi.withHandle(new HandleCallback<U>() { @Override public U withHandle(final Handle handle) throws Exception { final U result = query.execute(handle.attach(sqlDaoClass)); printSQLWarnings(handle); return result; } }); } protected <U> U executeTransaction(final Transaction<U, QueueSqlDao<T>> transaction) { return dbi.inTransaction(new TransactionCallback<U>() { @Override public U inTransaction(final Handle handle, final TransactionStatus status) throws Exception { final U result = transaction.inTransaction(handle.attach(sqlDaoClass), status); printSQLWarnings(handle); return result; } }); } protected void printSQLWarnings(final Handle handle) { try { SQLWarning warning = handle.getConnection().getWarnings(); while (warning != null) { log.debug("[SQL WARNING] {}", warning); warning = warning.getNextWarning(); } handle.getConnection().clearWarnings(); } catch (final SQLException e) { log.debug("Error whilst retrieving SQL warnings", e); } } protected interface Query<U, QueueSqlDao> { U execute(QueueSqlDao sqlDao); } public QueueSqlDao<T> getSqlDao() { return sqlDao; } }
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/queue/dao/EventEntryModelDao.java
queue/src/main/java/org/killbill/queue/dao/EventEntryModelDao.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.queue.dao; import java.util.UUID; import org.joda.time.DateTime; import org.killbill.queue.api.PersistentQueueEntryLifecycleState; public interface EventEntryModelDao { Long getRecordId(); String getClassName(); String getEventJson(); UUID getUserToken(); String getProcessingOwner(); String getCreatingOwner(); DateTime getNextAvailableDate(); PersistentQueueEntryLifecycleState getProcessingState(); boolean isAvailableForProcessing(DateTime now); Long getErrorCount(); Long getSearchKey1(); Long getSearchKey2(); // setters void setClassName(final String className); void setEventJson(final String eventJson); void setUserToken(final UUID userToken); void setCreatingOwner(final String creatingOwner); void setProcessingState(final PersistentQueueEntryLifecycleState processingState); void setProcessingOwner(final String processingOwner); void setCreatedDate(final DateTime createdDate); void setErrorCount(final Long errorCount); void setSearchKey1(final Long searchKey1); void setSearchKey2(final Long searchKey2); }
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/queue/dao/QueueSqlDao.java
queue/src/main/java/org/killbill/queue/dao/QueueSqlDao.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.queue.dao; import java.util.Collection; import java.util.Date; import java.util.List; import javax.annotation.Nullable; import org.killbill.commons.jdbi.binder.SmartBindBean; import org.killbill.commons.jdbi.template.KillBillSqlDaoStringTemplate; import org.skife.jdbi.v2.sqlobject.Bind; import org.skife.jdbi.v2.sqlobject.GetGeneratedKeys; import org.skife.jdbi.v2.sqlobject.SqlBatch; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.SqlUpdate; import org.skife.jdbi.v2.sqlobject.customizers.BatchChunkSize; import org.skife.jdbi.v2.sqlobject.customizers.Define; import org.skife.jdbi.v2.sqlobject.mixins.CloseMe; import org.skife.jdbi.v2.sqlobject.mixins.Transactional; import org.skife.jdbi.v2.unstable.BindIn; import org.skife.jdbi.v2.util.LongMapper; @KillBillSqlDaoStringTemplate public interface QueueSqlDao<T extends EventEntryModelDao> extends Transactional<QueueSqlDao<T>>, CloseMe { @SqlQuery Long getMaxRecordId(@Define("tableName") final String tableName); @SqlQuery T getByRecordId(@Bind("recordId") Long id, @Define("tableName") final String tableName); @SqlQuery List<T> getEntriesFromIds(@BindIn("record_ids") final List<Long> recordIds, @Define("tableName") final String tableName); @SqlQuery List<T> getReadyEntries(@Bind("now") Date now, @Bind("max") int max, // This is somewhat a hack, should really be a @Bind parameter but we also use it // for StringTemplate to modify the query based whether value is null or not. @Nullable @Define("owner") String owner, @Define("tableName") final String tableName); @SqlQuery long getNbReadyEntries(@Bind("now") Date now, // This is somewhat a hack, should really be a @Bind parameter but we also use it // for StringTemplate to modify the query based whether value is null or not. @Nullable @Define("owner") String owner, @Define("tableName") final String tableName); @SqlQuery List<T> getInProcessingEntries(@Define("tableName") final String tableName); @SqlQuery List<T> getEntriesLeftBehind(@Bind("max") int max, @Bind("now") Date now, @Bind("reapingDate") Date reapingDate, @Define("tableName") final String tableName); @SqlUpdate int claimEntry(@Bind("recordId") Long id, @Bind("owner") String owner, @Bind("nextAvailable") Date nextAvailable, @Define("tableName") final String tableName); @SqlUpdate int claimEntries(@BindIn("record_ids") final Collection<Long> recordIds, @Bind("owner") String owner, @Bind("nextAvailable") Date nextAvailable, @Define("tableName") final String tableName); @SqlUpdate int updateOnError(@Bind("recordId") Long id, @Bind("now") Date now, @Bind("errorCount") Long errorCount, @Define("tableName") final String tableName); @SqlUpdate void removeEntry(@Bind("recordId") Long id, @Define("tableName") final String tableName); @SqlUpdate void removeEntries(@BindIn("record_ids") final Collection<Long> recordIds, @Define("tableName") final String tableName); @SqlUpdate @GetGeneratedKeys(value = LongMapper.class, columnName = "record_id") Long insertEntry(@SmartBindBean T evt, @Define("tableName") final String tableName); @SqlBatch @BatchChunkSize(100) void insertEntries(@SmartBindBean Iterable<T> evts, @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/queue/dispatching/Dispatcher.java
queue/src/main/java/org/killbill/queue/dispatching/Dispatcher.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 java.lang.reflect.InvocationTargetException; import java.util.UUID; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.killbill.clock.Clock; import org.killbill.commons.concurrent.DynamicThreadPoolExecutorWithLoggingOnExceptions; import org.killbill.queue.DefaultQueueLifecycle; import org.killbill.queue.api.PersistentQueueConfig; import org.killbill.queue.api.PersistentQueueEntryLifecycleState; import org.killbill.queue.api.QueueEvent; import org.killbill.queue.dao.EventEntryModelDao; import org.killbill.queue.retry.RetryableInternalException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; public class Dispatcher<E extends QueueEvent, M extends EventEntryModelDao> { private static final Logger log = LoggerFactory.getLogger(Dispatcher.class); // Dynamic ThreadPool Executor private final int corePoolSize; private final int maximumPoolSize; private final long keepAliveTime; private final TimeUnit keepAliveTimeUnit; private final long shutdownTimeout; private final TimeUnit shutdownTimeUnit; private final BlockingQueue<Runnable> workQueue; private final ThreadFactory threadFactory; private final RejectedExecutionHandler rejectionHandler; private final int maxFailureRetries; private final CallableCallback<E, M> handlerCallback; private final DefaultQueueLifecycle parentLifeCycle; private final Clock clock; // Deferred in start sequence to allow for restart, which is not possible after the shutdown (mostly for test purpose) private ExecutorService handlerExecutor; public Dispatcher(final int corePoolSize, final PersistentQueueConfig config, final long keepAliveTime, final TimeUnit keepAliveTimeUnit, final long shutdownTimeout, final TimeUnit shutdownTimeUnit, final BlockingQueue<Runnable> workQueue, final ThreadFactory threadFactory, final RejectedExecutionHandler rejectionHandler, final Clock clock, final CallableCallback<E, M> handlerCallback, final DefaultQueueLifecycle parentLifeCycle) { this.corePoolSize = corePoolSize; this.maximumPoolSize = config.geMaxDispatchThreads(); this.keepAliveTime = keepAliveTime; this.keepAliveTimeUnit = keepAliveTimeUnit; this.shutdownTimeout = shutdownTimeout; this.shutdownTimeUnit = shutdownTimeUnit; this.workQueue = workQueue; this.threadFactory = threadFactory; this.rejectionHandler = rejectionHandler; this.clock = clock; this.maxFailureRetries = config.getMaxFailureRetries(); this.handlerCallback = handlerCallback; this.parentLifeCycle = parentLifeCycle; } public void start() { this.handlerExecutor = new DynamicThreadPoolExecutorWithLoggingOnExceptions(corePoolSize, maximumPoolSize, keepAliveTime, keepAliveTimeUnit, workQueue, threadFactory, rejectionHandler); } // Stop the dispatcher threads, which are doing the work public boolean stopDispatcher() { handlerExecutor.shutdown(); try { return handlerExecutor.awaitTermination(shutdownTimeout, shutdownTimeUnit); } catch (final InterruptedException e) { log.info("Stop sequence, handlerExecutor has been interrupted"); return false; } } public void dispatch(final M modelDao) { log.debug("Dispatching entry {}", modelDao); final CallableQueueHandler<E, M> entry = new CallableQueueHandler<E, M>(modelDao, handlerCallback, parentLifeCycle, clock, maxFailureRetries); handlerExecutor.submit(entry); } public static class CallableQueueHandler<E extends QueueEvent, M extends EventEntryModelDao> implements Callable<E> { private static final String MDC_KB_USER_TOKEN = "kb.userToken"; private static final Logger log = LoggerFactory.getLogger(CallableQueueHandler.class); private final M entry; private final CallableCallback<E, M> callback; private final DefaultQueueLifecycle parentLifeCycle; private final int maxFailureRetries; private final Clock clock; public CallableQueueHandler(final M entry, final CallableCallback<E, M> callback, final DefaultQueueLifecycle parentLifeCycle, final Clock clock, final int maxFailureRetries) { this.entry = entry; this.callback = callback; this.parentLifeCycle = parentLifeCycle; this.clock = clock; this.maxFailureRetries = maxFailureRetries; } @Override public E call() throws Exception { try { final UUID userToken = entry.getUserToken(); MDC.put(MDC_KB_USER_TOKEN, userToken != null ? userToken.toString() : null); log.debug("Starting processing entry {}", entry); final E event = callback.deserialize(entry); if (event != null) { Throwable lastException = null; long errorCount = entry.getErrorCount(); try { callback.dispatch(event, entry); } catch (final Exception e) { if (e.getCause() != null && e.getCause() instanceof InvocationTargetException) { lastException = e.getCause().getCause(); } else if (e.getCause() != null && e.getCause() instanceof RetryableInternalException) { lastException = e.getCause(); } else { lastException = e; } errorCount++; } finally { if (parentLifeCycle != null) { if (lastException == null) { final M newEntry = callback.buildEntry(entry, clock.getUTCNow(), PersistentQueueEntryLifecycleState.PROCESSED, entry.getErrorCount()); parentLifeCycle.dispatchCompletedOrFailedEvents(newEntry); log.debug("Done handling notification {}, key = {}", entry.getRecordId(), entry.getEventJson()); } else if (lastException instanceof RetryableInternalException) { final M newEntry = callback.buildEntry(entry, clock.getUTCNow(), PersistentQueueEntryLifecycleState.FAILED, entry.getErrorCount()); parentLifeCycle.dispatchCompletedOrFailedEvents(newEntry); } else if (errorCount <= maxFailureRetries) { log.info("Dispatch error, will attempt a retry ", lastException); final M newEntry = callback.buildEntry(entry, clock.getUTCNow(), PersistentQueueEntryLifecycleState.AVAILABLE, errorCount); parentLifeCycle.dispatchRetriedEvents(newEntry); } else { log.error("Fatal NotificationQ dispatch error, data corruption...", lastException); final M newEntry = callback.buildEntry(entry, clock.getUTCNow(), PersistentQueueEntryLifecycleState.FAILED, entry.getErrorCount()); parentLifeCycle.dispatchCompletedOrFailedEvents(newEntry); } } } } return event; } finally { // Clear all entries in the MDC: when creating an InternalCallContext while processing an event, // Kill Bill will add entries (e.g. kb.accountRecordId) that we don't want to persist in our queue thread pool. MDC.clear(); } } } }
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/queue/dispatching/CallableCallback.java
queue/src/main/java/org/killbill/queue/dispatching/CallableCallback.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.queue.dispatching; import org.joda.time.DateTime; import org.killbill.queue.api.PersistentQueueEntryLifecycleState; import org.killbill.queue.api.QueueEvent; import org.killbill.queue.dao.EventEntryModelDao; public interface CallableCallback<E extends QueueEvent, M extends EventEntryModelDao> { E deserialize(final M modelDao); void dispatch(final E event, final M modelDao) throws Exception; M buildEntry(final M modelDao, final DateTime now, final PersistentQueueEntryLifecycleState newState, final long newErrorCount); void moveCompletedOrFailedEvents(final Iterable<M> entries); void updateRetriedEvents(final M updatedEntry); }
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/queue/dispatching/EventEntryDeserializer.java
queue/src/main/java/org/killbill/queue/dispatching/EventEntryDeserializer.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.queue.dispatching; import org.killbill.queue.api.QueueEvent; import org.killbill.queue.dao.EventEntryModelDao; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.ObjectReader; public final class EventEntryDeserializer { private static final Logger log = LoggerFactory.getLogger(EventEntryDeserializer.class); public static <E extends QueueEvent, M extends EventEntryModelDao> E deserialize(final M modelDao, final ObjectReader objectReader) { try { final Class<?> claz = Class.forName(modelDao.getClassName()); return (E) objectReader.readValue(modelDao.getEventJson(), claz); } catch (final Exception e) { log.error("Failed to deserialize json object {} for class {}", modelDao.getEventJson(), modelDao.getClassName(), e); 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/main/java/org/killbill/queue/dispatching/CallableCallbackBase.java
queue/src/main/java/org/killbill/queue/dispatching/CallableCallbackBase.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.queue.dispatching; import org.joda.time.DateTime; import org.killbill.clock.Clock; import org.killbill.queue.DBBackedQueue; import org.killbill.queue.api.PersistentQueueConfig; import org.killbill.queue.api.PersistentQueueEntryLifecycleState; import org.killbill.queue.api.QueueEvent; import org.killbill.queue.dao.EventEntryModelDao; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.ObjectReader; public abstract class CallableCallbackBase<E extends QueueEvent, M extends EventEntryModelDao> implements CallableCallback<E, M> { private static final Logger log = LoggerFactory.getLogger(CallableCallbackBase.class); private final DBBackedQueue<M> dao; private final Clock clock; private final PersistentQueueConfig config; private final ObjectReader objectReader; public CallableCallbackBase(final DBBackedQueue<M> dao, final Clock clock, final PersistentQueueConfig config, final ObjectReader objectReader) { this.dao = dao; this.clock = clock; this.config = config; this.objectReader = objectReader; } @Override public E deserialize(final M modelDao) { return EventEntryDeserializer.deserialize(modelDao, objectReader); } @Override public void moveCompletedOrFailedEvents(final Iterable<M> entries) { dao.moveEntriesToHistory(entries); } @Override public void updateRetriedEvents(final M updatedEntry) { dao.updateOnError(updatedEntry); } @Override public abstract void dispatch(final E event, final M modelDao) throws Exception; public abstract M buildEntry(final M modelDao, final DateTime now, final PersistentQueueEntryLifecycleState newState, final long newErrorCount); }
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/queue/dispatching/BlockingRejectionExecutionHandler.java
queue/src/main/java/org/killbill/queue/dispatching/BlockingRejectionExecutionHandler.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.queue.dispatching; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; public class BlockingRejectionExecutionHandler implements RejectedExecutionHandler { private final Logger logger = LoggerFactory.getLogger(BlockingRejectionExecutionHandler.class); public BlockingRejectionExecutionHandler() { } @Override public void rejectedExecution(final Runnable r, final ThreadPoolExecutor executor) { try { if (!executor.isShutdown()) { logger.info("BlockingRejectionExecutionHandler will block request"); executor.getQueue().put(r); } } catch (final InterruptedException e) { Thread.currentThread().interrupt(); throw new RejectedExecutionException("Executor was interrupted while the task was waiting to put on work queue", 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/main/java/org/killbill/queue/retry/SubscriberNotificationEventDeserializer.java
queue/src/main/java/org/killbill/queue/retry/SubscriberNotificationEventDeserializer.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.queue.retry; import java.io.IOException; import org.killbill.bus.api.BusEvent; import org.killbill.queue.QueueObjectMapper; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class SubscriberNotificationEventDeserializer extends JsonDeserializer<SubscriberNotificationEvent> { private static final ObjectMapper objectMapper = QueueObjectMapper.get(); @Override public SubscriberNotificationEvent deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException, JsonProcessingException { final JsonNode node = p.getCodec().readTree(p); final Class<BusEvent> busEventClass; try { busEventClass = (Class<BusEvent>) Class.forName(node.get("busEventClass").textValue()); } catch (final ClassNotFoundException e) { throw new IOException(e); } return new SubscriberNotificationEvent(objectMapper.treeToValue(node.get("busEvent"), busEventClass), busEventClass); } }
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/queue/retry/RetryableSubscriber.java
queue/src/main/java/org/killbill/queue/retry/RetryableSubscriber.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.queue.retry; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.UUID; import org.joda.time.DateTime; import org.killbill.bus.api.BusEvent; import org.killbill.clock.Clock; import org.killbill.commons.utils.cache.Cache; import org.killbill.commons.utils.cache.DefaultSynchronizedCache; import org.killbill.notificationq.api.NotificationEvent; import org.killbill.notificationq.api.NotificationQueueService.NotificationQueueHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RetryableSubscriber extends RetryableHandler { private static final Logger log = LoggerFactory.getLogger(RetryableSubscriber.class); public RetryableSubscriber(final Clock clock, final RetryableService retryableService, final NotificationQueueHandler handlerDelegate) { super(clock, retryableService, handlerDelegate); } public void handleEvent(final BusEvent event) { handleReadyNotification(new SubscriberNotificationEvent(event, event.getClass()), clock.getUTCNow(), event.getUserToken(), event.getSearchKey1(), event.getSearchKey2()); } public interface SubscriberAction<T extends BusEvent> { void run(T event); } public static final class SubscriberQueueHandler implements NotificationQueueHandler { // Similar to org.killbill.commons.eventbus.SubscriberRegistry private static final Cache<Class<?>, Set<Class<?>>> FLATTEN_HIERARCHY_CACHE = new DefaultSynchronizedCache<>( // LinkedHashSet to make sure maintains its order. See // org.killbill.commons.eventbus.SubscriberRegistry comments (on line ~204) to find out more why. key -> new LinkedHashSet<>(org.killbill.commons.utils.TypeToken.getRawTypes(key))); private final Map<Class<?>, SubscriberAction<? extends BusEvent>> actions = new HashMap<>(); public SubscriberQueueHandler() { } public <B extends BusEvent> void subscribe(final Class<B> busEventClass, final SubscriberAction<B> action) { actions.put(busEventClass, action); } @Override public void handleReadyNotification(final NotificationEvent eventJson, final DateTime eventDateTime, final UUID userToken, final Long searchKey1, final Long searchKey2) { if (!(eventJson instanceof SubscriberNotificationEvent)) { log.error("SubscriberQueueHandler received an unexpected event className='{}'", eventJson.getClass()); } else { final BusEvent busEvent = ((SubscriberNotificationEvent) eventJson).getBusEvent(); final Set<Class<?>> eventTypes = FLATTEN_HIERARCHY_CACHE.get(busEvent.getClass()); for (final Class<?> eventType : eventTypes) { final SubscriberAction<BusEvent> next = (SubscriberAction<BusEvent>) actions.get(eventType); if (next != null) { next.run(busEvent); } } } } } }
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/queue/retry/RetryableService.java
queue/src/main/java/org/killbill/queue/retry/RetryableService.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.queue.retry; import java.io.IOException; import java.util.List; import java.util.UUID; import org.joda.time.DateTime; import org.joda.time.Period; import org.killbill.billing.util.queue.QueueRetryException; import org.killbill.notificationq.api.NotificationEvent; import org.killbill.notificationq.api.NotificationQueue; import org.killbill.notificationq.api.NotificationQueueService; import org.killbill.notificationq.api.NotificationQueueService.NoSuchNotificationQueue; import org.killbill.notificationq.api.NotificationQueueService.NotificationQueueAlreadyExists; import org.killbill.notificationq.api.NotificationQueueService.NotificationQueueHandler; import org.killbill.queue.QueueObjectMapper; import org.killbill.queue.api.QueueEvent; 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 abstract class RetryableService { public static final String RETRYABLE_SERVICE_NAME = "notifications-retries"; private static final Logger log = LoggerFactory.getLogger(RetryableService.class); private final ObjectReader objectReader; private final ObjectWriter objectWriter; private final NotificationQueueService notificationQueueService; private NotificationQueue retryNotificationQueue; public RetryableService(NotificationQueueService notificationQueueService) { this(notificationQueueService, QueueObjectMapper.get()); } public RetryableService(final NotificationQueueService notificationQueueService, final ObjectMapper objectMapper) { this.notificationQueueService = notificationQueueService; this.objectReader = objectMapper.reader(); this.objectWriter = objectMapper.writer(); } public void initialize(final NotificationQueue originalQueue, final NotificationQueueHandler originalQueueHandler) { initialize(originalQueue.getQueueName(), originalQueueHandler); } public void initialize(final String queueName, final NotificationQueueHandler originalQueueHandler) { try { final NotificationQueueHandler notificationQueueHandler = new NotificationQueueHandler() { @Override public void handleReadyNotification(final NotificationEvent eventJson, final DateTime eventDateTime, final UUID userToken, final Long searchKey1, final Long searchKey2) { if (eventJson instanceof RetryNotificationEvent) { final RetryNotificationEvent retryNotificationEvent = (RetryNotificationEvent) eventJson; final NotificationEvent notificationEvent; try { notificationEvent = (NotificationEvent) objectReader.readValue(retryNotificationEvent.getOriginalEvent(), retryNotificationEvent.getOriginalEventClass()); } catch (final IOException e) { throw new RuntimeException(e); } try { originalQueueHandler.handleReadyNotification(notificationEvent, eventDateTime, userToken, searchKey1, searchKey2); } catch (final QueueRetryException e) { scheduleRetry(e, notificationEvent, retryNotificationEvent.getOriginalEffectiveDate(), userToken, searchKey1, searchKey2, retryNotificationEvent.getRetryNb() + 1); } } else { log.error("Retry service received an unexpected event className='{}'", eventJson.getClass()); } } }; this.retryNotificationQueue = notificationQueueService.createNotificationQueue(RETRYABLE_SERVICE_NAME, queueName, notificationQueueHandler); } catch (final NotificationQueueAlreadyExists notificationQueueAlreadyExists) { throw new RuntimeException(notificationQueueAlreadyExists); } } public void start() { retryNotificationQueue.startQueue(); } public void stop() throws NoSuchNotificationQueue { if (retryNotificationQueue != null) { retryNotificationQueue.stopQueue(); notificationQueueService.deleteNotificationQueue(retryNotificationQueue.getServiceName(), retryNotificationQueue.getQueueName()); } } public void scheduleRetry(final QueueRetryException exception, final QueueEvent originalNotificationEvent, final DateTime originalEffectiveDate, final UUID userToken, final Long searchKey1, final Long searchKey2, final int retryNb) { final DateTime effectiveDate = computeRetryDate(exception, originalEffectiveDate, retryNb); if (effectiveDate == null) { log.warn("Error processing event, NOT scheduling retry for event='{}', retryNb='{}'", originalNotificationEvent, retryNb, exception); throw new RetryableInternalException(false); } log.warn("Error processing event, scheduling retry for event='{}', effectiveDate='{}', retryNb='{}'", originalNotificationEvent, effectiveDate, retryNb, exception); try { final NotificationEvent retryNotificationEvent = new RetryNotificationEvent(objectWriter.writeValueAsString(originalNotificationEvent), originalNotificationEvent.getClass(), originalEffectiveDate, retryNb); retryNotificationQueue.recordFutureNotification(effectiveDate, retryNotificationEvent, userToken, searchKey1, searchKey2); throw new RetryableInternalException(true); } catch (final IOException e) { log.error("Unable to schedule retry for event='{}', effectiveDate='{}'", originalNotificationEvent, effectiveDate, e); throw new RetryableInternalException(false); } } private DateTime computeRetryDate(final QueueRetryException queueRetryException, final DateTime initialEventDateTime, final int retryNb) { final List<Period> retrySchedule = queueRetryException.getRetrySchedule(); if (retrySchedule == null || retryNb > retrySchedule.size()) { return null; } else { final Period nextDelay = retrySchedule.get(retryNb - 1); return initialEventDateTime.plus(nextDelay); } } }
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/queue/retry/SubscriberNotificationEvent.java
queue/src/main/java/org/killbill/queue/retry/SubscriberNotificationEvent.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.queue.retry; import org.killbill.bus.api.BusEvent; import org.killbill.notificationq.api.NotificationEvent; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; @JsonDeserialize(using = SubscriberNotificationEventDeserializer.class) public class SubscriberNotificationEvent implements NotificationEvent { private final BusEvent busEvent; private final Class busEventClass; @JsonCreator public SubscriberNotificationEvent(@JsonProperty("busEvent") final BusEvent busEvent, @JsonProperty("busEventClass") final Class busEventClass) { this.busEvent = busEvent; this.busEventClass = busEventClass; } public BusEvent getBusEvent() { return busEvent; } public Class getBusEventClass() { return busEventClass; } @Override public String toString() { final StringBuilder sb = new StringBuilder("SubscriberNotificationEvent{"); sb.append("busEvent=").append(busEvent); sb.append(", busEventClass=").append(busEventClass); sb.append('}'); return sb.toString(); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final SubscriberNotificationEvent that = (SubscriberNotificationEvent) o; if (busEvent != null ? !busEvent.equals(that.busEvent) : that.busEvent != null) { return false; } return busEventClass != null ? busEventClass.equals(that.busEventClass) : that.busEventClass == null; } @Override public int hashCode() { int result = busEvent != null ? busEvent.hashCode() : 0; result = 31 * result + (busEventClass != null ? busEventClass.hashCode() : 0); 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/main/java/org/killbill/queue/retry/RetryableInternalException.java
queue/src/main/java/org/killbill/queue/retry/RetryableInternalException.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.queue.retry; public class RetryableInternalException extends RuntimeException { private final boolean isRetried; public RetryableInternalException(final boolean isRetried) { this.isRetried = isRetried; } public boolean isRetried() { return isRetried; } }
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/queue/retry/RetryableHandler.java
queue/src/main/java/org/killbill/queue/retry/RetryableHandler.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.queue.retry; import java.util.UUID; import org.joda.time.DateTime; import org.killbill.billing.util.queue.QueueRetryException; import org.killbill.clock.Clock; import org.killbill.notificationq.api.NotificationEvent; import org.killbill.notificationq.api.NotificationQueueService.NotificationQueueHandler; public class RetryableHandler implements NotificationQueueHandler { protected final Clock clock; private final RetryableService retryableService; private final NotificationQueueHandler handlerDelegate; public RetryableHandler(final Clock clock, final RetryableService retryableService, final NotificationQueueHandler handlerDelegate) { this.clock = clock; this.retryableService = retryableService; this.handlerDelegate = handlerDelegate; } @Override public void handleReadyNotification(final NotificationEvent notificationEvent, final DateTime eventDateTime, final UUID userToken, final Long searchKey1, final Long searchKey2) { try { handlerDelegate.handleReadyNotification(notificationEvent, eventDateTime, userToken, searchKey1, searchKey2); } catch (final QueueRetryException e) { // Let the retry queue handle the exception retryableService.scheduleRetry(e, notificationEvent, eventDateTime, userToken, searchKey1, searchKey2, 1); } } }
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/queue/retry/RetryNotificationEvent.java
queue/src/main/java/org/killbill/queue/retry/RetryNotificationEvent.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.queue.retry; import org.joda.time.DateTime; import org.killbill.notificationq.api.NotificationEvent; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class RetryNotificationEvent implements NotificationEvent { private final String originalEvent; private final Class originalEventClass; private final DateTime originalEffectiveDate; private final int retryNb; @JsonCreator public RetryNotificationEvent(@JsonProperty("originalEvent") final String originalEvent, @JsonProperty("originalEventClass") final Class originalEventClass, @JsonProperty("originalEffectiveDate") final DateTime originalEffectiveDate, @JsonProperty("retryNb") final int retryNb) { this.originalEvent = originalEvent; this.originalEventClass = originalEventClass; this.originalEffectiveDate = originalEffectiveDate; this.retryNb = retryNb; } public String getOriginalEvent() { return originalEvent; } public Class getOriginalEventClass() { return originalEventClass; } public DateTime getOriginalEffectiveDate() { return originalEffectiveDate; } public int getRetryNb() { return retryNb; } @Override public String toString() { final StringBuilder sb = new StringBuilder("RetryNotificationEvent{"); sb.append("originalEvent=").append(originalEvent); sb.append(", originalEventClass=").append(originalEventClass); sb.append(", originalEffectiveDate=").append(originalEffectiveDate); sb.append(", retryNb=").append(retryNb); sb.append('}'); return sb.toString(); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final RetryNotificationEvent that = (RetryNotificationEvent) o; if (retryNb != that.retryNb) { return false; } if (originalEvent != null ? !originalEvent.equals(that.originalEvent) : that.originalEvent != null) { return false; } if (originalEventClass != null ? !originalEventClass.equals(that.originalEventClass) : that.originalEventClass != null) { return false; } return originalEffectiveDate != null ? originalEffectiveDate.compareTo(that.originalEffectiveDate) == 0 : that.originalEffectiveDate == null; } @Override public int hashCode() { int result = originalEvent != null ? originalEvent.hashCode() : 0; result = 31 * result + (originalEventClass != null ? originalEventClass.hashCode() : 0); result = 31 * result + (originalEffectiveDate != null ? originalEffectiveDate.hashCode() : 0); result = 31 * result + retryNb; 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/main/java/org/killbill/queue/api/QueueLifecycle.java
queue/src/main/java/org/killbill/queue/api/QueueLifecycle.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.api; public interface QueueLifecycle { boolean initQueue(); /** * Starts the queue */ boolean startQueue(); /** * Stops the queue */ boolean stopQueue(); boolean isStarted(); }
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/queue/api/PersistentQueueConfig.java
queue/src/main/java/org/killbill/queue/api/PersistentQueueConfig.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.api; import org.skife.config.TimeSpan; public interface PersistentQueueConfig { // We support 3 different modes to the queue enum PersistentQueueMode { // Entries written from a given node (server) will also be dispatched to that same node; the code will poll for new entries STICKY_POLLING, // Entries written from a given node (server) will also be dispatched to that same node; the code will react to database commit/abort events to fetch new entries STICKY_EVENTS, // Entries written from a given node (server) will may be dispatched to any nodes by polling for all available entries POLLING } boolean isInMemory(); int getMaxFailureRetries(); PersistentQueueMode getPersistentQueueMode(); int getMinInFlightEntries(); int getMaxInFlightEntries(); int getMaxEntriesClaimed(); TimeSpan getClaimedTime(); long getPollingSleepTimeMs(); boolean isProcessingOff(); int getEventQueueCapacity(); int geMaxDispatchThreads(); int geNbLifecycleDispatchThreads(); int geNbLifecycleCompleteThreads(); String getTableName(); String getHistoryTableName(); TimeSpan getReapThreshold(); int getMaxReDispatchCount(); TimeSpan getReapSchedule(); TimeSpan getShutdownTimeout(); }
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/queue/api/Reaper.java
queue/src/main/java/org/killbill/queue/api/Reaper.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.api; public interface Reaper { /** * Starts the reaper */ void start(); /** * Stops the reaper */ boolean stop(); boolean isStarted(); }
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/queue/api/PersistentQueueEntryLifecycleState.java
queue/src/main/java/org/killbill/queue/api/PersistentQueueEntryLifecycleState.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.queue.api; public enum PersistentQueueEntryLifecycleState { AVAILABLE, IN_PROCESSING, PROCESSED, REMOVED, FAILED, REAPED }
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/queue/api/QueueEvent.java
queue/src/main/java/org/killbill/queue/api/QueueEvent.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.queue.api; public interface QueueEvent { }
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/bus/BusReaper.java
queue/src/main/java/org/killbill/bus/BusReaper.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.bus.api.PersistentBusConfig; import org.killbill.bus.dao.BusEventModelDao; import org.killbill.clock.Clock; import org.killbill.queue.DBBackedQueue; import org.killbill.queue.DefaultReaper; public class BusReaper extends DefaultReaper { public BusReaper(final DBBackedQueue<BusEventModelDao> dao, final PersistentBusConfig config, final Clock clock) { super(dao, config, clock, "BusReaper"); } }
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/bus/DefaultPersistentBus.java
queue/src/main/java/org/killbill/bus/DefaultPersistentBus.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.sql.Connection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import javax.annotation.Nullable; import javax.inject.Inject; import javax.inject.Named; import javax.sql.DataSource; import org.joda.time.DateTime; import org.killbill.CreatorName; import org.killbill.bus.api.BusEvent; import org.killbill.bus.api.BusEventWithMetadata; import org.killbill.bus.api.PersistentBus; import org.killbill.bus.api.PersistentBusConfig; import org.killbill.bus.dao.BusEventModelDao; import org.killbill.bus.dao.PersistentBusSqlDao; import org.killbill.bus.dispatching.BusCallableCallback; import org.killbill.clock.Clock; import org.killbill.clock.DefaultClock; import org.killbill.commons.eventbus.EventBus; import org.killbill.commons.jdbi.notification.DatabaseTransactionNotificationApi; import org.killbill.commons.metrics.api.MetricRegistry; import org.killbill.commons.metrics.api.Timer; import org.killbill.commons.metrics.impl.NoOpMetricRegistry; import org.killbill.commons.profiling.Profiling; import org.killbill.commons.profiling.ProfilingFeature; import org.killbill.commons.utils.collect.Iterables; import org.killbill.queue.DBBackedQueue; import org.killbill.queue.DBBackedQueue.ReadyEntriesWithMetrics; import org.killbill.queue.DBBackedQueueWithInflightQueue; import org.killbill.queue.DBBackedQueueWithPolling; import org.killbill.queue.DefaultQueueLifecycle; import org.killbill.queue.InTransaction; import org.killbill.queue.api.PersistentQueueConfig.PersistentQueueMode; import org.killbill.queue.api.QueueEvent; import org.killbill.queue.dao.EventEntryModelDao; import org.killbill.queue.dispatching.BlockingRejectionExecutionHandler; import org.killbill.queue.dispatching.Dispatcher; import org.killbill.queue.dispatching.EventEntryDeserializer; import org.skife.config.AugmentedConfigurationObjectFactory; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.IDBI; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonProcessingException; public class DefaultPersistentBus extends DefaultQueueLifecycle implements PersistentBus { private static final Logger log = LoggerFactory.getLogger(DefaultPersistentBus.class); private final DBI dbi; private final EventBus eventBusDelegate; private final DBBackedQueue<BusEventModelDao> dao; private final Clock clock; private final PersistentBusConfig config; private final Profiling<Iterable<BusEventModelDao>, RuntimeException> prof; private final BusReaper reaper; private final Dispatcher<BusEvent, BusEventModelDao> dispatcher; // Time it takes to handle the bus request (going through multiple handles potentially) private final Timer busHandlersProcessingTime; private final AtomicBoolean isInitialized; private final AtomicBoolean isStarted; private final String dbBackedQId; private final BusCallableCallback busCallableCallback; private static final class EventBusDelegate extends EventBus { public EventBusDelegate(final String busName) { super(busName); } } @Inject public DefaultPersistentBus(@Named(QUEUE_NAME) final IDBI dbi, final Clock clock, final PersistentBusConfig config, final MetricRegistry metricRegistry, final DatabaseTransactionNotificationApi databaseTransactionNotificationApi) { super(config.getTableName(), config, metricRegistry); this.dbi = (DBI) dbi; this.clock = clock; this.config = config; this.dbBackedQId = config.getTableName(); this.dao = config.getPersistentQueueMode() == PersistentQueueMode.STICKY_EVENTS ? new DBBackedQueueWithInflightQueue<>(clock, dbi, PersistentBusSqlDao.class, config, dbBackedQId, metricRegistry, databaseTransactionNotificationApi) : new DBBackedQueueWithPolling<>(clock, dbi, PersistentBusSqlDao.class, config, dbBackedQId, metricRegistry); this.prof = new Profiling<>(); final ThreadFactory busThreadFactory = new ThreadFactory() { @Override public Thread newThread(final Runnable r) { return new Thread(new ThreadGroup(EVENT_BUS_GROUP_NAME), r, config.getTableName() + "-th"); } }; this.busHandlersProcessingTime = metricRegistry.timer(String.format("%s.%s.%s", DefaultPersistentBus.class.getName(), dbBackedQId, "busHandlersProcessingTime")); this.eventBusDelegate = new EventBusDelegate("Killbill EventBus"); this.isInitialized = new AtomicBoolean(false); this.isStarted = new AtomicBoolean(false); this.reaper = new BusReaper(this.dao, config, clock); this.busCallableCallback = new BusCallableCallback(this); this.dispatcher = new Dispatcher<>(1, config, 10, TimeUnit.MINUTES, config.getShutdownTimeout().getPeriod(), config.getShutdownTimeout().getUnit(), new LinkedBlockingQueue<>(config.getEventQueueCapacity()), busThreadFactory, new BlockingRejectionExecutionHandler(), clock, busCallableCallback, this); } public DefaultPersistentBus(final DataSource dataSource, final Properties properties) { this(InTransaction.buildDDBI(dataSource), new DefaultClock(), new AugmentedConfigurationObjectFactory(properties).buildWithReplacements(PersistentBusConfig.class, Map.of("instanceName", "main")), new NoOpMetricRegistry(), new DatabaseTransactionNotificationApi()); } @Override public boolean initQueue() { if (config.isProcessingOff()) { log.warn("PersistentBus processing is off, cannot be initialized"); return false; } if (isInitialized.compareAndSet(false, true)) { dao.initialize(); dispatcher.start(); return true; } else { return false; } } @Override public boolean startQueue() { if (config.isProcessingOff()) { log.warn("PersistentBus processing is off, cannot be started"); return false; } if (!isInitialized.get()) { // Make it easy for our tests, so they simply call startQueue initQueue(); } if (isStarted.compareAndSet(false, true)) { reaper.start(); super.startQueue(); return true; } else { return false; } } @Override public boolean stopQueue() { if (!isStarted.compareAndSet(true, false)) { return true; } log.info("Shutting down bus"); 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(); return terminated; } @Override public DispatchResultMetrics doDispatchEvents() { final ReadyEntriesWithMetrics<BusEventModelDao> eventsWithMetrics = dao.getReadyEntries(); final List<BusEventModelDao> events = eventsWithMetrics.getEntries(); if (events.isEmpty()) { return new DispatchResultMetrics(0, eventsWithMetrics.getTime()); } log.debug("Bus events from {} to process: {}", config.getTableName(), events); long ini = System.nanoTime(); for (final BusEventModelDao cur : events) { dispatcher.dispatch(cur); } return new DispatchResultMetrics(events.size(), (System.nanoTime() - ini) + eventsWithMetrics.getTime()); } @Override public void doProcessCompletedEvents(final Iterable<? extends EventEntryModelDao> completed) { busCallableCallback.moveCompletedOrFailedEvents((Iterable<BusEventModelDao>) completed); } @Override public void doProcessRetriedEvents(final Iterable<? extends EventEntryModelDao> retried) { Iterator<? extends EventEntryModelDao> it = retried.iterator(); while (it.hasNext()) { BusEventModelDao cur = (BusEventModelDao) it.next(); busCallableCallback.updateRetriedEvents(cur); } } @Override public boolean isStarted() { return isStarted.get(); } @Override public void register(final Object handlerInstance) throws EventBusException { if (isInitialized.get()) { eventBusDelegate.register(handlerInstance); } else { log.warn("Attempting to register handler " + handlerInstance + " in a non initialized bus"); } } @Override public void unregister(final Object handlerInstance) throws EventBusException { if (isInitialized.get()) { eventBusDelegate.unregister(handlerInstance); } else { log.warn("Attempting to unregister handler " + handlerInstance + " in a non initialized bus"); } } @Override public void post(final BusEvent event) throws EventBusException { try { if (isInitialized.get()) { final String json = objectWriter.writeValueAsString(event); final BusEventModelDao entry = new BusEventModelDao(CreatorName.get(), clock.getUTCNow(), event.getClass().getName(), json, event.getUserToken(), event.getSearchKey1(), event.getSearchKey2()); dao.insertEntry(entry); } else { log.warn("Attempting to post event " + event + " in a non initialized bus"); } } catch (final Exception e) { log.error("Failed to post BusEvent " + event, e); } } @Override public void postFromTransaction(final BusEvent event, final Connection connection) throws EventBusException { if (!isInitialized.get()) { log.warn("Attempting to post event " + event + " in a non initialized bus"); return; } final String json; try { json = objectWriter.writeValueAsString(event); } catch (final JsonProcessingException e) { log.warn("Unable to serialize event " + event, e); return; } final BusEventModelDao entry = new BusEventModelDao(CreatorName.get(), clock.getUTCNow(), event.getClass().getName(), json, event.getUserToken(), event.getSearchKey1(), event.getSearchKey2()); final InTransaction.InTransactionHandler<PersistentBusSqlDao, Void> handler = new InTransaction.InTransactionHandler<PersistentBusSqlDao, Void>() { @Override public Void withSqlDao(final PersistentBusSqlDao transactional) { dao.insertEntryFromTransaction(transactional, entry); return null; } }; InTransaction.execute(dbi, connection, handler, PersistentBusSqlDao.class); } @Override public <T extends BusEvent> Iterable<BusEventWithMetadata<T>> getAvailableBusEventsForSearchKeys(final Long searchKey1, final Long searchKey2) { return getAvailableBusEventsForSearchKeysInternal((PersistentBusSqlDao) dao.getSqlDao(), null, searchKey1, searchKey2); } @Override public <T extends BusEvent> Iterable<BusEventWithMetadata<T>> getAvailableBusEventsFromTransactionForSearchKeys(final Long searchKey1, final Long searchKey2, final Connection connection) { final InTransaction.InTransactionHandler<PersistentBusSqlDao, Iterable<BusEventWithMetadata<T>>> handler = new InTransaction.InTransactionHandler<PersistentBusSqlDao, Iterable<BusEventWithMetadata<T>>>() { @Override public Iterable<BusEventWithMetadata<T>> withSqlDao(final PersistentBusSqlDao transactional) { return getAvailableBusEventsForSearchKeysInternal(transactional, null, searchKey1, searchKey2); } }; return InTransaction.execute(dbi, connection, handler, PersistentBusSqlDao.class); } @Override public <T extends BusEvent> Iterable<BusEventWithMetadata<T>> getAvailableBusEventsForSearchKey2(final DateTime maxCreatedDate, final Long searchKey2) { return getAvailableBusEventsForSearchKeysInternal((PersistentBusSqlDao) dao.getSqlDao(), maxCreatedDate, null, searchKey2); } @Override public <T extends BusEvent> Iterable<BusEventWithMetadata<T>> getAvailableBusEventsFromTransactionForSearchKey2(final DateTime maxCreatedDate, final Long searchKey2, final Connection connection) { final InTransaction.InTransactionHandler<PersistentBusSqlDao, Iterable<BusEventWithMetadata<T>>> handler = new InTransaction.InTransactionHandler<PersistentBusSqlDao, Iterable<BusEventWithMetadata<T>>>() { @Override public Iterable<BusEventWithMetadata<T>> withSqlDao(final PersistentBusSqlDao transactional) { return getAvailableBusEventsForSearchKeysInternal(transactional, maxCreatedDate, null, searchKey2); } }; return InTransaction.execute(dbi, connection, handler, PersistentBusSqlDao.class); } @Override public <T extends BusEvent> Iterable<BusEventWithMetadata<T>> getInProcessingBusEvents() { return toBusEventWithMetadata(dao.getSqlDao().getInProcessingEntries(config.getTableName())); } @Override public <T extends BusEvent> Iterable<BusEventWithMetadata<T>> getAvailableOrInProcessingBusEventsForSearchKeys(final Long searchKey1, final Long searchKey2) { return getAvailableOrInProcessingBusEventsForSearchKeysInternal((PersistentBusSqlDao) dao.getSqlDao(), null, searchKey1, searchKey2); } @Override public <T extends BusEvent> Iterable<BusEventWithMetadata<T>> getAvailableOrInProcessingBusEventsFromTransactionForSearchKeys(final Long searchKey1, final Long searchKey2, final Connection connection) { final InTransaction.InTransactionHandler<PersistentBusSqlDao, Iterable<BusEventWithMetadata<T>>> handler = new InTransaction.InTransactionHandler<PersistentBusSqlDao, Iterable<BusEventWithMetadata<T>>>() { @Override public Iterable<BusEventWithMetadata<T>> withSqlDao(final PersistentBusSqlDao transactional) { return getAvailableOrInProcessingBusEventsForSearchKeysInternal(transactional, null, searchKey1, searchKey2); } }; return InTransaction.execute(dbi, connection, handler, PersistentBusSqlDao.class); } @Override public <T extends BusEvent> Iterable<BusEventWithMetadata<T>> getAvailableOrInProcessingBusEventsForSearchKey2(final DateTime maxCreatedDate, final Long searchKey2) { return getAvailableOrInProcessingBusEventsForSearchKeysInternal((PersistentBusSqlDao) dao.getSqlDao(), maxCreatedDate, null, searchKey2); } @Override public <T extends BusEvent> Iterable<BusEventWithMetadata<T>> getAvailableOrInProcessingBusEventsFromTransactionForSearchKey2(final DateTime maxCreatedDate, final Long searchKey2, final Connection connection) { final InTransaction.InTransactionHandler<PersistentBusSqlDao, Iterable<BusEventWithMetadata<T>>> handler = new InTransaction.InTransactionHandler<PersistentBusSqlDao, Iterable<BusEventWithMetadata<T>>>() { @Override public Iterable<BusEventWithMetadata<T>> withSqlDao(final PersistentBusSqlDao transactional) { return getAvailableOrInProcessingBusEventsForSearchKeysInternal(transactional, maxCreatedDate, null, searchKey2); } }; return InTransaction.execute(dbi, connection, handler, PersistentBusSqlDao.class); } @Override public <T extends BusEvent> Iterable<BusEventWithMetadata<T>> getHistoricalBusEventsForSearchKeys(final Long searchKey1, final Long searchKey2) { return getHistoricalBusEventsForSearchKeysInternal((PersistentBusSqlDao) dao.getSqlDao(), null, searchKey1, searchKey2); } @Override public <T extends BusEvent> Iterable<BusEventWithMetadata<T>> getHistoricalBusEventsForSearchKey2(final DateTime minCreatedDate, final Long searchKey2) { return getHistoricalBusEventsForSearchKeysInternal((PersistentBusSqlDao) dao.getSqlDao(), minCreatedDate, null, searchKey2); } @Override public long getNbReadyEntries(final DateTime maxCreatedDate) { return dao.getNbReadyEntries(maxCreatedDate.toDate()); } @Override public String toString() { final StringBuilder sb = new StringBuilder("DefaultPersistentBus{"); sb.append("dbBackedQId='").append(dbBackedQId).append('\''); sb.append('}'); return sb.toString(); } public void dispatchBusEventWithMetrics(final QueueEvent event) throws org.killbill.commons.eventbus.EventBusException { final long ini = System.nanoTime(); try { eventBusDelegate.postWithException(event); } finally { busHandlersProcessingTime.update(System.nanoTime() - ini, TimeUnit.NANOSECONDS); } } private <T extends BusEvent> Iterable<BusEventWithMetadata<T>> getAvailableBusEventsForSearchKeysInternal(final PersistentBusSqlDao transactionalDao, @Nullable final DateTime maxCreatedDate, @Nullable final Long searchKey1, final Long searchKey2) { final Iterable<BusEventModelDao> entries = getReadyQueueEntriesForSearchKeysWithProfiling(transactionalDao, maxCreatedDate, searchKey1, searchKey2); return toBusEventWithMetadata(entries); } private <T extends BusEvent> Iterable<BusEventWithMetadata<T>> getAvailableOrInProcessingBusEventsForSearchKeysInternal(final PersistentBusSqlDao transactionalDao, @Nullable final DateTime maxCreatedDate, @Nullable final Long searchKey1, final Long searchKey2) { final Iterable<BusEventModelDao> entries = getReadyOrInProcessingQueueEntriesForSearchKeysWithProfiling(transactionalDao, maxCreatedDate, searchKey1, searchKey2); return toBusEventWithMetadata(entries); } private <T extends BusEvent> Iterable<BusEventWithMetadata<T>> getHistoricalBusEventsForSearchKeysInternal(final PersistentBusSqlDao transactionalDao, @Nullable final DateTime minCreatedDate, @Nullable final Long searchKey1, final Long searchKey2) { final Iterable<BusEventModelDao> entries = getHistoricalQueueEntriesForSearchKeysWithProfiling(transactionalDao, minCreatedDate, searchKey1, searchKey2); return toBusEventWithMetadata(entries); } private Iterable<BusEventModelDao> getReadyQueueEntriesForSearchKeysWithProfiling(final PersistentBusSqlDao transactionalDao, @Nullable final DateTime maxCreatedDate, @Nullable final Long searchKey1, final Long searchKey2) { return prof.executeWithProfiling(ProfilingFeature.ProfilingFeatureType.DAO, "DAO:PersistentBusSqlDao:getReadyQueueEntriesForSearchKeys", new Profiling.WithProfilingCallback<Iterable<BusEventModelDao>, RuntimeException>() { @Override public Iterable<BusEventModelDao> execute() throws RuntimeException { return new Iterable<BusEventModelDao>() { @Override public Iterator<BusEventModelDao> iterator() { return searchKey1 != null ? transactionalDao.getReadyQueueEntriesForSearchKeys(searchKey1, searchKey2, config.getTableName()) : transactionalDao.getReadyQueueEntriesForSearchKey2(maxCreatedDate, searchKey2, config.getTableName()); } }; } }); } private Iterable<BusEventModelDao> getReadyOrInProcessingQueueEntriesForSearchKeysWithProfiling(final PersistentBusSqlDao transactionalDao, @Nullable final DateTime maxCreatedDate, @Nullable final Long searchKey1, final Long searchKey2) { return prof.executeWithProfiling(ProfilingFeature.ProfilingFeatureType.DAO, "DAO:PersistentBusSqlDao:getReadyOrInProcessingQueueEntriesForSearchKeys", new Profiling.WithProfilingCallback<Iterable<BusEventModelDao>, RuntimeException>() { @Override public Iterable<BusEventModelDao> execute() throws RuntimeException { return new Iterable<BusEventModelDao>() { @Override public Iterator<BusEventModelDao> iterator() { return searchKey1 != null ? transactionalDao.getReadyOrInProcessingQueueEntriesForSearchKeys(searchKey1, searchKey2, config.getTableName()) : transactionalDao.getReadyOrInProcessingQueueEntriesForSearchKey2(maxCreatedDate, searchKey2, config.getTableName()); } }; } }); } private Iterable<BusEventModelDao> getHistoricalQueueEntriesForSearchKeysWithProfiling(final PersistentBusSqlDao transactionalDao, @Nullable final DateTime minCreatedDate, @Nullable final Long searchKey1, final Long searchKey2) { return prof.executeWithProfiling(ProfilingFeature.ProfilingFeatureType.DAO, "DAO:PersistentBusSqlDao:getHistoricalQueueEntriesForSearchKeys", new Profiling.WithProfilingCallback<Iterable<BusEventModelDao>, RuntimeException>() { @Override public Iterable<BusEventModelDao> execute() throws RuntimeException { return new Iterable<BusEventModelDao>() { @Override public Iterator<BusEventModelDao> iterator() { return searchKey1 != null ? transactionalDao.getHistoricalQueueEntriesForSearchKeys(searchKey1, searchKey2, config.getHistoryTableName()) : transactionalDao.getHistoricalQueueEntriesForSearchKey2(minCreatedDate, searchKey2, config.getHistoryTableName()); } }; } }); } private <T extends BusEvent> Iterable<BusEventWithMetadata<T>> toBusEventWithMetadata(final Iterable<BusEventModelDao> entries) { return Iterables.toStream(entries) .map(entry -> { final T event = EventEntryDeserializer.deserialize(entry, objectReader); return new BusEventWithMetadata<T>(entry.getRecordId(), entry.getUserToken(), entry.getCreatedDate(), entry.getSearchKey1(), entry.getSearchKey2(), event); }) .collect(Collectors.toUnmodifiableList()); } public DBBackedQueue<BusEventModelDao> getDao() { return dao; } public Clock getClock() { return clock; } public PersistentBusConfig getConfig() { return 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/bus/InMemoryPersistentBus.java
queue/src/main/java/org/killbill/bus/InMemoryPersistentBus.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.sql.Connection; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import javax.inject.Inject; import org.joda.time.DateTime; import org.killbill.bus.api.BusEvent; import org.killbill.bus.api.BusEventWithMetadata; import org.killbill.bus.api.PersistentBus; import org.killbill.bus.api.PersistentBusConfig; import org.killbill.commons.eventbus.EventBus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class InMemoryPersistentBus implements PersistentBus { private static final Logger log = LoggerFactory.getLogger(InMemoryPersistentBus.class); private final EventBusDelegate delegate; private final AtomicBoolean isInitialized; private final PersistentBusConfig config; @Override public boolean isStarted() { return true; } public static class EventBusDelegate extends EventBus { public EventBusDelegate() { super("Bus"); } public void completeDispatch() { } // No way to really 'stop' an executor; what we do is: // i) disallow any new events into the queue // ii) empty the queue // // That will only work if the event submitter handles EventBusException correctly when posting. // public void stop() { } } @Inject public InMemoryPersistentBus(final PersistentBusConfig config) { this.config = config; this.delegate = new EventBusDelegate(); this.isInitialized = new AtomicBoolean(false); } @Override public void register(final Object handlerInstance) throws EventBusException { checkInitialized("register"); delegate.register(handlerInstance); } @Override public void unregister(final Object handlerInstance) throws EventBusException { checkInitialized("unregister"); delegate.unregister(handlerInstance); } @Override public void post(final BusEvent event) throws EventBusException { checkInitialized("post"); try { delegate.postWithException(event); } catch (final org.killbill.commons.eventbus.EventBusException e) { throw new EventBusException(e.getMessage(), e); } } @Override public void postFromTransaction(final BusEvent event, final Connection connection) throws EventBusException { checkInitialized("postFromTransaction"); try { delegate.postWithException(event); } catch (final org.killbill.commons.eventbus.EventBusException e) { throw new EventBusException(e.getMessage(), e); } } @Override public boolean initQueue() { if (config.isProcessingOff()) { log.warn("InMemoryPersistentBus processing is off, cannot be initialized"); return false; } if (isInitialized.compareAndSet(false, true)) { log.info("InMemoryPersistentBus initialized"); return true; } else { return false; } } @Override public boolean startQueue() { if (config.isProcessingOff()) { log.warn("InMemoryPersistentBus processing is off, cannot be started"); return false; } if (!isInitialized.get()) { // Make it easy for our tests, so they simply call startQueue initQueue(); } log.info("InMemoryPersistentBus started"); return true; } private void checkInitialized(final String operation) throws EventBusException { if (!isInitialized.get()) { throw new EventBusException(String.format("Attempting operation %s on an non initialized bus", operation)); } } @Override public boolean stopQueue() { if (isInitialized.compareAndSet(true, false)) { log.info("InMemoryPersistentBus stopping..."); delegate.completeDispatch(); delegate.stop(); log.info("InMemoryPersistentBus stopped..."); return true; } return true; } @Override public <T extends BusEvent> List<BusEventWithMetadata<T>> getAvailableBusEventsForSearchKeys(final Long searchKey1, final Long searchKey2) { throw new UnsupportedOperationException("Guava doesn't expose the events to dispatch"); } @Override public <T extends BusEvent> List<BusEventWithMetadata<T>> getAvailableBusEventsFromTransactionForSearchKeys(final Long searchKey1, final Long searchKey2, final Connection connection) { throw new UnsupportedOperationException("Guava doesn't expose the events to dispatch"); } @Override public <T extends BusEvent> List<BusEventWithMetadata<T>> getAvailableBusEventsForSearchKey2(final DateTime maxCreatedDate, final Long searchKey2) { throw new UnsupportedOperationException("Guava doesn't expose the events to dispatch"); } @Override public <T extends BusEvent> List<BusEventWithMetadata<T>> getAvailableBusEventsFromTransactionForSearchKey2(final DateTime maxCreatedDate, final Long searchKey2, final Connection connection) { throw new UnsupportedOperationException("Guava doesn't expose the events to dispatch"); } @Override public <T extends BusEvent> List<BusEventWithMetadata<T>> getInProcessingBusEvents() { throw new UnsupportedOperationException("Guava doesn't expose the events to dispatch"); } @Override public <T extends BusEvent> List<BusEventWithMetadata<T>> getAvailableOrInProcessingBusEventsForSearchKeys(final Long searchKey1, final Long searchKey2) { throw new UnsupportedOperationException("Guava doesn't expose the events to dispatch"); } @Override public <T extends BusEvent> List<BusEventWithMetadata<T>> getAvailableOrInProcessingBusEventsFromTransactionForSearchKeys(final Long searchKey1, final Long searchKey2, final Connection connection) { throw new UnsupportedOperationException("Guava doesn't expose the events to dispatch"); } @Override public <T extends BusEvent> List<BusEventWithMetadata<T>> getAvailableOrInProcessingBusEventsForSearchKey2(final DateTime maxCreatedDate, final Long searchKey2) { throw new UnsupportedOperationException("Guava doesn't expose the events to dispatch"); } @Override public <T extends BusEvent> List<BusEventWithMetadata<T>> getAvailableOrInProcessingBusEventsFromTransactionForSearchKey2(final DateTime maxCreatedDate, final Long searchKey2, final Connection connection) { throw new UnsupportedOperationException("Guava doesn't expose the events to dispatch"); } @Override public <T extends BusEvent> List<BusEventWithMetadata<T>> getHistoricalBusEventsForSearchKeys(final Long searchKey1, final Long searchKey2) { throw new UnsupportedOperationException("Guava doesn't expose the events to dispatch"); } @Override public <T extends BusEvent> List<BusEventWithMetadata<T>> getHistoricalBusEventsForSearchKey2(final DateTime minCreatedDate, final Long searchKey2) { throw new UnsupportedOperationException("Guava doesn't expose the events to dispatch"); } @Override public long getNbReadyEntries(final DateTime maxCreatedDate) { throw new UnsupportedOperationException("Guava doesn't expose the events to dispatch"); } }
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/bus/dao/PersistentBusSqlDao.java
queue/src/main/java/org/killbill/bus/dao/PersistentBusSqlDao.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.Date; import java.util.Iterator; import java.util.List; import javax.annotation.Nullable; 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.customizers.Define; @KillBillSqlDaoStringTemplate public interface PersistentBusSqlDao extends QueueSqlDao<BusEventModelDao> { @SqlQuery List<Long> getReadyEntryIds(@Bind("now") Date now, @Bind("from") long from, @Bind("max") int max, // This is somewhat a hack, should really be a @Bind parameter but we also use it // for StringTemplate to modify the query based whether value is null or not. @Nullable @Define("owner") String owner, @Define("tableName") final String tableName); @SqlQuery @SmartFetchSize(shouldStream = true) public Iterator<BusEventModelDao> getReadyQueueEntriesForSearchKeys(@Bind("searchKey1") final Long searchKey1, @Bind("searchKey2") final Long searchKey2, @Define("tableName") final String tableName); @SqlQuery @SmartFetchSize(shouldStream = true) public Iterator<BusEventModelDao> getReadyQueueEntriesForSearchKey2(@Bind("maxCreatedDate") final DateTime maxCreatedDate, @Bind("searchKey2") final Long searchKey2, @Define("tableName") final String tableName); @SqlQuery @SmartFetchSize(shouldStream = true) public Iterator<BusEventModelDao> getReadyOrInProcessingQueueEntriesForSearchKeys(@Bind("searchKey1") final Long searchKey1, @Bind("searchKey2") final Long searchKey2, @Define("tableName") final String tableName); @SqlQuery @SmartFetchSize(shouldStream = true) public Iterator<BusEventModelDao> getReadyOrInProcessingQueueEntriesForSearchKey2(@Bind("maxCreatedDate") final DateTime maxCreatedDate, @Bind("searchKey2") final Long searchKey2, @Define("tableName") final String tableName); @SqlQuery @SmartFetchSize(shouldStream = true) public Iterator<BusEventModelDao> getHistoricalQueueEntriesForSearchKeys(@Bind("searchKey1") final Long searchKey1, @Bind("searchKey2") final Long searchKey2, @Define("historyTableName") final String historyTableName); @SqlQuery @SmartFetchSize(shouldStream = true) public Iterator<BusEventModelDao> getHistoricalQueueEntriesForSearchKey2(@Bind("minCreatedDate") final DateTime minCreatedDate, @Bind("searchKey2") final Long searchKey2, @Define("historyTableName") final String historyTableName); }
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/bus/dao/BusEventModelDao.java
queue/src/main/java/org/killbill/bus/dao/BusEventModelDao.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.UUID; import org.joda.time.DateTime; import org.killbill.queue.api.PersistentQueueEntryLifecycleState; import org.killbill.queue.dao.EventEntryModelDao; public class BusEventModelDao implements EventEntryModelDao { private Long recordId; private String className; private String eventJson; private UUID userToken; private DateTime createdDate; private String creatingOwner; private String processingOwner; private DateTime processingAvailableDate; private Long errorCount; private PersistentQueueEntryLifecycleState processingState; private Long searchKey1; private Long searchKey2; public BusEventModelDao() { /* DAO mapper */ } public BusEventModelDao(final Long recordId, final String createdOwner, final String owner, final DateTime createdDate, final DateTime nextAvailable, final PersistentQueueEntryLifecycleState processingState, final String busEventClass, final String busEventJson, final Long errorCount, final UUID userToken, final Long searchKey1, final Long searchKey2) { this.recordId = recordId; this.creatingOwner = createdOwner; this.processingOwner = owner; this.createdDate = createdDate; this.processingAvailableDate = nextAvailable; this.processingState = processingState; this.className = busEventClass; this.errorCount = errorCount; this.eventJson = busEventJson; this.userToken = userToken; this.searchKey1 = searchKey1; this.searchKey2 = searchKey2; } public BusEventModelDao(final String createdOwner, final DateTime createdDate, final String busEventClass, final String busEventJson, final UUID userToken, final Long searchKey1, final Long searchKey2) { this(-1L, createdOwner, null, createdDate, null, PersistentQueueEntryLifecycleState.AVAILABLE, busEventClass, busEventJson, 0L, userToken, searchKey1, searchKey2); } public BusEventModelDao(final BusEventModelDao 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()); } public BusEventModelDao(final BusEventModelDao 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()); } @Override public Long getRecordId() { return recordId; } public void setRecordId(final Long recordId) { this.recordId = recordId; } @Override public String getClassName() { return className; } @Override public void setClassName(final String className) { this.className = className; } @Override public String getEventJson() { return eventJson; } @Override public void setEventJson(final String eventJson) { this.eventJson = eventJson; } @Override public UUID getUserToken() { return userToken; } @Override public void setUserToken(final UUID userToken) { this.userToken = userToken; } public DateTime getCreatedDate() { return createdDate; } @Override public void setCreatedDate(final DateTime createdDate) { this.createdDate = createdDate; } @Override public String getCreatingOwner() { return creatingOwner; } @Override public void setCreatingOwner(final String creatingOwner) { this.creatingOwner = creatingOwner; } @Override public String getProcessingOwner() { return processingOwner; } @Override public void setProcessingOwner(final String processingOwner) { this.processingOwner = processingOwner; } @Override public DateTime getNextAvailableDate() { return processingAvailableDate; } // Required for serialization public DateTime getProcessingAvailableDate() { return processingAvailableDate; } public void setProcessingAvailableDate(final DateTime processingAvailableDate) { this.processingAvailableDate = processingAvailableDate; } @Override public void setErrorCount(final Long errorCount) { this.errorCount = errorCount; } @Override public PersistentQueueEntryLifecycleState getProcessingState() { return processingState; } @Override public void setProcessingState(final PersistentQueueEntryLifecycleState processingState) { this.processingState = processingState; } @Override public void setSearchKey1(final Long searchKey1) { this.searchKey1 = searchKey1; } @Override public void setSearchKey2(final Long searchKey2) { this.searchKey2 = searchKey2; } @Override public boolean isAvailableForProcessing(final DateTime now) { switch (processingState) { case AVAILABLE: break; case IN_PROCESSING: // Somebody already got the event, not available yet if (processingAvailableDate.isAfter(now)) { return false; } break; case PROCESSED: return false; default: throw new RuntimeException(String.format("Unknown IEvent processing state %s", processingState)); } return true; } @Override public Long getErrorCount() { return errorCount; } @Override public Long getSearchKey1() { return searchKey1; } @Override public Long getSearchKey2() { return searchKey2; } @Override public String toString() { final StringBuilder sb = new StringBuilder("BusEventModelDao{"); sb.append("recordId=").append(recordId); sb.append(", className='").append(className).append('\''); sb.append(", eventJson='").append(eventJson).append('\''); sb.append(", userToken=").append(userToken); sb.append(", createdDate=").append(createdDate); sb.append(", creatingOwner='").append(creatingOwner).append('\''); sb.append(", processingOwner='").append(processingOwner).append('\''); sb.append(", processingAvailableDate=").append(processingAvailableDate); sb.append(", errorCount=").append(errorCount); sb.append(", processingState=").append(processingState); sb.append(", searchKey1=").append(searchKey1); sb.append(", searchKey2=").append(searchKey2); 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/bus/dispatching/BusCallableCallback.java
queue/src/main/java/org/killbill/bus/dispatching/BusCallableCallback.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.dispatching; import org.joda.time.DateTime; import org.killbill.CreatorName; import org.killbill.bus.DefaultPersistentBus; import org.killbill.bus.api.BusEvent; import org.killbill.bus.dao.BusEventModelDao; import org.killbill.commons.eventbus.EventBusException; import org.killbill.queue.api.PersistentQueueEntryLifecycleState; import org.killbill.queue.dispatching.CallableCallbackBase; public class BusCallableCallback extends CallableCallbackBase<BusEvent, BusEventModelDao> { private final DefaultPersistentBus parent; public BusCallableCallback(final DefaultPersistentBus parent) { super(parent.getDao(), parent.getClock(), parent.getConfig(), parent.getObjectReader()); this.parent = parent; } @Override public void dispatch(final BusEvent event, final BusEventModelDao modelDao) throws EventBusException { parent.dispatchBusEventWithMetrics(event); } @Override public BusEventModelDao buildEntry(final BusEventModelDao modelDao, final DateTime now, final PersistentQueueEntryLifecycleState newState, final long newErrorCount) { return new BusEventModelDao(modelDao, CreatorName.get(), now, newState, newErrorCount); } }
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/bus/api/BusEvent.java
queue/src/main/java/org/killbill/bus/api/BusEvent.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.api; import java.util.UUID; import org.killbill.queue.api.QueueEvent; /** * Base interface for all bus/notiication events */ public interface BusEvent extends QueueEvent { /** * * @return the search key1 */ public Long getSearchKey1(); /** * * @return the search key2 */ public Long getSearchKey2(); /** * * @return the user token */ public UUID getUserToken(); }
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/bus/api/BusEventWithMetadata.java
queue/src/main/java/org/killbill/bus/api/BusEventWithMetadata.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.api; import java.util.UUID; import org.joda.time.DateTime; import org.killbill.queue.api.QueueEvent; /** * The BusEventWithMetadata return to the user. It encapsulates the de-serialized version of the json event on disk. * * @param <T> The type of event serialized on disk */ public class BusEventWithMetadata<T extends QueueEvent> { private final Long recordId; private final UUID userToken; private final DateTime createdDate; private final Long searchKey1; private final Long searchKey2; private final T event; public BusEventWithMetadata(final Long recordId, final UUID userToken, final DateTime createdDate, final Long searchKey1, final Long searchKey2, final T event) { this.recordId = recordId; this.userToken = userToken; this.createdDate = createdDate; this.searchKey1 = searchKey1; this.searchKey2 = searchKey2; this.event = event; } public Long getRecordId() { return recordId; } public UUID getUserToken() { return userToken; } public DateTime getCreatedDate() { return createdDate; } public Long getSearchKey1() { return searchKey1; } public Long getSearchKey2() { return searchKey2; } public T getEvent() { return event; } }
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/bus/api/PersistentBus.java
queue/src/main/java/org/killbill/bus/api/PersistentBus.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.api; import java.sql.Connection; import org.joda.time.DateTime; import org.killbill.queue.api.QueueLifecycle; /** * When an Iterable is returned, the client must iterate through all results to close the DB connection. */ public interface PersistentBus extends QueueLifecycle { String EVENT_BUS_GROUP_NAME = "bus-grp"; String EVENT_BUS_SERVICE = "bus-service"; String EVENT_BUS_IDENTIFIER = EVENT_BUS_SERVICE; class EventBusException extends Exception { private static final long serialVersionUID = 12355236L; public EventBusException() { super(); } public EventBusException(final String message, final Throwable cause) { super(message, cause); } public EventBusException(final String message) { super(message); } } /** * Registers all handler methods on {@code object} to receive events. * Handler methods need to be Annotated with {@link com.google.common.eventbus.Subscribe} * * @param handlerInstance handler to register * @throws EventBusException if bus not been started yet */ void register(Object handlerInstance) throws EventBusException; /** * Unregister the handler for a particular type of event * * @param handlerInstance handler to unregister * @throws EventBusException */ void unregister(Object handlerInstance) throws EventBusException; /** * Post an event asynchronously * * @param event to be posted * @throws EventBusException if bus not been started yet */ void post(BusEvent event) throws EventBusException; /** * Post an event from within a transaction. * Guarantees that the event is persisted on disk from within the same transaction * * @param event to be posted * @param connection current connection * @throws EventBusException if bus not been started yet */ void postFromTransaction(BusEvent event, Connection connection) throws EventBusException; /** * Retrieve all available bus events matching that search key * * @param searchKey1 the value for key1 * @param searchKey2 the value for key2 * @return a list of BusEventWithMetadata objects matching the search */ <T extends BusEvent> Iterable<BusEventWithMetadata<T>> getAvailableBusEventsForSearchKeys(Long searchKey1, Long searchKey2); /** * Retrieve all available bus events matching that search key * * @param searchKey1 the value for key1 * @param searchKey2 the value for key2 * @param connection the transaction that should be used to make that search * @return a list of BusEventWithMetadata objects matching the search */ <T extends BusEvent> Iterable<BusEventWithMetadata<T>> getAvailableBusEventsFromTransactionForSearchKeys(Long searchKey1, Long searchKey2, Connection connection); /** * Retrieve all available bus events matching that search key * * @param maxCreatedDate created_date cutoff, to limit the search * @param searchKey2 the value for key2 * @return a list of BusEventWithMetadata objects matching the search */ <T extends BusEvent> Iterable<BusEventWithMetadata<T>> getAvailableBusEventsForSearchKey2(DateTime maxCreatedDate, Long searchKey2); /** * Retrieve all available bus events matching that search key * * @param maxCreatedDate created_date cutoff, to limit the search * @param searchKey2 the value for key2 * @param connection the transaction that should be used to make that search * @return a list of BusEventWithMetadata objects matching the search */ <T extends BusEvent> Iterable<BusEventWithMetadata<T>> getAvailableBusEventsFromTransactionForSearchKey2(DateTime maxCreatedDate, Long searchKey2, Connection connection); /** * @return the bus events that have been claimed and are being processed */ <T extends BusEvent> Iterable<BusEventWithMetadata<T>> getInProcessingBusEvents(); /** * Retrieve all available or in processing bus events matching that search key * * @param searchKey1 the value for key1 * @param searchKey2 the value for key2 * @return a list of BusEventWithMetadata objects matching the search */ <T extends BusEvent> Iterable<BusEventWithMetadata<T>> getAvailableOrInProcessingBusEventsForSearchKeys(Long searchKey1, Long searchKey2); /** * Retrieve all available or in processing bus events matching that search key * * @param searchKey1 the value for key1 * @param searchKey2 the value for key2 * @param connection the transaction that should be used to make that search * @return a list of BusEventWithMetadata objects matching the search */ <T extends BusEvent> Iterable<BusEventWithMetadata<T>> getAvailableOrInProcessingBusEventsFromTransactionForSearchKeys(Long searchKey1, Long searchKey2, Connection connection); /** * Retrieve all available or in processing bus events matching that search key * * @param maxCreatedDate created_date cutoff, to limit the search * @param searchKey2 the value for key2 * @return a list of BusEventWithMetadata objects matching the search */ <T extends BusEvent> Iterable<BusEventWithMetadata<T>> getAvailableOrInProcessingBusEventsForSearchKey2(DateTime maxCreatedDate, Long searchKey2); /** * Retrieve all available or in processing bus events matching that search key * * @param maxCreatedDate created_date cutoff, to limit the search * @param searchKey2 the value for key2 * @param connection the transaction that should be used to make that search * @return a list of BusEventWithMetadata objects matching the search */ <T extends BusEvent> Iterable<BusEventWithMetadata<T>> getAvailableOrInProcessingBusEventsFromTransactionForSearchKey2(DateTime maxCreatedDate, Long searchKey2, Connection connection); /** * Retrieve all historical bus events matching that search key * * @param searchKey1 the value for key1 * @param searchKey2 the value for key2 * @return a list of BusEventWithMetadata objects matching the search */ <T extends BusEvent> Iterable<BusEventWithMetadata<T>> getHistoricalBusEventsForSearchKeys(Long searchKey1, Long searchKey2); /** * Retrieve all historical bus events matching that search key * * @param minCreatedDate created_date cutoff, to limit the search * @param searchKey2 the value for key2 * @return a list of BusEventWithMetadata objects matching the search */ <T extends BusEvent> Iterable<BusEventWithMetadata<T>> getHistoricalBusEventsForSearchKey2(DateTime minCreatedDate, Long searchKey2); /** * Count the number of bus entries ready to be processed * * @param maxCreatedDate created_date cutoff (typically now()) * @return the number of ready entries */ long getNbReadyEntries(final DateTime maxCreatedDate); }
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/bus/api/PersistentBusConfig.java
queue/src/main/java/org/killbill/bus/api/PersistentBusConfig.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.api; import org.killbill.queue.api.PersistentQueueConfig; import org.skife.config.Config; import org.skife.config.Default; import org.skife.config.Description; import org.skife.config.TimeSpan; public abstract class PersistentBusConfig implements PersistentQueueConfig { @Override @Config("org.killbill.persistent.bus.${instanceName}.inMemory") @Default("false") @Description("Whether the bus should be an in memory bus") public abstract boolean isInMemory(); @Override @Config("org.killbill.persistent.bus.${instanceName}.max.failure.retry") @Default("3") @Description("Number of retries for a given event when an exception occurs") public abstract int getMaxFailureRetries(); @Override @Config("org.killbill.persistent.bus.${instanceName}.inflight.min") @Default("1") @Description("Min number of bus events to fetch from the database at once (only valid in 'STICKY_EVENTS')") public abstract int getMinInFlightEntries(); @Override @Config("org.killbill.persistent.bus.${instanceName}.inflight.max") @Default("100") @Description("Max number of bus events to fetch from the database at once (only valid in 'STICKY_EVENTS')") public abstract int getMaxInFlightEntries(); @Override @Config("org.killbill.persistent.bus.${instanceName}.claimed") @Default("10") @Description("Number of bus events to fetch from the database at once (only valid in 'polling mode')") public abstract int getMaxEntriesClaimed(); @Override @Config("org.killbill.persistent.bus.${instanceName}.queue.mode") @Default("POLLING") @Description("How entries are put in the queue") public abstract PersistentQueueMode getPersistentQueueMode(); @Override @Config("org.killbill.persistent.bus.${instanceName}.claim.time") @Default("5m") @Description("Claim time") public abstract TimeSpan getClaimedTime(); @Override @Config("org.killbill.persistent.bus.${instanceName}.sleep") @Default("3000") @Description("Time in milliseconds to sleep between runs (only valid in STICKY_POLLING, POLLING)") public abstract long getPollingSleepTimeMs(); @Override @Config("org.killbill.persistent.bus.${instanceName}.off") @Default("false") @Description("Whether to turn off the persistent bus") public abstract boolean isProcessingOff(); @Override @Config("org.killbill.persistent.bus.${instanceName}.nbThreads") @Default("30") @Description("Max number of dispatch threads to use") public abstract int geMaxDispatchThreads(); @Override @Config("org.killbill.persistent.bus.${instanceName}.lifecycle.dispatch.nbThreads") @Default("1") @Description("Max number of lifecycle dispatch threads to use") public abstract int geNbLifecycleDispatchThreads(); @Override @Config("org.killbill.persistent.bus.${instanceName}.lifecycle.complete.nbThreads") @Default("2") @Description("Max number of lifecycle complete threads to use") public abstract int geNbLifecycleCompleteThreads(); @Override @Config("org.killbill.persistent.bus.${instanceName}.queue.capacity") @Default("30000") @Description("Size of the inflight queue (only valid in STICKY_EVENTS mode)") public abstract int getEventQueueCapacity(); @Override @Config("org.killbill.persistent.bus.${instanceName}.tableName") @Default("bus_events") @Description("Bus events table name") public abstract String getTableName(); @Override @Config("org.killbill.persistent.bus.${instanceName}.historyTableName") @Default("bus_events_history") @Description("Bus events history table name") public abstract String getHistoryTableName(); @Override @Config("org.killbill.persistent.bus.${instanceName}.reapThreshold") @Default("10m") @Description("Time span when the bus event must be re-dispatched") public abstract TimeSpan getReapThreshold(); @Override @Config("org.killbill.persistent.bus.${instanceName}.maxReDispatchCount") @Default("10") @Description("Max number of bus events to be re-dispatched at a time") public abstract int getMaxReDispatchCount(); @Override @Config("org.killbill.persistent.bus.${instanceName}.reapSchedule") @Default("3m") @Description("Reaper schedule period") public abstract TimeSpan getReapSchedule(); @Override @Config("org.killbill.persistent.bus.${instanceName}.shutdownTimeout") @Default("15s") @Description("Shutdown sequence timeout") public abstract TimeSpan getShutdownTimeout(); }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/locker/src/test/java/org/killbill/commons/locker/TestReentrantLock.java
locker/src/test/java/org/killbill/commons/locker/TestReentrantLock.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.locker; import org.killbill.commons.locker.ReentrantLock.ReentrantLockState; import org.killbill.commons.locker.ReentrantLock.TryAcquireLockState; import org.killbill.commons.request.Request; import org.killbill.commons.request.RequestData; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class TestReentrantLock { private ReentrantLock lockTable; @BeforeMethod(groups = "fast") public void beforeMethod() throws Exception { Request.resetPerThreadRequestData(); lockTable = new ReentrantLock(); } @AfterMethod(groups = "fast") public void afterMethod() throws Exception { Request.resetPerThreadRequestData(); lockTable = new ReentrantLock(); } @Test(groups = "fast") public void testHeldByOwner() { Request.setPerThreadRequestData(new RequestData("12345")); TryAcquireLockState lockState = lockTable.tryAcquireLockForExistingOwner("foo"); Assert.assertEquals(lockState.getLockState(), ReentrantLockState.FREE); // Assume we were able to get distributed lock, so the next poeration would be to createLock lockTable.createLock("foo", null); lockState = lockTable.tryAcquireLockForExistingOwner("foo"); Assert.assertEquals(lockState.getLockState(), ReentrantLockState.HELD_OWNER); lockState = lockTable.tryAcquireLockForExistingOwner("foo"); Assert.assertEquals(lockState.getLockState(), ReentrantLockState.HELD_OWNER); // Ref count should be 3, so last attempt should return true boolean free = lockTable.releaseLock("foo"); Assert.assertFalse(free); free = lockTable.releaseLock("foo"); Assert.assertFalse(free); free = lockTable.releaseLock("foo"); Assert.assertTrue(free); } @Test(groups = "fast") public void testNotHeldByOwner() { Request.setPerThreadRequestData(new RequestData("12345")); TryAcquireLockState lockState = lockTable.tryAcquireLockForExistingOwner("bar"); Assert.assertEquals(lockState.getLockState(), ReentrantLockState.FREE); // Assume we were able to get distributed lock, so the next poeration would be to createLock lockTable.createLock("bar", null); Request.setPerThreadRequestData(new RequestData("54321")); lockState = lockTable.tryAcquireLockForExistingOwner("bar"); Assert.assertEquals(lockState.getLockState(), ReentrantLockState.HELD_NOT_OWNER); try { lockTable.releaseLock("foo"); Assert.fail("Should fail to decrement lock we don't hold"); } catch (final IllegalStateException ignore) { } Request.setPerThreadRequestData(new RequestData("12345")); final boolean free = lockTable.releaseLock("bar"); Assert.assertTrue(free); } @Test(groups = "fast") public void testInvalidCreateLock() { Request.setPerThreadRequestData(new RequestData("55555")); lockTable.createLock("bar", null); try { lockTable.createLock("bar", null); Assert.fail("Should fail to creating lock"); } catch (final IllegalStateException ignore) { } } @Test(groups = "fast") public void testInvalidReleaseLock() { Request.setPerThreadRequestData(new RequestData("222222")); try { lockTable.releaseLock("bar"); Assert.fail("Should fail to releasing lock"); } catch (final IllegalStateException ignore) { } } @Test(groups = "fast") public void testWithNoRequestId() { // We have no requestId and nobody owns it TryAcquireLockState lockState = lockTable.tryAcquireLockForExistingOwner("snoopy"); Assert.assertEquals(lockState.getLockState(), ReentrantLockState.FREE); Request.setPerThreadRequestData(new RequestData("33333")); lockTable.createLock("snoopy", null); Request.resetPerThreadRequestData(); // We have no requestId but somebody owns it lockState = lockTable.tryAcquireLockForExistingOwner("snoopy"); Assert.assertEquals(lockState.getLockState(), ReentrantLockState.HELD_NOT_OWNER); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/locker/src/test/java/org/killbill/commons/locker/postgresql/TestPostgreSQLGlobalLocker.java
locker/src/test/java/org/killbill/commons/locker/postgresql/TestPostgreSQLGlobalLocker.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.locker.postgresql; import org.killbill.commons.embeddeddb.postgresql.PostgreSQLEmbeddedDB; import org.killbill.commons.locker.GlobalLock; import org.killbill.commons.locker.GlobalLocker; import org.killbill.commons.locker.LockFailedException; import org.killbill.commons.request.Request; import org.killbill.commons.request.RequestData; 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 java.io.IOException; import java.util.UUID; public class TestPostgreSQLGlobalLocker { private PostgreSQLEmbeddedDB embeddedDB; @BeforeMethod(groups = "postgresql") public void beforeMethod() throws Exception { Request.resetPerThreadRequestData(); } @AfterMethod(groups = "postgresql") public void afterMethod() throws Exception { Request.resetPerThreadRequestData(); } @BeforeClass(groups = "postgresql") public void setUp() throws Exception { embeddedDB = new PostgreSQLEmbeddedDB(); embeddedDB.initialize(); embeddedDB.start(); } @AfterClass(groups = "postgresql") public void tearDown() throws Exception { embeddedDB.stop(); } @Test(groups = "postgresql") public void testSimpleLocking() throws IOException, LockFailedException { final String serviceLock = "MY_AWESOME_LOCK"; final String lockName = UUID.randomUUID().toString(); final GlobalLocker locker = new PostgreSQLGlobalLocker(embeddedDB.getDataSource()); final GlobalLock lock = locker.lockWithNumberOfTries(serviceLock, lockName, 3); Assert.assertFalse(locker.isFree(serviceLock, lockName)); boolean gotException = false; try { locker.lockWithNumberOfTries(serviceLock, lockName, 1); } catch (final LockFailedException e) { gotException = true; } Assert.assertTrue(gotException); lock.release(); Assert.assertTrue(locker.isFree(serviceLock, lockName)); } @Test(groups = "postgresql") public void testReentrantLock() throws IOException, LockFailedException { final String serviceLock = "MY_SHITTY_LOCK"; final String lockName = UUID.randomUUID().toString(); final String requestId = "12345"; Request.setPerThreadRequestData(new RequestData(requestId)); final GlobalLocker locker = new PostgreSQLGlobalLocker(embeddedDB.getDataSource()); final GlobalLock lock = locker.lockWithNumberOfTries(serviceLock, lockName, 3); Assert.assertFalse(locker.isFree(serviceLock, lockName)); Assert.assertTrue(lock instanceof PostgreSQLGlobalLock); // Re-aquire the createLock with the same requestId, should work final GlobalLock reentrantLock = locker.lockWithNumberOfTries(serviceLock, lockName, 1); Assert.assertTrue(reentrantLock instanceof PostgreSQLGlobalLock); lock.release(); Assert.assertFalse(locker.isFree(serviceLock, lockName)); reentrantLock.release(); Assert.assertTrue(locker.isFree(serviceLock, lockName)); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/locker/src/test/java/org/killbill/commons/locker/mysql/TestMysqlGlobalLocker.java
locker/src/test/java/org/killbill/commons/locker/mysql/TestMysqlGlobalLocker.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.locker.mysql; import org.killbill.commons.embeddeddb.mysql.MySQLEmbeddedDB; import org.killbill.commons.locker.GlobalLock; import org.killbill.commons.locker.GlobalLocker; import org.killbill.commons.locker.LockFailedException; import org.killbill.commons.request.Request; import org.killbill.commons.request.RequestData; 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 java.io.IOException; import java.util.UUID; public class TestMysqlGlobalLocker { private MySQLEmbeddedDB embeddedDB; @BeforeMethod(groups = "mysql") public void beforeMethod() throws Exception { Request.resetPerThreadRequestData(); } @AfterMethod(groups = "mysql") public void afterMethod() throws Exception { Request.resetPerThreadRequestData(); } @BeforeClass(groups = "mysql") public void setUp() throws Exception { embeddedDB = new MySQLEmbeddedDB(); embeddedDB.initialize(); embeddedDB.start(); } @AfterClass(groups = "mysql") public void tearDown() throws Exception { embeddedDB.stop(); } @Test(groups = "mysql") public void testSimpleLocking() throws IOException, LockFailedException { final String serviceLock = "MY_AWESOME_LOCK"; final String lockName = UUID.randomUUID().toString(); final GlobalLocker locker = new MySqlGlobalLocker(embeddedDB.getDataSource()); final GlobalLock lock = locker.lockWithNumberOfTries(serviceLock, lockName, 3); Assert.assertFalse(locker.isFree(serviceLock, lockName)); boolean gotException = false; try { locker.lockWithNumberOfTries(serviceLock, lockName, 1); } catch (final LockFailedException e) { gotException = true; } Assert.assertTrue(gotException); lock.release(); Assert.assertTrue(locker.isFree(serviceLock, lockName)); } @Test(groups = "mysql") public void testReentrantLockInOrder() throws IOException, LockFailedException { final String serviceLock = "MY_LOCK_2"; final String lockName = UUID.randomUUID().toString(); final String requestId = "12345"; Request.setPerThreadRequestData(new RequestData(requestId)); final GlobalLocker locker = new MySqlGlobalLocker(embeddedDB.getDataSource()); final GlobalLock lock = locker.lockWithNumberOfTries(serviceLock, lockName, 3); Assert.assertFalse(locker.isFree(serviceLock, lockName)); Assert.assertTrue(lock instanceof MysqlGlobalLock); // Re-aquire the createLock with the same requestId, should work final GlobalLock reentrantLock = locker.lockWithNumberOfTries(serviceLock, lockName, 1); Assert.assertTrue(reentrantLock instanceof MysqlGlobalLock); reentrantLock.release(); Assert.assertFalse(locker.isFree(serviceLock, lockName)); lock.release(); Assert.assertTrue(locker.isFree(serviceLock, lockName)); } @Test(groups = "mysql") public void testReentrantLockOufOfOrder() throws IOException, LockFailedException { final String serviceLock = "MY_LOCK_3"; final String lockName = UUID.randomUUID().toString(); final String requestId = "12345"; Request.setPerThreadRequestData(new RequestData(requestId)); final GlobalLocker locker = new MySqlGlobalLocker(embeddedDB.getDataSource()); final GlobalLock lock = locker.lockWithNumberOfTries(serviceLock, lockName, 3); Assert.assertFalse(locker.isFree(serviceLock, lockName)); Assert.assertTrue(lock instanceof MysqlGlobalLock); // Re-aquire the createLock with the same requestId, should work final GlobalLock reentrantLock = locker.lockWithNumberOfTries(serviceLock, lockName, 1); Assert.assertTrue(reentrantLock instanceof MysqlGlobalLock); lock.release(); Assert.assertFalse(locker.isFree(serviceLock, lockName)); reentrantLock.release(); Assert.assertTrue(locker.isFree(serviceLock, lockName)); } @Test(groups = "mysql") public void testReentrantNLevelLock() throws IOException, LockFailedException { final String serviceLock = "MY_LOCK_N"; final String lockName = UUID.randomUUID().toString(); final String requestId = "44444"; Request.setPerThreadRequestData(new RequestData(requestId)); final GlobalLocker locker = new MySqlGlobalLocker(embeddedDB.getDataSource()); final GlobalLock lock = locker.lockWithNumberOfTries(serviceLock, lockName, 3); Assert.assertFalse(locker.isFree(serviceLock, lockName)); Assert.assertTrue(lock instanceof MysqlGlobalLock); // Re-aquire the createLock with the same requestId, should work final GlobalLock reentrantLock1 = locker.lockWithNumberOfTries(serviceLock, lockName, 1); Assert.assertTrue(reentrantLock1 instanceof MysqlGlobalLock); lock.release(); Assert.assertFalse(locker.isFree(serviceLock, lockName)); final GlobalLock reentrantLock2 = locker.lockWithNumberOfTries(serviceLock, lockName, 1); Assert.assertTrue(reentrantLock2 instanceof MysqlGlobalLock); reentrantLock1.release(); Assert.assertFalse(locker.isFree(serviceLock, lockName)); final GlobalLock reentrantLock3 = locker.lockWithNumberOfTries(serviceLock, lockName, 1); Assert.assertTrue(reentrantLock3 instanceof MysqlGlobalLock); reentrantLock3.release(); Assert.assertFalse(locker.isFree(serviceLock, lockName)); reentrantLock2.release(); Assert.assertTrue(locker.isFree(serviceLock, lockName)); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/locker/src/test/java/org/killbill/commons/locker/memory/TestMemoryGlobalLocker.java
locker/src/test/java/org/killbill/commons/locker/memory/TestMemoryGlobalLocker.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.locker.memory; import java.io.IOException; import java.util.UUID; import org.killbill.commons.locker.GlobalLock; import org.killbill.commons.locker.GlobalLocker; import org.killbill.commons.locker.LockFailedException; import org.killbill.commons.request.Request; import org.killbill.commons.request.RequestData; import org.testng.Assert; import org.testng.annotations.Test; public class TestMemoryGlobalLocker { @Test(groups = "fast") public void testReentrantLockInOrder() throws IOException, LockFailedException { final String serviceLock = "MY_LOCK_2"; final String lockName = UUID.randomUUID().toString(); final String requestId = "12345"; Request.setPerThreadRequestData(new RequestData(requestId)); final GlobalLocker locker = new MemoryGlobalLocker(); final GlobalLock lock = locker.lockWithNumberOfTries(serviceLock, lockName, 3); Assert.assertFalse(locker.isFree(serviceLock, lockName)); // Re-acquire the createLock with the same requestId, should work final GlobalLock reentrantLock = locker.lockWithNumberOfTries(serviceLock, lockName, 1); reentrantLock.release(); Assert.assertFalse(locker.isFree(serviceLock, lockName)); lock.release(); Assert.assertTrue(locker.isFree(serviceLock, lockName)); } @Test(groups = "fast") public void testReentrantLockOufOfOrder() throws IOException, LockFailedException { final String serviceLock = "MY_LOCK_3"; final String lockName = UUID.randomUUID().toString(); final String requestId = "12345"; Request.setPerThreadRequestData(new RequestData(requestId)); final GlobalLocker locker = new MemoryGlobalLocker(); final GlobalLock lock = locker.lockWithNumberOfTries(serviceLock, lockName, 3); Assert.assertFalse(locker.isFree(serviceLock, lockName)); // Re-acquire the createLock with the same requestId, should work final GlobalLock reentrantLock = locker.lockWithNumberOfTries(serviceLock, lockName, 1); lock.release(); Assert.assertFalse(locker.isFree(serviceLock, lockName)); reentrantLock.release(); Assert.assertTrue(locker.isFree(serviceLock, lockName)); } @Test(groups = "fast") public void testReentrantNLevelLock() throws IOException, LockFailedException { final String serviceLock = "MY_LOCK_N"; final String lockName = UUID.randomUUID().toString(); final String requestId = "44444"; Request.setPerThreadRequestData(new RequestData(requestId)); final GlobalLocker locker = new MemoryGlobalLocker(); final GlobalLock lock = locker.lockWithNumberOfTries(serviceLock, lockName, 3); Assert.assertFalse(locker.isFree(serviceLock, lockName)); // Re-acquire the createLock with the same requestId, should work final GlobalLock reentrantLock1 = locker.lockWithNumberOfTries(serviceLock, lockName, 1); lock.release(); Assert.assertFalse(locker.isFree(serviceLock, lockName)); final GlobalLock reentrantLock2 = locker.lockWithNumberOfTries(serviceLock, lockName, 1); reentrantLock1.release(); Assert.assertFalse(locker.isFree(serviceLock, lockName)); final GlobalLock reentrantLock3 = locker.lockWithNumberOfTries(serviceLock, lockName, 1); reentrantLock3.release(); Assert.assertFalse(locker.isFree(serviceLock, lockName)); reentrantLock2.release(); Assert.assertTrue(locker.isFree(serviceLock, lockName)); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/locker/src/main/java/org/killbill/commons/locker/LockFailedException.java
locker/src/main/java/org/killbill/commons/locker/LockFailedException.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.locker; public class LockFailedException extends Exception { public LockFailedException() { super(); } public LockFailedException(final Throwable t) { super(t); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/locker/src/main/java/org/killbill/commons/locker/GlobalLocker.java
locker/src/main/java/org/killbill/commons/locker/GlobalLocker.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.locker; public interface GlobalLocker { GlobalLock lockWithNumberOfTries(String service, String lockKey, int retry) throws LockFailedException; boolean isFree(String service, String lockKey); }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/locker/src/main/java/org/killbill/commons/locker/ResetReentrantLockCallback.java
locker/src/main/java/org/killbill/commons/locker/ResetReentrantLockCallback.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.locker; public interface ResetReentrantLockCallback { boolean reset(String lockName); }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/locker/src/main/java/org/killbill/commons/locker/GlobalLockDao.java
locker/src/main/java/org/killbill/commons/locker/GlobalLockDao.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.locker; import java.sql.Connection; import java.sql.SQLException; import java.util.concurrent.TimeUnit; public interface GlobalLockDao { boolean lock(final Connection connection, final String lockName, final long timeout, final TimeUnit timeUnit) throws SQLException; boolean releaseLock(final Connection connection, final String lockName) throws SQLException; boolean isLockFree(final Connection connection, final String lockName) throws SQLException; }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/locker/src/main/java/org/killbill/commons/locker/GlobalLock.java
locker/src/main/java/org/killbill/commons/locker/GlobalLock.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.locker; public interface GlobalLock { void release(); }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/locker/src/main/java/org/killbill/commons/locker/GlobalLockBase.java
locker/src/main/java/org/killbill/commons/locker/GlobalLockBase.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.locker; import java.sql.Connection; import java.sql.SQLException; import org.killbill.commons.profiling.Profiling; import org.killbill.commons.profiling.Profiling.WithProfilingCallback; import org.killbill.commons.profiling.ProfilingFeature.ProfilingFeatureType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class GlobalLockBase implements GlobalLock { private static final Logger logger = LoggerFactory.getLogger(GlobalLockBase.class); private final GlobalLockDao lockDao; private final Connection connection; private final String lockName; private final ResetReentrantLockCallback resetCallback; private final Profiling<Void, RuntimeException> prof; public GlobalLockBase(final Connection connection, final String lockName, final GlobalLockDao lockDao, final ResetReentrantLockCallback resetCallback) { this.lockDao = lockDao; this.connection = connection; this.lockName = lockName; this.resetCallback = resetCallback; this.prof = new Profiling<>(); } @Override public void release() { prof.executeWithProfiling(ProfilingFeatureType.GLOCK, "release", new WithProfilingCallback<Void, RuntimeException>() { @Override public Void execute() throws RuntimeException { if (resetCallback != null && !resetCallback.reset(lockName)) { // We are not the last one using that lock, bail early (AND don't close the connection)... return null; } try { lockDao.releaseLock(connection, lockName); } catch (final SQLException e) { logger.warn("Unable to release lock for " + lockName, e); } finally { try { connection.close(); } catch (final SQLException e) { logger.warn("Unable to close connection", e); } } 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/locker/src/main/java/org/killbill/commons/locker/ReentrantLock.java
locker/src/main/java/org/killbill/commons/locker/ReentrantLock.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.locker; import org.killbill.commons.request.Request; import org.killbill.commons.request.RequestData; import java.util.HashMap; import java.util.Map; public class ReentrantLock { private final Map<String, LockHolder> lockTable; public ReentrantLock() { this.lockTable = new HashMap<String, LockHolder>(); } public enum ReentrantLockState { FREE, HELD_OWNER, HELD_NOT_OWNER } public static class TryAcquireLockState { private final ReentrantLockState lockState; private final GlobalLock originalLock; public TryAcquireLockState(final ReentrantLockState lockState) { this(lockState, null); } public TryAcquireLockState(final ReentrantLockState lockState, final GlobalLock originalLock) { this.lockState = lockState; this.originalLock = originalLock; } public ReentrantLockState getLockState() { return lockState; } public GlobalLock getOriginalLock() { return originalLock; } } /** * Atomically increment the refCount lock if we are already the owner of that lock. * * @param lockName * @return the ReentrantLockState: lock is FREE, or we already hold it (and incremented the refCount) or it held by somebody else */ public TryAcquireLockState tryAcquireLockForExistingOwner(final String lockName) { synchronized (lockTable) { final LockHolder lockHolder = lockTable.get(lockName); if (lockHolder == null) { return new TryAcquireLockState(ReentrantLockState.FREE); } final String maybeNullRequestId = getRequestId(); if (maybeNullRequestId == null || !lockHolder.getRequestId().equals(maybeNullRequestId)) { return new TryAcquireLockState(ReentrantLockState.HELD_NOT_OWNER); } else { // Increment value before we return while we hold the lockTable lock. lockHolder.increment(); return new TryAcquireLockState(ReentrantLockState.HELD_OWNER, lockHolder.getOriginalLock()); } } } /** * Create a new LockHolder. This is done *after* the distributed lock was acquired. * * @param lockName */ public void createLock(final String lockName, final GlobalLock originalLock) { final String requestId = getRequestId(); if (requestId == null) { return; } synchronized (lockTable) { LockHolder lockHolder = lockTable.get(lockName); if (lockHolder != null) { throw new IllegalStateException(String.format("ReentrantLock createLock %s : lock already current request = %s, owner request = %s", lockName, requestId, lockHolder.getRequestId())); } lockHolder = new LockHolder(requestId, originalLock); lockTable.put(lockName, lockHolder); lockHolder.increment(); } } /** * Release a lock. This is always called when the resources are feed * * @param lockName * @return true if nobody still holds the reentrant lock (and thefeore distributed lock can be freed) */ public boolean releaseLock(final String lockName) { // In case there no requestId set, this was not a 'reentrant' lock, so nothing to do but we need to return true // so distributed lock can be released // final String requestId = getRequestId(); if (requestId == null) { return true; } synchronized (lockTable) { final LockHolder lockHolder = lockTable.get(lockName); if (lockHolder == null) { throw new IllegalStateException(String.format("ReentrantLock releaseLock %s : cannot find lock in the table, current request = %s", lockName, requestId)); } if (!lockHolder.getRequestId().equals(requestId)) { throw new IllegalStateException(String.format("ReentrantLock releaseLock %s : current request = %s, owner request = %s", lockName, requestId, lockHolder.getRequestId())); } final boolean free = lockHolder.decrement(); if (free) { lockTable.remove(lockName); } return free; } } private String getRequestId() { final RequestData requestData = Request.getPerThreadRequestData(); return requestData != null ? requestData.getRequestId() : null; } private static class LockHolder { private final String requestId; private final GlobalLock originalLock; private int refCount; public LockHolder(final String requestId, final GlobalLock originalLock) { this.requestId = requestId; this.originalLock = originalLock; this.refCount = 0; } public void increment() { refCount++; } public boolean decrement() { return --refCount == 0; } public String getRequestId() { return requestId; } public GlobalLock getOriginalLock() { return originalLock; } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/locker/src/main/java/org/killbill/commons/locker/GlobalLockerBase.java
locker/src/main/java/org/killbill/commons/locker/GlobalLockerBase.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.locker; import java.util.concurrent.TimeUnit; import org.killbill.commons.locker.ReentrantLock.TryAcquireLockState; import org.killbill.commons.profiling.Profiling; import org.killbill.commons.profiling.Profiling.WithProfilingCallback; import org.killbill.commons.profiling.ProfilingFeature.ProfilingFeatureType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class GlobalLockerBase implements GlobalLocker { protected static final long DEFAULT_TIMEOUT_MILLIS = 100L; protected static final Logger logger = LoggerFactory.getLogger(GlobalLockerBase.class); protected final long timeout; protected final TimeUnit timeUnit; protected final ReentrantLock lockTable; private final Profiling<GlobalLock, LockFailedException> prof; public GlobalLockerBase(final long timeout, final TimeUnit timeUnit) { this.timeout = timeout; this.timeUnit = timeUnit; this.lockTable = new ReentrantLock(); this.prof = new Profiling<GlobalLock, LockFailedException>(); } @Override public GlobalLock lockWithNumberOfTries(final String service, final String lockKey, final int retry) throws LockFailedException { return prof.executeWithProfiling(ProfilingFeatureType.GLOCK, "lock", new WithProfilingCallback<GlobalLock, LockFailedException>() { @Override public GlobalLock execute() throws LockFailedException { final String lockName = getLockName(service, lockKey); int tries_left = retry; while (tries_left-- > 0) { final GlobalLock lock = lock(lockName); if (lock != null) { return lock; } if (tries_left > 0) { sleep(); } } logger.warn(String.format("Failed to acquire lock %s for service %s after %s retries", lockKey, service, retry)); throw new LockFailedException(); } }); } protected GlobalLock lock(final String lockName) { final TryAcquireLockState lockState = lockTable.tryAcquireLockForExistingOwner(lockName); if (lockState.getLockState() == ReentrantLock.ReentrantLockState.HELD_OWNER) { return lockState.getOriginalLock(); } if (lockState.getLockState() == ReentrantLock.ReentrantLockState.HELD_NOT_OWNER) { // In that case, we need to respect the provided timeout value try { Thread.sleep(TimeUnit.MILLISECONDS.convert(timeout, timeUnit)); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); logger.warn("lock got interrupted", e); } return null; } return doLock(lockName); } protected abstract GlobalLock doLock(final String lockName); protected abstract String getLockName(final String service, final String lockKey); private void sleep() { try { Thread.sleep(TimeUnit.MILLISECONDS.convert(timeout, timeUnit)); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); logger.warn("GlobalLockerBase got interrupted", e); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/locker/src/main/java/org/killbill/commons/locker/GlobalLockerBaseWithDao.java
locker/src/main/java/org/killbill/commons/locker/GlobalLockerBaseWithDao.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.locker; import java.sql.Connection; import java.sql.SQLException; import java.util.concurrent.TimeUnit; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class GlobalLockerBaseWithDao extends GlobalLockerBase { private static final Logger logger = LoggerFactory.getLogger(GlobalLockerBaseWithDao.class); protected final GlobalLockDao globalLockDao; private final DataSource dataSource; public GlobalLockerBaseWithDao(final DataSource dataSource, final GlobalLockDao globalLockDao, final long timeout, final TimeUnit timeUnit) { super(timeout, timeUnit); this.dataSource = dataSource; this.globalLockDao = globalLockDao; } @Override public boolean isFree(final String service, final String lockKey) { final String lockName = getLockName(service, lockKey); Connection connection = null; try { connection = dataSource.getConnection(); return globalLockDao.isLockFree(connection, lockName); } catch (final SQLException e) { logger.warn("Unable to check if lock is free", e); return false; } finally { if (connection != null) { try { connection.close(); } catch (final SQLException e) { logger.warn("Unable to close connection", e); } } } } @Override protected GlobalLock doLock(final String lockName) { Connection connection = null; boolean obtained = false; try { connection = dataSource.getConnection(); obtained = globalLockDao.lock(connection, lockName, timeout, timeUnit); if (obtained) { final GlobalLock lock = getGlobalLock(connection, lockName, new ResetReentrantLockCallback() { @Override public boolean reset(final String lockName) { return lockTable.releaseLock(lockName); } }); lockTable.createLock(lockName, lock); return lock; } } catch (final SQLException e) { logger.warn("Unable to obtain lock for {}", lockName, e); } finally { if (!obtained && connection != null) { try { connection.close(); } catch (final SQLException e) { logger.warn("Unable to close connection", e); } } } return null; } protected abstract GlobalLock getGlobalLock(final Connection connection, final String lockName, final ResetReentrantLockCallback resetCb); }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/locker/src/main/java/org/killbill/commons/locker/postgresql/PostgreSQLGlobalLockDao.java
locker/src/main/java/org/killbill/commons/locker/postgresql/PostgreSQLGlobalLockDao.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.locker.postgresql; import org.killbill.commons.locker.GlobalLockDao; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.concurrent.TimeUnit; // Note: the lock is connection specific (closing the connection releases the lock) public class PostgreSQLGlobalLockDao implements GlobalLockDao { @Override public boolean lock(final Connection connection, final String lockName, final long timeout, final TimeUnit timeUnit) throws SQLException { final String sql = String.format("SELECT pg_try_advisory_lock(%s);", lockName); return executeLockQuery(connection, sql); } @Override public boolean releaseLock(final Connection connection, final String lockName) throws SQLException { final String sql = String.format("SELECT pg_advisory_unlock(%s);", lockName); return executeLockQuery(connection, sql); } @Override public boolean isLockFree(final Connection connection, final String lockName) throws SQLException { final String sql = String.format("SELECT CASE WHEN pg_try_advisory_lock(%s) THEN pg_advisory_unlock(%s) ELSE FALSE END;", lockName, lockName); return executeLockQuery(connection, sql); } private boolean executeLockQuery(final Connection connection, final String query) throws SQLException { try (final Statement statement = connection.createStatement(); final ResultSet rs = statement.executeQuery(query)) { return rs.next() && (rs.getBoolean(1)); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/locker/src/main/java/org/killbill/commons/locker/postgresql/PostgreSQLGlobalLock.java
locker/src/main/java/org/killbill/commons/locker/postgresql/PostgreSQLGlobalLock.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.locker.postgresql; import org.killbill.commons.locker.GlobalLock; import org.killbill.commons.locker.GlobalLockBase; import org.killbill.commons.locker.GlobalLockDao; import org.killbill.commons.locker.ResetReentrantLockCallback; import java.sql.Connection; public class PostgreSQLGlobalLock extends GlobalLockBase implements GlobalLock { public PostgreSQLGlobalLock(final Connection connection, final String lockName, final GlobalLockDao lockDao, final ResetReentrantLockCallback resetCb) { super(connection, lockName, lockDao, resetCb); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/locker/src/main/java/org/killbill/commons/locker/postgresql/PostgreSQLGlobalLocker.java
locker/src/main/java/org/killbill/commons/locker/postgresql/PostgreSQLGlobalLocker.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.locker.postgresql; import java.nio.ByteBuffer; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.Connection; import java.util.concurrent.TimeUnit; import javax.sql.DataSource; import org.killbill.commons.locker.GlobalLock; import org.killbill.commons.locker.GlobalLocker; import org.killbill.commons.locker.GlobalLockerBaseWithDao; import org.killbill.commons.locker.ResetReentrantLockCallback; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static java.nio.charset.StandardCharsets.UTF_8; public class PostgreSQLGlobalLocker extends GlobalLockerBaseWithDao implements GlobalLocker { private static final Logger logger = LoggerFactory.getLogger(PostgreSQLGlobalLocker.class); public PostgreSQLGlobalLocker(final DataSource dataSource) { this(dataSource, DEFAULT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); } public PostgreSQLGlobalLocker(final DataSource dataSource, final long timeout, final TimeUnit timeUnit) { super(dataSource, new PostgreSQLGlobalLockDao(), timeout, timeUnit); } @Override protected GlobalLock getGlobalLock(final Connection connection, final String lockName, final ResetReentrantLockCallback resetCb) { return new PostgreSQLGlobalLock(connection, lockName, globalLockDao, resetCb); } protected String getLockName(final String service, final String lockKey) { final String lockName = service + "-" + lockKey; try { final MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); final byte[] bytes = messageDigest.digest(lockName.getBytes(UTF_8)); return String.valueOf(ByteBuffer.wrap(bytes).getLong()); } catch (final NoSuchAlgorithmException e) { logger.warn("Unable to allocate MessageDigest", e); return String.valueOf(lockName.hashCode()); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/locker/src/main/java/org/killbill/commons/locker/mysql/MysqlGlobalLockDao.java
locker/src/main/java/org/killbill/commons/locker/mysql/MysqlGlobalLockDao.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.locker.mysql; import org.killbill.commons.locker.GlobalLockDao; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.concurrent.TimeUnit; // Note: the MySQL lock is connection specific (closing the connection releases the lock) public class MysqlGlobalLockDao implements GlobalLockDao { @Override public boolean lock(final Connection connection, final String lockName, final long timeout, final TimeUnit timeUnit) throws SQLException { // // We pass 0 so as to not wait at all. // This is not optimal but mysql only supports seconds and also it make the code more readable/symetrical // by having the same implementation between mysql and postgreSQL (which does not have timeout) // final String sql = String.format("select GET_LOCK('%s', %d);", lockName.replace("'", "\'"), 0); return executeLockQuery(connection, sql); } @Override public boolean releaseLock(final Connection connection, final String lockName) throws SQLException { final String sql = String.format("select RELEASE_LOCK('%s');", lockName.replace("'", "\'")); return executeLockQuery(connection, sql); } @Override public boolean isLockFree(final Connection connection, final String lockName) throws SQLException { final String sql = String.format("select IS_FREE_LOCK('%s');", lockName.replace("'", "\'")); return executeLockQuery(connection, sql); } private boolean executeLockQuery(final Connection connection, final String query) throws SQLException { try (final Statement statement = connection.createStatement(); final ResultSet rs = statement.executeQuery(query)) { return rs.next() && (rs.getByte(1) == 1); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/locker/src/main/java/org/killbill/commons/locker/mysql/MySqlGlobalLocker.java
locker/src/main/java/org/killbill/commons/locker/mysql/MySqlGlobalLocker.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.locker.mysql; import org.killbill.commons.locker.GlobalLock; import org.killbill.commons.locker.GlobalLocker; import org.killbill.commons.locker.GlobalLockerBaseWithDao; import org.killbill.commons.locker.ResetReentrantLockCallback; import javax.sql.DataSource; import java.sql.Connection; import java.util.concurrent.TimeUnit; public class MySqlGlobalLocker extends GlobalLockerBaseWithDao implements GlobalLocker { public MySqlGlobalLocker(final DataSource dataSource) { this(dataSource, DEFAULT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); } public MySqlGlobalLocker(final DataSource dataSource, final long timeout, final TimeUnit timeUnit) { super(dataSource, new MysqlGlobalLockDao(), timeout, timeUnit); } @Override protected GlobalLock getGlobalLock(final Connection connection, final String lockName, final ResetReentrantLockCallback resetCb) { return new MysqlGlobalLock(connection, lockName, globalLockDao, resetCb); } protected String getLockName(final String service, final String lockKey) { return service + "-" + lockKey; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/locker/src/main/java/org/killbill/commons/locker/mysql/MysqlGlobalLock.java
locker/src/main/java/org/killbill/commons/locker/mysql/MysqlGlobalLock.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.locker.mysql; import org.killbill.commons.locker.GlobalLock; import org.killbill.commons.locker.GlobalLockBase; import org.killbill.commons.locker.GlobalLockDao; import org.killbill.commons.locker.ResetReentrantLockCallback; import java.sql.Connection; public class MysqlGlobalLock extends GlobalLockBase implements GlobalLock { public MysqlGlobalLock(final Connection connection, final String lockName, final GlobalLockDao lockDao, final ResetReentrantLockCallback resetCb) { super(connection, lockName, lockDao, resetCb); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/locker/src/main/java/org/killbill/commons/locker/memory/MemoryGlobalLocker.java
locker/src/main/java/org/killbill/commons/locker/memory/MemoryGlobalLocker.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.locker.memory; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.killbill.commons.locker.GlobalLock; import org.killbill.commons.locker.GlobalLocker; import org.killbill.commons.locker.GlobalLockerBase; public class MemoryGlobalLocker extends GlobalLockerBase implements GlobalLocker { private final Map<String, AtomicBoolean> locks = new ConcurrentHashMap<String, AtomicBoolean>(); public MemoryGlobalLocker() { super(DEFAULT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); } @Override public synchronized boolean isFree(final String service, final String lockKey) { final String lockName = getLockName(service, lockKey); return isFree(lockName); } private synchronized Boolean isFree(final String lockName) { final AtomicBoolean lock = locks.get(lockName); return lock == null || !lock.get(); } @Override protected synchronized GlobalLock doLock(final String lockName) { if (!isFree(lockName)) { return null; } if (locks.get(lockName) == null) { locks.put(lockName, new AtomicBoolean(true)); } else { locks.get(lockName).set(true); } final GlobalLock lock = new GlobalLock() { @Override public void release() { if (lockTable.releaseLock(lockName)) { locks.get(lockName).set(false); } } }; lockTable.createLock(lockName, lock); return lock; } @Override protected String getLockName(final String service, final String lockKey) { return service + "-" + lockKey; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/HandyMapThing.java
jdbi/src/test/java/org/skife/jdbi/HandyMapThing.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi; import java.util.HashMap; /** * */ public class HandyMapThing<K> extends HashMap<K, Object> { public HandyMapThing<K> add(K k, Object v) { this.put(k, v); return this; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/derby/TestDerbyStuff.java
jdbi/src/test/java/org/skife/jdbi/derby/TestDerbyStuff.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.derby; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.JDBITests; import java.sql.Connection; import java.sql.Statement; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @Category(JDBITests.class) public class TestDerbyStuff { private final DerbyHelper derbyHelper = new DerbyHelper(); @Test public void testNoExceptionOnCreationAndDeletion() throws Exception { try { derbyHelper.start(); derbyHelper.stop(); } catch (Exception e) { fail("Unable to create and delete test directory: " + e.getMessage()); } } @Test public void testCreateSchema() throws Exception { derbyHelper.start(); derbyHelper.dropAndCreateSomething(); final Connection conn = derbyHelper.getConnection(); final Statement stmt = conn.createStatement(); assertTrue(stmt.execute("select count(*) from something")); stmt.close(); conn.close(); derbyHelper.stop(); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/derby/DerbyHelper.java
jdbi/src/test/java/org/skife/jdbi/derby/DerbyHelper.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.derby; import org.apache.derby.jdbc.EmbeddedDataSource; import org.skife.jdbi.HandyMapThing; import java.io.File; import java.io.IOException; import java.sql.Connection; import java.sql.Driver; import java.sql.SQLException; import java.sql.Statement; import java.util.UUID; import javax.sql.DataSource; public class DerbyHelper { public static final String DERBY_SYSTEM_HOME = "target/test-db"; private Driver driver; private boolean running = false; private DataSource dataSource; private final String dbName; public DerbyHelper() { this.dbName = "testing-" + UUID.randomUUID().toString(); } public void start() throws SQLException, IOException { if (!running) { System.setProperty("derby.system.home", DERBY_SYSTEM_HOME); File db = new File("target/test-db"); db.mkdirs(); EmbeddedDataSource newDataSource = new EmbeddedDataSource(); newDataSource.setCreateDatabase("create"); newDataSource.setDatabaseName(dbName); dataSource = newDataSource; final Connection conn = dataSource.getConnection(); conn.close(); running = true; } } public void stop() throws SQLException { final Connection conn = getConnection(); final Statement delete = conn.createStatement(); try { delete.execute("delete from something"); } catch (SQLException e) { // may not exist } delete.close(); final String[] drops = {"drop table something", "drop function do_it", "drop procedure INSERTSOMETHING"}; for (String drop : drops) { final Statement stmt = conn.createStatement(); try { stmt.execute(drop); } catch (Exception e) { // may not exist } } } public Connection getConnection() throws SQLException { return dataSource.getConnection(); } public String getDbName() { return dbName; } public String getJdbcConnectionString() { return "jdbc:derby:" + getDbName(); } public void dropAndCreateSomething() throws SQLException { final Connection conn = getConnection(); final Statement create = conn.createStatement(); try { create.execute("create table something ( id integer, name varchar(50), integerValue integer, intValue integer )"); } catch (Exception e) { // probably still exists because of previous failed test, just delete then create.execute("delete from something"); } create.close(); conn.close(); } public DataSource getDataSource() { return dataSource; } public static String doIt() { return "it"; } public static <K> HandyMapThing<K> map(K k, Object v) { HandyMapThing<K>s = new HandyMapThing<K>(); return s.add(k, v); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestClasspathStatementLocator.java
jdbi/src/test/java/org/skife/jdbi/v2/TestClasspathStatementLocator.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import java.io.InputStream; import java.util.HashMap; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.exceptions.StatementException; import org.skife.jdbi.v2.exceptions.UnableToCreateStatementException; import org.skife.jdbi.v2.sqlobject.stringtemplate.TestingStatementContext; import org.skife.jdbi.v2.tweak.StatementLocator; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * */ @Category(JDBITests.class) public class TestClasspathStatementLocator extends DBITestCase { @Test public void testLocateNamedWithoutSuffix() throws Exception { Handle h = openHandle(); h.createStatement("insert-keith").execute(); assertEquals(1, h.select("select name from something").size()); } @Test public void testLocateNamedWithSuffix() throws Exception { Handle h = openHandle(); h.insert("insert-keith.sql"); assertEquals(1, h.select("select name from something").size()); } @Test public void testCommentsInExternalSql() throws Exception { Handle h = openHandle(); h.insert("insert-eric-with-comments"); assertEquals(1, h.select("select name from something").size()); } @Test public void testNamedPositionalNamedParamsInPrepared() throws Exception { Handle h = openHandle(); h.insert("insert-id-name", 3, "Tip"); assertEquals(1, h.select("select name from something").size()); } @Test public void testNamedParamsInExternal() throws Exception { Handle h = openHandle(); h.createStatement("insert-id-name").bind("id", 1).bind("name", "Tip").execute(); assertEquals(1, h.select("select name from something").size()); } @Test public void testUsefulExceptionForBackTracing() throws Exception { Handle h = openHandle(); try { h.createStatement("insert-id-name").bind("id", 1).execute(); fail("should have raised an exception"); } catch (StatementException e) { assertTrue(e.getMessage().contains("insert into something(id, name) values (:id, :name)")); assertTrue(e.getMessage().contains("insert into something(id, name) values (?, ?)")); assertTrue(e.getMessage().contains("insert-id-name")); } } @Test public void testTriesToParseNameIfNothingFound() throws Exception { Handle h = openHandle(); try { h.insert("this-does-not-exist.sql"); fail("Should have raised an exception"); } catch (UnableToCreateStatementException e) { assertTrue(true); } } @Test public void testCachesResultAfterFirstLookup() throws Exception { ClassLoader ctx_loader = Thread.currentThread().getContextClassLoader(); final AtomicInteger load_count = new AtomicInteger(0); Thread.currentThread().setContextClassLoader(new ClassLoader() { @Override public InputStream getResourceAsStream(final String name) { // will be called twice, once for raw name, once for name + .sql InputStream in = super.getResourceAsStream(name); load_count.incrementAndGet(); return in; } }); Handle h = openHandle(); h.execute("caches-result-after-first-lookup", 1, "Brian"); assertThat(load_count.get(), equalTo(2)); // two lookups, name and name.sql h.execute("caches-result-after-first-lookup", 2, "Sean"); assertThat(load_count.get(), equalTo(2)); // has not increased since previous Thread.currentThread().setContextClassLoader(ctx_loader); } @Test public void testCachesOriginalQueryWhenNotFound() throws Exception { StatementLocator statementLocator = new ClasspathStatementLocator(); StatementContext statementContext = new TestingStatementContext(new HashMap<String, Object>()) { @Override public Class<?> getSqlObjectType() { return TestClasspathStatementLocator.class; } }; String input = "missing query"; String located = statementLocator.locate(input, statementContext); assertEquals(input, located); // first time just caches it located = statementLocator.locate(input, statementContext); assertEquals(input, located); // second time reads from cache } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/DBITestCase.java
jdbi/src/test/java/org/skife/jdbi/v2/DBITestCase.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.skife.jdbi.derby.DerbyHelper; import org.skife.jdbi.v2.logging.NoOpLog; import org.skife.jdbi.v2.tweak.StatementLocator; import org.skife.jdbi.v2.tweak.TransactionHandler; import org.skife.jdbi.v2.tweak.transactions.LocalTransactionHandler; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * */ public abstract class DBITestCase { protected static final List<BasicHandle> HANDLES = new ArrayList<BasicHandle>(); private ExecutorService executor; protected static final DerbyHelper DERBY_HELPER = new DerbyHelper(); @BeforeClass public static void setUpClass() throws Exception { DERBY_HELPER.start(); } @Before public final void setUp() throws Exception { DERBY_HELPER.dropAndCreateSomething(); doSetUp(); } protected void doSetUp() throws Exception { } @After public final void tearDown() throws Exception { doTearDown(); } protected void doTearDown() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { for (BasicHandle handle : HANDLES) { handle.close(); } DERBY_HELPER.stop(); } protected StatementLocator getStatementLocator() { return new ClasspathStatementLocator(); } protected BasicHandle openHandle() throws SQLException { return openHandle(DERBY_HELPER.getConnection()); } protected BasicHandle openHandle(Connection connection) throws SQLException { BasicHandle h = new BasicHandle(getTransactionHandler(), getStatementLocator(), new CachingStatementBuilder(new DefaultStatementBuilder()), new ColonPrefixNamedParamStatementRewriter(), connection, new HashMap<String, Object>(), new NoOpLog(), TimingCollector.NOP_TIMING_COLLECTOR, new MappingRegistry(), new Foreman(), new ContainerFactoryRegistry()); HANDLES.add(h); return h; } protected TransactionHandler getTransactionHandler() { return new LocalTransactionHandler(); } protected <T> Future<T> run(Callable<T> it) { if (this.executor == null) { this.executor = Executors.newCachedThreadPool(); } return executor.submit(it); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestColonStatementRewriter.java
jdbi/src/test/java/org/skife/jdbi/v2/TestColonStatementRewriter.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.exceptions.UnableToCreateStatementException; import org.skife.jdbi.v2.tweak.RewrittenStatement; import java.util.HashMap; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.assertEquals; /** * */ @Category(JDBITests.class) public class TestColonStatementRewriter { private ColonPrefixNamedParamStatementRewriter rw; @Before public void setUp() throws Exception { this.rw = new ColonPrefixNamedParamStatementRewriter(); } private RewrittenStatement rewrite(String sql) { return rw.rewrite(sql, new Binding(), new ConcreteStatementContext(new HashMap<String, Object>())); } @Test public void testNewlinesOkay() throws Exception { RewrittenStatement rws = rewrite("select * from something\n where id = :id"); assertEquals("select * from something\n where id = ?", rws.getSql()); } @Test public void testOddCharacters() throws Exception { RewrittenStatement rws = rewrite("~* :boo ':nope' _%&^& *@ :id"); assertEquals("~* ? ':nope' _%&^& *@ ?", rws.getSql()); } @Test public void testNumbers() throws Exception { RewrittenStatement rws = rewrite(":bo0 ':nope' _%&^& *@ :id"); assertEquals("? ':nope' _%&^& *@ ?", rws.getSql()); } @Test public void testDollarSignOkay() throws Exception { RewrittenStatement rws = rewrite("select * from v$session"); assertEquals("select * from v$session", rws.getSql()); } @Test public void testHashInColumnNameOkay() throws Exception { RewrittenStatement rws = rewrite("select column# from thetable where id = :id"); assertEquals("select column# from thetable where id = ?", rws.getSql()); } @Test public void testBacktickOkay() throws Exception { RewrittenStatement rws = rewrite("select * from `v$session"); assertEquals("select * from `v$session", rws.getSql()); } @Test(expected = UnableToCreateStatementException.class) public void testBailsOutOnInvalidInput() throws Exception { rewrite("select * from something\n where id = :\u0087\u008e\u0092\u0097\u009c"); Assert.fail("Expected 'UnableToCreateStatementException' but got none"); } @Test public void testCachesRewrittenStatements() throws Exception { final AtomicInteger ctr = new AtomicInteger(0); rw = new ColonPrefixNamedParamStatementRewriter() { @Override protected ParsedStatement parseString(final String sql) throws IllegalArgumentException { ctr.incrementAndGet(); return super.parseString(sql); } }; rewrite("insert into something (id, name) values (:id, :name)"); assertEquals(1, ctr.get()); rewrite("insert into something (id, name) values (:id, :name)"); assertEquals(1, ctr.get()); } public void testCommentQuote() throws Exception { rewrite("select 1 /* ' \" */"); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestQueries.java
jdbi/src/test/java/org/skife/jdbi/v2/TestQueries.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.HandyMapThing; import org.skife.jdbi.v2.exceptions.NoResultsException; import org.skife.jdbi.v2.exceptions.StatementException; import org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException; import org.skife.jdbi.v2.tweak.ResultSetMapper; import org.skife.jdbi.v2.util.StringMapper; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @Category(JDBITests.class) public class TestQueries extends DBITestCase { private BasicHandle h; @Override public void doSetUp() throws Exception { h = openHandle(); } @Override public void doTearDown() throws Exception { if (h != null) h.close(); } @Test public void testCreateQueryObject() throws Exception { h.createStatement("insert into something (id, name) values (1, 'eric')").execute(); h.createStatement("insert into something (id, name) values (2, 'brian')").execute(); List<Map<String, Object>> results = h.createQuery("select * from something order by id").list(); assertEquals(2, results.size()); Map<String, Object> first_row = results.get(0); assertEquals("eric", first_row.get("name")); } @Test public void testMappedQueryObject() throws Exception { h.insert("insert into something (id, name) values (1, 'eric')"); h.insert("insert into something (id, name) values (2, 'brian')"); Query<Something> query = h.createQuery("select * from something order by id").map(Something.class); List<Something> r = query.list(); Something eric = r.get(0); assertEquals("eric", eric.getName()); assertEquals(1, eric.getId()); } @Test public void testMappedQueryObjectWithNulls() throws Exception { h.insert("insert into something (id, name, integerValue) values (1, 'eric', null)"); Query<Something> query = h.createQuery("select * from something order by id").map(Something.class); List<Something> r = query.list(); Something eric = r.get(0); assertEquals("eric", eric.getName()); assertEquals(1, eric.getId()); assertNull(eric.getIntegerValue()); } @Test public void testMappedQueryObjectWithNullForPrimitiveIntField() throws Exception { h.insert("insert into something (id, name, intValue) values (1, 'eric', null)"); Query<Something> query = h.createQuery("select * from something order by id").map(Something.class); List<Something> r = query.list(); Something eric = r.get(0); assertEquals("eric", eric.getName()); assertEquals(1, eric.getId()); assertEquals(0, eric.getIntValue()); } @Test public void testMapper() throws Exception { h.insert("insert into something (id, name) values (1, 'eric')"); h.insert("insert into something (id, name) values (2, 'brian')"); Query<String> query = h.createQuery("select name from something order by id").map(new ResultSetMapper<String>() { @Override public String map(int index, ResultSet r, StatementContext ctx) throws SQLException { return r.getString(1); } }); String name = query.list().get(0); assertEquals("eric", name); } @Test public void testConvenienceMethod() throws Exception { h.insert("insert into something (id, name) values (1, 'eric')"); h.insert("insert into something (id, name) values (2, 'brian')"); List<Map<String, Object>> r = h.select("select * from something order by id"); assertEquals(2, r.size()); assertEquals("eric", r.get(0).get("name")); } @Test public void testConvenienceMethodWithParam() throws Exception { h.insert("insert into something (id, name) values (1, 'eric')"); h.insert("insert into something (id, name) values (2, 'brian')"); List<Map<String, Object>> r = h.select("select * from something where id = ?", 1); assertEquals(1, r.size()); assertEquals("eric", r.get(0).get("name")); } @Test public void testPositionalArgWithNamedParam() throws Exception { h.insert("insert into something (id, name) values (1, 'eric')"); h.insert("insert into something (id, name) values (2, 'brian')"); List<Something> r = h.createQuery("select * from something where name = :name") .bind(0, "eric") .map(Something.class) .list(); assertEquals(1, r.size()); assertEquals("eric", r.get(0).getName()); } @Test public void testMixedSetting() throws Exception { h.insert("insert into something (id, name) values (1, 'eric')"); h.insert("insert into something (id, name) values (2, 'brian')"); List<Something> r = h.createQuery("select * from something where name = :name and id = :id") .bind(0, "eric") .bind("id", 1) .map(Something.class) .list(); assertEquals(1, r.size()); assertEquals("eric", r.get(0).getName()); } @Test public void testHelpfulErrorOnNothingSet() throws Exception { try { h.createQuery("select * from something where name = :name").list(); fail("should have raised exception"); } catch (UnableToExecuteStatementException e) { assertTrue("execution goes through here", true); } catch (Exception e) { fail("Raised incorrect exception"); } } @Test public void testFirstResult() throws Exception { h.insert("insert into something (id, name) values (1, 'eric')"); h.insert("insert into something (id, name) values (2, 'brian')"); Something r = h.createQuery("select * from something order by id") .map(Something.class) .first(); assertNotNull(r); assertEquals("eric", r.getName()); } @Test public void testIteratedResult() throws Exception { h.insert("insert into something (id, name) values (1, 'eric')"); h.insert("insert into something (id, name) values (2, 'brian')"); ResultIterator<Something> i = h.createQuery("select * from something order by id") .map(Something.class) .iterator(); assertTrue(i.hasNext()); Something first = i.next(); assertEquals("eric", first.getName()); assertTrue(i.hasNext()); Something second = i.next(); assertEquals(2, second.getId()); assertFalse(i.hasNext()); i.close(); } @Test public void testIteratorBehavior() throws Exception { h.insert("insert into something (id, name) values (1, 'eric')"); h.insert("insert into something (id, name) values (2, 'brian')"); ResultIterator<Something> i = h.createQuery("select * from something order by id") .map(Something.class) .iterator(); assertTrue(i.hasNext()); assertTrue(i.hasNext()); Something first = i.next(); assertEquals("eric", first.getName()); assertTrue(i.hasNext()); Something second = i.next(); assertEquals(2, second.getId()); assertFalse(i.hasNext()); i.close(); } @Test public void testIteratorBehavior2() throws Exception { h.insert("insert into something (id, name) values (1, 'eric')"); h.insert("insert into something (id, name) values (2, 'brian')"); ResultIterator<Something> i = h.createQuery("select * from something order by id") .map(Something.class) .iterator(); Something first = i.next(); assertEquals("eric", first.getName()); Something second = i.next(); assertEquals(2, second.getId()); assertFalse(i.hasNext()); i.close(); } @Test public void testIteratorBehavior3() throws Exception { h.insert("insert into something (id, name) values (1, 'eric')"); h.insert("insert into something (id, name) values (2, 'eric')"); int count = 0; for (Something s : h.createQuery("select * from something order by id").map(Something.class)) { count++; assertEquals("eric", s.getName()); } assertEquals(2, count); } @Test public void testFetchSize() throws Exception { h.createScript("default-data").execute(); Query<Something> q = h.createQuery("select id, name from something order by id").map(Something.class); q.setFetchSize(1); ResultIterator<Something> r = q.iterator(); assertTrue(r.hasNext()); r.next(); assertTrue(r.hasNext()); r.next(); assertFalse(r.hasNext()); } @Test public void testFirstWithNoResult() throws Exception { Something s = h.createQuery("select id, name from something").map(Something.class).first(); assertNull(s); } @Test public void testListWithMaxRows() throws Exception { h.prepareBatch("insert into something (id, name) values (:id, :name)") .add(1, "Brian") .add(2, "Keith") .add(3, "Eric") .execute(); assertEquals(1, h.createQuery("select id, name from something").map(Something.class).list(1).size()); assertEquals(2, h.createQuery("select id, name from something").map(Something.class).list(2).size()); } @Test public void testFold() throws Exception { h.prepareBatch("insert into something (id, name) values (:id, :name)") .add(1, "Brian") .add(2, "Keith") .execute(); Map<String, Integer> rs = h.createQuery("select id, name from something") .fold(new HashMap<String, Integer>(), new Folder2<Map<String, Integer>>() { @Override public Map<String, Integer> fold(Map<String, Integer> a, ResultSet rs, StatementContext context) throws SQLException { a.put(rs.getString("name"), rs.getInt("id")); return a; } }); assertEquals(2, rs.size()); assertEquals(Integer.valueOf(1), rs.get("Brian")); assertEquals(Integer.valueOf(2), rs.get("Keith")); } @Test public void testFold3() throws Exception { h.prepareBatch("insert into something (id, name) values (:id, :name)") .add(1, "Brian") .add(2, "Keith") .execute(); List<String> rs = h.createQuery("select name from something order by id") .map(StringMapper.FIRST) .fold(new ArrayList<String>(), new Folder3<List<String>, String>() { @Override public List<String> fold(List<String> a, String rs, FoldController ctl, StatementContext ctx) throws SQLException { a.add(rs); return a; } }); assertEquals(2, rs.size()); assertEquals(Arrays.asList("Brian", "Keith"), rs); } @Test public void testUsefulArgumentOutputForDebug() throws Exception { try { h.createStatement("insert into something (id, name) values (:id, :name)") .bind("name", "brian") .bind(7, 8) .bindFromMap(new HandyMapThing<String>().add("one", "two")) .bindFromProperties(new Object()) .execute(); } catch (StatementException e) { assertTrue(e.getMessage() .contains("arguments:{ positional:{7:8}, named:{name:'brian'}, finder:[{one=two},{lazy bean proprty arguments \"java.lang.Object")); } } @Test public void testStatementCustomizersPersistAfterMap() throws Exception { h.insert("insert into something (id, name) values (?, ?)", 1, "hello"); h.insert("insert into something (id, name) values (?, ?)", 2, "world"); List<Something> rs = h.createQuery("select id, name from something") .setMaxRows(1) .map(Something.class) .list(); assertEquals(1, rs.size()); } @Test public void testQueriesWithNullResultSets() throws Exception { try { h.select("insert into something (id, name) values (?, ?)", 1, "hello"); } catch (NoResultsException e) { return; } fail("expected NoResultsException"); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestForeman.java
jdbi/src/test/java/org/skife/jdbi/v2/TestForeman.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.tweak.Argument; import org.skife.jdbi.v2.tweak.ArgumentFactory; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import java.sql.PreparedStatement; import java.sql.SQLException; @Category(JDBITests.class) public class TestForeman { @Test public void testWaffling() { final Foreman foreman = new Foreman(); final Argument longArgument = foreman.waffle(Object.class, new Long(3L), null); assertSame(LongArgument.class, longArgument.getClass()); final Argument shortArgument = foreman.waffle(Object.class, (short) 2000, null); assertSame(ShortArgument.class, shortArgument.getClass()); final Argument stringArgument = foreman.waffle(Object.class, "I am a String!", null); assertSame(StringArgument.class, stringArgument.getClass()); } @Test public void testExplicitWaffling() { final Foreman foreman = new Foreman(); final Argument longArgument = foreman.waffle(Long.class, new Long(3L), null); assertSame(LongArgument.class, longArgument.getClass()); final Argument shortArgument = foreman.waffle(short.class, (short) 2000, null); assertSame(ShortArgument.class, shortArgument.getClass()); final Argument stringArgument = foreman.waffle(String.class, "I am a String!", null); assertSame(StringArgument.class, stringArgument.getClass()); } @Test public void testPull88WeirdClassArgumentFactory() { final Foreman foreman = new Foreman(); foreman.register(new WeirdClassArgumentFactory()); // Pull Request #88 changes the outcome of this waffle call from ObjectArgument to WeirdArgument // when using SqlStatement#bind(..., Object) and the Object is != null assertEquals(WeirdArgument.class, foreman.waffle(Weird.class, new Weird(), null).getClass()); assertEquals(ObjectArgument.class, foreman.waffle(Object.class, new Weird(), null).getClass()); } @Test public void testPull88NullClassArgumentFactory() { final Foreman foreman = new Foreman(); foreman.register(new WeirdClassArgumentFactory()); assertEquals(WeirdArgument.class, foreman.waffle(Weird.class, null, null).getClass()); assertEquals(ObjectArgument.class, foreman.waffle(Object.class, null, null).getClass()); } @Test public void testPull88WeirdValueArgumentFactory() { final Foreman foreman = new Foreman(); foreman.register(new WeirdValueArgumentFactory()); // Pull Request #88 changes the outcome of this waffle call from ObjectArgument to WeirdArgument // when using SqlStatement#bind(..., Object) and the Object is != null assertEquals(WeirdArgument.class, foreman.waffle(Weird.class, new Weird(), null).getClass()); assertEquals(WeirdArgument.class, foreman.waffle(Object.class, new Weird(), null).getClass()); } @Test public void testPull88NullValueArgumentFactory() { final Foreman foreman = new Foreman(); foreman.register(new WeirdValueArgumentFactory()); assertEquals(ObjectArgument.class, foreman.waffle(Weird.class, null, null).getClass()); assertEquals(ObjectArgument.class, foreman.waffle(Object.class, null, null).getClass()); } private static class Weird { } private static class WeirdClassArgumentFactory implements ArgumentFactory<Weird> { @Override public boolean accepts(Class<?> expectedType, Object value, StatementContext ctx) { return expectedType == Weird.class; } @Override public Argument build(Class<?> expectedType, Weird value, StatementContext ctx) { return new WeirdArgument(); } } private static class WeirdValueArgumentFactory implements ArgumentFactory<Weird> { @Override public boolean accepts(Class<?> expectedType, Object value, StatementContext ctx) { return value instanceof Weird; } @Override public Argument build(Class<?> expectedType, Weird value, StatementContext ctx) { return new WeirdArgument(); } } private static class WeirdArgument implements Argument { @Override public void apply(int position, PreparedStatement statement, StatementContext ctx) throws SQLException { } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestIterator.java
jdbi/src/test/java/org/skife/jdbi/v2/TestIterator.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @Category(JDBITests.class) public class TestIterator extends DBITestCase { private BasicHandle h; @Override public void doSetUp() throws Exception { h = openHandle(); } @Override public void doTearDown() throws Exception { assertTrue("Handle was not closed correctly!", h.isClosed()); } @Test public void testSimple() throws Exception { h.createStatement("insert into something (id, name) values (1, 'eric')").execute(); h.createStatement("insert into something (id, name) values (2, 'brian')").execute(); h.createStatement("insert into something (id, name) values (3, 'john')").execute(); ResultIterator<Map<String, Object>> it = h.createQuery("select * from something order by id") .cleanupHandle() .iterator(); assertTrue(it.hasNext()); it.next(); assertTrue(it.hasNext()); it.next(); assertTrue(it.hasNext()); it.next(); assertFalse(it.hasNext()); } @Test public void testEmptyWorksToo() throws Exception { ResultIterator<Map<String, Object>> it = h.createQuery("select * from something order by id") .cleanupHandle() .iterator(); assertFalse(it.hasNext()); } @Test public void testHasNext() throws Exception { h.createStatement("insert into something (id, name) values (1, 'eric')").execute(); h.createStatement("insert into something (id, name) values (2, 'brian')").execute(); h.createStatement("insert into something (id, name) values (3, 'john')").execute(); ResultIterator<Map<String, Object>> it = h.createQuery("select * from something order by id") .cleanupHandle() .iterator(); assertTrue(it.hasNext()); assertTrue(it.hasNext()); assertTrue(it.hasNext()); it.next(); assertTrue(it.hasNext()); assertTrue(it.hasNext()); assertTrue(it.hasNext()); it.next(); assertTrue(it.hasNext()); assertTrue(it.hasNext()); assertTrue(it.hasNext()); it.next(); assertFalse(it.hasNext()); assertFalse(it.hasNext()); assertFalse(it.hasNext()); } @Test public void testNext() throws Exception { h.createStatement("insert into something (id, name) values (1, 'eric')").execute(); h.createStatement("insert into something (id, name) values (2, 'brian')").execute(); h.createStatement("insert into something (id, name) values (3, 'john')").execute(); ResultIterator<Map<String, Object>> it = h.createQuery("select * from something order by id") .cleanupHandle() .iterator(); assertTrue(it.hasNext()); it.next(); it.next(); it.next(); assertFalse(it.hasNext()); } @Test public void testJustNext() throws Exception { h.createStatement("insert into something (id, name) values (1, 'eric')").execute(); h.createStatement("insert into something (id, name) values (2, 'brian')").execute(); h.createStatement("insert into something (id, name) values (3, 'john')").execute(); ResultIterator<Map<String, Object>> it = h.createQuery("select * from something order by id") .cleanupHandle() .iterator(); it.next(); it.next(); it.next(); } @Test public void testTwoTwo() throws Exception { h.createStatement("insert into something (id, name) values (1, 'eric')").execute(); h.createStatement("insert into something (id, name) values (2, 'brian')").execute(); h.createStatement("insert into something (id, name) values (3, 'john')").execute(); ResultIterator<Map<String, Object>> it = h.createQuery("select * from something order by id") .cleanupHandle() .iterator(); it.next(); it.next(); assertTrue(it.hasNext()); assertTrue(it.hasNext()); it.next(); assertFalse(it.hasNext()); assertFalse(it.hasNext()); } @Test public void testTwoOne() throws Exception { h.createStatement("insert into something (id, name) values (1, 'eric')").execute(); h.createStatement("insert into something (id, name) values (2, 'brian')").execute(); h.createStatement("insert into something (id, name) values (3, 'john')").execute(); ResultIterator<Map<String, Object>> it = h.createQuery("select * from something order by id") .cleanupHandle() .iterator(); assertTrue(it.hasNext()); it.next(); it.next(); assertTrue(it.hasNext()); it.next(); assertFalse(it.hasNext()); } @Test public void testExplodeIterator() throws Exception { h.createStatement("insert into something (id, name) values (1, 'eric')").execute(); h.createStatement("insert into something (id, name) values (2, 'brian')").execute(); h.createStatement("insert into something (id, name) values (3, 'john')").execute(); ResultIterator<Map<String, Object>> it = h.createQuery("select * from something order by id") .cleanupHandle() .iterator(); try { assertTrue(it.hasNext()); it.next(); assertTrue(it.hasNext()); it.next(); assertTrue(it.hasNext()); it.next(); assertFalse(it.hasNext()); } catch (Throwable t) { fail("unexpected throwable:" + t.getMessage()); } try { it.next(); fail("Expected IllegalStateException did not show up!"); } catch (IllegalStateException iae) { // TestCase does not deal with the annotations... } } @Test public void testEmptyExplosion() throws Exception { ResultIterator<Map<String, Object>> it = h.createQuery("select * from something order by id") .cleanupHandle() .iterator(); try { it.next(); fail("Expected IllegalStateException did not show up!"); } catch (IllegalStateException iae) { // TestCase does not deal with the annotations... } } @Test public void testNonPathologicalJustNext() throws Exception { h.createStatement("insert into something (id, name) values (1, 'eric')").execute(); // Yes, you *should* use first(). But sometimes, an iterator is passed 17 levels deep and then // used in this way (Hello Jackson!). final Map<String, Object> result = h.createQuery("select * from something order by id") .cleanupHandle() .iterator() .next(); assertEquals(1, result.get("id")); assertEquals("eric", result.get("name")); } @Test public void testStillLeakingJustNext() throws Exception { h.createStatement("insert into something (id, name) values (1, 'eric')").execute(); h.createStatement("insert into something (id, name) values (2, 'brian')").execute(); // Yes, you *should* use first(). But sometimes, an iterator is passed 17 levels deep and then // used in this way (Hello Jackson!). final Map<String, Object> result = h.createQuery("select * from something order by id") .cleanupHandle() .iterator() .next(); assertEquals(1, result.get("id")); assertEquals("eric", result.get("name")); assertFalse(h.isClosed()); // The Query created by createQuery() above just leaked a Statement and a ResultSet. It is necessary // to explicitly close the iterator in that case. However, as this test case is using the CachingStatementBuilder, // closing the handle will close the statements (which also closes the result sets). // // Don't try this at home folks. It is still very possible to leak stuff with the iterators. h.close(); } @Test public void testLessLeakingJustNext() throws Exception { h.createStatement("insert into something (id, name) values (1, 'eric')").execute(); h.createStatement("insert into something (id, name) values (2, 'brian')").execute(); final ResultIterator<Map<String, Object>> it = h.createQuery("select * from something order by id") .cleanupHandle() .iterator(); try { final Map<String, Object> result = it.next(); assertEquals(1, result.get("id")); assertEquals("eric", result.get("name")); assertFalse(h.isClosed()); } finally { it.close(); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestBeanMapper.java
jdbi/src/test/java/org/skife/jdbi/v2/TestBeanMapper.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.skife.jdbi.v2; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import org.mockito.Mockito; import org.testng.Assert; import org.testng.annotations.Test; public class TestBeanMapper { private <T> BeanMapper<T> newBeanMapper(final Class<T> beanClass) { final BeanMapper<T> toSpy = new BeanMapper<>(beanClass); return Mockito.spy(toSpy); } private ResultSet createResultSet() throws SQLException { final ResultSetMetaData rsmd = Mockito.mock(ResultSetMetaData.class); Mockito.when(rsmd.getColumnCount()).thenReturn(3); Mockito.when(rsmd.getColumnLabel(1)).thenReturn("name"); Mockito.when(rsmd.getColumnLabel(2)).thenReturn("age"); Mockito.when(rsmd.getColumnLabel(3)).thenReturn("address"); // mocking result from db, make sure that db operation considered as valid operation final ResultSet rs = Mockito.mock(ResultSet.class); Mockito.when(rs.getMetaData()).thenReturn(rsmd); Mockito.when(rs.getString(1)).thenReturn("some name"); Mockito.when(rs.getInt(2)).thenReturn(30); Mockito.when(rs.getString(3)).thenReturn("some address"); // make sure that db operation considered as valid operation return rs; } @Test(groups = "fast") public void testMapWithClassWithSetter() throws SQLException { final BeanMapper<PersonWithSetter> spied = newBeanMapper(PersonWithSetter.class); final ResultSet rs = createResultSet(); final PersonWithSetter mapped = spied.map(0, rs, null); Assert.assertEquals(mapped.getName(), "some name"); Assert.assertEquals(mapped.getAge(), 30); } @Test(groups = "fast") public void testMapWithClassWithoutSetter() throws SQLException { final BeanMapper<PersonWithoutSetter> spied = newBeanMapper(PersonWithoutSetter.class); final ResultSet rs = createResultSet(); try { spied.map(0, rs, null); Assert.fail("PersonWithoutSetter contains no setter method, and should fails"); } catch (final IllegalArgumentException e) { Assert.assertTrue(e.getMessage().contains("No appropriate method to write property")); } } static class PersonWithSetter { private String name; private int age; public String getName() { return name; } public void setName(final String name) { this.name = name; } public int getAge() { return age; } public void setAge(final int age) { this.age = age; } } static class PersonWithoutSetter { // No setter for address private String name; private int age; private String address; public String getName() { return name; } public void setName(final String name) { this.name = name; } public int getAge() { return age; } public void setAge(final int age) { this.age = age; } public String getAddress() { return address; } public void doSomething(final String address) { this.address = address; } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestStatements.java
jdbi/src/test/java/org/skife/jdbi/v2/TestStatements.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.junit.Test; import org.junit.experimental.categories.Category; import static org.junit.Assert.assertEquals; /** * */ @Category(JDBITests.class) public class TestStatements extends DBITestCase { private BasicHandle h; @Override public void doSetUp() throws Exception { h = openHandle(); } @Override public void doTearDown() throws Exception { if (h != null) h.close(); } @Test public void testStatement() throws Exception { int rows = h.createStatement("insert into something (id, name) values (1, 'eric')").execute(); assertEquals(1, rows); } @Test public void testSimpleInsert() throws Exception { int c = h.insert("insert into something (id, name) values (1, 'eric')"); assertEquals(1, c); } @Test public void testUpdate() throws Exception { h.insert("insert into something (id, name) values (1, 'eric')"); h.createStatement("update something set name = 'ERIC' where id = 1").execute(); Something eric = h.createQuery("select * from something where id = 1").map(Something.class).list().get(0); assertEquals("ERIC", eric.getName()); } @Test public void testSimpleUpdate() throws Exception { h.insert("insert into something (id, name) values (1, 'eric')"); h.update("update something set name = 'cire' where id = 1"); Something eric = h.createQuery("select * from something where id = 1").map(Something.class).list().get(0); assertEquals("cire", eric.getName()); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestScript.java
jdbi/src/test/java/org/skife/jdbi/v2/TestScript.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.exceptions.StatementException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; /** * */ @Category(JDBITests.class) public class TestScript extends DBITestCase { @Test public void testScriptStuff() throws Exception { Handle h = openHandle(); Script s = h.createScript("default-data"); s.execute(); assertEquals(2, h.select("select * from something").size()); } @Test public void testScriptWithComments() throws Exception{ BasicHandle h = openHandle(); Script script = h.createScript("insert-script-with-comments"); script.execute(); assertEquals(3, h.select("select * from something").size()); } @Test public void testScriptAsSetOfSeparateStatements() throws Exception { try { BasicHandle h = openHandle(); Script script = h.createScript("malformed-sql-script"); script.executeAsSeparateStatements(); fail("Should fail because the script is malformed"); } catch (StatementException e) { StatementContext context = e.getStatementContext(); assertEquals(context.getRawSql().trim(), "insert into something(id, name) values (2, eric)"); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestUpdateGeneratedKeys.java
jdbi/src/test/java/org/skife/jdbi/v2/TestUpdateGeneratedKeys.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.util.LongMapper; import java.sql.Connection; import java.sql.Statement; @Category(JDBITests.class) public class TestUpdateGeneratedKeys extends DBITestCase { @Override protected void doSetUp() throws Exception { final Connection conn = DERBY_HELPER.getConnection(); final Statement create = conn.createStatement(); try { create.execute("create table something_else ( id integer not null generated always as identity, name varchar(50) )"); } catch (Exception e) { // probably still exists because of previous failed test, just delete then create.execute("delete from something_else"); } create.close(); conn.close(); } @Test public void testInsert() throws Exception { Handle h = openHandle(); Update insert1 = h.createStatement("insert into something_else (name) values (:name)"); insert1.bind("name", "Brian"); Long id1 = insert1.executeAndReturnGeneratedKeys(LongMapper.FIRST).first(); Assert.assertNotNull(id1); Update insert2 = h.createStatement("insert into something_else (name) values (:name)"); insert2.bind("name", "Tom"); Long id2 = insert2.executeAndReturnGeneratedKeys(LongMapper.FIRST).first(); Assert.assertNotNull(id2); Assert.assertTrue(id2 > id1); } @Test public void testUpdate() throws Exception { Handle h = openHandle(); Update insert = h.createStatement("insert into something_else (name) values (:name)"); insert.bind("name", "Brian"); Long id1 = insert.executeAndReturnGeneratedKeys(LongMapper.FIRST).first(); Assert.assertNotNull(id1); Update update = h.createStatement("update something_else set name = :name where id = :id"); update.bind("id", id1); update.bind("name", "Tom"); Long id2 = update.executeAndReturnGeneratedKeys(LongMapper.FIRST).first(); // https://issues.apache.org/jira/browse/DERBY-6742 //Assert.assertNull(id2); Assert.assertEquals(0, (long) id2); } @Test public void testDelete() throws Exception { Handle h = openHandle(); Update insert = h.createStatement("insert into something_else (name) values (:name)"); insert.bind("name", "Brian"); Long id1 = insert.executeAndReturnGeneratedKeys(LongMapper.FIRST).first(); Assert.assertNotNull(id1); Update delete = h.createStatement("delete from something_else where id = :id"); delete.bind("id", id1); Long id2 = delete.executeAndReturnGeneratedKeys(LongMapper.FIRST).first(); Assert.assertNull(id2); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestStatementContext.java
jdbi/src/test/java/org/skife/jdbi/v2/TestStatementContext.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.tweak.StatementLocator; import static org.junit.Assert.assertEquals; /** * */ @Category(JDBITests.class) public class TestStatementContext extends DBITestCase { @Test public void testFoo() throws Exception { Handle h = openHandle(); h.setStatementLocator(new StatementLocator() { @Override public String locate(String name, StatementContext ctx) throws Exception { return name.replaceAll("<table>", String.valueOf(ctx.getAttribute("table"))); } }); final int inserted = h.createStatement("insert into <table> (id, name) values (:id, :name)") .bind("id", 7) .bind("name", "Martin") .define("table", "something") .execute(); assertEquals(1, inserted); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/JDBITests.java
jdbi/src/test/java/org/skife/jdbi/v2/JDBITests.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; public interface JDBITests { }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestRegisteredMappers.java
jdbi/src/test/java/org/skife/jdbi/v2/TestRegisteredMappers.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.sqlobject.SomethingMapper; import org.skife.jdbi.v2.tweak.HandleCallback; import java.util.UUID; import static org.junit.Assert.assertEquals; @Category(JDBITests.class) public class TestRegisteredMappers { private DBI dbi; private Handle handle; @Before public void setUp() throws Exception { dbi = new DBI("jdbc:h2:mem:" + UUID.randomUUID()); handle = dbi.open(); handle.execute("create table something (id int primary key, name varchar(100))"); } @After public void tearDown() throws Exception { handle.execute("drop table something"); handle.close(); } @Test public void testRegisterInferredOnDBI() throws Exception { dbi.registerMapper(new SomethingMapper()); Something sam = dbi.withHandle(new HandleCallback<Something>() { @Override public Something withHandle(Handle handle) throws Exception { handle.insert("insert into something (id, name) values (18, 'Sam')"); return handle.createQuery("select id, name from something where id = :id") .bind("id", 18) .mapTo(Something.class) .first(); } }); assertEquals("Sam", sam.getName()); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestHandle.java
jdbi/src/test/java/org/skife/jdbi/v2/TestHandle.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.tweak.HandleCallback; import org.skife.jdbi.v2.tweak.ResultSetMapper; import java.sql.ResultSet; import java.sql.SQLException; import static org.junit.Assert.assertEquals; /** * */ @Category(JDBITests.class) public class TestHandle extends DBITestCase { @Test public void testInTransaction() throws Exception { Handle h = this.openHandle(); String value = h.inTransaction(new TransactionCallback<String>() { @Override public String inTransaction(Handle handle, TransactionStatus status) throws Exception { handle.insert("insert into something (id, name) values (1, 'Brian')"); return handle.createQuery("select name from something where id = 1").map(Something.class).first().getName(); } }); assertEquals("Brian", value); } @Test public void testSillyNumberOfCallbacks() throws Exception { Handle h = openHandle(); h.insert("insert into something (id, name) values (1, 'Keith')"); h.close(); String value = new DBI(DERBY_HELPER.getJdbcConnectionString()).withHandle(new HandleCallback<String>() { @Override public String withHandle(Handle handle) throws Exception { return handle.inTransaction(new TransactionCallback<String>() { @Override public String inTransaction(Handle handle, TransactionStatus status) throws Exception { return handle.createQuery("select name from something where id = 1").map(new ResultSetMapper<String>() { @Override public String map(int index, ResultSet r, StatementContext ctx) throws SQLException { return r.getString(1); } }).first(); } }); } }); assertEquals("Keith", value); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestDBI.java
jdbi/src/test/java/org/skife/jdbi/v2/TestDBI.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.exceptions.UnableToObtainConnectionException; import org.skife.jdbi.v2.tweak.ConnectionFactory; import org.skife.jdbi.v2.tweak.HandleCallback; import java.sql.Connection; import java.sql.SQLException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @Category(JDBITests.class) public class TestDBI extends DBITestCase { @Test public void testDataSourceConstructor() throws Exception { DBI dbi = new DBI(DERBY_HELPER.getDataSource()); Handle h = dbi.open(); assertNotNull(h); h.close(); } @Test public void testConnectionFactoryCtor() throws Exception { DBI dbi = new DBI(new ConnectionFactory() { @Override public Connection openConnection() { try { return DERBY_HELPER.getConnection(); } catch (SQLException e) { throw new UnableToObtainConnectionException(e); } } }); Handle h = dbi.open(); assertNotNull(h); h.close(); } @Test public void testCorrectExceptionOnSQLException() throws Exception { DBI dbi = new DBI(new ConnectionFactory() { @Override public Connection openConnection() throws SQLException { throw new SQLException(); } }); try { dbi.open(); fail("Should have raised an exception"); } catch (UnableToObtainConnectionException e) { assertTrue(true); } } @Test public void testStaticHandleOpener() throws Exception { Handle h = DBI.open(DERBY_HELPER.getDataSource()); assertNotNull(h); h.close(); } @Test public void testWithHandle() throws Exception { DBI dbi = new DBI(DERBY_HELPER.getDataSource()); String value = dbi.withHandle(new HandleCallback<String>() { @Override public String withHandle(Handle handle) throws Exception { handle.insert("insert into something (id, name) values (1, 'Brian')"); return handle.createQuery("select name from something where id = 1").map(Something.class).first().getName(); } }); assertEquals("Brian", value); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/ReflectionBeanMapperTest.java
jdbi/src/test/java/org/skife/jdbi/v2/ReflectionBeanMapperTest.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.easymock.EasyMockRunner; import org.easymock.Mock; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import java.math.BigDecimal; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.junit.Assert.*; @RunWith(EasyMockRunner.class) @Category(JDBITests.class) public class ReflectionBeanMapperTest { @Mock ResultSet resultSet; @Mock ResultSetMetaData resultSetMetaData; @Mock StatementContext ctx; ReflectionBeanMapper<SampleBean> mapper = new ReflectionBeanMapper<SampleBean>(SampleBean.class); @Test public void shouldSetValueOnPrivateField() throws Exception { expect(resultSetMetaData.getColumnCount()).andReturn(1).anyTimes(); expect(resultSetMetaData.getColumnLabel(1)).andReturn("longField"); replay(resultSetMetaData); expect(resultSet.getMetaData()).andReturn(resultSetMetaData); Long aLongVal = 100l; expect(resultSet.getLong(1)).andReturn(aLongVal); expect(resultSet.wasNull()).andReturn(false); replay(resultSet); SampleBean sampleBean = mapper.map(0, resultSet, ctx); assertSame(aLongVal, sampleBean.getLongField()); } @Test public void shouldHandleEmptyResult() throws Exception { expect(resultSetMetaData.getColumnCount()).andReturn(0); replay(resultSetMetaData); expect(resultSet.getMetaData()).andReturn(resultSetMetaData); replay(resultSet); SampleBean sampleBean = mapper.map(0, resultSet, ctx); assertNotNull(sampleBean); } @Test public void shouldBeCaseInSensitiveOfColumnAndFieldNames() throws Exception { expect(resultSetMetaData.getColumnCount()).andReturn(1).anyTimes(); expect(resultSetMetaData.getColumnLabel(1)).andReturn("LoNgfielD"); replay(resultSetMetaData); expect(resultSet.getMetaData()).andReturn(resultSetMetaData); Long aLongVal = 100l; expect(resultSet.getLong(1)).andReturn(aLongVal); expect(resultSet.wasNull()).andReturn(false); replay(resultSet); SampleBean sampleBean = mapper.map(0, resultSet, ctx); assertSame(aLongVal, sampleBean.getLongField()); } @Test public void shouldHandleNullValue() throws Exception { expect(resultSetMetaData.getColumnCount()).andReturn(1).anyTimes(); expect(resultSetMetaData.getColumnLabel(1)).andReturn("LoNgfielD"); replay(resultSetMetaData); expect(resultSet.getMetaData()).andReturn(resultSetMetaData); expect(resultSet.getLong(1)).andReturn(0l); expect(resultSet.wasNull()).andReturn(true); replay(resultSet); SampleBean sampleBean = mapper.map(0, resultSet, ctx); assertNull(sampleBean.getLongField()); } @Test public void shouldSetValuesOnAllFieldAccessTypes() throws Exception { expect(resultSetMetaData.getColumnCount()).andReturn(4).anyTimes(); expect(resultSetMetaData.getColumnLabel(1)).andReturn("longField"); expect(resultSetMetaData.getColumnLabel(2)).andReturn("stringField"); expect(resultSetMetaData.getColumnLabel(3)).andReturn("intField"); expect(resultSetMetaData.getColumnLabel(4)).andReturn("bigDecimalField"); replay(resultSetMetaData); expect(resultSet.getMetaData()).andReturn(resultSetMetaData); Long aLongVal = 100l; String aStringVal = "something"; int aIntVal = 1; BigDecimal aBigDecimal = BigDecimal.TEN; expect(resultSet.getLong(1)).andReturn(aLongVal); expect(resultSet.getString(2)).andReturn(aStringVal); expect(resultSet.getInt(3)).andReturn(aIntVal); expect(resultSet.getBigDecimal(4)).andReturn(aBigDecimal); expect(resultSet.wasNull()).andReturn(false).anyTimes(); replay(resultSet); SampleBean sampleBean = mapper.map(0, resultSet, ctx); assertSame(aLongVal, sampleBean.getLongField()); assertSame(aBigDecimal, sampleBean.getBigDecimalField()); assertSame(aIntVal, sampleBean.getIntField()); assertSame(aStringVal, sampleBean.getStringField()); } @Test public void shouldSetValuesInSuperClassFields() throws Exception { expect(resultSetMetaData.getColumnCount()).andReturn(2).anyTimes(); expect(resultSetMetaData.getColumnLabel(1)).andReturn("longField"); expect(resultSetMetaData.getColumnLabel(2)).andReturn("blongField"); replay(resultSetMetaData); expect(resultSet.getMetaData()).andReturn(resultSetMetaData); Long aLongVal = 100l; Long bLongVal = 200l; expect(resultSet.getLong(1)).andReturn(aLongVal); expect(resultSet.getLong(2)).andReturn(bLongVal); expect(resultSet.wasNull()).andReturn(false).anyTimes(); replay(resultSet); ReflectionBeanMapper<DerivedBean> mapper = new ReflectionBeanMapper<DerivedBean>(DerivedBean.class); DerivedBean derivedBean = mapper.map(0, resultSet, ctx); assertEquals(aLongVal, derivedBean.getLongField()); assertEquals(bLongVal, derivedBean.getBlongField()); } } class SampleBean { private Long longField; protected String stringField; public int intField; BigDecimal bigDecimalField; public Long getLongField() { return longField; } public String getStringField() { return stringField; } public int getIntField() { return intField; } public BigDecimal getBigDecimalField() { return bigDecimalField; } } class DerivedBean extends SampleBean { private Long blongField; public Long getBlongField() { return blongField; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestTransactionsAutoCommit.java
jdbi/src/test/java/org/skife/jdbi/v2/TestTransactionsAutoCommit.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.junit.Test; import org.junit.experimental.categories.Category; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import static org.easymock.EasyMock.createNiceMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expectLastCall; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; @Category(JDBITests.class) public class TestTransactionsAutoCommit extends DBITestCase { @Test public void restoreAutoCommitInitialStateOnUnexpectedError() throws Exception { final Connection connection = createNiceMock(Connection.class); final PreparedStatement statement = createNiceMock(PreparedStatement.class); Handle h = openHandle(connection); // expected behaviour chain: // 1. store initial auto-commit state expect(connection.getAutoCommit()).andReturn(true); // 2. turn off auto-commit connection.setAutoCommit(false); expectLastCall().once(); // 3. execute statement (without commit) expect(connection.prepareStatement("insert into something (id, name) values (?, ?)")).andReturn(statement); expect(statement.execute()).andReturn(true); expect(statement.getUpdateCount()).andReturn(1); // 4. commit transaction (throw e.g some underlying database error) connection.commit(); expectLastCall().andThrow(new SQLException("infrastructure error")); // 5. set auto-commit back to initial state connection.setAutoCommit(true); expectLastCall().once(); replay(connection, statement); h.begin(); try { h.insert("insert into something (id, name) values (?, ?)", 1L, "Tom"); // throws exception on commit h.commit(); } catch (final Exception exception) { // ignore } verify(connection); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/ExtraMatchers.java
jdbi/src/test/java/org/skife/jdbi/v2/ExtraMatchers.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.hamcrest.BaseMatcher; import org.hamcrest.CoreMatchers; import org.hamcrest.Description; import org.hamcrest.Matcher; import java.util.Arrays; import java.util.List; public class ExtraMatchers { public static <T, S extends T> Matcher<T> isEqualTo(S it) { return (Matcher<T>) CoreMatchers.equalTo(it); } public static <T> Matcher<T> equalsOneOf(T... options) { final List opts = Arrays.asList(options); return new BaseMatcher<T>() { @Override public boolean matches(Object item) { for (Object opt : opts) { if (opt.equals(item)) { return true; } } return false; } @Override public void describeTo(Description d) { d.appendText("one of " + opts); } }; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestSqlLogging.java
jdbi/src/test/java/org/skife/jdbi/v2/TestSqlLogging.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.exceptions.TransactionFailedException; import org.skife.jdbi.v2.logging.PrintStreamLog; import org.skife.jdbi.v2.tweak.SQLLog; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * */ @Category(JDBITests.class) public class TestSqlLogging extends DBITestCase { private Handle h; private List<String> logged; private SQLLog log; @Override public void doSetUp() throws Exception { h = openHandle(); logged = new ArrayList<String>(); log = new SQLLog() { @Override public void logBeginTransaction(Handle h) { logged.add("begin"); } @Override public void logCommitTransaction(long time, Handle h) { logged.add("commit"); } @Override public void logRollbackTransaction(long time, Handle h) { logged.add("rollback"); } @Override public void logObtainHandle(long time, Handle h) { logged.add("open"); } @Override public void logReleaseHandle(Handle h) { logged.add("close"); } @Override public void logSQL(long time, String sql) { logged.add(sql); } @Override public void logPreparedBatch(long time, String sql, int count) { logged.add(String.format("%d:%s", count, sql)); } @Override public BatchLogger logBatch() { return new SQLLog.BatchLogger() { @Override public void add(String sql) { logged.add(sql); } @Override public void log(long time) { } }; } @Override public void logCheckpointTransaction(Handle h, String name) { logged.add(String.format("checkpoint %s created", name)); } @Override public void logReleaseCheckpointTransaction(Handle h, String name) { logged.add(String.format("checkpoint %s released", name)); } @Override public void logRollbackToCheckpoint(long time, Handle h, String name) { logged.add(String.format("checkpoint %s rolled back to", name)); } }; h.setSQLLog(log); } @Override public void doTearDown() throws Exception { if (h != null) h.close(); } @Test public void testInsert() throws Exception { h.insert("insert into something (id, name) values (?, ?)", 1, "Hello"); assertEquals(1, logged.size()); assertEquals("insert into something (id, name) values (?, ?)", logged.get(0)); } @Test public void testBatch() throws Exception { String sql1 = "insert into something (id, name) values (1, 'Eric')"; String sql2 = "insert into something (id, name) values (2, 'Keith')"; h.createBatch().add(sql1).add(sql2).execute(); assertEquals(2, logged.size()); assertEquals(sql1, logged.get(0)); assertEquals(sql2, logged.get(1)); } @Test public void testPreparedBatch() throws Exception { String sql = "insert into something (id, name) values (?, ?)"; h.prepareBatch(sql).add(1, "Eric").add(2, "Keith").execute(); assertEquals(1, logged.size()); assertEquals(String.format("%d:%s", 2, sql), logged.get(0)); } private static final String linesep = System.getProperty("line.separator"); @Test public void testPrintStream() throws Exception { ByteArrayOutputStream bout = new ByteArrayOutputStream(); h.setSQLLog(new PrintStreamLog(new PrintStream(bout))); String sql = "insert into something (id, name) values (?, ?)"; h.insert(sql, 1, "Brian"); assertTrue(new String(bout.toByteArray()) .matches("statement:\\[insert into something \\(id, name\\) values \\(\\?, \\?\\)\\] took \\d+ millis" + linesep)); } @Test public void testCloseLogged() throws Exception { h.close(); assertTrue(logged.contains("close")); } @Test public void testLogBegin() throws Exception { h.begin(); assertTrue(logged.contains("begin")); h.commit(); } @Test public void testLogCommit() throws Exception { h.begin(); h.commit(); assertTrue(logged.contains("commit")); } @Test public void testLogBeginCommit() throws Exception { h.inTransaction(new TransactionCallback<Object>() { @Override public Object inTransaction(Handle handle, TransactionStatus status) throws Exception { assertTrue(logged.contains("begin")); return null; } }); assertTrue(logged.contains("commit")); } @Test public void testLogBeginRollback() throws Exception { try { h.inTransaction(new TransactionCallback<Object>() { @Override public Object inTransaction(Handle handle, TransactionStatus status) throws Exception { assertTrue(logged.contains("begin")); throw new Exception(); } }); fail("should have raised exception"); } catch (TransactionFailedException e) { assertTrue(logged.contains("rollback")); } } @Test public void testLogRollback() throws Exception { h.begin(); h.rollback(); assertTrue(logged.contains("rollback")); } @Test public void testCheckpoint() throws Exception { h.begin(); h.checkpoint("a"); assertTrue(logged.contains("checkpoint a created")); h.rollback("a"); assertTrue(logged.contains("checkpoint a rolled back to")); h.checkpoint("b"); assertTrue(logged.contains("checkpoint b created")); h.release("b"); assertTrue(logged.contains("checkpoint b released")); h.commit(); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestEscapedCharacters.java
jdbi/src/test/java/org/skife/jdbi/v2/TestEscapedCharacters.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; /** * */ @Category(JDBITests.class) public class TestEscapedCharacters { private final ColonPrefixNamedParamStatementRewriter rewriter = new ColonPrefixNamedParamStatementRewriter(); private String parseString(final String src) { return rewriter.parseString(src).getParsedSql(); } @Test public void testSimpleString() { Assert.assertEquals("hello, world", parseString("hello, world")); } @Test public void testSimpleSql() { Assert.assertEquals("insert into foo (xyz) values (?)", parseString("insert into foo (xyz) values (:bar)")); } @Test public void testEscapedSql() { Assert.assertEquals("insert into foo (xyz) values (?::some_strange_type)", parseString("insert into foo (xyz) values (:bar\\:\\:some_strange_type)")); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestBooleanIntegerArgument.java
jdbi/src/test/java/org/skife/jdbi/v2/TestBooleanIntegerArgument.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.easymock.EasyMock; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.tweak.Argument; import java.sql.PreparedStatement; @Category(JDBITests.class) public class TestBooleanIntegerArgument { @Test public void testTrue() throws Exception { PreparedStatement mockStmt = EasyMock.createMock(PreparedStatement.class); mockStmt.setInt(5, 1); EasyMock.replay(mockStmt); Argument arrrgh = new BooleanIntegerArgument(true); arrrgh.apply(5, mockStmt, null); EasyMock.verify(mockStmt); } @Test public void testFalse() throws Exception { PreparedStatement mockStmt = EasyMock.createMock(PreparedStatement.class); mockStmt.setInt(5, 0); EasyMock.replay(mockStmt); Argument arrrgh = new BooleanIntegerArgument(false); arrrgh.apply(5, mockStmt, null); EasyMock.verify(mockStmt); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestNoOpStatementRewriter.java
jdbi/src/test/java/org/skife/jdbi/v2/TestNoOpStatementRewriter.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.junit.Test; import org.junit.experimental.categories.Category; import static org.junit.Assert.assertEquals; /** * */ @Category(JDBITests.class) public class TestNoOpStatementRewriter extends DBITestCase { private DBI dbi; @Override public void doSetUp() throws Exception { this.dbi = new DBI(DERBY_HELPER.getDataSource()); dbi.setStatementRewriter(new NoOpStatementRewriter()); } @Test public void testFoo() throws Exception { Handle h = dbi.open(); h.insert("insert into something (id, name) values (1, 'Keith')"); String name = h.createQuery("select name from something where id = ?") .bind(0, 1) .map(Something.class) .first() .getName(); assertEquals("Keith", name); } @Test public void testBar() throws Exception { Handle h = dbi.open(); h.insert("insert into something (id, name) values (1, 'Keith')"); String name = h.createQuery("select name from something where id = ? and name = ?") .bind(0, 1) .bind(1, "Keith") .map(Something.class) .first().getName(); assertEquals("Keith", name); } @Test public void testBaz() throws Exception { Handle h = dbi.open(); h.insert("insert into something (id, name) values (1, 'Keith')"); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestTimingCollector.java
jdbi/src/test/java/org/skife/jdbi/v2/TestTimingCollector.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.logging.NoOpLog; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import static org.junit.Assert.assertEquals; /** * */ @Category(JDBITests.class) public class TestTimingCollector extends DBITestCase { private BasicHandle h; private TTC tc; @Override protected BasicHandle openHandle() throws SQLException { tc = new TTC(); Connection conn = DERBY_HELPER.getConnection(); BasicHandle h = new BasicHandle(getTransactionHandler(), getStatementLocator(), new CachingStatementBuilder(new DefaultStatementBuilder()), new ColonPrefixNamedParamStatementRewriter(), conn, new HashMap<String, Object>(), new NoOpLog(), tc, new MappingRegistry(), new Foreman(), new ContainerFactoryRegistry()); HANDLES.add(h); return h; } @Override public void doSetUp() throws Exception { h = openHandle(); } @Override public void doTearDown() throws Exception { if (h != null) h.close(); } @Test public void testStatement() throws Exception { int rows = h.createStatement("insert into something (id, name) values (1, 'eric')").execute(); assertEquals(1, rows); } @Test public void testSimpleInsert() throws Exception { String statement = "insert into something (id, name) values (1, 'eric')"; int c = h.insert(statement); assertEquals(1, c); final List<String> statements = tc.getStatements(); assertEquals(1, statements.size()); assertEquals(statement, statements.get(0)); } @Test public void testUpdate() throws Exception { String stmt1 = "insert into something (id, name) values (1, 'eric')"; String stmt2 = "update something set name = 'ERIC' where id = 1"; String stmt3 = "select * from something where id = 1"; h.insert(stmt1); h.createStatement(stmt2).execute(); Something eric = h.createQuery(stmt3).map(Something.class).list().get(0); assertEquals("ERIC", eric.getName()); final List<String> statements = tc.getStatements(); assertEquals(3, statements.size()); assertEquals(stmt1, statements.get(0)); assertEquals(stmt2, statements.get(1)); assertEquals(stmt3, statements.get(2)); } @Test public void testSimpleUpdate() throws Exception { String stmt1 = "insert into something (id, name) values (1, 'eric')"; String stmt2 = "update something set name = 'cire' where id = 1"; String stmt3 = "select * from something where id = 1"; h.insert(stmt1); h.update(stmt2); Something eric = h.createQuery(stmt3).map(Something.class).list().get(0); assertEquals("cire", eric.getName()); final List<String> statements = tc.getStatements(); assertEquals(3, statements.size()); assertEquals(stmt1, statements.get(0)); assertEquals(stmt2, statements.get(1)); assertEquals(stmt3, statements.get(2)); } private static class TTC implements TimingCollector { private List<String> statements = new ArrayList<String>(); @Override public synchronized void collect(final long elapsedTime, final StatementContext ctx) { statements.add(ctx.getRawSql()); } public synchronized List<String> getStatements() { return statements; } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestPreparedBatch.java
jdbi/src/test/java/org/skife/jdbi/v2/TestPreparedBatch.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.derby.DerbyHelper; import org.skife.jdbi.v2.tweak.ResultSetMapper; import org.skife.jdbi.v2.util.StringMapper; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; @Category(JDBITests.class) public class TestPreparedBatch extends DBITestCase { @Test public void testDesignApi() throws Exception { Handle h = openHandle(); PreparedBatch b = h.prepareBatch("insert into something (id, name) values (:id, :name)"); PreparedBatchPart p = b.add(); p = p.bind("id", 1).bind("name", "Eric").next(); p.bind("id", 2).bind("name", "Brian").next().bind("id", 3).bind("name", "Keith"); b.execute(); List<Something> r = h.createQuery("select * from something order by id").map(Something.class).list(); assertEquals(3, r.size()); assertEquals("Keith", r.get(2).getName()); } @Test public void testBigishBatch() throws Exception { Handle h = openHandle(); PreparedBatch b = h.prepareBatch("insert into something (id, name) values (:id, :name)"); int count = 100; for (int i = 0; i < count; ++i) { b.add().bind("id", i).bind("name", "A Name"); } b.execute(); int row_count = h.createQuery("select count(id) from something").map(new ResultSetMapper<Integer>() { @Override public Integer map(int index, ResultSet r, StatementContext ctx) throws SQLException { return r.getInt(1); } }).first(); assertEquals(count, row_count); } @Test public void testBindProperties() throws Exception { Handle h = openHandle(); PreparedBatch b = h.prepareBatch("insert into something (id, name) values (?, ?)"); b.add(0, "Keith"); b.add(1, "Eric"); b.add(2, "Brian"); b.execute(); List<Something> r = h.createQuery("select * from something order by id").map(Something.class).list(); assertEquals(3, r.size()); assertEquals("Brian", r.get(2).getName()); } @Test public void testBindMaps() throws Exception { Handle h = openHandle(); PreparedBatch b = h.prepareBatch("insert into something (id, name) values (:id, :name)"); Map<String, Object> one = DerbyHelper.map("id", 0).add("name", "Keith"); b.add(one); b.add(DerbyHelper.map("id", Integer.parseInt("1")).add("name", "Eric")); b.add(DerbyHelper.map("id", Integer.parseInt("2")).add("name", "Brian")); b.execute(); List<Something> r = h.createQuery("select * from something order by id").map(Something.class).list(); assertEquals(3, r.size()); assertEquals("Brian", r.get(2).getName()); } @Test public void testMixedModeBatch() throws Exception { Handle h = openHandle(); PreparedBatch b = h.prepareBatch("insert into something (id, name) values (:id, :name)"); Map<String, Object> one = DerbyHelper.map("id", 0); b.add(one).bind("name", "Keith"); b.execute(); List<Something> r = h.createQuery("select * from something order by id").map(Something.class).list(); assertEquals(1, r.size()); assertEquals("Keith", r.get(0).getName()); } @Test public void testPositionalBinding() throws Exception { Handle h = openHandle(); PreparedBatch b = h.prepareBatch("insert into something (id, name) values (:id, :name)"); b.add().bind(0, 0).bind(1, "Keith").submit().execute(); List<Something> r = h.createQuery("select * from something order by id").map(Something.class).list(); assertEquals(1, r.size()); assertEquals("Keith", r.get(0).getName()); } @Test public void testSetOnTheBatchItself() throws Exception { Handle h = openHandle(); PreparedBatch b = h.prepareBatch("insert into something (id, name) values (:id, :name)"); b.bind("id", 1); b.bind("name", "Jeff"); b.add(); b.bind("id", 2); b.bind("name", "Tom"); b.add(); b.execute(); assertEquals(h.createQuery("select name from something order by id").map(StringMapper.FIRST).list(), Arrays.asList("Jeff", "Tom")); } @Test public void testMixedBatchSetting() throws Exception { Handle h = openHandle(); PreparedBatch b = h.prepareBatch("insert into something (id, name) values (:id, :name)"); b.bind("id", 1); b.add().bind("name", "Jeff"); b.bind("id", 2); b.add().bind("name", "Tom"); b.execute(); assertEquals(h.createQuery("select name from something order by id").map(StringMapper.FIRST).list(), Arrays.asList("Jeff", "Tom")); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestEnums.java
jdbi/src/test/java/org/skife/jdbi/v2/TestEnums.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.junit.Test; import org.junit.experimental.categories.Category; import java.sql.SQLException; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; @Category(JDBITests.class) public class TestEnums extends DBITestCase { public static class SomethingElse { public enum Name { eric, brian } private int id; private Name name; public Name getName() { return name; } public void setName(Name name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } } @Test public void testMapEnumValues() throws Exception { Handle h = openHandle(); h.createStatement("insert into something (id, name) values (1, 'eric')").execute(); h.createStatement("insert into something (id, name) values (2, 'brian')").execute(); List<SomethingElse> results = h.createQuery("select * from something order by id") .map(SomethingElse.class) .list(); assertEquals(SomethingElse.Name.eric, results.get(0).name); assertEquals(SomethingElse.Name.brian, results.get(1).name); } @Test public void testMapInvalidEnumValue() throws SQLException { Handle h = openHandle(); h.createStatement("insert into something (id, name) values (1, 'joe')").execute(); try { h.createQuery("select * from something order by id") .map(SomethingElse.class) .first(); fail("Expected IllegalArgumentException was not thrown"); } catch (IllegalArgumentException e) { assertEquals("flow control goes here", 2 + 2, 4); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestNamedParams.java
jdbi/src/test/java/org/skife/jdbi/v2/TestNamedParams.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; /** * */ @Category(JDBITests.class) public class TestNamedParams extends DBITestCase { @Test public void testInsert() throws Exception { Handle h = openHandle(); Update insert = h.createStatement("insert into something (id, name) values (:id, :name)"); insert.bind("id", 1); insert.bind("name", "Brian"); int count = insert.execute(); assertEquals(1, count); } @Test public void testDemo() throws Exception { Handle h = DBI.open(DERBY_HELPER.getDataSource()); h.createStatement("insert into something (id, name) values (:id, :name)") .bind("id", 1) .bind("name", "Brian") .execute(); h.insert("insert into something (id, name) values (?, ?)", 2, "Eric"); h.insert("insert into something (id, name) values (?, ?)", 3, "Erin"); List<Something> r = h.createQuery("select id, name from something " + "where name like :name " + "order by id") .bind("name", "Eri%") .map(Something.class) .list(); assertEquals(2, r.size()); assertEquals(2, r.get(0).getId()); assertEquals(3, r.get(1).getId()); h.close(); } @Test public void testBeanPropertyBinding() throws Exception { Handle h = this.openHandle(); Update s = h.createStatement("insert into something (id, name) values (:id, :name)"); s.bindFromProperties(new Something(0, "Keith")); int insert_count = s.execute(); assertEquals(1, insert_count); } @Test public void testMapKeyBinding() throws Exception { Handle h = this.openHandle(); Update s = h.createStatement("insert into something (id, name) values (:id, :name)"); Map<String, Object> args = new HashMap<String, Object>(); args.put("id", 0); args.put("name", "Keith"); s.bindFromMap(args); int insert_count = s.execute(); assertEquals(1, insert_count); } @Test public void testCascadedLazyArgs() throws Exception { Handle h = this.openHandle(); Update s = h.createStatement("insert into something (id, name) values (:id, :name)"); Map<String, Object> args = new HashMap<String, Object>(); args.put("id", 0); s.bindFromMap(args); s.bindFromProperties(new Object() { @SuppressWarnings("unused") public String getName() { return "Keith"; } }); int insert_count = s.execute(); assertEquals(1, insert_count); Something something = h.createQuery("select id, name from something").map(Something.class).first(); assertEquals("Keith", something.getName()); assertEquals(0, something.getId()); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestPositionalParameterBinding.java
jdbi/src/test/java/org/skife/jdbi/v2/TestPositionalParameterBinding.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * */ @Category(JDBITests.class) public class TestPositionalParameterBinding extends DBITestCase { private BasicHandle h; @Override public void doSetUp() throws Exception { h = openHandle(); } @Test public void testSetPositionalString() throws Exception { h.insert("insert into something (id, name) values (1, 'eric')"); h.insert("insert into something (id, name) values (2, 'brian')"); Something eric = h.createQuery("select * from something where name = ?") .bind(0, "eric") .map(Something.class) .list() .get(0); assertEquals(1, eric.getId()); } @Test public void testSetPositionalInteger() throws Exception { h.insert("insert into something (id, name) values (1, 'eric')"); h.insert("insert into something (id, name) values (2, 'brian')"); Something eric = h.createQuery("select * from something where id = ?") .bind(0, 1) .map(Something.class) .list().get(0); assertEquals(1, eric.getId()); } @Test public void testBehaviorOnBadBinding1() throws Exception { Query<Something> q = h.createQuery("select * from something where id = ? and name = ?") .bind(0, 1) .map(Something.class); try { q.list(); fail("should have thrown exception"); } catch (UnableToExecuteStatementException e) { assertTrue("Execution goes through here", true); } catch (Exception e) { fail("Threw an incorrect exception type"); } } @Test public void testBehaviorOnBadBinding2() throws Exception { Query<Something> q = h.createQuery("select * from something where id = ?") .bind(1, 1) .bind(2, "Hi") .map(Something.class); try { q.list(); fail("should have thrown exception"); } catch (UnableToExecuteStatementException e) { assertTrue("Execution goes through here", true); } catch (Exception e) { fail("Threw an incorrect exception type"); } } @Test public void testInsertParamBinding() throws Exception { int count = h.createStatement("insert into something (id, name) values (?, 'eric')") .bind(0, 1) .execute(); assertEquals(1, count); } @Test public void testPositionalConvenienceInsert() throws Exception { int count = h.insert("insert into something (id, name) values (?, ?)", 1, "eric"); assertEquals(1, count); } @Test public void testWeirdPositionalSyntax() throws Exception { } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/Something.java
jdbi/src/test/java/org/skife/jdbi/v2/Something.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; /** * */ public class Something { private int id; private String name; private Integer integerValue; private int intValue; public Something() { } public Something(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getIntegerValue() { return integerValue; } public void setIntegerValue(Integer integerValue) { this.integerValue = integerValue; } public int getIntValue() { return intValue; } public void setIntValue(int intValue) { this.intValue = intValue; } // Issue #61: @BindBean fails if there is a writable but not readable property, so let's have one... public void setWithoutGetter(String bogus) { throw new UnsupportedOperationException(); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Something)) return false; Something something = (Something) o; if (id != something.id) return false; if (intValue != something.intValue) return false; if (integerValue != null ? !integerValue.equals(something.integerValue) : something.integerValue != null) return false; if (name != null ? !name.equals(something.name) : something.name != null) return false; return true; } @Override public int hashCode() { int result = id; result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (integerValue != null ? integerValue.hashCode() : 0); result = 31 * result + intValue; return result; } @Override public String toString() { return "Something{" + "id=" + id + ", name='" + name + '\'' + ", integerValue=" + integerValue + ", intValue=" + intValue + '}'; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestClosingHandle.java
jdbi/src/test/java/org/skife/jdbi/v2/TestClosingHandle.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @Category(JDBITests.class) public class TestClosingHandle extends DBITestCase { private BasicHandle h; @Override public void doSetUp() throws Exception { h = openHandle(); } @Override public void doTearDown() throws Exception { if (h != null) h.close(); } @Test public void testNotClosing() throws Exception { h.createStatement("insert into something (id, name) values (1, 'eric')").execute(); h.createStatement("insert into something (id, name) values (2, 'brian')").execute(); List<Map<String, Object>> results = h.createQuery("select * from something order by id").list(); assertEquals(2, results.size()); Map<String, Object> first_row = results.get(0); assertEquals("eric", first_row.get("name")); assertFalse(h.isClosed()); } @Test public void testClosing() throws Exception { h.createStatement("insert into something (id, name) values (1, 'eric')").execute(); h.createStatement("insert into something (id, name) values (2, 'brian')").execute(); List<Map<String, Object>> results = h.createQuery("select * from something order by id") .cleanupHandle() .list(); assertEquals(2, results.size()); Map<String, Object> first_row = results.get(0); assertEquals("eric", first_row.get("name")); assertTrue(h.isClosed()); } @Test public void testIterateKeepHandle() throws Exception { h.createStatement("insert into something (id, name) values (1, 'eric')").execute(); h.createStatement("insert into something (id, name) values (2, 'brian')").execute(); ResultIterator<Map<String, Object>> it = h.createQuery("select * from something order by id") .iterator(); int cnt = 0; while(it.hasNext()) { cnt++; it.next(); } assertEquals(2, cnt); assertFalse(h.isClosed()); } @Test public void testIterateAllTheWay() throws Exception { h.createStatement("insert into something (id, name) values (1, 'eric')").execute(); h.createStatement("insert into something (id, name) values (2, 'brian')").execute(); ResultIterator<Map<String, Object>> it = h.createQuery("select * from something order by id") .cleanupHandle() .iterator(); int cnt = 0; while(it.hasNext()) { cnt++; it.next(); } assertEquals(2, cnt); assertTrue(h.isClosed()); } @Test public void testIteratorBehaviour() throws Exception { h.createStatement("insert into something (id, name) values (1, 'eric')").execute(); h.createStatement("insert into something (id, name) values (2, 'brian')").execute(); h.createStatement("insert into something (id, name) values (3, 'john')").execute(); ResultIterator<Map<String, Object>> it = h.createQuery("select * from something order by id") .cleanupHandle() .iterator(); assertTrue(it.hasNext()); assertFalse(h.isClosed()); it.next(); assertTrue(it.hasNext()); assertFalse(h.isClosed()); it.next(); assertTrue(it.hasNext()); assertFalse(h.isClosed()); it.next(); assertFalse(it.hasNext()); assertTrue(h.isClosed()); } @Test public void testIteratorClose() throws Exception { h.createStatement("insert into something (id, name) values (1, 'eric')").execute(); h.createStatement("insert into something (id, name) values (2, 'brian')").execute(); h.createStatement("insert into something (id, name) values (3, 'john')").execute(); ResultIterator<Map<String, Object>> it = h.createQuery("select * from something order by id") .cleanupHandle() .iterator(); assertTrue(it.hasNext()); assertFalse(h.isClosed()); it.next(); assertTrue(it.hasNext()); assertFalse(h.isClosed()); it.close(); assertFalse(it.hasNext()); assertTrue(h.isClosed()); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestHashPrefixStatementRewriter.java
jdbi/src/test/java/org/skife/jdbi/v2/TestHashPrefixStatementRewriter.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.exceptions.UnableToCreateStatementException; import org.skife.jdbi.v2.tweak.RewrittenStatement; import java.util.HashMap; import static org.junit.Assert.assertEquals; /** * */ @Category(JDBITests.class) public class TestHashPrefixStatementRewriter { private HashPrefixStatementRewriter rw; @Before public void setUp() throws Exception { this.rw = new HashPrefixStatementRewriter(); } @Test public void testNewlinesOkay() throws Exception { RewrittenStatement rws = rw.rewrite("select * from something\n where id = #id", new Binding(), new ConcreteStatementContext(new HashMap<String, Object>())); assertEquals("select * from something\n where id = ?", rws.getSql()); } @Test public void testOddCharacters() throws Exception { RewrittenStatement rws = rw.rewrite("~* #boo '#nope' _%&^& *@ #id", new Binding(), new ConcreteStatementContext(new HashMap<String, Object>())); assertEquals("~* ? '#nope' _%&^& *@ ?", rws.getSql()); } @Test public void testNumbers() throws Exception { RewrittenStatement rws = rw.rewrite("#bo0 '#nope' _%&^& *@ #id", new Binding(), new ConcreteStatementContext(new HashMap<String, Object>())); assertEquals("? '#nope' _%&^& *@ ?", rws.getSql()); } @Test public void testDollarSignOkay() throws Exception { RewrittenStatement rws = rw.rewrite("select * from v$session", new Binding(), new ConcreteStatementContext(new HashMap<String, Object>())); assertEquals("select * from v$session", rws.getSql()); } @Test public void testColonIsLiteral() throws Exception { RewrittenStatement rws = rw.rewrite("select * from foo where id = :id", new Binding(), new ConcreteStatementContext(new HashMap<String, Object>())); assertEquals("select * from foo where id = :id", rws.getSql()); } @Test public void testBacktickOkay() throws Exception { RewrittenStatement rws = rw.rewrite("select * from `v$session", new Binding(), new ConcreteStatementContext(new HashMap<String, Object>())); assertEquals("select * from `v$session", rws.getSql()); } @Test public void testBailsOutOnInvalidInput() throws Exception { try { rw.rewrite("select * from something\n where id = #\u0087\u008e\u0092\u0097\u009c", new Binding(), new ConcreteStatementContext(new HashMap<String, Object>())); Assert.fail("Expected 'UnableToCreateStatementException' but got none"); } catch (UnableToCreateStatementException e) { } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestArgumentFactory.java
jdbi/src/test/java/org/skife/jdbi/v2/TestArgumentFactory.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.h2.jdbcx.JdbcDataSource; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.tweak.Argument; import org.skife.jdbi.v2.tweak.ArgumentFactory; import org.skife.jdbi.v2.util.StringMapper; import java.util.UUID; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; public class TestArgumentFactory { private DBI dbi; private Handle h; @Before public void setUp() throws Exception { JdbcDataSource ds = new JdbcDataSource(); ds.setURL("jdbc:h2:mem:" + UUID.randomUUID()); dbi = new DBI(ds); h = dbi.open(); h.execute("create table something (id int primary key, name varchar(100))"); } @After public void tearDown() throws Exception { h.execute("drop table something"); h.close(); } @Test @Category(JDBITests.class) public void testRegisterOnDBI() throws Exception { dbi.registerArgumentFactory(new NameAF()); Handle h2 = dbi.open(); h2.createStatement("insert into something (id, name) values (:id, :name)") .bind("id", 7) .bind("name", new Name("Brian", "McCallister")) .execute(); String full_name = h.createQuery("select name from something where id = 7").map(StringMapper.FIRST).first(); assertThat(full_name, equalTo("Brian McCallister")); h2.close(); } public static class NameAF implements ArgumentFactory<Name> { @Override public boolean accepts(Class<?> expectedType, Object value, StatementContext ctx) { return expectedType == Object.class && value instanceof Name; } @Override public Argument build(Class<?> expectedType, Name value, StatementContext ctx) { return new StringArgument(value.getFullName()); } } public static class Name { private final String first; private final String last; public Name(String first, String last) { this.first = first; this.last = last; } public String getFullName() { return first + " " + last; } @Override public String toString() { return "<Name first=" + first + " last=" + last + " >"; } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestPreparedStatementCache.java
jdbi/src/test/java/org/skife/jdbi/v2/TestPreparedStatementCache.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.logging.NoOpLog; import org.skife.jdbi.v2.tweak.transactions.LocalTransactionHandler; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.HashMap; import static org.junit.Assert.assertEquals; @Category(JDBITests.class) public class TestPreparedStatementCache extends DBITestCase { @Test public void testSomething() throws Exception { final int[] prep_count = { 0 }; Connection c = new DelegatingConnection(DERBY_HELPER.getConnection()) { @Override public PreparedStatement prepareStatement(String s, int flag) throws SQLException { prep_count[0]++; return super.prepareStatement(s, flag); } @Override public PreparedStatement prepareStatement(String s) throws SQLException { prep_count[0]++; return super.prepareStatement(s); } }; CachingStatementBuilder builder = new CachingStatementBuilder(new DefaultStatementBuilder()); BasicHandle h = new BasicHandle(new LocalTransactionHandler(), new ClasspathStatementLocator(), builder, new ColonPrefixNamedParamStatementRewriter(), c, new HashMap<String, Object>(), new NoOpLog(), TimingCollector.NOP_TIMING_COLLECTOR, new MappingRegistry(), new Foreman(), new ContainerFactoryRegistry()); h.createStatement("insert into something (id, name) values (:id, :name)") .bindFromProperties(new Something(0, "Keith")) .execute(); assertEquals(1, prep_count[0]); h.createStatement("insert into something (id, name) values (:id, :name)") .bindFromProperties(new Something(0, "Keith")) .execute(); assertEquals(1, prep_count[0]); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestTransactions.java
jdbi/src/test/java/org/skife/jdbi/v2/TestTransactions.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.exceptions.DBIException; import org.skife.jdbi.v2.exceptions.TransactionException; import org.skife.jdbi.v2.exceptions.TransactionFailedException; import org.skife.jdbi.v2.util.IntegerMapper; import java.io.IOException; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @Category(JDBITests.class) public class TestTransactions extends DBITestCase { @Test public void testCallback() throws Exception { Handle h = this.openHandle(); String woot = h.inTransaction(new TransactionCallback<String>() { @Override public String inTransaction(Handle handle, TransactionStatus status) throws Exception { return "Woot!"; } }); assertEquals("Woot!", woot); } @Test public void testRollbackOutsideTx() throws Exception { Handle h = openHandle(); h.insert("insert into something (id, name) values (?, ?)", 7, "Tom"); h.rollback(); } @Test public void testDoubleOpen() throws Exception { Handle h = openHandle(); assertTrue(h.getConnection().getAutoCommit()); h.begin(); h.begin(); assertFalse(h.getConnection().getAutoCommit()); h.commit(); assertTrue(h.getConnection().getAutoCommit()); } @Test public void testExceptionAbortsTransaction() throws Exception { Handle h = this.openHandle(); try { h.inTransaction(new TransactionCallback<Object>() { @Override public Object inTransaction(Handle handle, TransactionStatus status) throws Exception { handle.insert("insert into something (id, name) values (:id, :name)", 0, "Keith"); throw new IOException(); } }); fail("Should have thrown exception"); } catch (TransactionFailedException e) { assertTrue(true); } List<Something> r = h.createQuery("select * from something").map(Something.class).list(); assertEquals(0, r.size()); } @Test public void testRollbackOnlyAbortsTransaction() throws Exception { Handle h = this.openHandle(); try { h.inTransaction(new TransactionCallback<Object>() { @Override public Object inTransaction(Handle handle, TransactionStatus status) throws Exception { handle.insert("insert into something (id, name) values (:id, :name)", 0, "Keith"); status.setRollbackOnly(); return "Hi"; } }); fail("Should have thrown exception"); } catch (TransactionFailedException e) { assertTrue(true); } List<Something> r = h.createQuery("select * from something").map(Something.class).list(); assertEquals(0, r.size()); } @Test public void testCheckpoint() throws Exception { Handle h = openHandle(); h.begin(); h.insert("insert into something (id, name) values (:id, :name)", 1, "Tom"); h.checkpoint("first"); h.insert("insert into something (id, name) values (:id, :name)", 1, "Martin"); assertEquals(Integer.valueOf(2), h.createQuery("select count(*) from something").map(new IntegerMapper()).first()); h.rollback("first"); assertEquals(Integer.valueOf(1), h.createQuery("select count(*) from something").map(new IntegerMapper()).first()); h.commit(); assertEquals(Integer.valueOf(1), h.createQuery("select count(*) from something").map(new IntegerMapper()).first()); } @Test public void testReleaseCheckpoint() throws Exception { Handle h = openHandle(); h.begin(); h.checkpoint("first"); h.insert("insert into something (id, name) values (:id, :name)", 1, "Martin"); h.release("first"); try { h.rollback("first"); fail("Should have thrown an exception of some kind"); } catch (TransactionException e) { h.rollback(); assertTrue(true); } } @Test public void testThrowingRuntimeExceptionPercolatesOriginal() throws Exception { Handle h = openHandle(); try { h.inTransaction(new TransactionCallback<Object>() { @Override public Object inTransaction(Handle handle, TransactionStatus status) throws Exception { throw new IllegalArgumentException(); } }); } catch (DBIException e) { fail("Should have thrown a straight RuntimeException"); } catch (IllegalArgumentException e) { assertEquals("Go here", 2, 1 + 1); } catch (Exception e) { fail("Should have been caught at IllegalArgumentException"); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestDataSourceConnectionFactory.java
jdbi/src/test/java/org/skife/jdbi/v2/TestDataSourceConnectionFactory.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.derby.DerbyHelper; import java.sql.Connection; import static org.junit.Assert.assertFalse; @Category(JDBITests.class) public class TestDataSourceConnectionFactory { private static final DerbyHelper DERBY_HELPER = new DerbyHelper(); @BeforeClass public static void setUpClass() throws Exception { DERBY_HELPER.start(); } @AfterClass public static void tearDownClass() throws Exception { DERBY_HELPER.stop(); } private DataSourceConnectionFactory f; @Before public void setUp() throws Exception { this.f = new DataSourceConnectionFactory(DERBY_HELPER.getDataSource()); } @Test public void testObtainConnection() throws Exception { Connection c = f.openConnection(); assertFalse(c.isClosed()); c.close(); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestMapArguments.java
jdbi/src/test/java/org/skife/jdbi/v2/TestMapArguments.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.tweak.Argument; import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.MatcherAssert.assertThat; @Category(JDBITests.class) public class TestMapArguments { @Test public void testBind() throws Exception { Map<String, Object> args = new HashMap<String, Object>(); args.put("foo", BigDecimal.ONE); Foreman foreman = new Foreman(); StatementContext ctx = new ConcreteStatementContext(new HashMap<String, Object>()); MapArguments mapArguments = new MapArguments(foreman, ctx, args); Argument argument = mapArguments.find("foo"); assertThat(argument, instanceOf(BigDecimalArgument.class)); } @Test public void testNullBinding() throws Exception { Map<String, Object> args = new HashMap<String, Object>(); args.put("foo", null); Foreman foreman = new Foreman(); StatementContext ctx = new ConcreteStatementContext(new HashMap<String, Object>()); MapArguments mapArguments = new MapArguments(foreman, ctx, args); Argument argument = mapArguments.find("foo"); assertThat(argument, instanceOf(ObjectArgument.class)); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestBatch.java
jdbi/src/test/java/org/skife/jdbi/v2/TestBatch.java
/* * Copyright 2004-2014 Brian McCallister * 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.skife.jdbi.v2; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.List; import static org.junit.Assert.assertEquals; /** * */ @Category(JDBITests.class) public class TestBatch extends DBITestCase { @Test public void testBasics() throws Exception { Handle h = this.openHandle(); Batch b = h.createBatch(); b.add("insert into something (id, name) values (0, 'Keith')"); b.add("insert into something (id, name) values (1, 'Eric')"); b.add("insert into something (id, name) values (2, 'Brian')"); b.execute(); List<Something> r = h.createQuery("select * from something order by id").map(Something.class).list(); assertEquals(3, r.size()); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false