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/jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/EqualsHandler.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/EqualsHandler.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.sqlobject; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Callable; class EqualsHandler implements Handler { @Override public Object invoke(final HandleDing h, final Object target, final Object[] args, final Callable<?> methodProxy) { // basic reference equals for now. return target == args[0]; } static Map<Method, Handler> handler() { try { Map<Method, Handler> handler = new HashMap<Method, Handler>(); handler.put(Object.class.getMethod("equals", Object.class), new EqualsHandler()); return handler; } catch (NoSuchMethodException e) { throw new IllegalStateException("JVM error"); } } }
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/main/java/org/skife/jdbi/v2/sqlobject/CommitHandler.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/CommitHandler.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.sqlobject; import java.util.concurrent.Callable; class CommitHandler implements Handler { @Override public Object invoke(HandleDing h, Object target, Object[] args, Callable<?> methodProxy) { h.release("transaction#explicit"); h.getHandle().commit(); 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/jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/GetHandleHandler.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/GetHandleHandler.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.sqlobject; import java.util.concurrent.Callable; class GetHandleHandler implements Handler { @Override public Object invoke(HandleDing h, Object target, Object[] args, Callable<?> methodProxy) { return h.getHandle(); } }
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/main/java/org/skife/jdbi/v2/sqlobject/BindMap.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/BindMap.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.sqlobject; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Bind a {@code Map<String, Object>} */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.PARAMETER}) @BindingAnnotation(BindMapFactory.class) public @interface BindMap { /** * The list of allowed map keys to bind. * If not specified, to binds all provided {@code Map} entries. Any missing parameters will cause an exception. * If specified, binds all provided keys. Missing entries are bound with a SQL {@code NULL}. */ String[] value() default {}; /** * If specified, key {@code key} will be bound as {@code prefix.key}. */ String prefix() default BindBean.BARE_BINDING; /** * Specify key handling. * If false, {@code Map} keys must be strings, or an exception is thrown. * If true, any object may be the key, and it will be converted with {@link Object#toString()}. */ boolean implicitKeyStringConversion() default false; }
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/main/java/org/skife/jdbi/v2/sqlobject/BatchHandler.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/BatchHandler.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.sqlobject; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.concurrent.Callable; import org.skife.jdbi.v2.GeneratedKeys; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.PreparedBatch; import org.skife.jdbi.v2.PreparedBatchPart; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.TransactionCallback; import org.skife.jdbi.v2.TransactionStatus; import org.skife.jdbi.v2.exceptions.DBIException; import org.skife.jdbi.v2.exceptions.UnableToCreateStatementException; import org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException; import org.skife.jdbi.v2.sqlobject.customizers.BatchChunkSize; import org.skife.jdbi.v2.tweak.ResultSetMapper; import com.fasterxml.classmate.members.ResolvedMethod; class BatchHandler extends CustomizingStatementHandler { private final String sql; private final boolean transactional; private final ChunkSizeFunction batchChunkSize; private final Returner returner; BatchHandler(Class<?> sqlObjectType, ResolvedMethod method) { super(sqlObjectType, method); Method raw_method = method.getRawMember(); SqlBatch anno = raw_method.getAnnotation(SqlBatch.class); this.sql = SqlObject.getSql(anno, raw_method); this.transactional = anno.transactional(); this.batchChunkSize = determineBatchChunkSize(sqlObjectType, raw_method); final GetGeneratedKeys getGeneratedKeys = raw_method.getAnnotation(GetGeneratedKeys.class); if (getGeneratedKeys == null) { if (!returnTypeIsValid(method.getRawMember().getReturnType())) { throw new DBIException(invalidReturnTypeMessage(method)) {}; } returner = new Returner() { @Override public Object value(PreparedBatch batch, HandleDing baton) { return batch.execute(); } }; } else { final ResultSetMapper mapper; try { mapper = getGeneratedKeys.value().newInstance(); } catch (Exception e) { throw new UnableToCreateStatementException("Unable to instantiate result set mapper for statement", e); } final ResultReturnThing magic = ResultReturnThing.forType(method); if (getGeneratedKeys.columnName().isEmpty()) { returner = new Returner() { @Override public Object value(PreparedBatch batch, HandleDing baton) { GeneratedKeys o = batch.executeAndGenerateKeys(mapper); return magic.result(o, baton); } }; } else { returner = new Returner() { @Override public Object value(PreparedBatch batch, HandleDing baton) { String columnName = getGeneratedKeys.columnName(); GeneratedKeys o = batch.executeAndGenerateKeys(mapper, columnName); return magic.result(o, baton); } }; } } } private ChunkSizeFunction determineBatchChunkSize(Class<?> sqlObjectType, Method raw_method) { // this next big if chain determines the batch chunk size. It looks from most specific // scope to least, that is: as an argument, then on the method, then on the class, // then default to Integer.MAX_VALUE int index_of_batch_chunk_size_annotation_on_parameter; if ((index_of_batch_chunk_size_annotation_on_parameter = findBatchChunkSizeFromParam(raw_method)) >= 0) { return new ParamBasedChunkSizeFunction(index_of_batch_chunk_size_annotation_on_parameter); } else if (raw_method.isAnnotationPresent(BatchChunkSize.class)) { final int size = raw_method.getAnnotation(BatchChunkSize.class).value(); if (size <= 0) { throw new IllegalArgumentException("Batch chunk size must be >= 0"); } return new ConstantChunkSizeFunction(size); } else if (sqlObjectType.isAnnotationPresent(BatchChunkSize.class)) { final int size = BatchChunkSize.class.cast(sqlObjectType.getAnnotation(BatchChunkSize.class)).value(); return new ConstantChunkSizeFunction(size); } else { return new ConstantChunkSizeFunction(Integer.MAX_VALUE); } } private int findBatchChunkSizeFromParam(Method raw_method) { Annotation[][] param_annos = raw_method.getParameterAnnotations(); for (int i = 0; i < param_annos.length; i++) { Annotation[] annos = param_annos[i]; for (Annotation anno : annos) { if (anno.annotationType().isAssignableFrom(BatchChunkSize.class)) { return i; } } } return -1; } @Override public Object invoke(HandleDing h, Object target, Object[] args, Callable<?> methodProxy) { boolean foundIterator = false; Handle handle = h.getHandle(); List<Iterator> extras = new ArrayList<Iterator>(); for (final Object arg : args) { if (arg instanceof Iterable) { extras.add(((Iterable) arg).iterator()); foundIterator = true; } else if (arg instanceof Iterator) { extras.add((Iterator) arg); foundIterator = true; } else if (arg.getClass().isArray()) { extras.add(Arrays.asList((Object[])arg).iterator()); foundIterator = true; } else { extras.add(new Iterator() { @Override public boolean hasNext() { return true; } @Override public Object next() { // This is the table name for instance (repeated during iteration) return arg; } @Override public void remove() { // NOOP } } ); } } if (!foundIterator) { throw new UnableToExecuteStatementException("@SqlBatch must have at least one iterable parameter", (StatementContext)null); } int processed = 0; List<Object> results = new LinkedList<Object>(); PreparedBatch batch = handle.prepareBatch(sql); applyCustomizers(batch, args); Object[] _args; int chunk_size = batchChunkSize.call(args); while ((_args = next(extras)) != null) { PreparedBatchPart part = batch.add(); applyBinders(part, _args); if (++processed == chunk_size) { // execute this chunk processed = 0; executeBatch(results, h, handle, batch); batch = handle.prepareBatch(sql); applyCustomizers(batch, args); } } //execute the rest if (batch.getSize() > 0) { executeBatch(results, h, handle, batch); } return results; } private void executeBatch(final Collection<Object> results, final HandleDing h, final Handle handle, final PreparedBatch batch) { final Object res = executeBatch(h, handle, batch); if (res instanceof Collection) { results.addAll((Collection) res); } else { results.add(res); } } private Object executeBatch(final HandleDing h, final Handle handle, final PreparedBatch batch) { if (!handle.isInTransaction() && transactional) { // it is safe to use same prepared batch as the inTransaction passes in the same // Handle instance. return handle.inTransaction(new TransactionCallback<Object>() { @Override public Object inTransaction(Handle conn, TransactionStatus status) throws Exception { return returner.value(batch, h); } }); } else { return returner.value(batch, h); } } private static Object[] next(List<Iterator> args) { List<Object> rs = new ArrayList<Object>(); for (Iterator arg : args) { if (arg.hasNext()) { rs.add(arg.next()); } else { return null; } } return rs.toArray(); } private interface Returner { Object value(PreparedBatch batch, HandleDing baton); } private interface ChunkSizeFunction { int call(Object[] args); } private static class ConstantChunkSizeFunction implements ChunkSizeFunction { private final int value; ConstantChunkSizeFunction(int value) { this.value = value; } @Override public int call(Object[] args) { return value; } } private static class ParamBasedChunkSizeFunction implements ChunkSizeFunction { private final int index; ParamBasedChunkSizeFunction(int index) { this.index = index; } @Override public int call(Object[] args) { return (Integer)args[index]; } } private static boolean returnTypeIsValid(Class<?> type) { if (type.equals(Void.TYPE) || type.isArray() && type.getComponentType().equals(Integer.TYPE)) { return true; } return false; } private static String invalidReturnTypeMessage(ResolvedMethod method) { return method.getDeclaringType() + "." + method + " method is annotated with @SqlBatch so should return void or int[] but is returning: " + method.getReturnType(); } }
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/main/java/org/skife/jdbi/v2/sqlobject/SqlObjectInterceptor.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/SqlObjectInterceptor.java
/* * 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.skife.jdbi.v2.sqlobject; import java.lang.reflect.Method; import java.util.concurrent.Callable; import net.bytebuddy.implementation.bind.annotation.AllArguments; import net.bytebuddy.implementation.bind.annotation.Origin; import net.bytebuddy.implementation.bind.annotation.RuntimeType; import net.bytebuddy.implementation.bind.annotation.SuperCall; import net.bytebuddy.implementation.bind.annotation.This; public class SqlObjectInterceptor { SqlObject so; public SqlObjectInterceptor(final SqlObject so) {this.so = so;} /** * This method intercepts all abstract methods with any annotations. */ @RuntimeType public Object intercept(@This Object target, @Origin Method method, @AllArguments Object[] args) throws Throwable { // Method proxy is null as super method invocation is not needed for abstract methods. return so.invoke(target, method, args, null); } /** * This method intercepts all non-abstract methods. * It passes callable method proxy reference to downstream logic so that the actual super method can be invoked. */ @RuntimeType public Object intercept(@Origin Method method, @SuperCall Callable<?> methodProxy, @This Object target, @AllArguments Object[] args) throws Throwable { return so.invoke(target, method, args, methodProxy); } }
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/main/java/org/skife/jdbi/v2/sqlobject/ReleaseCheckpointHandler.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/ReleaseCheckpointHandler.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.sqlobject; import java.util.concurrent.Callable; class ReleaseCheckpointHandler implements Handler { @Override public Object invoke(HandleDing h, Object target, Object[] args, Callable<?> methodProxy) { h.getHandle().release(String.valueOf(args[0])); 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/jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/SqlQuery.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/SqlQuery.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.sqlobject; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Used to indicate that a method should execute a query. */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface SqlQuery { String DEFAULT_VALUE = " $#@!!@#% "; /** * The query (or query name if using a statement locator) to be executed. The default value will use * the method name of the method being annotated. This default behavior is only useful in conjunction * with a statement locator. */ String value() default DEFAULT_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/main/java/org/skife/jdbi/v2/sqlobject/SqlStatementCustomizer.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/SqlStatementCustomizer.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.sqlobject; import org.skife.jdbi.v2.SQLStatement; import java.sql.SQLException; /** * Used with {@link org.skife.jdbi.v2.sqlobject.SqlStatementCustomizerFactory} to * customize sql statements via annotations */ public interface SqlStatementCustomizer { /** * Invoked to customize the sql statement * @param q the statement being customized * @throws SQLException will abort statement creation */ void apply(SQLStatement q) 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/main/java/org/skife/jdbi/v2/sqlobject/PassThroughHandler.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/PassThroughHandler.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.sqlobject; import java.lang.reflect.Method; import java.util.concurrent.Callable; class PassThroughHandler implements Handler { private final Method method; PassThroughHandler(Method method) { this.method = method; } @Override public Object invoke(HandleDing h, Object target, Object[] args, Callable<?> methodProxy) { try { return methodProxy.call(); } catch (AbstractMethodError e) { throw new AbstractMethodError("Method " + method.getDeclaringClass().getName() + "#" + method.getName() + " doesn't make sense -- it probably needs a @Sql* annotation of some kind."); } catch (Throwable throwable) { /* */ if (throwable instanceof RuntimeException) { throw (RuntimeException) throwable; } else if (throwable instanceof Error) { throw (Error) throwable; } else { throw new RuntimeException(throwable); } } } }
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/main/java/org/skife/jdbi/v2/sqlobject/BeginHandler.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/BeginHandler.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.sqlobject; import java.util.concurrent.Callable; class BeginHandler implements Handler { @Override public Object invoke(HandleDing h, Object target, Object[] args, Callable<?> methodProxy) { h.retain("transaction#explicit"); h.getHandle().begin(); 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/jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/PositionalBinder.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/PositionalBinder.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.sqlobject; import org.skife.jdbi.v2.SQLStatement; import java.lang.annotation.Annotation; /** * A binder that bind an argument by its position in the arguments list */ public class PositionalBinder implements Binder<Annotation, Object> { private final int position; public PositionalBinder(int position) { this.position = position; } @Override public void bind(SQLStatement<?> q, Annotation bind, Object arg) { q.bind(String.valueOf(position), arg); } }
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/main/java/org/skife/jdbi/v2/sqlobject/InTransactionHandler.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/InTransactionHandler.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.sqlobject; import java.util.concurrent.Callable; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.Transaction; import org.skife.jdbi.v2.TransactionCallback; import org.skife.jdbi.v2.TransactionStatus; class InTransactionHandler implements Handler { @Override public Object invoke(HandleDing h, final Object target, Object[] args, Callable<?> methodProxy) { h.retain("transaction#implicit"); try { final Transaction t = (Transaction) args[0]; return h.getHandle().inTransaction(new TransactionCallback() { @Override public Object inTransaction(Handle conn, TransactionStatus status) throws Exception { return t.inTransaction(target, status); } }); } finally { h.release("transaction#implicit"); } } }
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/main/java/org/skife/jdbi/v2/sqlobject/BinderFactory.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/BinderFactory.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.sqlobject; import java.lang.annotation.Annotation; /** * Factor for building {@link Binder} instances. This interface is used by * the {@link BindingAnnotation} */ public interface BinderFactory { /** * Called to build a Binder * @param annotation the {@link BindingAnnotation} which lead to this call * @return a binder to use */ Binder build(Annotation annotation); }
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/main/java/org/skife/jdbi/v2/sqlobject/ToStringHandler.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/ToStringHandler.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.sqlobject; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Callable; class ToStringHandler implements Handler { private final String className; ToStringHandler(String className) { this.className = className; } @Override public Object invoke(final HandleDing h, final Object target, final Object[] args, final Callable<?> methodProxy) { return className + '@' + Integer.toHexString(target.hashCode()); } static Map<Method, Handler> handler(String className) { try { Map<Method, Handler> handler = new HashMap<Method, Handler>(); handler.put(Object.class.getMethod("toString"), new ToStringHandler(className)); return handler; } catch (NoSuchMethodException e) { throw new IllegalStateException("JVM error"); } } }
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/main/java/org/skife/jdbi/v2/sqlobject/SqlStatementCustomizerFactory.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/SqlStatementCustomizerFactory.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.sqlobject; import java.lang.annotation.Annotation; import java.lang.reflect.Method; /** * Interface used in conjunction with {@link SqlStatementCustomizingAnnotation} to generate * {@link SqlStatementCustomizer} instances. */ public interface SqlStatementCustomizerFactory { /** * Used to create customizers for annotations on methods. * * @param annotation the annotation which lead to the method being called * @param sqlObjectType sql object class (interface) * @param method the method which was annotated * @return the customizer which will be applied to the generated statement */ SqlStatementCustomizer createForMethod(Annotation annotation, Class sqlObjectType, Method method); /** * Used to create customizers for annotations on sql object interfaces * * @param annotation the annotation which lead to the method being called * @param sqlObjectType sql object class (interface) * @return the customizer which will be applied to the generated statement */ SqlStatementCustomizer createForType(Annotation annotation, Class sqlObjectType); /** * Used to create customizers for annotations on parameters * * @param annotation the annotation which lead to the method being called * @param sqlObjectType sql object class (interface) * @param method the method which was annotated * @param arg the argument value for the annotated parameter * @return the customizer which will be applied to the generated statement */ SqlStatementCustomizer createForParameter(Annotation annotation, Class sqlObjectType, Method method, Object arg); }
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/main/java/org/skife/jdbi/v2/sqlobject/CreateSqlObject.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/CreateSqlObject.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.sqlobject; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Use this annotation on a sql object method to create a new sql object * with the same underlying handle source (onDemand, attached, etc) as the * sql object the method is invoked on. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface CreateSqlObject { }
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/main/java/org/skife/jdbi/v2/sqlobject/OnDemandHandleDing.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/OnDemandHandleDing.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.sqlobject; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.IDBI; import java.util.HashSet; import java.util.Set; class OnDemandHandleDing implements HandleDing { private final IDBI dbi; private final ThreadLocal<LocalDing> threadDing = new ThreadLocal<LocalDing>(); OnDemandHandleDing(IDBI dbi) { this.dbi = dbi; } @Override public Handle getHandle() { if (threadDing.get() == null) { threadDing.set(new LocalDing(dbi.open())); } return threadDing.get().getHandle(); } @Override public void retain(String name) { getHandle(); // need to ensure the local ding has been created as this is called before getHandle sometimes. threadDing.get().retain(name); } @Override public void release(String name) { LocalDing ding = threadDing.get(); if (ding == null) { return; } ding.release(name); } class LocalDing implements HandleDing { private final Set<String> retentions = new HashSet<String>(); private final Handle handle; public LocalDing(Handle handle) { this.handle = handle; } @Override public Handle getHandle() { return handle; } @Override public void release(String name) { retentions.remove(name); if (retentions.isEmpty()) { threadDing.set(null); handle.close(); } } @Override public void retain(String name) { retentions.add(name); } } }
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/main/java/org/skife/jdbi/v2/sqlobject/FigureItOutResultSetMapper.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/FigureItOutResultSetMapper.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.sqlobject; import org.skife.jdbi.v2.PrimitivesMapperFactory; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.tweak.ResultSetMapper; import org.skife.jdbi.v2.util.BigDecimalMapper; import org.skife.jdbi.v2.util.BooleanMapper; import org.skife.jdbi.v2.util.ByteArrayMapper; import org.skife.jdbi.v2.util.ShortMapper; import org.skife.jdbi.v2.util.FloatMapper; import org.skife.jdbi.v2.util.DoubleMapper; import org.skife.jdbi.v2.util.ByteMapper; import org.skife.jdbi.v2.util.URLMapper; import org.skife.jdbi.v2.util.IntegerMapper; import org.skife.jdbi.v2.util.LongMapper; import org.skife.jdbi.v2.util.TimestampMapper; import org.skife.jdbi.v2.util.StringMapper; import java.lang.reflect.Method; import java.math.BigDecimal; import java.net.URL; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; class FigureItOutResultSetMapper implements ResultSetMapper<Object> { private static final PrimitivesMapperFactory factory = new PrimitivesMapperFactory(); @Override public Object map(int index, ResultSet r, StatementContext ctx) throws SQLException { Method m = ctx.getSqlObjectMethod(); Class<?> rt = m.getReturnType(); GetGeneratedKeys ggk = m.getAnnotation(GetGeneratedKeys.class); String keyColumn = ggk.columnName(); ResultSetMapper f; if (!"".equals(keyColumn)) { f = figureOutMapper(rt, keyColumn); } else { f = factory.mapperFor(rt, ctx); } return f.map(index, r, ctx); } ResultSetMapper figureOutMapper(Class keyType, String keyColumn) { ResultSetMapper f; if (keyType.isAssignableFrom(BigDecimal.class)) { f = new BigDecimalMapper(keyColumn); } else if (keyType.isAssignableFrom(Boolean.class) || keyType.isAssignableFrom(boolean.class)) { f = new BooleanMapper(keyColumn); } else if (keyType.isAssignableFrom(byte[].class)) { f = new ByteArrayMapper(keyColumn); } else if (keyType.isAssignableFrom(Short.class) || keyType.isAssignableFrom(short.class)) { f = new ShortMapper(keyColumn); } else if (keyType.isAssignableFrom(float.class) || keyType.isAssignableFrom(Float.class)) { f = new FloatMapper(keyColumn); } else if (keyType.isAssignableFrom(Double.class) || keyType.isAssignableFrom(double.class)) { f = new DoubleMapper(keyColumn); } else if (keyType.isAssignableFrom(Byte.class) || keyType.isAssignableFrom(byte.class)) { f = new ByteMapper(keyColumn); } else if (keyType.isAssignableFrom(URL.class)) { f = new URLMapper(keyColumn); } else if (keyType.isAssignableFrom(Integer.class) || keyType.isAssignableFrom(int.class)) { f = new IntegerMapper(keyColumn); } else if (keyType.isAssignableFrom(Long.class) || keyType.isAssignableFrom(long.class)) { f = new LongMapper(keyColumn); } else if (keyType.isAssignableFrom(Timestamp.class)) { f = new TimestampMapper(keyColumn); } else if (keyType.isAssignableFrom(String.class)) { f = new StringMapper(keyColumn); } else { f = new LongMapper(keyColumn); } return f; } }
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/main/java/org/skife/jdbi/v2/sqlobject/TransmogrifierHelper.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/TransmogrifierHelper.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.sqlobject; import org.skife.jdbi.v2.sqlobject.mixins.Transmogrifier; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; class TransmogrifierHelper { static Map<Method, Handler> handlers() { try { Map<Method, Handler> h = new HashMap<Method, Handler>(); h.put(Transmogrifier.class.getMethod("become", Class.class), new TransformHandler()); return h; } catch (NoSuchMethodException e) { throw new IllegalStateException("someone wonkered up the bytecode", 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/main/java/org/skife/jdbi/v2/sqlobject/SqlObject.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/SqlObject.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.sqlobject; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicLong; import com.fasterxml.classmate.MemberResolver; import com.fasterxml.classmate.ResolvedType; import com.fasterxml.classmate.ResolvedTypeWithMembers; import com.fasterxml.classmate.TypeResolver; import com.fasterxml.classmate.members.ResolvedMethod; import net.bytebuddy.ByteBuddy; import net.bytebuddy.TypeCache; import net.bytebuddy.TypeCache.WithInlineExpunction; import net.bytebuddy.description.modifier.Visibility; import net.bytebuddy.dynamic.loading.ClassLoadingStrategy.Default; import net.bytebuddy.implementation.MethodDelegation; import static net.bytebuddy.matcher.ElementMatchers.any; class SqlObject { private static final TypeResolver typeResolver = new TypeResolver(); private static final Map<Method, Handler> mixinHandlers = new HashMap<>(); private static final ConcurrentMap<Class<?>, Map<Method, Handler>> handlersCache = new ConcurrentHashMap<>(); private static final TypeCache<Class<?>> typeCache = new WithInlineExpunction<>(TypeCache.Sort.SOFT); static { mixinHandlers.putAll(TransactionalHelper.handlers()); mixinHandlers.putAll(GetHandleHelper.handlers()); mixinHandlers.putAll(TransmogrifierHelper.handlers()); } static <T> T buildSqlObject(final Class<T> sqlObjectType, final HandleDing handle) { final T sqlObjectProxy; final Class<?> loadedClass = typeCache.findOrInsert(sqlObjectType.getClassLoader(), sqlObjectType, () -> new ByteBuddy() .subclass(sqlObjectType) .implement(CloseInternalDoNotUseThisClass.class) .defineField("delegateToSqlObjectInterceptor", SqlObjectInterceptor.class, Visibility.PUBLIC) .method(any()) .intercept(MethodDelegation.toField("delegateToSqlObjectInterceptor")) .make() .load(sqlObjectType.getClassLoader(), Default.INJECTION) .getLoaded()); try { sqlObjectProxy = sqlObjectType.cast(loadedClass.getConstructor().newInstance()); } catch (final ReflectiveOperationException e) { throw new AssertionError("Failed to instantiate proxy class for " + sqlObjectType.getName(), e); } final SqlObject sqlObject = new SqlObject(buildHandlersFor(sqlObjectType), handle); final SqlObjectInterceptor sqlObjectInterceptor = new SqlObjectInterceptor(sqlObject); try { final Field sqlObjectField = sqlObjectProxy.getClass().getField("delegateToSqlObjectInterceptor"); sqlObjectField.setAccessible(true); sqlObjectField.set(sqlObjectProxy, sqlObjectInterceptor); } catch (final NoSuchFieldException | IllegalAccessException e) { throw new AssertionError("Failed to delegate a method call to " + SqlObjectInterceptor.class.getName(), e); } return sqlObjectProxy; } private static Map<Method, Handler> buildHandlersFor(Class<?> sqlObjectType) { if (handlersCache.containsKey(sqlObjectType)) { return handlersCache.get(sqlObjectType); } final MemberResolver mr = new MemberResolver(typeResolver); final ResolvedType sql_object_type = typeResolver.resolve(sqlObjectType); final ResolvedTypeWithMembers d = mr.resolve(sql_object_type, null, null); final Map<Method, Handler> handlers = new HashMap<Method, Handler>(); for (final ResolvedMethod method : d.getMemberMethods()) { final Method raw_method = method.getRawMember(); if (raw_method.isAnnotationPresent(SqlQuery.class)) { handlers.put(raw_method, new QueryHandler(sqlObjectType, method, ResultReturnThing.forType(method))); } else if (raw_method.isAnnotationPresent(SqlUpdate.class)) { handlers.put(raw_method, new UpdateHandler(sqlObjectType, method)); } else if (raw_method.isAnnotationPresent(SqlBatch.class)) { handlers.put(raw_method, new BatchHandler(sqlObjectType, method)); } else if (raw_method.isAnnotationPresent(SqlCall.class)) { handlers.put(raw_method, new CallHandler(sqlObjectType, method)); } else if(raw_method.isAnnotationPresent(CreateSqlObject.class)) { handlers.put(raw_method, new CreateSqlObjectHandler(raw_method.getReturnType())); } else if (method.getName().equals("close") && method.getRawMember().getParameterTypes().length == 0) { handlers.put(raw_method, new CloseHandler()); } else if (raw_method.isAnnotationPresent(Transaction.class)) { handlers.put(raw_method, new PassThroughTransactionHandler(raw_method, raw_method.getAnnotation(Transaction.class))); } else if (mixinHandlers.containsKey(raw_method)) { handlers.put(raw_method, mixinHandlers.get(raw_method)); } else { handlers.put(raw_method, new PassThroughHandler(raw_method)); } } // this is an implicit mixin, not an explicit one, so we need to *always* add it handlers.putAll(CloseInternalDoNotUseThisClass.Helper.handlers()); handlers.putAll(EqualsHandler.handler()); handlers.putAll(ToStringHandler.handler(sqlObjectType.getName())); handlers.putAll(HashCodeHandler.handler()); handlersCache.put(sqlObjectType, handlers); return handlers; } private final Map<Method, Handler> handlers; private final HandleDing ding; private static final AtomicLong RETAINER = new AtomicLong(); public SqlObject(Map<Method, Handler> handlers, HandleDing ding) { this.handlers = handlers; this.ding = ding; } public Object invoke(Object proxy, Method method, Object[] args, Callable<?> methodProxy) throws Throwable { Handler handler = handlers.get(method); // If there is no handler, pretend we are just an Object and don't open a connection (Issue #82) if (handler == null || handler instanceof PassThroughHandler) { if (Objects.isNull(methodProxy)) { throw new AbstractMethodError("Method " + method.getDeclaringClass().getName() + "#" + method.getName() + " doesn't make sense -- it probably needs a @Sql* annotation of some kind."); } return methodProxy.call(); } Throwable doNotMask = null; // [OPTIMIZATION] method.toString() is expensive final String retainName = String.valueOf(RETAINER.getAndIncrement()); try { ding.retain(retainName); return handler.invoke(ding, proxy, args, methodProxy); } catch (Throwable e) { doNotMask = e; throw e; } finally { try { ding.release(retainName); } catch (Throwable e) { if (doNotMask==null) { throw e; } } } } public static void close(Object sqlObject) { if (!(sqlObject instanceof CloseInternalDoNotUseThisClass)) { throw new IllegalArgumentException(sqlObject + " is not a sql object"); } CloseInternalDoNotUseThisClass closer = (CloseInternalDoNotUseThisClass) sqlObject; closer.___jdbi_close___(); } static String getSql(SqlCall q, Method m) { if (SqlQuery.DEFAULT_VALUE.equals(q.value())) { return m.getName(); } else { return q.value(); } } static String getSql(SqlQuery q, Method m) { if (SqlQuery.DEFAULT_VALUE.equals(q.value())) { return m.getName(); } else { return q.value(); } } static String getSql(SqlUpdate q, Method m) { if (SqlQuery.DEFAULT_VALUE.equals(q.value())) { return m.getName(); } else { return q.value(); } } static String getSql(SqlBatch q, Method m) { if (SqlQuery.DEFAULT_VALUE.equals(q.value())) { return m.getName(); } else { return q.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/main/java/org/skife/jdbi/v2/sqlobject/HashCodeHandler.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/HashCodeHandler.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.sqlobject; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Callable; class HashCodeHandler implements Handler { static Map<Method, Handler> handler() { try { Map<Method, Handler> handler = new HashMap<Method, Handler>(); handler.put(Object.class.getMethod("hashCode"), new HashCodeHandler()); return handler; } catch (NoSuchMethodException e) { throw new IllegalStateException("JVM error"); } } @Override public Object invoke(HandleDing h, Object target, Object[] args, Callable<?> methodProxy) { return System.identityHashCode(target); } }
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/main/java/org/skife/jdbi/v2/sqlobject/Handler.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/Handler.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.sqlobject; import java.util.concurrent.Callable; interface Handler { Object invoke(HandleDing h, Object target, Object[] args, Callable<?> methodProxy); }
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/main/java/org/skife/jdbi/v2/sqlobject/SqlObjectBuilder.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/SqlObjectBuilder.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.sqlobject; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.IDBI; /** * This duplicates the API on {@link org.skife.jdbi.v2.DBI} and {@link Handle} for creating sql objects. While it is fine to use these * methods to create sql objects, there is no real difference between them and the oones on DBI and Handle. */ public class SqlObjectBuilder { /** * Creates a sql object of the specified type bound to this handle. Any state changes to the handle, or the * sql object, such as transaction status, closing it, etc., will apply to both the object and the handle. * * @param handle the Handle instance to attach ths sql object to * @param sqlObjectType the type of sql object to create * @return the new sql object bound to this handle */ public static <T> T attach(Handle handle, Class<T> sqlObjectType) { return SqlObject.buildSqlObject(sqlObjectType, new ConstantHandleDing(handle)); } /** * Open a handle and attach a new sql object of the specified type to that handle. Be sure to close the * sql object (via a close() method, or calling {@link org.skife.jdbi.v2.IDBI#close(Object)} * * @param dbi the dbi to be used for opening the underlying handle * @param sqlObjectType an interface with annotations declaring desired behavior * * @return a new sql object of the specified type, with a dedicated handle */ public static <T> T open(IDBI dbi, Class<T> sqlObjectType) { return SqlObject.buildSqlObject(sqlObjectType, new ConstantHandleDing(dbi.open())); } /** * Create a new sql object which will obtain and release connections from this dbi instance, as it needs to, * and can, respectively. You should not explicitely close this sql object * * @param dbi the DBI instance to be used for obtaining connections when they are required * @param sqlObjectType an interface with annotations declaring desired behavior * * @return a new sql object of the specified type, with a dedicated handle */ public static <T> T onDemand(final IDBI dbi, final Class<T> sqlObjectType) { return SqlObject.buildSqlObject(sqlObjectType, new OnDemandHandleDing(dbi)); } /** * Used to close a sql object which lacks a close() method. * @param sqlObject the sql object to close */ public static void close(Object sqlObject) { SqlObject.close(sqlObject); } }
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/main/java/org/skife/jdbi/v2/sqlobject/BindingAnnotation.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/BindingAnnotation.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.sqlobject; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation used to mark binding annotations. This allows for custom binding annotations. * Implementations must provide a {@link BinderFactory} class which will be used to create * Binders to do the binding */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.ANNOTATION_TYPE}) public @interface BindingAnnotation { /** * Build a BinderFactory which will be used to build Binders, which will bind arguments */ Class<? extends BinderFactory> 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/main/java/org/skife/jdbi/v2/sqlobject/TransactionalHelper.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/TransactionalHelper.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.sqlobject; import org.skife.jdbi.v2.Transaction; import org.skife.jdbi.v2.TransactionIsolationLevel; import org.skife.jdbi.v2.sqlobject.mixins.Transactional; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; class TransactionalHelper { static Map<Method, Handler> handlers() { try { Map<Method, Handler> h = new HashMap<Method, Handler>(); h.put(Transactional.class.getMethod("begin"), new BeginHandler()); h.put(Transactional.class.getMethod("commit"), new CommitHandler()); h.put(Transactional.class.getMethod("rollback"), new RollbackHandler()); h.put(Transactional.class.getMethod("checkpoint", String.class), new CheckpointHandler()); h.put(Transactional.class.getMethod("release", String.class), new ReleaseCheckpointHandler()); h.put(Transactional.class.getMethod("rollback", String.class), new RollbackCheckpointHandler()); h.put(Transactional.class.getMethod("inTransaction", Transaction.class), new InTransactionHandler()); h.put(Transactional.class.getMethod("inTransaction", TransactionIsolationLevel.class, Transaction.class), new InTransactionWithIsolationLevelHandler()); return h; } catch (NoSuchMethodException e) { throw new IllegalStateException("someone wonkered up the bytecode", 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/main/java/org/skife/jdbi/v2/sqlobject/BindMapFactory.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/BindMapFactory.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.sqlobject; import java.lang.annotation.Annotation; import java.util.Arrays; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.skife.jdbi.v2.SQLStatement; class BindMapFactory implements BinderFactory { @Override public Binder build(Annotation annotation) { return new Binder<BindMap, Object>() { @SuppressWarnings("unchecked") @Override public void bind(SQLStatement q, BindMap bind, Object arg) { final String prefix; if (BindBean.BARE_BINDING.equals(bind.prefix())) { prefix = ""; } else { prefix = bind.prefix() + "."; } final Set<String> allowedKeys = new HashSet<String>(Arrays.asList(bind.value())); final Map<String, Object> map = (Map<String, Object>) arg; for (Entry e : map.entrySet()) { final Object keyObj = e.getKey(); final String key; if (bind.implicitKeyStringConversion() || (keyObj instanceof String)) { key = keyObj.toString(); } else { throw new IllegalArgumentException("Key " + keyObj + " (of " + keyObj.getClass() + ") must be a String"); } if (allowedKeys.isEmpty() || allowedKeys.remove(key)) { q.bind(prefix + key, e.getValue()); } } // Any leftover keys were specified but not found in the map, so bind as null for (String key : allowedKeys) { final Object val = map.get(key); if (val != null) { throw new IllegalStateException("Internal error: map iteration missed key " + key); } q.bind(prefix + key, (Object) null); } } }; } }
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/main/java/org/skife/jdbi/v2/sqlobject/CloseHandler.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/CloseHandler.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.sqlobject; import java.util.concurrent.Callable; class CloseHandler implements Handler { @Override public Object invoke(HandleDing h, Object target, Object[] args, Callable<?> methodProxy) { h.getHandle().close(); 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/jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/SqlStatementCustomizingAnnotation.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/SqlStatementCustomizingAnnotation.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.sqlobject; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Annotation used to build customizing annotations. Use this to annotate an annotation. See examples * in the org.skife.jdbi.v2.sqlobject.customizers package. */ @Retention(RetentionPolicy.RUNTIME) public @interface SqlStatementCustomizingAnnotation { /** * Specify a sql statement customizer factory which will be used to create * sql statement customizers. * @return a factory used to crate customizers for the customizing annotation */ Class<? extends SqlStatementCustomizerFactory> 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/main/java/org/skife/jdbi/v2/sqlobject/SqlBatch.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/SqlBatch.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.sqlobject; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotate a method to indicate that it will create and execute a SQL batch. At least one * bound argument must be an Iterator or Iterable, values from this will be taken and applied * to each row of the batch. Non iterable bound arguments will be treated as constant values and * bound to each row. * <p> * Unfortunately, because of how batches work, statement customizers and sql statement customizers * which affect SQL generation will *not* work with batches. This primarily effects statement location * and rewriting, which will always use the values defined on the bound Handle. * <p> * If you want to chunk up the logical batch into a number of smaller batches (say around 1000 rows at * a time in order to not wreck havoc on the transaction log, you should see * {@link org.skife.jdbi.v2.sqlobject.customizers.BatchChunkSize} */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface SqlBatch { /** * SQL String (or name) */ String value() default SqlQuery.DEFAULT_VALUE; /** * Should the batch, or batch chunks be executed in a transaction. Default is * true (and it will be strange if you want otherwise). */ boolean transactional() default true; }
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/main/java/org/skife/jdbi/v2/sqlobject/CallHandler.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/CallHandler.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.sqlobject; import java.util.concurrent.Callable; import org.skife.jdbi.v2.Call; import org.skife.jdbi.v2.ConcreteStatementContext; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.OutParameters; import com.fasterxml.classmate.members.ResolvedMethod; class CallHandler extends CustomizingStatementHandler { private final String sql; private final boolean returnOutParams; CallHandler(Class<?> sqlObjectType, ResolvedMethod method) { super(sqlObjectType, method); if (null != method.getReturnType() ) { if (method.getReturnType().isInstanceOf(OutParameters.class)){ returnOutParams = true; } else { throw new IllegalArgumentException("@SqlCall methods may only return null or OutParameters at present"); } } else { returnOutParams = false; } this.sql = SqlObject.getSql(method.getRawMember().getAnnotation(SqlCall.class), method.getRawMember()); } @Override public Object invoke(HandleDing ding, Object target, Object[] args, Callable<?> methodProxy) { Handle h = ding.getHandle(); Call call = h.createCall(sql); populateSqlObjectData((ConcreteStatementContext)call.getContext()); applyCustomizers(call, args); applyBinders(call, args); OutParameters ou = call.invoke(); if (returnOutParams) { return ou; } else { 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/jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/Binder.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/Binder.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.sqlobject; import org.skife.jdbi.v2.SQLStatement; import java.lang.annotation.Annotation; public interface Binder<AnnotationType extends Annotation, ArgType> { void bind(SQLStatement<?> q, AnnotationType bind, ArgType arg); }
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/main/java/org/skife/jdbi/v2/sqlobject/CustomizingStatementHandler.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/CustomizingStatementHandler.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.sqlobject; import com.fasterxml.classmate.members.ResolvedMethod; import org.skife.jdbi.v2.ConcreteStatementContext; import org.skife.jdbi.v2.SQLStatement; import org.skife.jdbi.v2.exceptions.UnableToCreateStatementException; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; abstract class CustomizingStatementHandler implements Handler { private final List<Bindifier> binders = new ArrayList<Bindifier>(); private final List<FactoryAnnotationPair> typeBasedCustomizerFactories = new ArrayList<FactoryAnnotationPair>(); private final List<FactoryAnnotationPair> methodBasedCustomizerFactories = new ArrayList<FactoryAnnotationPair>(); private final List<FactoryAnnotationIndexTriple> paramBasedCustomizerFactories = new ArrayList<FactoryAnnotationIndexTriple>(); private final Class<?> sqlObjectType; private final Method method; CustomizingStatementHandler(Class<?> sqlObjectType, ResolvedMethod method) { this.sqlObjectType = sqlObjectType; this.method = method.getRawMember(); for (final Annotation annotation : sqlObjectType.getAnnotations()) { if (annotation.annotationType().isAnnotationPresent(SqlStatementCustomizingAnnotation.class)) { final SqlStatementCustomizingAnnotation a = annotation.annotationType() .getAnnotation(SqlStatementCustomizingAnnotation.class); final SqlStatementCustomizerFactory f; try { f = a.value().newInstance(); } catch (Exception e) { throw new IllegalStateException("unable to create sql statement customizer factory", e); } typeBasedCustomizerFactories.add(new FactoryAnnotationPair(f, annotation)); } } final Annotation[] method_annotations = method.getRawMember().getAnnotations(); for (final Annotation method_annotation : method_annotations) { final Class<? extends Annotation> m_anno_class = method_annotation.annotationType(); if (m_anno_class.isAnnotationPresent(SqlStatementCustomizingAnnotation.class)) { final SqlStatementCustomizingAnnotation scf = m_anno_class.getAnnotation(SqlStatementCustomizingAnnotation.class); final SqlStatementCustomizerFactory f; try { f = scf.value().newInstance(); } catch (Exception e) { throw new IllegalStateException("unable to instantiate statement customizer factory", e); } methodBasedCustomizerFactories.add(new FactoryAnnotationPair(f, method_annotation)); } } final Annotation[][] param_annotations = method.getRawMember().getParameterAnnotations(); for (int param_idx = 0; param_idx < param_annotations.length; param_idx++) { boolean thereBindingAnnotation = false; for (final Annotation annotation : param_annotations[param_idx]) { final Class<? extends Annotation> anno_class = annotation.annotationType(); if (anno_class.isAnnotationPresent(BindingAnnotation.class)) { // we have a binder BindingAnnotation ba = annotation.annotationType().getAnnotation(BindingAnnotation.class); try { BinderFactory fact = ba.value().newInstance(); binders.add(new Bindifier(annotation, param_idx, fact.build(annotation))); } catch (Exception e) { throw new IllegalStateException("unable to instantiate cusotmizer", e); } thereBindingAnnotation = true; } if (anno_class.isAnnotationPresent(SqlStatementCustomizingAnnotation.class)) { SqlStatementCustomizingAnnotation sca = annotation.annotationType() .getAnnotation(SqlStatementCustomizingAnnotation.class); final SqlStatementCustomizerFactory f; try { f = sca.value().newInstance(); } catch (Exception e) { throw new IllegalStateException("unable to instantiate sql statement customizer factory", e); } paramBasedCustomizerFactories.add(new FactoryAnnotationIndexTriple(f, annotation, param_idx)); thereBindingAnnotation = true; } } if (!thereBindingAnnotation) { // If there is no binding annotation on a parameter, // then add a positional parameter binder binders.add(new Bindifier(null, param_idx, new PositionalBinder(param_idx))); } } } protected final void populateSqlObjectData(ConcreteStatementContext q) { q.setSqlObjectMethod(method); q.setSqlObjectType(sqlObjectType); } protected void applyBinders(SQLStatement<?> q, Object[] args) { for (Bindifier binder : binders) { binder.bind(q, args); } } protected void applyCustomizers(SQLStatement<?> q, Object[] args) { for (FactoryAnnotationPair pair : typeBasedCustomizerFactories) { try { pair.factory.createForType(pair.annotation, sqlObjectType).apply(q); } catch (SQLException e) { throw new UnableToCreateStatementException("unable to apply customizer", e, q.getContext()); } } for (FactoryAnnotationPair pair : methodBasedCustomizerFactories) { try { pair.factory.createForMethod(pair.annotation, sqlObjectType, method).apply(q); } catch (SQLException e) { throw new UnableToCreateStatementException("unable to apply customizer", e, q.getContext()); } } if (args != null) { for (FactoryAnnotationIndexTriple triple : paramBasedCustomizerFactories) { try { triple.factory .createForParameter(triple.annotation, sqlObjectType, method, args[triple.index]) .apply(q); } catch (SQLException e) { throw new UnableToCreateStatementException("unable to apply customizer", e, q.getContext()); } } } } private static class FactoryAnnotationPair { private final SqlStatementCustomizerFactory factory; private final Annotation annotation; FactoryAnnotationPair(SqlStatementCustomizerFactory factory, Annotation annotation) { this.factory = factory; this.annotation = annotation; } } private static class FactoryAnnotationIndexTriple { private final SqlStatementCustomizerFactory factory; private final Annotation annotation; private final int index; FactoryAnnotationIndexTriple(SqlStatementCustomizerFactory factory, Annotation annotation, int index) { this.factory = factory; this.annotation = annotation; this.index = index; } } }
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/main/java/org/skife/jdbi/v2/sqlobject/BindBeanFactory.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/BindBeanFactory.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.sqlobject; import org.skife.jdbi.v2.SQLStatement; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.annotation.Annotation; import java.lang.reflect.Method; class BindBeanFactory implements BinderFactory { @Override public Binder build(Annotation annotation) { return new Binder<BindBean, Object>() { @Override public void bind(SQLStatement q, BindBean bind, Object arg) { final String prefix; if (BindBean.BARE_BINDING.equals(bind.value())) { prefix = ""; } else { prefix = bind.value() + "."; } try { BeanInfo infos = Introspector.getBeanInfo(arg.getClass()); PropertyDescriptor[] props = infos.getPropertyDescriptors(); for (PropertyDescriptor prop : props) { Method readMethod = prop.getReadMethod(); if (readMethod != null) { q.dynamicBind(readMethod.getReturnType(), prefix + prop.getName(), readMethod.invoke(arg)); } } } catch (Exception e) { throw new IllegalStateException("unable to bind bean properties", 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/main/java/org/skife/jdbi/v2/sqlobject/GetHandleHelper.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/GetHandleHelper.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.sqlobject; import org.skife.jdbi.v2.sqlobject.mixins.GetHandle; import org.skife.jdbi.v2.tweak.HandleCallback; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; class GetHandleHelper { static Map<Method, Handler> handlers() { try { Map<Method, Handler> h = new HashMap<Method, Handler>(); h.put(GetHandle.class.getMethod("getHandle"), new GetHandleHandler()); h.put(GetHandle.class.getMethod("withHandle", HandleCallback.class), new WithHandleHandler()); return h; } catch (NoSuchMethodException e) { throw new IllegalStateException("someone wonkered up the bytecode", 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/main/java/org/skife/jdbi/v2/sqlobject/ConstantHandleDing.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/ConstantHandleDing.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.sqlobject; import org.skife.jdbi.v2.Handle; class ConstantHandleDing implements HandleDing { private final Handle handle; ConstantHandleDing(Handle handle) { this.handle = handle; } @Override public Handle getHandle() { return handle; } @Override public void release(String name) { } @Override public void retain(String name) { } public boolean isRetained() { return false; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/Bind.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/Bind.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.sqlobject; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * A binding annotation */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.PARAMETER}) @BindingAnnotation(BindFactory.class) public @interface Bind { String value() default "it"; Class<? extends Binder> binder() default DefaultObjectBinder.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/main/java/org/skife/jdbi/v2/sqlobject/HandleDing.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/HandleDing.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.sqlobject; import org.skife.jdbi.v2.Handle; interface HandleDing { Handle getHandle(); void release(String name); void retain(String name); }
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/main/java/org/skife/jdbi/v2/sqlobject/QueryHandler.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/QueryHandler.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.sqlobject; import java.util.concurrent.Callable; import org.skife.jdbi.v2.ConcreteStatementContext; import org.skife.jdbi.v2.Query; import com.fasterxml.classmate.members.ResolvedMethod; class QueryHandler extends CustomizingStatementHandler { private final String sql; private final ResolvedMethod method; private final ResultReturnThing magic; public QueryHandler(Class<?> sqlObjectType, ResolvedMethod method, ResultReturnThing magic) { super(sqlObjectType, method); this.method = method; this.magic = magic; this.sql = SqlObject.getSql(method.getRawMember().getAnnotation(SqlQuery.class), method.getRawMember()); } @Override public Object invoke(HandleDing h, Object target, Object[] args, Callable<?> methodProxy) { Query q = h.getHandle().createQuery(sql); populateSqlObjectData((ConcreteStatementContext) q.getContext()); applyCustomizers(q, args); applyBinders(q, args); return magic.map(method, q, h); } }
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/main/java/org/skife/jdbi/v2/sqlobject/BindBean.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/BindBean.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.sqlobject; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.PARAMETER}) @BindingAnnotation(BindBeanFactory.class) public @interface BindBean { final String BARE_BINDING = "___jdbi_bare___"; String value() default BARE_BINDING; }
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/main/java/org/skife/jdbi/v2/sqlobject/CloseInternalDoNotUseThisClass.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/CloseInternalDoNotUseThisClass.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.sqlobject; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Callable; /** * This is public as we need it to be for some stuff to work. It is an internal api and NOT to be used * by users! */ public interface CloseInternalDoNotUseThisClass { void ___jdbi_close___(); static class CloseHandler implements Handler { @Override public Object invoke(HandleDing h, Object target, Object[] args, Callable<?> methodProxy) { h.getHandle().close(); return null; } } static class Helper { static Map<Method, Handler> handlers() { try { Map<Method, Handler> h = new HashMap<Method, Handler>(); h.put(CloseInternalDoNotUseThisClass.class.getMethod("___jdbi_close___"), new CloseHandler()); return h; } catch (NoSuchMethodException e) { throw new IllegalStateException("someone wonkered up the bytecode", 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/main/java/org/skife/jdbi/v2/sqlobject/ResultReturnThing.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/ResultReturnThing.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.sqlobject; import com.fasterxml.classmate.ResolvedType; import com.fasterxml.classmate.TypeBindings; import com.fasterxml.classmate.members.ResolvedMethod; import org.skife.jdbi.v2.Query; import org.skife.jdbi.v2.ResultBearing; import org.skife.jdbi.v2.ResultIterator; import org.skife.jdbi.v2.exceptions.UnableToCreateStatementException; import org.skife.jdbi.v2.sqlobject.customizers.Mapper; import org.skife.jdbi.v2.sqlobject.customizers.SingleValueResult; import org.skife.jdbi.v2.tweak.ResultSetMapper; import java.util.Iterator; import java.util.List; abstract class ResultReturnThing { public Object map(ResolvedMethod method, Query q, HandleDing h) { if (method.getRawMember().isAnnotationPresent(Mapper.class)) { final ResultSetMapper mapper; try { mapper = method.getRawMember().getAnnotation(Mapper.class).value().newInstance(); } catch (Exception e) { throw new UnableToCreateStatementException("unable to access mapper", e); } return result(q.map(mapper), h); } else { return result(q.mapTo(mapTo(method)), h); } } static ResultReturnThing forType(ResolvedMethod method) { ResolvedType return_type = method.getReturnType(); if (return_type == null) { throw new IllegalStateException(String.format( "Method %s#%s is annotated as if it should return a value, but the method is void.", method.getDeclaringType().getErasedType().getName(), method.getName())); } else if (return_type.isInstanceOf(ResultBearing.class)) { return new ResultBearingResultReturnThing(method); } else if (return_type.isInstanceOf(Iterable.class)) { return new IterableReturningThing(method); } else if (return_type.isInstanceOf(Iterator.class)) { return new IteratorResultReturnThing(method); } else { return new SingleValueResultReturnThing(method); } } protected abstract Object result(ResultBearing q, HandleDing baton); protected abstract Class<?> mapTo(ResolvedMethod method); static class SingleValueResultReturnThing extends ResultReturnThing { private final Class<?> returnType; private final Class<?> containerType; public SingleValueResultReturnThing(ResolvedMethod method) { if (method.getRawMember().isAnnotationPresent(SingleValueResult.class)) { SingleValueResult svr = method.getRawMember().getAnnotation(SingleValueResult.class); // try to guess generic type if(SingleValueResult.Default.class == svr.value()){ TypeBindings typeBindings = method.getReturnType().getTypeBindings(); if(typeBindings.size() == 1){ this.returnType = typeBindings.getBoundType(0).getErasedType(); }else{ throw new IllegalArgumentException("Ambiguous generic information. SingleValueResult type could not be fetched."); } }else{ this.returnType = svr.value(); } this.containerType = method.getReturnType().getErasedType(); } else { this.returnType = method.getReturnType().getErasedType(); this.containerType = null; } } @Override protected Object result(ResultBearing q, HandleDing baton) { return null == containerType ? q.first() : q.first(containerType); } @Override protected Class<?> mapTo(ResolvedMethod method) { return returnType; } } static class ResultBearingResultReturnThing extends ResultReturnThing { private final ResolvedType resolvedType; public ResultBearingResultReturnThing(ResolvedMethod method) { // extract T from Query<T> ResolvedType query_type = method.getReturnType(); List<ResolvedType> query_return_types = query_type.typeParametersFor(org.skife.jdbi.v2.Query.class); this.resolvedType = query_return_types.get(0); } @Override protected Object result(ResultBearing q, HandleDing baton) { return q; } @Override protected Class<?> mapTo(ResolvedMethod method) { return resolvedType.getErasedType(); } } static class IteratorResultReturnThing extends ResultReturnThing { private final ResolvedType resolvedType; public IteratorResultReturnThing(ResolvedMethod method) { ResolvedType query_type = method.getReturnType(); List<ResolvedType> query_return_types = query_type.typeParametersFor(Iterator.class); this.resolvedType = query_return_types.get(0); } @Override protected Object result(ResultBearing q, final HandleDing baton) { final ResultIterator itty = q.iterator(); final boolean isEmpty = !itty.hasNext(); if (isEmpty) { itty.close(); } else { baton.retain("iterator"); } return new ResultIterator() { private boolean closed = isEmpty; private boolean hasNext = !isEmpty; @Override public void close() { if (!closed) { closed = true; try { itty.close(); } finally { baton.release("iterator"); } } } @Override public boolean hasNext() { return hasNext; } @Override public Object next() { Object rs; try { rs = itty.next(); hasNext = itty.hasNext(); } catch (RuntimeException e) { closeIgnoreException(); throw e; } if (!hasNext) { close(); } return rs; } @SuppressWarnings("PMD.EmptyCatchBlock") public void closeIgnoreException() { try { close(); } catch (RuntimeException ex) {} } @Override public void remove() { itty.remove(); } }; } @Override protected Class<?> mapTo(ResolvedMethod method) { return resolvedType.getErasedType(); } } static class IterableReturningThing extends ResultReturnThing { private final ResolvedType resolvedType; private final Class<?> erased_type; public IterableReturningThing(ResolvedMethod method) { // extract T from List<T> ResolvedType query_type = method.getReturnType(); List<ResolvedType> query_return_types = query_type.typeParametersFor(Iterable.class); this.resolvedType = query_return_types.get(0); erased_type = method.getReturnType().getErasedType(); } @Override protected Object result(ResultBearing q, HandleDing baton) { return q.list(erased_type); } @Override protected Class<?> mapTo(ResolvedMethod method) { return resolvedType.getErasedType(); } } }
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/main/java/org/skife/jdbi/v2/sqlobject/DefaultObjectBinder.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/DefaultObjectBinder.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.sqlobject; import org.skife.jdbi.v2.SQLStatement; class DefaultObjectBinder implements Binder<Bind, Object> { @Override public void bind(SQLStatement q, Bind b, Object arg) { q.bind(b.value(), arg); } }
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/main/java/org/skife/jdbi/v2/sqlobject/Bindifier.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/Bindifier.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.sqlobject; import org.skife.jdbi.v2.SQLStatement; import java.lang.annotation.Annotation; class Bindifier { private final int param_idx; private final Binder binder; private final Annotation annotation; Bindifier(Annotation bind, int param_idx, Binder binder) { this.annotation = bind; this.param_idx = param_idx; this.binder = binder; } void bind(SQLStatement q, Object[] args) { binder.bind(q, annotation, args[param_idx]); } }
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/main/java/org/skife/jdbi/v2/sqlobject/TransformHandler.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/TransformHandler.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.sqlobject; import java.util.concurrent.Callable; class TransformHandler implements Handler { @Override public Object invoke(HandleDing h, final Object target, Object[] args, Callable<?> methodProxy) { Class t = (Class) args[0]; return SqlObject.buildSqlObject(t, h); } }
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/main/java/org/skife/jdbi/v2/sqlobject/CheckpointHandler.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/CheckpointHandler.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.sqlobject; import java.util.concurrent.Callable; class CheckpointHandler implements Handler { @Override public Object invoke(HandleDing h, Object target, Object[] args, Callable<?> methodProxy) { h.getHandle().checkpoint(String.valueOf(args[0])); 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/jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/InTransactionWithIsolationLevelHandler.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/InTransactionWithIsolationLevelHandler.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.sqlobject; import java.util.concurrent.Callable; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.Transaction; import org.skife.jdbi.v2.TransactionCallback; import org.skife.jdbi.v2.TransactionIsolationLevel; import org.skife.jdbi.v2.TransactionStatus; class InTransactionWithIsolationLevelHandler implements Handler { @Override public Object invoke(HandleDing h, final Object target, Object[] args, Callable<?> methodProxy) { h.retain("transaction#withlevel"); try { final TransactionIsolationLevel level = (TransactionIsolationLevel) args[0]; final Transaction t = (Transaction) args[1]; return h.getHandle().inTransaction(level, new TransactionCallback() { @Override public Object inTransaction(Handle conn, TransactionStatus status) throws Exception { return t.inTransaction(target, status); } }); } finally { h.release("transaction#withlevel"); } } }
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/main/java/org/skife/jdbi/v2/sqlobject/RollbackHandler.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/RollbackHandler.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.sqlobject; import java.util.concurrent.Callable; class RollbackHandler implements Handler { @Override public Object invoke(HandleDing h, Object target, Object[] args, Callable<?> methodProxy) { h.release("transaction#explicit"); h.getHandle().rollback(); 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/jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/UpdateHandler.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/UpdateHandler.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.sqlobject; import java.util.concurrent.Callable; import org.skife.jdbi.v2.ConcreteStatementContext; import org.skife.jdbi.v2.GeneratedKeys; import org.skife.jdbi.v2.Update; import org.skife.jdbi.v2.exceptions.UnableToCreateStatementException; import org.skife.jdbi.v2.tweak.ResultSetMapper; import com.fasterxml.classmate.members.ResolvedMethod; class UpdateHandler extends CustomizingStatementHandler { private final String sql; private final Returner returner; public UpdateHandler(Class<?> sqlObjectType, ResolvedMethod method) { super(sqlObjectType, method); this.sql = SqlObject.getSql(method.getRawMember().getAnnotation(SqlUpdate.class), method.getRawMember()); if (method.getRawMember().isAnnotationPresent(GetGeneratedKeys.class)) { final ResultReturnThing magic = ResultReturnThing.forType(method); final GetGeneratedKeys ggk = method.getRawMember().getAnnotation(GetGeneratedKeys.class); final ResultSetMapper mapper; try { mapper = ggk.value().newInstance(); } catch (Exception e) { throw new UnableToCreateStatementException("Unable to instantiate result set mapper for statement", e); } if (ggk.columnName().isEmpty()) { returner = new Returner() { @Override public Object value(Update update, HandleDing baton) { GeneratedKeys o = update.executeAndReturnGeneratedKeys(mapper); return magic.result(o, baton); } }; } else { returner = new Returner() { @Override public Object value(Update update, HandleDing baton) { String columnName = ggk.columnName(); GeneratedKeys o = update.executeAndReturnGeneratedKeys(mapper, columnName); return magic.result(o, baton); } }; } } else { this.returner = new Returner() { @Override public Object value(Update update, HandleDing baton) { return update.execute(); } }; } } @Override public Object invoke(HandleDing h, Object target, Object[] args, Callable<?> methodProxy) { Update q = h.getHandle().createStatement(sql); populateSqlObjectData((ConcreteStatementContext)q.getContext()); applyCustomizers(q, args); applyBinders(q, args); return this.returner.value(q, h); } private interface Returner { Object value(Update update, HandleDing baton); } }
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/main/java/org/skife/jdbi/v2/sqlobject/PassThroughTransactionHandler.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/PassThroughTransactionHandler.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.sqlobject; import java.lang.reflect.Method; import java.util.Objects; import java.util.concurrent.Callable; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.TransactionCallback; import org.skife.jdbi.v2.TransactionIsolationLevel; import org.skife.jdbi.v2.TransactionStatus; class PassThroughTransactionHandler implements Handler { private final TransactionIsolationLevel isolation; PassThroughTransactionHandler(Method m, Transaction tx) { this.isolation = tx.value(); } @Override public Object invoke(HandleDing ding, final Object target, final Object[] args, Callable<?> methodProxy) { ding.retain("pass-through-transaction"); try { Handle h = ding.getHandle(); if (Objects.isNull(methodProxy)) { throw new AbstractMethodError("Method in " + target.getClass() + " could not be invoked " + " -- it probably needs a @Sql* annotation of some kind."); } if (isolation == TransactionIsolationLevel.INVALID_LEVEL) { return h.inTransaction(new TransactionCallback<Object>() { @Override public Object inTransaction(Handle conn, TransactionStatus status) throws Exception { try { return methodProxy.call(); } catch (Throwable throwable) { if (throwable instanceof Exception) { throw (Exception) throwable; } else { throw new RuntimeException(throwable); } } } }); } else { return h.inTransaction(isolation, new TransactionCallback<Object>() { @Override public Object inTransaction(Handle conn, TransactionStatus status) throws Exception { try { return methodProxy.call(); } catch (Throwable throwable) { if (throwable instanceof Exception) { throw (Exception) throwable; } else { throw new RuntimeException(throwable); } } } }); } } finally { ding.release("pass-through-transaction"); } } }
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/main/java/org/skife/jdbi/v2/sqlobject/SqlUpdate.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/SqlUpdate.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.sqlobject; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Used to indicate that a method should execute a non-query sql statement */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface SqlUpdate { /** * The sql (or statement name if using a statement locator) to be executed. The default value will use * the method name of the method being annotated. This default behavior is only useful in conjunction * with a statement locator. */ String value() default SqlQuery.DEFAULT_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/main/java/org/skife/jdbi/v2/sqlobject/helpers/MapResultAsBean.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/helpers/MapResultAsBean.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.sqlobject.helpers; import org.skife.jdbi.v2.Query; import org.skife.jdbi.v2.SQLStatement; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizer; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizerFactory; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizingAnnotation; import org.skife.jdbi.v2.tweak.BeanMapperFactory; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.sql.SQLException; @Retention(RetentionPolicy.RUNTIME) @SqlStatementCustomizingAnnotation(MapResultAsBean.MapAsBeanFactory.class) @Target(ElementType.METHOD) public @interface MapResultAsBean { public static class MapAsBeanFactory implements SqlStatementCustomizerFactory { @Override public SqlStatementCustomizer createForMethod(Annotation annotation, Class sqlObjectType, Method method) { return new SqlStatementCustomizer() { @Override public void apply(SQLStatement s) throws SQLException { Query q = (Query) s; q.registerMapper(new BeanMapperFactory()); } }; } @Override public SqlStatementCustomizer createForType(Annotation annotation, Class sqlObjectType) { throw new UnsupportedOperationException("Not allowed on type"); } @Override public SqlStatementCustomizer createForParameter(Annotation annotation, Class sqlObjectType, Method method, Object arg) { throw new UnsupportedOperationException("Not allowed on parameter"); } } }
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/main/java/org/skife/jdbi/v2/sqlobject/customizers/RegisterMapper.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/customizers/RegisterMapper.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.sqlobject.customizers; import org.skife.jdbi.v2.Query; import org.skife.jdbi.v2.SQLStatement; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizer; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizerFactory; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizingAnnotation; import org.skife.jdbi.v2.tweak.ResultSetMapper; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; /** * Used to register a result set mapper with either a sql object type or for a specific method. */ @SqlStatementCustomizingAnnotation(RegisterMapper.Factory.class) @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD}) public @interface RegisterMapper { /** * The result set mapper class to register */ Class<? extends ResultSetMapper<?>>[] value(); static class Factory implements SqlStatementCustomizerFactory { @Override public SqlStatementCustomizer createForMethod(Annotation annotation, Class sqlObjectType, Method method) { final RegisterMapper ma = (RegisterMapper) annotation; final ResultSetMapper[] m = new ResultSetMapper[ma.value().length]; try { Class<? extends ResultSetMapper<?>>[] mcs = ma.value(); for (int i = 0; i < mcs.length; i++) { m[i] = mcs[i].newInstance(); } } catch (Exception e) { throw new IllegalStateException("unable to create a specified result set mapper", e); } return new SqlStatementCustomizer() { @Override public void apply(SQLStatement statement) { if (statement instanceof Query) { Query q = (Query) statement; for (ResultSetMapper mapper : m) { q.registerMapper(mapper); } } } }; } @Override public SqlStatementCustomizer createForType(Annotation annotation, Class sqlObjectType) { final RegisterMapper ma = (RegisterMapper) annotation; final ResultSetMapper[] m = new ResultSetMapper[ma.value().length]; try { Class<? extends ResultSetMapper<?>>[] mcs = ma.value(); for (int i = 0; i < mcs.length; i++) { m[i] = mcs[i].newInstance(); } } catch (Exception e) { throw new IllegalStateException("unable to create a specified result set mapper", e); } return new SqlStatementCustomizer() { @Override public void apply(SQLStatement statement) { if (statement instanceof Query) { Query q = (Query) statement; for (ResultSetMapper mapper : m) { q.registerMapper(mapper); } } } }; } @Override public SqlStatementCustomizer createForParameter(Annotation annotation, Class sqlObjectType, Method method, Object arg) { throw new UnsupportedOperationException("Not defined for parameter"); } } }
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/main/java/org/skife/jdbi/v2/sqlobject/customizers/BatchChunkSize.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/customizers/BatchChunkSize.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.sqlobject.customizers; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Used to control the batch chunk size for sql batch operations. * If this annotation is present the value (or argument value if on * a parameter) will be used as the size for each batch statement to * execute. */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE}) public @interface BatchChunkSize { /** * The batch chunk size. Defaults to -1 which will raise an error, so * do not use the default. It is present for when the annotation is used * on a parameter, in which case this value will be ignored and the parameter value * will be used. The parameter type must be an int (or castable to an int). */ int value() default -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/main/java/org/skife/jdbi/v2/sqlobject/customizers/OverrideStatementRewriterWith.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/customizers/OverrideStatementRewriterWith.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.sqlobject.customizers; import org.skife.jdbi.v2.SQLStatement; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizer; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizerFactory; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizingAnnotation; import org.skife.jdbi.v2.tweak.StatementRewriter; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Constructor; import java.lang.reflect.Method; /** * Use this to override the statement rewriter on a sql object, May be specified on either the interface * or method level. */ @Retention(RetentionPolicy.RUNTIME) @SqlStatementCustomizingAnnotation(OverrideStatementRewriterWith.Factory.class) @Target({ElementType.TYPE, ElementType.METHOD}) public @interface OverrideStatementRewriterWith { /** * Specify the StatementRewriter class to use. */ Class<? extends StatementRewriter> value(); public static class Factory implements SqlStatementCustomizerFactory { @Override public SqlStatementCustomizer createForMethod(Annotation annotation, Class sqlObjectType, Method method) { OverrideStatementRewriterWith anno = (OverrideStatementRewriterWith) annotation; try { final StatementRewriter rw = instantiate(anno.value(), sqlObjectType, method); return new SqlStatementCustomizer() { @Override public void apply(SQLStatement q) { q.setStatementRewriter(rw); } }; } catch (Exception e) { throw new IllegalStateException(e); } } @Override public SqlStatementCustomizer createForType(Annotation annotation, Class sqlObjectType) { OverrideStatementRewriterWith anno = (OverrideStatementRewriterWith) annotation; try { final StatementRewriter rw = instantiate(anno.value(), sqlObjectType, null); return new SqlStatementCustomizer() { @Override public void apply(SQLStatement q) { q.setStatementRewriter(rw); } }; } catch (Exception e) { throw new IllegalStateException(e); } } @Override public SqlStatementCustomizer createForParameter(Annotation annotation, Class sqlObjectType, Method method, Object arg) { throw new IllegalStateException("Not defined on parameters!"); } private StatementRewriter instantiate(Class<? extends StatementRewriter> value, Class sqlObjectType, Method m) throws Exception { try { Constructor<? extends StatementRewriter> no_arg = value.getConstructor(); return no_arg.newInstance(); } catch (NoSuchMethodException e) { try { Constructor<? extends StatementRewriter> class_arg = value.getConstructor(Class.class); return class_arg.newInstance(sqlObjectType); } catch (NoSuchMethodException e1) { if (m != null) { Constructor<? extends StatementRewriter> c_m_arg = value.getConstructor(Class.class, Method.class); return c_m_arg.newInstance(sqlObjectType, m); } throw new IllegalStateException("Unable to instantiate, no viable constructor " + value.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/main/java/org/skife/jdbi/v2/sqlobject/customizers/FetchDirection.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/customizers/FetchDirection.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.sqlobject.customizers; import org.skife.jdbi.v2.SQLStatement; import org.skife.jdbi.v2.StatementCustomizers; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizer; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizerFactory; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizingAnnotation; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.sql.SQLException; /** * Used to specify the fetch direction, per JDBC, of a result set. */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE}) @SqlStatementCustomizingAnnotation(FetchDirection.Factory.class) public @interface FetchDirection { /** * Set to a value valid for fetch direction on the jdc statement */ int value(); static class Factory implements SqlStatementCustomizerFactory { public SqlStatementCustomizer createForParameter(Annotation annotation, Object arg) { return new FetchDirectionSqlStatementCustomizer((Integer) arg); } @Override public SqlStatementCustomizer createForMethod(Annotation annotation, Class sqlObjectType, Method method) { final FetchDirection fs = (FetchDirection) annotation; return new FetchDirectionSqlStatementCustomizer(fs.value()); } @Override public SqlStatementCustomizer createForType(Annotation annotation, Class sqlObjectType) { final FetchDirection fs = (FetchDirection) annotation; return new FetchDirectionSqlStatementCustomizer(fs.value()); } @Override public SqlStatementCustomizer createForParameter(Annotation annotation, Class sqlObjectType, Method method, Object arg) { return new FetchDirectionSqlStatementCustomizer((Integer) arg); } } static class FetchDirectionSqlStatementCustomizer implements SqlStatementCustomizer { private final Integer direction; public FetchDirectionSqlStatementCustomizer(final Integer direction) { this.direction = direction; } @Override public void apply(SQLStatement q) throws SQLException { q.addStatementCustomizer(new StatementCustomizers.FetchDirectionStatementCustomizer(direction)); } } }
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/main/java/org/skife/jdbi/v2/sqlobject/customizers/Mapper.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/customizers/Mapper.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.sqlobject.customizers; import org.skife.jdbi.v2.tweak.ResultSetMapper; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Used to specify specific result set mapper on a query method. */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface Mapper { /** * The class implementing {@link ResultSetMapper}. It must have a no-arg constructor. */ Class<? extends ResultSetMapper<?>> 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/main/java/org/skife/jdbi/v2/sqlobject/customizers/OverrideStatementLocatorWith.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/customizers/OverrideStatementLocatorWith.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.sqlobject.customizers; import org.skife.jdbi.v2.SQLStatement; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizer; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizerFactory; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizingAnnotation; import org.skife.jdbi.v2.tweak.StatementLocator; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Constructor; import java.lang.reflect.Method; /** * Use this to override the statement locator on a sql object, May be specified on either the interface * or method level. */ @Retention(RetentionPolicy.RUNTIME) @SqlStatementCustomizingAnnotation(OverrideStatementLocatorWith.Factory.class) @Target({ElementType.TYPE, ElementType.METHOD}) public @interface OverrideStatementLocatorWith { /** * Specify the statement locator class to use */ Class<? extends org.skife.jdbi.v2.tweak.StatementLocator> value(); static class Factory implements SqlStatementCustomizerFactory { @Override public SqlStatementCustomizer createForMethod(Annotation annotation, Class sqlObjectType, Method method) { OverrideStatementLocatorWith sl = (OverrideStatementLocatorWith) annotation; final org.skife.jdbi.v2.tweak.StatementLocator f; try { f = instantiate(sl.value(), sqlObjectType, method); } catch (Exception e) { throw new IllegalStateException("unable to instantiate a statement locator", e); } return new SqlStatementCustomizer() { @Override public void apply(SQLStatement q) { q.setStatementLocator(f); } }; } @Override public SqlStatementCustomizer createForType(Annotation annotation, Class sqlObjectType) { OverrideStatementLocatorWith sl = (OverrideStatementLocatorWith) annotation; final StatementLocator f; try { f = instantiate(sl.value(), sqlObjectType, null); } catch (Exception e) { throw new IllegalStateException("unable to instantiate a statement locator", e); } return new SqlStatementCustomizer() { @Override public void apply(SQLStatement q) { q.setStatementLocator(f); } }; } private StatementLocator instantiate(Class<? extends StatementLocator> value, Class sqlObjectType, Method m) throws Exception { try { Constructor<? extends StatementLocator> no_arg = value.getConstructor(); return no_arg.newInstance(); } catch (NoSuchMethodException e) { try { Constructor<? extends StatementLocator> class_arg = value.getConstructor(Class.class); return class_arg.newInstance(sqlObjectType); } catch (NoSuchMethodException e1) { if (m != null) { Constructor<? extends StatementLocator> c_m_arg = value.getConstructor(Class.class, Method.class); return c_m_arg.newInstance(sqlObjectType, m); } throw new IllegalStateException("Unable to instantiate, no viable constructor " + value.getName()); } } } @Override public SqlStatementCustomizer createForParameter(Annotation annotation, Class sqlObjectType, Method method, Object arg) { throw new UnsupportedOperationException("Not applicable to parameter"); } } }
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/main/java/org/skife/jdbi/v2/sqlobject/customizers/QueryTimeOut.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/customizers/QueryTimeOut.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.sqlobject.customizers; import org.skife.jdbi.v2.SQLStatement; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizer; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizerFactory; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizingAnnotation; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.sql.SQLException; /** * Specify the query timeout in seconds. May be used on a method or parameter, the parameter must be of an int type. */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.PARAMETER}) @SqlStatementCustomizingAnnotation(QueryTimeOut.Factory.class) public @interface QueryTimeOut { int value() default Integer.MAX_VALUE; static class Factory implements SqlStatementCustomizerFactory { @Override public SqlStatementCustomizer createForMethod(Annotation annotation, Class sqlObjectType, Method method) { final QueryTimeOut fs = (QueryTimeOut) annotation; return new SqlStatementCustomizer() { @Override public void apply(SQLStatement q) throws SQLException { q.setQueryTimeout(fs.value()); } }; } @Override public SqlStatementCustomizer createForType(Annotation annotation, Class sqlObjectType) { final QueryTimeOut fs = (QueryTimeOut) annotation; return new SqlStatementCustomizer() { @Override public void apply(SQLStatement q) throws SQLException { q.setQueryTimeout(fs.value()); } }; } @Override public SqlStatementCustomizer createForParameter(Annotation annotation, Class sqlObjectType, Method method, Object arg) { final Integer va = (Integer) arg; return new SqlStatementCustomizer() { @Override public void apply(SQLStatement q) throws SQLException { q.setQueryTimeout(va); } }; } } }
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/main/java/org/skife/jdbi/v2/sqlobject/customizers/RegisterContainerMapper.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/customizers/RegisterContainerMapper.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.sqlobject.customizers; import org.skife.jdbi.v2.Query; import org.skife.jdbi.v2.SQLStatement; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizer; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizerFactory; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizingAnnotation; import org.skife.jdbi.v2.tweak.ContainerFactory; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; @SqlStatementCustomizingAnnotation(RegisterContainerMapper.Factory.class) @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface RegisterContainerMapper { Class<? extends ContainerFactory>[] value(); public static class Factory implements SqlStatementCustomizerFactory { @Override public SqlStatementCustomizer createForMethod(Annotation annotation, Class sqlObjectType, Method method) { return new MyCustomizer((RegisterContainerMapper) annotation); } @Override public SqlStatementCustomizer createForType(Annotation annotation, Class sqlObjectType) { return new MyCustomizer((RegisterContainerMapper) annotation); } @Override public SqlStatementCustomizer createForParameter(Annotation annotation, Class sqlObjectType, Method method, Object arg) { throw new UnsupportedOperationException("Not Yet Implemented!"); } } static class MyCustomizer implements SqlStatementCustomizer { private final List<ContainerFactory> factory; MyCustomizer(RegisterContainerMapper annotation) { List<ContainerFactory> ls = new ArrayList<ContainerFactory>(); try { for (Class<? extends ContainerFactory> type : annotation.value()) { ls.add(type.newInstance()); } } catch (Exception e) { throw new IllegalStateException("Unable to instantiate container factory", e); } this.factory = ls; } @Override public void apply(SQLStatement q) throws SQLException { if (q instanceof Query) { Query query = (Query) q; for (ContainerFactory containerFactory : factory) { query.registerContainerFactory(containerFactory); } } } } }
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/main/java/org/skife/jdbi/v2/sqlobject/customizers/FetchSize.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/customizers/FetchSize.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.sqlobject.customizers; import org.skife.jdbi.v2.Query; import org.skife.jdbi.v2.SQLStatement; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizer; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizerFactory; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizingAnnotation; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.sql.SQLException; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.PARAMETER}) @SqlStatementCustomizingAnnotation(FetchSize.Factory.class) public @interface FetchSize { int value() default 0; static class Factory implements SqlStatementCustomizerFactory { @Override public SqlStatementCustomizer createForMethod(Annotation annotation, Class sqlObjectType, Method method) { final FetchSize fs = (FetchSize) annotation; return new SqlStatementCustomizer() { @Override public void apply(SQLStatement q) throws SQLException { assert q instanceof Query; ((Query) q).setFetchSize(fs.value()); } }; } @Override public SqlStatementCustomizer createForType(Annotation annotation, Class sqlObjectType) { final FetchSize fs = (FetchSize) annotation; return new SqlStatementCustomizer() { @Override public void apply(SQLStatement q) throws SQLException { assert q instanceof Query; ((Query) q).setFetchSize(fs.value()); } }; } @Override public SqlStatementCustomizer createForParameter(Annotation annotation, Class sqlObjectType, Method method, Object arg) { final Integer va = (Integer) arg; return new SqlStatementCustomizer() { @Override public void apply(SQLStatement q) throws SQLException { assert q instanceof Query; ((Query) q).setFetchSize(va); } }; } } }
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/main/java/org/skife/jdbi/v2/sqlobject/customizers/RegisterArgumentFactory.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/customizers/RegisterArgumentFactory.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.sqlobject.customizers; import org.skife.jdbi.v2.SQLStatement; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizer; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizerFactory; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizingAnnotation; import org.skife.jdbi.v2.tweak.ArgumentFactory; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * Used to set attributes on the StatementContext for the statement generated for this method. * These values will be available to other customizers, such as the statement locator or rewriter. */ @SqlStatementCustomizingAnnotation(RegisterArgumentFactory.Factory.class) @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface RegisterArgumentFactory { /** * The key for the attribute to set. The value will be the value passed to the annotated argument */ Class<? extends ArgumentFactory>[] value(); static class Factory implements SqlStatementCustomizerFactory { @Override public SqlStatementCustomizer createForType(Annotation annotation, Class sqlObjectType) { return create(annotation); } @Override public SqlStatementCustomizer createForMethod(Annotation annotation, Class sqlObjectType, Method method) { return create(annotation); } @Override public SqlStatementCustomizer createForParameter(Annotation annotation, Class sqlObjectType, Method method, final Object arg) { throw new IllegalStateException("not allowed on parameter"); } private SqlStatementCustomizer create(Annotation annotation) { final RegisterArgumentFactory raf = (RegisterArgumentFactory) annotation; final List<ArgumentFactory> ary = new ArrayList<ArgumentFactory>(raf.value().length); for (Class<? extends ArgumentFactory> aClass : raf.value()) { try { ary.add(aClass.newInstance()); } catch (Exception e) { throw new IllegalStateException("unable to instantiate specified argument factory", e); } } return new SqlStatementCustomizer() { @Override public void apply(SQLStatement q) throws SQLException { for (ArgumentFactory argumentFactory : ary) { q.registerArgumentFactory(argumentFactory); } } }; } } }
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/main/java/org/skife/jdbi/v2/sqlobject/customizers/RegisterMapperFactory.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/customizers/RegisterMapperFactory.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.sqlobject.customizers; import org.skife.jdbi.v2.Query; import org.skife.jdbi.v2.ResultSetMapperFactory; import org.skife.jdbi.v2.SQLStatement; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizer; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizerFactory; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizingAnnotation; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; /** * Used to register a result set mapper with either a sql object type or for a specific method. */ @SqlStatementCustomizingAnnotation(RegisterMapperFactory.Factory.class) @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD}) public @interface RegisterMapperFactory { Class<? extends ResultSetMapperFactory>[] value(); public static class Factory implements SqlStatementCustomizerFactory { @Override public SqlStatementCustomizer createForMethod(Annotation annotation, Class sqlObjectType, Method method) { final RegisterMapperFactory ma = (RegisterMapperFactory) annotation; final ResultSetMapperFactory[] m = new ResultSetMapperFactory[ma.value().length]; try { Class<? extends ResultSetMapperFactory>[] mcs = ma.value(); for (int i = 0; i < mcs.length; i++) { m[i] = mcs[i].newInstance(); } } catch (Exception e) { throw new IllegalStateException("unable to create a specified result set mapper", e); } return new SqlStatementCustomizer() { @Override public void apply(SQLStatement statement) { if (statement instanceof Query) { Query q = (Query) statement; for (ResultSetMapperFactory factory : m) { q.registerMapper(factory); } } } }; } @Override public SqlStatementCustomizer createForType(Annotation annotation, Class sqlObjectType) { final RegisterMapperFactory ma = (RegisterMapperFactory) annotation; final ResultSetMapperFactory[] m = new ResultSetMapperFactory[ma.value().length]; try { Class<? extends ResultSetMapperFactory>[] mcs = ma.value(); for (int i = 0; i < mcs.length; i++) { m[i] = mcs[i].newInstance(); } } catch (Exception e) { throw new IllegalStateException("unable to create a specified result set mapper", e); } return new SqlStatementCustomizer() { @Override public void apply(SQLStatement statement) { if (statement instanceof Query) { Query q = (Query) statement; for (ResultSetMapperFactory factory : m) { q.registerMapper(factory); } } } }; } @Override public SqlStatementCustomizer createForParameter(Annotation annotation, Class sqlObjectType, Method method, Object arg) { throw new UnsupportedOperationException("Not defined for parameter"); } } }
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/main/java/org/skife/jdbi/v2/sqlobject/customizers/TransactionIsolation.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/customizers/TransactionIsolation.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.sqlobject.customizers; import org.skife.jdbi.v2.SQLStatement; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.TransactionIsolationLevel; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizer; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizerFactory; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizingAnnotation; import org.skife.jdbi.v2.tweak.BaseStatementCustomizer; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; /** * Used to specify the transaction isolation level for an object or method (via annotating the method * or passing it in as an annotated param). If used on a parameter, the parameter type must be a * {@link org.skife.jdbi.v2.TransactionIsolationLevel} */ @SqlStatementCustomizingAnnotation(TransactionIsolation.Factory.class) @Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface TransactionIsolation { TransactionIsolationLevel value() default TransactionIsolationLevel.INVALID_LEVEL; static class Factory implements SqlStatementCustomizerFactory { @Override public SqlStatementCustomizer createForMethod(Annotation annotation, Class sqlObjectType, Method method) { return new MyCustomizer(((TransactionIsolation) annotation).value()); } @Override public SqlStatementCustomizer createForType(Annotation annotation, Class sqlObjectType) { return new MyCustomizer(((TransactionIsolation) annotation).value()); } @Override public SqlStatementCustomizer createForParameter(Annotation annotation, Class sqlObjectType, Method method, Object arg) { assert arg instanceof TransactionIsolationLevel; return new MyCustomizer((TransactionIsolationLevel) arg); } } static class MyCustomizer implements SqlStatementCustomizer { private final TransactionIsolationLevel level; public MyCustomizer(TransactionIsolationLevel level) {this.level = level;} @Override public void apply(SQLStatement q) throws SQLException { final int initial_level = q.getContext().getConnection().getTransactionIsolation(); q.addStatementCustomizer(new BaseStatementCustomizer() { @Override public void beforeExecution(PreparedStatement stmt, StatementContext ctx) throws SQLException { setTxnIsolation(ctx, level.intValue()); } @Override public void afterExecution(PreparedStatement stmt, StatementContext ctx) throws SQLException { setTxnIsolation(ctx, initial_level); } private void setTxnIsolation(StatementContext ctx, int level) throws SQLException { final Connection c = ctx.getConnection(); if (c.getTransactionIsolation() != level) { c.setTransactionIsolation(level); } } }); } } }
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/main/java/org/skife/jdbi/v2/sqlobject/customizers/MaxRows.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/customizers/MaxRows.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.sqlobject.customizers; import org.skife.jdbi.v2.Query; import org.skife.jdbi.v2.SQLStatement; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizer; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizerFactory; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizingAnnotation; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.sql.SQLException; /** * Used to specify the maximum numb er of rows to return on a result set. Passes through to * setMaxRows on the JDBC prepared statement. */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.PARAMETER}) @SqlStatementCustomizingAnnotation(MaxRows.Factory.class) public @interface MaxRows { /** * The max number of rows to return from the query. */ int value(); static class Factory implements SqlStatementCustomizerFactory { @Override public SqlStatementCustomizer createForMethod(Annotation annotation, Class sqlObjectType, Method method) { final int va = ((MaxRows)annotation).value(); return new SqlStatementCustomizer() { @Override public void apply(SQLStatement q) throws SQLException { assert q instanceof Query; ((Query)q).setMaxRows(va); } }; } @Override public SqlStatementCustomizer createForType(Annotation annotation, Class sqlObjectType) { final int va = ((MaxRows)annotation).value(); return new SqlStatementCustomizer() { @Override public void apply(SQLStatement q) throws SQLException { assert q instanceof Query; ((Query)q).setMaxRows(va); } }; } @Override public SqlStatementCustomizer createForParameter(Annotation annotation, Class sqlObjectType, Method method, Object arg) { final Integer va = (Integer) arg; return new SqlStatementCustomizer() { @Override public void apply(SQLStatement q) throws SQLException { assert q instanceof Query; ((Query)q).setMaxRows(va); } }; } } }
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/main/java/org/skife/jdbi/v2/sqlobject/customizers/Define.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/customizers/Define.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.sqlobject.customizers; import org.skife.jdbi.v2.SQLStatement; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizer; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizerFactory; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizingAnnotation; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; /** * Used to set attributes on the StatementContext for the statement generated for this method. * These values will be available to other customizers, such as the statement locator or rewriter. */ @SqlStatementCustomizingAnnotation(Define.Factory.class) @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) public @interface Define { /** * The key for the attribute to set. The value will be the value passed to the annotated argument */ String value(); static class Factory implements SqlStatementCustomizerFactory { @Override public SqlStatementCustomizer createForType(Annotation annotation, Class sqlObjectType) { throw new UnsupportedOperationException("Not allowed on Type"); } @Override public SqlStatementCustomizer createForMethod(Annotation annotation, Class sqlObjectType, Method method) { throw new UnsupportedOperationException("Not allowed on Method"); } @Override public SqlStatementCustomizer createForParameter(Annotation annotation, Class sqlObjectType, Method method, final Object arg) { Define d = (Define) annotation; final String key = d.value(); return new SqlStatementCustomizer() { @Override public void apply(SQLStatement q) { q.define(key, arg); } }; } } }
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/main/java/org/skife/jdbi/v2/sqlobject/customizers/SingleValueResult.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/customizers/SingleValueResult.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.sqlobject.customizers; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface SingleValueResult { Class<?> value() default Default.class; final class Default{} }
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/main/java/org/skife/jdbi/v2/sqlobject/mixins/Transactional.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/mixins/Transactional.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.sqlobject.mixins; import org.skife.jdbi.v2.Transaction; import org.skife.jdbi.v2.TransactionIsolationLevel; /** * A mixin interface to expose transaction methods on the sql object. * * @param <SelfType> must match the interface that is extending this one. */ public interface Transactional<SelfType extends Transactional<SelfType>> { void begin(); void commit(); void rollback(); void checkpoint(String name); void release(String name); void rollback(String name); <ReturnType> ReturnType inTransaction(Transaction<ReturnType, SelfType> func); <ReturnType> ReturnType inTransaction(TransactionIsolationLevel isolation, Transaction<ReturnType, SelfType> func); }
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/main/java/org/skife/jdbi/v2/sqlobject/mixins/Transmogrifier.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/mixins/Transmogrifier.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.sqlobject.mixins; /** * Mixin interface which provides a means of creating a sql object from another sql object. * The created sql object will obtain handles from the same source as the original. * * @deprecated use @CreateSqlObject instead */ @Deprecated public interface Transmogrifier { /** * Create a new sql object of the specified type, which shares the same means of obtaining * handles (or same handle, as the case may be!) */ <T> T become(Class<T> typeToBecome); }
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/main/java/org/skife/jdbi/v2/sqlobject/mixins/GetHandle.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/mixins/GetHandle.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.sqlobject.mixins; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.exceptions.CallbackFailedException; import org.skife.jdbi.v2.tweak.HandleCallback; /** * A mixin interface to define a method for obtaining the Handle attached to a sql object */ public interface GetHandle { /** * Obtain the handle associated to this sql object. * * @return the handle */ Handle getHandle(); /** * A convenience function which manages the lifecycle of the handle associated to this sql object, * and yields it to a callback for use by clients. * * @param callback A callback which will receive the handle associated to this sql object * * @return the value returned by callback * * @throws CallbackFailedException Will be thrown if callback raises an exception. This exception will * wrap the exception thrown by the callback. */ <ReturnType> ReturnType withHandle(HandleCallback<ReturnType> callback) throws CallbackFailedException; }
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/main/java/org/skife/jdbi/v2/sqlobject/mixins/CloseMe.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/mixins/CloseMe.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.sqlobject.mixins; /** * A convenience mixin interface which defines the close() method. */ public interface CloseMe { /** * Close the underlying handle on the sql object */ void 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/main/java/org/skife/jdbi/v2/sqlobject/stringtemplate/ST4StatementLocator.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/stringtemplate/ST4StatementLocator.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.sqlobject.stringtemplate; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import org.killbill.commons.utils.annotation.VisibleForTesting; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.tweak.StatementLocator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.stringtemplate.v4.ST; import org.stringtemplate.v4.STErrorListener; import org.stringtemplate.v4.STGroup; import org.stringtemplate.v4.STGroupFile; import org.stringtemplate.v4.compiler.CompiledST; import org.stringtemplate.v4.misc.ErrorManager; import org.stringtemplate.v4.misc.STMessage; public class ST4StatementLocator implements StatementLocator { private static final Logger logger = LoggerFactory.getLogger(ST4StatementLocator.class); private static final ErrorManager ERROR_MANAGER = new ErrorManager(new SLF4JSTErrorListener()); private static final Map<String, STGroup> CACHE = new ConcurrentHashMap<String, STGroup>(); private static final String COMPOSITE_KEY_SEPARATOR = "___#___"; @VisibleForTesting final Map<String, String> locatedSqlCache = new ConcurrentHashMap<>(); private final STGroup group; public ST4StatementLocator(final STGroup group) { this.group = group; } /** * Obtains a locator based on a classpath path, using a global template group CACHE. */ public static StatementLocator fromClasspath(final String path) { return fromClasspath(UseSTGroupCache.YES, path); } /** * Obtains a locator based on a classpath path. Allows flag to indicate whether the global STGroup CACHE should be * used. In general, the only reasons to NOT use the CACHE are: (1) if you are fiddling with the templates during development * and want to make changes without having to restart the server; and (2) if you use something like the tomcat * deployer to push new versions without restarting the JVM which causes static maps to leak memory. */ public static StatementLocator fromClasspath(final UseSTGroupCache useCache, final String path) { return forURL(useCache, ST4StatementLocator.class.getResource(path)); } /** * Obtains a locator based on the type passed in, using a global template group CACHE. * <p> * STGroup is loaded from the classpath via sqlObjectType.getResource( ), such that names line * up with the package and class, so: com.example.Foo will look for /com/example/Foo.sql.stg . Inner classes * are seperated in the file name by a '.' not a '$', so com.example.Foo.Bar (Bar is an inner class of Foo) would * be at /com/example/Foo.Bar.sql.stg . */ public static StatementLocator forType(final Class sqlObjectType) { return forType(UseSTGroupCache.YES, sqlObjectType); } /** * Obtains a locator based on the type passed in. Allows flag to indicate whether the global STGroup CACHE should be * used. In general, the only reasons to NOT use the CACHE are: (1) if you are fiddling with the templates during development * and want to make changes without having to restart the server; and (2) if you use something like the tomcat * deployer to push new versions without restarting the JVM which causes static maps to leak memory. * <p> * STGroup is loaded from the classpath via sqlObjectType.getResource( ), such that names line * up with the package and class, so: com.example.Foo will look for /com/example/Foo.sql.stg . Inner classes * are seperated in the file name by a '.' not a '$', so com.example.Foo.Bar (Bar is an inner class of Foo) would * be at /com/example/Foo.Bar.sql.stg . */ public static StatementLocator forType(final UseSTGroupCache useCache, final Class<?> sqlObjectType) { return forURL(useCache, classToUrl(sqlObjectType)); } public static StatementLocator forURL(final UseSTGroupCache useCache, final URL url) { final STGroup stg; if (useCache == UseSTGroupCache.YES) { stg = computeIfAbsent(CACHE, url.toString(), new Function<String, STGroup>() { @Override public STGroup apply(final String u) { return u == null ? null : urlToSTGroup(u); } }); } else { stg = urlToSTGroup(url.toString()); } return new ST4StatementLocator(stg); } /** * Create a statement locator intended for setting on a DBI or Handle instance which will * lookup a template group to use based on the name of the sql object type for a particular query, using * the same logic as {@link UseST4StatementLocator}. */ public static StatementLocator perType(final UseSTGroupCache useCache) { return perType(useCache, new STGroup('<', '>')); } /** * Create a statement locator intended for setting on a DBI or Handle instance which will * lookup a template group to use based on the name of the sql object type for a particular query, using * the same logic as {@link UseST4StatementLocator}. * <p> * Supports a fallback template group for statements created not using a sql object. */ public static StatementLocator perType(final UseSTGroupCache useCache, final String fallbackTemplateGroupPath) { return perType(useCache, ST4StatementLocator.class.getResource(fallbackTemplateGroupPath)); } /** * Create a statement locator intended for setting on a DBI or Handle instance which will * lookup a template group to use based on the name of the sql object type for a particular query, using * the same logic as {@link UseST4StatementLocator}. * <p> * Supports a fallback template group for statements created not using a sql object. */ public static StatementLocator perType(final UseSTGroupCache useCache, final URL baseTemplate) { return perType(useCache, urlToSTGroup(baseTemplate)); } /** * Create a statement locator intended for setting on a DBI or Handle instance which will * lookup a template group to use based on the name of the sql object type for a particular query, using * the same logic as {@link UseST4StatementLocator}. * <p> * Supports a fallback template group for statements created not using a sql object. */ public static StatementLocator perType(final UseSTGroupCache useCache, final STGroup fallbackTemplateGroup) { final StatementLocator fallback = new ST4StatementLocator(fallbackTemplateGroup); if (useCache == UseSTGroupCache.YES) { final Map<Class<?>, StatementLocator> sqlObjectCache = new ConcurrentHashMap<Class<?>, StatementLocator>(); return new StatementLocator() { @Override public String locate(final String name, final StatementContext ctx) throws Exception { if (ctx.getSqlObjectType() != null) { final StatementLocator sl = computeIfAbsent(sqlObjectCache, ctx.getSqlObjectType(), new Function<Class<?>, StatementLocator>() { @Override public StatementLocator apply(final Class<?> c) { return ST4StatementLocator.forType(useCache, ctx.getSqlObjectType()); } }); return sl.locate(name, ctx); } else { return fallback.locate(name, ctx); } } }; } else { // if we are not caching, let's not cache the lookup of the template group either! return new StatementLocator() { @Override public String locate(final String name, final StatementContext ctx) throws Exception { if (ctx.getSqlObjectType() != null) { return ST4StatementLocator.forType(useCache, ctx.getSqlObjectType()).locate(name, ctx); } else { return fallback.locate(name, ctx); } } }; } } private static URL classToUrl(final Class c) { // handle naming of inner classes as Outer.Inner.sql.stg instead of Outer$Inner.sql.stg final String fullName = c.getName(); final String pkg = c.getPackage().getName(); final String className = fullName.substring(pkg.length() + 1, fullName.length()).replace('$', '.'); return c.getResource(className + ".sql.stg"); } private static STGroup urlToSTGroup(final String u) { try { return urlToSTGroup(new URL(u)); } catch (final MalformedURLException e) { throw new IllegalStateException("a URL failed to roundtrip from a string!", e); } } private static STGroup urlToSTGroup(final URL u) { return new STGroupFileWithThreadSafeLoading(u, "UTF-8", '<', '>'); } private static <K, V> V computeIfAbsent(final Map<K, V> map, final K key, final Function<K, V> mappingFunction) { V v; final V newValue; if ((v = map.get(key)) == null && (newValue = mappingFunction.apply(key)) != null) { if ((v = putIfAbsent(map, key, newValue)) == null) { return newValue; } else { return v; } } else { return v; } } private static <K, V> V putIfAbsent(final Map<K, V> map, final K key, final V value) { V v = map.get(key); if (v == null) { v = map.put(key, value); } return v; } @Override public String locate(final String name, final StatementContext ctx) throws Exception { final Iterator<Entry<String, Object>> entryIterator = ctx.getAttributes().entrySet().iterator(); if (!entryIterator.hasNext()) { // Easiest: no attribute defined, always the same SQL return locateFromCache(name, name, ctx); } else { final Entry<String, Object> attribute1 = entryIterator.next(); if (!entryIterator.hasNext()) { final String compositeKey = buildCompositeCacheKey(name, attribute1); return locateFromCache(compositeKey, name, ctx); } else { final Entry<String, Object> attribute2 = entryIterator.next(); if (!entryIterator.hasNext()) { // 2 attributes defined -- worth optimizing as it is heavily used for queue queries final String compositeKey = buildCompositeCacheKey(name, attribute1, attribute2); return locateFromCache(compositeKey, name, ctx); } else { // Too many attributes are defined, don't cache it return locateAndRender(name, ctx); } } } } private String buildCompositeCacheKey(final String name, final Entry<String, Object> attribute) { return name + COMPOSITE_KEY_SEPARATOR + attribute.getKey() + COMPOSITE_KEY_SEPARATOR + attribute.getValue(); } private String buildCompositeCacheKey(final String name, final Entry<String, Object> attribute1, final Entry<String, Object> attribute2) { if (attribute1.getKey().compareTo(attribute2.getKey()) <= 0) { return name + COMPOSITE_KEY_SEPARATOR + attribute1.getKey() + COMPOSITE_KEY_SEPARATOR + attribute1.getValue() + COMPOSITE_KEY_SEPARATOR + attribute2.getKey() + COMPOSITE_KEY_SEPARATOR + attribute2.getValue(); } else { return name + COMPOSITE_KEY_SEPARATOR + attribute2.getKey() + COMPOSITE_KEY_SEPARATOR + attribute2.getValue() + COMPOSITE_KEY_SEPARATOR + attribute1.getKey() + COMPOSITE_KEY_SEPARATOR + attribute1.getValue(); } } private String locateFromCache(final String cacheKey, final String name, final StatementContext ctx) { String locatedSql = locatedSqlCache.get(cacheKey); if (locatedSql != null) { return locatedSql; } else { locatedSql = locateAndRender(name, ctx); // Make sure the cache is bounded in case of lots of various attributes defined (shouldn't happen in Kill Bill though) // Note that when defining collections for instance, you must define a collection value that is not tied to the // values eventually bound (e.g. query.define("record_ids", ids)), instead define a collection of generic Strings (see @BindIn and TestST4StatementLocator) if (locatedSqlCache.size() < 500) { locatedSqlCache.put(cacheKey, locatedSql); } return locatedSql; } } private String locateAndRender(final String name, final StatementContext ctx) { ST st = this.group.getInstanceOf(name); if (st == null) { // if there is no template by this name in the group, treat it as a template literal. st = new ST(name); } // we add all context values, ST4 explodes if you add a value that lacks a formal argument, // iff hasFormalArgs is true. If it is false, it just uses values opportunistically. This is gross // but works. -brianm st.impl.hasFormalArgs = false; st.impl.nativeGroup.errMgr = ERROR_MANAGER; for (final Map.Entry<String, Object> attr : ctx.getAttributes().entrySet()) { st.add(attr.getKey(), attr.getValue()); } return st.render(); } public enum UseSTGroupCache { YES, NO } // See https://github.com/antlr/stringtemplate4/issues/61 and https://groups.google.com/forum/#!topic/stringtemplate-discussion/4WrHlleVDFg private static final class STGroupFileWithThreadSafeLoading extends STGroupFile { public STGroupFileWithThreadSafeLoading(final URL url, final String encoding, final char delimiterStartChar, final char delimiterStopChar) { super(url, encoding, delimiterStartChar, delimiterStopChar); } @Override public CompiledST lookupTemplate(String name) { final ClassLoader initialContextClassLoader = Thread.currentThread().getContextClassLoader(); try { if (initialContextClassLoader == null) { Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); } return lookupTemplateInternal(name); } finally { Thread.currentThread().setContextClassLoader(initialContextClassLoader); } } private CompiledST lookupTemplateInternal(String name) { if (name.charAt(0) != '/') { name = "/" + name; } if (logger.isDebugEnabled()) { // getName() is expensive logger.debug("{}.lookupTemplate({})", getName(), name); } CompiledST code = rawGetTemplate(name); if (code == NOT_FOUND_ST) { logger.debug("{} previously seen as not found", name); return null; } // Try to load from disk and look up again if (code == null) { synchronized (this) { code = rawGetTemplate(name); if (code == null) { code = load(name); } } } if (code == null) { synchronized (this) { code = rawGetTemplate(name); if (code == null) { // Note: we could do a bit better if we were to overwrite this method as well code = lookupImportedTemplate(name); } } } if (code == null) { logger.debug("{} recorded not found", name); templates.put(name, NOT_FOUND_ST); } if (code != null) { if (logger.isDebugEnabled()) { // getName() is expensive logger.debug("{}.lookupTemplate({}) found", getName(), name); } } return code; } } private static final class SLF4JSTErrorListener implements STErrorListener { @Override public void compileTimeError(final STMessage msg) { if (msg != null) { logger.warn(msg.toString()); } } @Override public void runTimeError(final STMessage msg) { if (msg != null) { logger.warn(msg.toString()); } } @Override public void IOError(final STMessage msg) { if (msg != null) { logger.warn(msg.toString()); } } @Override public void internalError(final STMessage msg) { if (msg != null) { logger.warn(msg.toString()); } } } }
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/main/java/org/skife/jdbi/v2/sqlobject/stringtemplate/ExternalizedSqlViaStringTemplate3.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/stringtemplate/ExternalizedSqlViaStringTemplate3.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.sqlobject.stringtemplate; import org.skife.jdbi.v2.SQLStatement; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizer; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizerFactory; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizingAnnotation; import org.skife.jdbi.v2.tweak.StatementLocator; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; /** * @deprecated use {@link UseStringTemplate3StatementLocator} */ @Deprecated @SqlStatementCustomizingAnnotation(ExternalizedSqlViaStringTemplate3.LocatorFactory.class) @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface ExternalizedSqlViaStringTemplate3 { String DEFAULT_VALUE = " ~ "; String value() default DEFAULT_VALUE; public static class LocatorFactory implements SqlStatementCustomizerFactory { @Override public SqlStatementCustomizer createForType(Annotation annotation, Class sqlObjectType) { final ExternalizedSqlViaStringTemplate3 a = (ExternalizedSqlViaStringTemplate3) annotation; final StringTemplate3StatementLocator.Builder builder; if (DEFAULT_VALUE.equals(a.value())) { builder = StringTemplate3StatementLocator.builder(sqlObjectType); } else { builder = StringTemplate3StatementLocator.builder(a.value()); } final StatementLocator l = builder.shouldCache().build(); return new SqlStatementCustomizer() { @Override public void apply(SQLStatement q) { q.setStatementLocator(l); } }; } @Override public SqlStatementCustomizer createForMethod(Annotation annotation, Class sqlObjectType, Method method) { throw new UnsupportedOperationException("Not Defined on Method"); } @Override public SqlStatementCustomizer createForParameter(Annotation annotation, Class sqlObjectType, Method method, Object arg) { throw new UnsupportedOperationException("Not defined on parameter"); } } }
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/main/java/org/skife/jdbi/v2/sqlobject/stringtemplate/UseST4StatementLocator.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/stringtemplate/UseST4StatementLocator.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.sqlobject.stringtemplate; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.sql.SQLException; import org.skife.jdbi.v2.SQLStatement; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizer; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizerFactory; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizingAnnotation; import org.skife.jdbi.v2.tweak.StatementLocator; /** * Use StringTemplate 4 to load a stringtemplate group containing named templates for each sql statement. * <p> * STGroup is loaded from the classpath via sqlObjectType.getResource( ), such that names line * up with the package and class, so: com.example.Foo will look for /com/example/Foo.sql.stg . Inner classes * are separated in the file name by a '.' not a '$', so com.example.Foo.Bar (Bar is an inner class of Foo) would * be at /com/example/Foo.Bar.sql.stg . */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.TYPE}) @SqlStatementCustomizingAnnotation(UseST4StatementLocator.LocatorFactory.class) public @interface UseST4StatementLocator { String USE_SQLOBJECT_TYPE_INDICATOR = "$$# ^&&*% $$!$$"; /** * Path on classpath to load group file from, if not using automagic naming conventions * If you want to use automagic naming conventions, don't set this value. * * @return path on classpath to load stringtemplate group file from, ie "/sql/all_the_sql.stg" */ String groupFile() default USE_SQLOBJECT_TYPE_INDICATOR; /** * Set to false if for some reason you don't want to cache STGroups. It is very unusual to NOT cache them, so if * you are not sure what to do, leave this alone. */ boolean useTemplateGroupCache() default true; class LocatorFactory implements SqlStatementCustomizerFactory { private static SqlStatementCustomizer make(final UseST4StatementLocator an, final Class sqlObjectType) { final StatementLocator locator; if (USE_SQLOBJECT_TYPE_INDICATOR.equals(an.groupFile())) { locator = ST4StatementLocator.forType(sqlObjectType); } else { final ST4StatementLocator.UseSTGroupCache useCache = an.useTemplateGroupCache() ? ST4StatementLocator.UseSTGroupCache.YES : ST4StatementLocator.UseSTGroupCache.NO; locator = ST4StatementLocator.fromClasspath(useCache, an.groupFile()); } return new SqlStatementCustomizer() { @Override public void apply(final SQLStatement q) throws SQLException { q.setStatementLocator(locator); } }; } @Override public SqlStatementCustomizer createForMethod(final Annotation annotation, final Class sqlObjectType, final Method method) { return make((UseST4StatementLocator) annotation, sqlObjectType); } @Override public SqlStatementCustomizer createForType(final Annotation annotation, final Class sqlObjectType) { return make((UseST4StatementLocator) annotation, sqlObjectType); } @Override public SqlStatementCustomizer createForParameter(final Annotation annotation, final Class sqlObjectType, final Method method, final Object arg) { throw new UnsupportedOperationException("Annotation cannot be applied to parameter"); } } }
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/main/java/org/skife/jdbi/v2/sqlobject/stringtemplate/UseStringTemplate3StatementLocator.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/stringtemplate/UseStringTemplate3StatementLocator.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.sqlobject.stringtemplate; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import org.antlr.stringtemplate.StringTemplateErrorListener; import org.antlr.stringtemplate.StringTemplateGroup; import org.skife.jdbi.v2.SQLStatement; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizer; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizerFactory; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizingAnnotation; import org.skife.jdbi.v2.tweak.StatementLocator; @SqlStatementCustomizingAnnotation(UseStringTemplate3StatementLocator.LocatorFactory.class) @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface UseStringTemplate3StatementLocator { String DEFAULT_VALUE = " ~ "; String value() default DEFAULT_VALUE; Class errorListener() default StringTemplateErrorListener.class; public static class LocatorFactory implements SqlStatementCustomizerFactory { @Override public SqlStatementCustomizer createForType(Annotation annotation, Class sqlObjectType) { final UseStringTemplate3StatementLocator a = (UseStringTemplate3StatementLocator) annotation; final StringTemplate3StatementLocator.Builder builder; if (DEFAULT_VALUE.equals(a.value())) { builder = StringTemplate3StatementLocator.builder(sqlObjectType); } else { builder = StringTemplate3StatementLocator.builder(a.value()); } StringTemplateErrorListener errorListener = StringTemplateGroup.DEFAULT_ERROR_LISTENER; if (!StringTemplateErrorListener.class.equals(a.errorListener())) { try { errorListener = (StringTemplateErrorListener) a.errorListener().newInstance(); } catch(Exception e) { throw new IllegalStateException("Error initializing StringTemplateErrorListener", e); } } final StatementLocator l = builder.allowImplicitTemplateGroup().treatLiteralsAsTemplates().shouldCache().withErrorListener(errorListener).build(); return new SqlStatementCustomizer() { @Override public void apply(SQLStatement q) { q.setStatementLocator(l); } }; } @Override public SqlStatementCustomizer createForMethod(Annotation annotation, Class sqlObjectType, Method method) { throw new UnsupportedOperationException("Not Defined on Method"); } @Override public SqlStatementCustomizer createForParameter(Annotation annotation, Class sqlObjectType, Method method, Object arg) { throw new UnsupportedOperationException("Not defined on parameter"); } } }
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/main/java/org/skife/jdbi/v2/sqlobject/stringtemplate/StringTemplate3StatementLocator.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/stringtemplate/StringTemplate3StatementLocator.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.sqlobject.stringtemplate; import org.antlr.stringtemplate.StringTemplate; import org.antlr.stringtemplate.StringTemplateErrorListener; import org.antlr.stringtemplate.StringTemplateGroup; import org.antlr.stringtemplate.language.AngleBracketTemplateLexer; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.tweak.StatementLocator; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.regex.Matcher; public class StringTemplate3StatementLocator implements StatementLocator { private static final Charset UTF_8 = Charset.forName("UTF-8"); private static final ConcurrentMap<String, StringTemplateGroup> ANNOTATION_LOCATOR_CACHE; private static final String SUPER_SEPARATOR = " > "; public static final String TEMPLATE_GROUP_EXTENSION = ".sql.stg"; static { final ConcurrentMap<String, StringTemplateGroup> cache = new ConcurrentHashMap<String, StringTemplateGroup>(); cache.put("empty template group", new StringTemplateGroup("empty template group", AngleBracketTemplateLexer.class)); ANNOTATION_LOCATOR_CACHE = cache; } private final StringTemplateGroup literals = new StringTemplateGroup("literals", AngleBracketTemplateLexer.class); private final StringTemplateGroup group; private final boolean treatLiteralsAsTemplates; public static final StringTemplate3StatementLocator.Builder builder(Class<?> baseClass) { return new Builder(baseClass); } public static final StringTemplate3StatementLocator.Builder builder(String templateGroupFilePathOnClasspath) { return new Builder(templateGroupFilePathOnClasspath); } /** * Use {@link StringTemplate3StatementLocator#builder()} and {@link StringTemplate3StatementLocator.Builder}. */ @Deprecated public StringTemplate3StatementLocator(Class baseClass) { this(mungify(baseClass), null, null, false, false, false); } /** * Use {@link StringTemplate3StatementLocator#builder()} and {@link StringTemplate3StatementLocator.Builder}. */ @Deprecated public StringTemplate3StatementLocator(Class baseClass, boolean allowImplicitTemplateGroup, boolean treatLiteralsAsTemplates) { this(mungify(baseClass), null, null, allowImplicitTemplateGroup, treatLiteralsAsTemplates, false); } /** * Use {@link StringTemplate3StatementLocator#builder()} and {@link StringTemplate3StatementLocator.Builder}. */ @Deprecated public StringTemplate3StatementLocator(String templateGroupFilePathOnClasspath) { this(templateGroupFilePathOnClasspath, null, null, false, false, false); } /** * Use {@link StringTemplate3StatementLocator#builder()} and {@link StringTemplate3StatementLocator.Builder}. */ @Deprecated public StringTemplate3StatementLocator(String templateGroupFilePathOnClasspath, boolean allowImplicitTemplateGroup, boolean treatLiteralsAsTemplates) { this(templateGroupFilePathOnClasspath, null, null, allowImplicitTemplateGroup, treatLiteralsAsTemplates, false); } /** * Use {@link StringTemplate3StatementLocator#builder()} and {@link StringTemplate3StatementLocator.Builder}. */ @Deprecated public StringTemplate3StatementLocator(Class baseClass, boolean allowImplicitTemplateGroup, boolean treatLiteralsAsTemplates, boolean shouldCache) { this(mungify(baseClass), null, null, allowImplicitTemplateGroup, treatLiteralsAsTemplates, shouldCache); } /** * Use {@link StringTemplate3StatementLocator#builder()} and {@link StringTemplate3StatementLocator.Builder}. */ @Deprecated public StringTemplate3StatementLocator(String templateGroupFilePathOnClasspath, boolean allowImplicitTemplateGroup, boolean treatLiteralsAsTemplates, boolean shouldCache) { this(templateGroupFilePathOnClasspath, null, null, allowImplicitTemplateGroup, treatLiteralsAsTemplates, shouldCache); } private StringTemplate3StatementLocator(String templateGroupFilePathOnClasspath, String superTemplateGroupFilePathOnClasspath, StringTemplateErrorListener errorListener, boolean allowImplicitTemplateGroup, boolean treatLiteralsAsTemplates, boolean shouldCache) { this.treatLiteralsAsTemplates = treatLiteralsAsTemplates; final StringTemplateGroup superGroup; final StringBuilder sb = new StringBuilder(templateGroupFilePathOnClasspath); if (superTemplateGroupFilePathOnClasspath != null) { sb.append(SUPER_SEPARATOR).append(superTemplateGroupFilePathOnClasspath); superGroup = createGroup(superTemplateGroupFilePathOnClasspath, errorListener, shouldCache ? superTemplateGroupFilePathOnClasspath : null, allowImplicitTemplateGroup, getClass(), null); } else { superGroup = null; } this.group = createGroup(templateGroupFilePathOnClasspath, errorListener, shouldCache ? sb.toString() : null, allowImplicitTemplateGroup, getClass(), superGroup); if(this.literals != null) { this.literals.setErrorListener(errorListener); } this.group.setErrorListener(errorListener); } private static StringTemplateGroup createGroup(final String templateGroupFilePathOnClasspath, final StringTemplateErrorListener errorListener, final String cacheKey, final boolean allowImplicitTemplateGroup, final Class<?> clazz, final StringTemplateGroup superGroup) { if (cacheKey != null && ANNOTATION_LOCATOR_CACHE.containsKey(cacheKey)) { return ANNOTATION_LOCATOR_CACHE.get(cacheKey); } InputStream ins = clazz.getResourceAsStream(templateGroupFilePathOnClasspath); if (allowImplicitTemplateGroup && ins == null) { return ANNOTATION_LOCATOR_CACHE.get("empty template group"); } else if (ins == null) { throw new IllegalStateException("unable to find group file " + templateGroupFilePathOnClasspath + " on classpath"); } else { InputStreamReader reader = new InputStreamReader(ins, UTF_8); StringTemplateGroup result; if (superGroup == null) { result = new StringTemplateGroup(reader, AngleBracketTemplateLexer.class, errorListener); } else { result = new StringTemplateGroup(reader, AngleBracketTemplateLexer.class, errorListener, superGroup); } if (cacheKey != null) { StringTemplateGroup oldGroup = ANNOTATION_LOCATOR_CACHE.putIfAbsent(cacheKey, result); if (oldGroup != null) { result = oldGroup; } } try { reader.close(); } catch (IOException e) { throw new IllegalStateException("unable to load string template group " + templateGroupFilePathOnClasspath, e); } return result; } } @Override public String locate(String name, StatementContext ctx) throws Exception { if (group.isDefined(name)) { // yeah, found template for it! StringTemplate t = group.getInstanceOf(name); t.reset(); for (Map.Entry<String, Object> entry : ctx.getAttributes().entrySet()) { t.setAttribute(entry.getKey(), entry.getValue()); } return t.toString(); } else if (treatLiteralsAsTemplates) { // no template in the template group, but we want literals to be templates final String key = new String(new Base64().encode(name.getBytes(UTF_8)), UTF_8); if (!literals.isDefined(key)) { literals.defineTemplate(key, name); } StringTemplate t = literals.lookupTemplate(key); for (Map.Entry<String, Object> entry : ctx.getAttributes().entrySet()) { t.setAttribute(entry.getKey(), entry.getValue()); } return t.toString(); } else { // no template, no literals as template, just use the literal as sql return name; } } private static final String sep = "/"; // *Not* System.getProperty("file.separator"), which breaks in jars private static String mungify(Class<?> clazz) { return "/" + clazz.getName().replaceAll("\\.", Matcher.quoteReplacement(sep)) + TEMPLATE_GROUP_EXTENSION; } // @VisibleForTesting static boolean templateCached(final Class<?> clazzKey, Class<?> superKey) { final StringBuilder sb = new StringBuilder(mungify(clazzKey)); if (superKey != null) { sb.append(SUPER_SEPARATOR); sb.append(mungify(superKey)); } return ANNOTATION_LOCATOR_CACHE.containsKey(sb.toString()); } public static class Builder { private final String basePath; private String superGroupPath; private StringTemplateErrorListener errorListener = null; private boolean allowImplicitTemplateGroupEnabled = false; private boolean treatLiteralsAsTemplatesEnabled = false; private boolean shouldCacheEnabled = false; Builder(final Class<?> baseClass) { this.basePath = mungify(baseClass); } Builder(final String basePath) { this.basePath = basePath; } public Builder withSuperGroup(final Class<?> superGroupClass) { this.superGroupPath = mungify(superGroupClass); return this; } public Builder withSuperGroup(final String superGroupPath) { this.superGroupPath = superGroupPath; return this; } public Builder withErrorListener(final StringTemplateErrorListener errorListener) { this.errorListener = errorListener; return this; } public Builder allowImplicitTemplateGroup() { this.allowImplicitTemplateGroupEnabled = true; return this; } public Builder treatLiteralsAsTemplates() { this.treatLiteralsAsTemplatesEnabled = true; return this; } public Builder shouldCache() { this.shouldCacheEnabled = true; return this; } public StringTemplate3StatementLocator build() { return new StringTemplate3StatementLocator(basePath, superGroupPath, errorListener, allowImplicitTemplateGroupEnabled, treatLiteralsAsTemplatesEnabled, shouldCacheEnabled); } } }
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/main/java/org/skife/jdbi/v2/sqlobject/stringtemplate/Base64.java
jdbi/src/main/java/org/skife/jdbi/v2/sqlobject/stringtemplate/Base64.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.sqlobject.stringtemplate; import java.nio.charset.Charset; /** * This class provides encode/decode for RFC 2045 Base64 as * defined by RFC 2045, N. Freed and N. Borenstein. * RFC 2045: Multipurpose Internet Mail Extensions (MIME) * Part One: Format of Internet Message Bodies. Reference * 1996 Available at: http://www.ietf.org/rfc/rfc2045.txt * This class is used by XML Schema binary format validation * * @author Jeffrey Rodriguez * @version $Id$ */ final class Base64 { private static final int BASELENGTH = 255; private static final int LOOKUPLENGTH = 64; private static final int TWENTYFOURBITGROUP = 24; private static final int EIGHTBIT = 8; private static final int SIXTEENBIT = 16; private static final int SIXBIT = 6; private static final int FOURBYTE = 4; private static final byte PAD = ( byte ) '='; private static byte [] base64Alphabet = new byte[BASELENGTH]; private static byte [] lookUpBase64Alphabet = new byte[LOOKUPLENGTH]; static { for (int i = 0; i<BASELENGTH; i++ ) { base64Alphabet[i] = -1; } for ( int i = 'Z'; i >= 'A'; i-- ) { base64Alphabet[i] = (byte) (i-'A'); } for ( int i = 'z'; i>= 'a'; i--) { base64Alphabet[i] = (byte) ( i-'a' + 26); } for ( int i = '9'; i >= '0'; i--) { base64Alphabet[i] = (byte) (i-'0' + 52); } base64Alphabet['+'] = 62; base64Alphabet['/'] = 63; for (int i = 0; i<=25; i++ ) { lookUpBase64Alphabet[i] = (byte) ('A'+i ); } for (int i = 26, j = 0; i<=51; i++, j++ ) { lookUpBase64Alphabet[i] = (byte) ('a'+ j ); } for (int i = 52, j = 0; i<=61; i++, j++ ) { lookUpBase64Alphabet[i] = (byte) ('0' + j ); } lookUpBase64Alphabet[62] = (byte) '+'; lookUpBase64Alphabet[63] = (byte) '/'; } public static boolean isBase64( String isValidString ){ return isArrayByteBase64( isValidString.getBytes(Charset.forName("UTF-8"))); } public static boolean isBase64( byte octect ) { //shall we ignore white space? JEFF?? return octect == PAD || base64Alphabet[octect] != -1; } public static boolean isArrayByteBase64( byte[] arrayOctect ) { int length = arrayOctect.length; if ( length == 0 ) { return false; } for ( int i=0; i < length; i++ ) { if ( Base64.isBase64( arrayOctect[i] ) == false) { return false; } } return true; } /** * Encodes hex octects into Base64 * * @param binaryData Array containing binaryData * @return Encoded Base64 array */ public byte[] encode( byte[] binaryData ) { int lengthDataBits = binaryData.length*EIGHTBIT; int fewerThan24bits = lengthDataBits%TWENTYFOURBITGROUP; int numberTriplets = lengthDataBits/TWENTYFOURBITGROUP; byte encodedData[] = null; if ( fewerThan24bits != 0 ) { encodedData = new byte[ (numberTriplets + 1 )*4 ]; } else { encodedData = new byte[ numberTriplets*4 ]; } byte k=0, l=0, b1=0,b2=0,b3=0; int encodedIndex = 0; int dataIndex = 0; int i = 0; for ( i = 0; i<numberTriplets; i++ ) { dataIndex = i*3; b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; b3 = binaryData[dataIndex + 2]; l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); encodedIndex = i*4; encodedData[encodedIndex] = lookUpBase64Alphabet[ b1 >>2 ]; encodedData[encodedIndex+1] = lookUpBase64Alphabet[(b2 >>4 ) | ( k<<4 )]; encodedData[encodedIndex+2] = lookUpBase64Alphabet[ (l <<2 ) | ( b3>>6)]; encodedData[encodedIndex+3] = lookUpBase64Alphabet[ b3 & 0x3f ]; } // form integral number of 6-bit groups dataIndex = i*3; encodedIndex = i*4; if (fewerThan24bits == EIGHTBIT ) { b1 = binaryData[dataIndex]; k = (byte) ( b1 &0x03 ); encodedData[encodedIndex] = lookUpBase64Alphabet[ b1 >>2 ]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[ k<<4 ]; encodedData[encodedIndex + 2] = PAD; encodedData[encodedIndex + 3] = PAD; } else if ( fewerThan24bits == SIXTEENBIT ) { b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex +1 ]; l = ( byte ) ( b2 &0x0f ); k = ( byte ) ( b1 &0x03 ); encodedData[encodedIndex] = lookUpBase64Alphabet[ b1 >>2 ]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[ (b2 >>4 ) | ( k<<4 )]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[ l<<2 ]; encodedData[encodedIndex + 3] = PAD; } return encodedData; } /** * Decodes Base64 data into octects * * @param binaryData Byte array containing Base64 data * @return Array containind decoded data. */ public byte[] decode( byte[] base64Data ) { int numberQuadruple = base64Data.length/FOURBYTE; byte decodedData[] = null; byte b1=0,b2=0,b3=0, b4=0, marker0=0, marker1=0; // Throw away anything not in base64Data // Adjust size int encodedIndex = 0; int dataIndex = 0; decodedData = new byte[ numberQuadruple*3 + 1 ]; for (int i = 0; i<numberQuadruple; i++ ) { dataIndex = i*4; marker0 = base64Data[dataIndex +2]; marker1 = base64Data[dataIndex +3]; b1 = base64Alphabet[base64Data[dataIndex]]; b2 = base64Alphabet[base64Data[dataIndex +1]]; if ( marker0 != PAD && marker1 != PAD ) { //No PAD e.g 3cQl b3 = base64Alphabet[ marker0 ]; b4 = base64Alphabet[ marker1 ]; decodedData[encodedIndex] = (byte)( b1 <<2 | b2>>4 ) ; decodedData[encodedIndex+1] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ); decodedData[encodedIndex+2] = (byte)( b3<<6 | b4 ); } else if ( marker0 == PAD ) { //Two PAD e.g. 3c[Pad][Pad] decodedData[encodedIndex] = (byte)( b1 <<2 | b2>>4 ) ; decodedData[encodedIndex+1] = (byte)((b2 & 0xf)<<4 ); decodedData[encodedIndex+2] = (byte) 0; } else if ( marker1 == PAD ) { //One PAD e.g. 3cQ[Pad] b3 = base64Alphabet[ marker0 ]; decodedData[encodedIndex] = (byte)( b1 <<2 | b2>>4 ); decodedData[encodedIndex+1] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ); decodedData[encodedIndex+2] = (byte)( b3<<6); } encodedIndex += 3; } return decodedData; } }
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/main/java/org/skife/jdbi/v2/unstable/BindIn.java
jdbi/src/main/java/org/skife/jdbi/v2/unstable/BindIn.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.unstable; import org.skife.jdbi.v2.SQLStatement; import org.skife.jdbi.v2.sqlobject.Binder; import org.skife.jdbi.v2.sqlobject.BinderFactory; import org.skife.jdbi.v2.sqlobject.BindingAnnotation; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizer; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizerFactory; import org.skife.jdbi.v2.sqlobject.SqlStatementCustomizingAnnotation; import java.lang.annotation.Annotation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Method; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; @Retention(RetentionPolicy.RUNTIME) @SqlStatementCustomizingAnnotation(BindIn.CustomizerFactory.class) @BindingAnnotation(BindIn.BindingFactory.class) public @interface BindIn { String value(); public static final class CustomizerFactory implements SqlStatementCustomizerFactory { @Override public SqlStatementCustomizer createForMethod(Annotation annotation, Class sqlObjectType, Method method) { throw new UnsupportedOperationException("Not supported on method!"); } @Override public SqlStatementCustomizer createForType(Annotation annotation, Class sqlObjectType) { throw new UnsupportedOperationException("Not supported on type"); } @Override public SqlStatementCustomizer createForParameter(Annotation annotation, Class sqlObjectType, Method method, Object arg) { Collection<?> coll = (Collection<?>) arg; BindIn in = (BindIn) annotation; final String key = in.value(); final List<String> ids = new ArrayList<String>(); for (int idx = 0; idx < coll.size(); idx++) { ids.add("__" + key + "_" + idx); } StringBuilder names = new StringBuilder(); for (Iterator<String> i = ids.iterator(); i.hasNext();) { names.append(":").append(i.next()); if (i.hasNext()) { names.append(","); } } final String ns = names.toString(); return new SqlStatementCustomizer() { @Override public void apply(SQLStatement q) throws SQLException { q.define(key, ns); } }; } } public static class BindingFactory implements BinderFactory { @Override public Binder build(Annotation annotation) { final BindIn in = (BindIn) annotation; final String key = in.value(); return new Binder() { @Override public void bind(SQLStatement q, Annotation bind, Object arg) { Iterable<?> coll = (Iterable<?>) arg; int idx = 0; for (Object s : coll) { q.bind("__" + key + "_" + idx++, s); } } }; } } }
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/main/java/org/skife/jdbi/v2/tweak/ContainerFactory.java
jdbi/src/main/java/org/skife/jdbi/v2/tweak/ContainerFactory.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.tweak; import org.skife.jdbi.v2.ContainerBuilder; public interface ContainerFactory<T> { boolean accepts(Class<?> type); ContainerBuilder<T> newContainerBuilderFor(Class<?> 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/main/java/org/skife/jdbi/v2/tweak/StatementBuilder.java
jdbi/src/main/java/org/skife/jdbi/v2/tweak/StatementBuilder.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.tweak; import org.skife.jdbi.v2.StatementContext; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; /** * Used to convert translated SQL into a prepared statement. The default implementation * created by {@link org.skife.jdbi.v2.CachingStatementBuilderFactory} caches all prepared * statements created against a given handle. * * A StatementBuilder is always associated with exactly one Handle instance * * @see StatementBuilderFactory */ public interface StatementBuilder { /** * Called each time a prepared statement needs to be created * * @param conn the JDBC Connection the statement is being created for * @param sql the translated SQL which should be prepared * @param columnNames an array of column names indicating the columns * that should be returned from the inserted row or rows * @param ctx Statement context associated with the SQLStatement this is building for */ PreparedStatement create(Connection conn, String sql, String columnNames[], StatementContext ctx) throws SQLException; /** * Called each time a Callable statement needs to be created * * @param conn the JDBC Connection the statement is being created for * @param sql the translated SQL which should be prepared * @param ctx Statement context associated with the SQLStatement this is building for */ CallableStatement createCall(Connection conn, String sql, StatementContext ctx) throws SQLException; /** * Called to close an individual prepared statement created from this builder. * * @param sql the translated SQL which was prepared * @param stmt the statement * * @throws SQLException if anything goes wrong closing the statement */ void close(Connection conn, String sql, Statement stmt) throws SQLException; /** * Called when the handle this StatementBuilder is attached to is closed. */ void close(Connection conn); }
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/main/java/org/skife/jdbi/v2/tweak/RewrittenStatement.java
jdbi/src/main/java/org/skife/jdbi/v2/tweak/RewrittenStatement.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.tweak; import org.skife.jdbi.v2.Binding; import java.sql.PreparedStatement; import java.sql.SQLException; /** * Return value from {@link StatementRewriter#rewrite(String, org.skife.jdbi.v2.Binding, org.skife.jdbi.v2.StatementContext)} calls */ public interface RewrittenStatement { /** * Called to bind a set of parameters to a prepared statement. The * statement will have been constructed from this RewrittenStatement's * getSql() return result * @param params * @param statement * @throws SQLException */ void bind(Binding params, PreparedStatement statement) throws SQLException; /** * Obtain the SQL in valid (rewritten) form to be used to prepare a statement */ String getSql(); }
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/main/java/org/skife/jdbi/v2/tweak/VoidHandleCallback.java
jdbi/src/main/java/org/skife/jdbi/v2/tweak/VoidHandleCallback.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.tweak; import org.skife.jdbi.v2.Handle; /** * Abstract {@link HandleCallback} that doesn't return a result. */ public abstract class VoidHandleCallback implements HandleCallback<Void> { /** * This implementation delegates to {@link #execute}. * * @param handle {@inheritDoc} * @return nothing * @throws Exception {@inheritDoc} */ @Override public final Void withHandle(Handle handle) throws Exception { execute(handle); return null; } /** * {@link #withHandle} will delegate to this method. * * @param handle Handle to be used only within scope of this callback * @throws Exception will result in a {@link org.skife.jdbi.v2.exceptions.CallbackFailedException} wrapping * the exception being thrown */ protected abstract void execute(Handle handle) 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/main/java/org/skife/jdbi/v2/tweak/SQLLog.java
jdbi/src/main/java/org/skife/jdbi/v2/tweak/SQLLog.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.tweak; import org.skife.jdbi.v2.Handle; /** * Interface used to receive sql logging events. */ public interface SQLLog { /** * Called when a transaction is started */ void logBeginTransaction(Handle h); /** * Called when a transaction is committed */ void logCommitTransaction(long time, Handle h); /** * Called when a transaction is committed */ void logRollbackTransaction(long time, Handle h); /** * Called when a handle is opened from a DBI instance */ void logObtainHandle(long time, Handle h); /** * Called when a handle is closed */ void logReleaseHandle(Handle h); /** * Called to log typical sql statements * @param sql the actual sql being exected */ void logSQL(long time, String sql); /** * Called to log a prepared batch execution * @param sql The sql for the prepared batch * @param count the number of elements in the prepared batch */ void logPreparedBatch(long time, String sql, int count); /** * Factory method used to obtain a SQLLog.BatchLogger which will be used to log * a specific batch statement. * * @return an instance of BatchLogger which will be used to log this batch */ BatchLogger logBatch(); /** * Called when a transaction is checkpointed * @param name the checkpoint name */ void logCheckpointTransaction(Handle h, String name); /** * Called when a transaction checkpoint is released * @param name the checkpoint name */ void logReleaseCheckpointTransaction(Handle h, String name); /** * Called when a transaction checkpoint is rolled back to */ void logRollbackToCheckpoint(long time, Handle h, String checkpointName); /** * Instances of this are used to log batch statements. SQLLog#logBatch will return one of these. * A new one will be requested for each batch execution. */ public interface BatchLogger { /** * Called once for each statement in the batch * @param sql sql for the statement */ void add(String sql); /** * Called when all statements have been passed to add() */ void log(long time); } }
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/main/java/org/skife/jdbi/v2/tweak/ResultSetMapper.java
jdbi/src/main/java/org/skife/jdbi/v2/tweak/ResultSetMapper.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.tweak; import org.skife.jdbi.v2.StatementContext; import java.sql.ResultSet; import java.sql.SQLException; /** * Used with a {@link org.skife.jdbi.v2.Query#map(ResultSetMapper)} call to specify * what to do with each row of a result set */ public interface ResultSetMapper<T> { /** * Map the row the result set is at when passed in. This method should not cause the result * set to advance, allow jDBI to do that, please. * * @param index which row of the result set we are at, starts at 0 * @param r the result set being iterated * @param ctx * @return the value to return for this row * @throws SQLException if anythign goes wrong go ahead and let this percolate, jDBI will handle it */ T map(int index, ResultSet r, 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/main/java/org/skife/jdbi/v2/tweak/ArgumentFactory.java
jdbi/src/main/java/org/skife/jdbi/v2/tweak/ArgumentFactory.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.tweak; import org.skife.jdbi.v2.StatementContext; public interface ArgumentFactory<T> { boolean accepts(Class<?> expectedType, Object value, StatementContext ctx); Argument build(Class<?> expectedType, T value, StatementContext ctx); }
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/main/java/org/skife/jdbi/v2/tweak/NamedArgumentFinder.java
jdbi/src/main/java/org/skife/jdbi/v2/tweak/NamedArgumentFinder.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.tweak; /** * Returns an Argument based on a name. Used to lookup multiple properties e.g. in a Bean or a Map. */ public interface NamedArgumentFinder { Argument find(String name); }
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/main/java/org/skife/jdbi/v2/tweak/Argument.java
jdbi/src/main/java/org/skife/jdbi/v2/tweak/Argument.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.tweak; import org.skife.jdbi.v2.StatementContext; import java.sql.PreparedStatement; import java.sql.SQLException; /** * Represents an argument to a prepared statement. It will be called right before the * statement is executed to bind the parameter. */ public interface Argument { /** * Callback method invoked right before statement execution. * * @param position the position to which the argument should be bound, using the * stupid JDBC "start at 1" bit * @param statement the prepared statement the argument is to be bound to * @param ctx * @throws SQLException if anything goes wrong */ void apply(final 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/main/java/org/skife/jdbi/v2/tweak/StatementBuilderFactory.java
jdbi/src/main/java/org/skife/jdbi/v2/tweak/StatementBuilderFactory.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.tweak; import java.sql.Connection; /** * Used to specify how prepared statements are built. A factory is attached to a DBI instance, and * whenever the DBI instance is used to create a Handle the factory will be used to create a * StatementBuilder for that specific handle. */ public interface StatementBuilderFactory { /** * Obtain a StatementBuilder, called when a new handle is opened */ StatementBuilder createStatementBuilder(Connection conn); }
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/main/java/org/skife/jdbi/v2/tweak/HandleCallback.java
jdbi/src/main/java/org/skife/jdbi/v2/tweak/HandleCallback.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.tweak; import org.skife.jdbi.v2.Handle; /** * Callback for use with {@link org.skife.jdbi.v2.DBI#withHandle(HandleCallback)} */ public interface HandleCallback<T> { /** * Will be invoked with an open Handle. The handle will be closed when this * callback returns. Any exception thrown will be wrapped in a * {@link org.skife.jdbi.v2.exceptions.CallbackFailedException} * * @param handle Handle to be used only within scope of this callback * @return The return value of the callback * @throws Exception will result in a {@link org.skife.jdbi.v2.exceptions.CallbackFailedException} wrapping * the exception being thrown */ T withHandle(Handle handle) 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/main/java/org/skife/jdbi/v2/tweak/StatementRewriter.java
jdbi/src/main/java/org/skife/jdbi/v2/tweak/StatementRewriter.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.tweak; import org.skife.jdbi.v2.Binding; import org.skife.jdbi.v2.StatementContext; /** * Use to provide arbitrary statement rewriting. */ public interface StatementRewriter { /** * Munge up the SQL as desired. Responsible for figuring out ow to bind any * arguments in to the resultant prepared statement. * * @param sql The SQL to rewrite * @param params contains the arguments which have been bound to this statement. * @param ctx The statement context for the statement being executed * @return somethign which can provde the actual SQL to prepare a statement from * and which can bind the correct arguments to that prepared statement */ RewrittenStatement rewrite(String sql, Binding params, StatementContext ctx); }
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/main/java/org/skife/jdbi/v2/tweak/ConnectionFactory.java
jdbi/src/main/java/org/skife/jdbi/v2/tweak/ConnectionFactory.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.tweak; import java.sql.Connection; import java.sql.SQLException; /** * Interface which abstracts away how JDBC Connections are obtained */ public interface ConnectionFactory { /** * Provides a Connection */ Connection openConnection() 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/main/java/org/skife/jdbi/v2/tweak/BaseStatementCustomizer.java
jdbi/src/main/java/org/skife/jdbi/v2/tweak/BaseStatementCustomizer.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.tweak; import org.skife.jdbi.v2.StatementContext; import java.sql.PreparedStatement; import java.sql.SQLException; /** * Convenience class which provides no-op stubs of the StatementCustomizer methods */ public class BaseStatementCustomizer implements StatementCustomizer { /** * Make the changes you need to inside this method. It will be invoked prior to execution of * the prepared statement * * @param stmt Prepared statement being customized * @param ctx Statement context associated with the statement being customized * * @throws java.sql.SQLException go ahead and percolate it for jDBI to handle */ @Override public void beforeExecution(PreparedStatement stmt, StatementContext ctx) throws SQLException { } /** * This will be invoked after execution of the prepared statement, but before any results * are accessed. * * @param stmt Prepared statement being customized * @param ctx Statement context associated with the statement being customized * * @throws java.sql.SQLException go ahead and percolate it for jDBI to handle */ @Override public void afterExecution(PreparedStatement stmt, StatementContext ctx) throws SQLException { } /** * Invoked at cleanup time to clean resources used by this statement. * * @param ctx Statement context associated with the statement being customized * @throws SQLException go ahead and percolate it for jDBI to handle */ @Override public void cleanup(final 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/main/java/org/skife/jdbi/v2/tweak/TransactionHandler.java
jdbi/src/main/java/org/skife/jdbi/v2/tweak/TransactionHandler.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.tweak; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.TransactionCallback; import org.skife.jdbi.v2.TransactionIsolationLevel; /** * Interface which defines callbacks to be used when transaction methods are called on a handle. * Used by specifying on an <code>IDBI</code> instance. All <code>Handle</code> instances * opened from that <code>IDBI</code> will use the handler specified. * <p /> * The default implementation, <code>ConnectionTransactionHandler</code>, explicitely manages * the transactions on the underlying JDBC <code>Connection</code>. */ public interface TransactionHandler { /** * Called when a transaction is started */ void begin(Handle handle); // TODO consider having this return a TransactionStatus /** * Called when a transaction is committed */ void commit(Handle handle); /** * Called when a transaction is rolled back */ void rollback(Handle handle); /** * Roll back to a named checkpoint * @param handle the handle the rollback is being performed on * @param name the name of the checkpoint to rollback to */ void rollback(Handle handle, String name); /** * Called to test if a handle is in a transaction */ boolean isInTransaction(Handle handle); /** * Create a new checkpoint (savepoint in JDBC terminology) * * @param handle the handle on which the transaction is being checkpointed * @param name The name of the chckpoint, used to rollback to or release late */ void checkpoint(Handle handle, String name); /** * Release a previously created checkpoint * * @param handle the handle on which the checkpoint is being released * @param checkpointName the checkpoint to release */ void release(Handle handle, String checkpointName); /** * Run a transaction. * @see Handle#inTransaction(TransactionCallback) */ <ReturnType> ReturnType inTransaction(Handle handle, TransactionCallback<ReturnType> callback); /** * Run a transaction. * @see Handle#inTransaction(TransactionIsolationLevel, TransactionCallback) */ <ReturnType> ReturnType inTransaction(Handle handle, TransactionIsolationLevel level, TransactionCallback<ReturnType> callback); }
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/main/java/org/skife/jdbi/v2/tweak/StatementCustomizer.java
jdbi/src/main/java/org/skife/jdbi/v2/tweak/StatementCustomizer.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.tweak; import org.skife.jdbi.v2.StatementContext; import java.sql.PreparedStatement; import java.sql.SQLException; /** * Allows tweaking of statement behaviour. */ public interface StatementCustomizer { /** * Make the changes you need to inside this method. It will be invoked prior to execution of * the prepared statement * * @param stmt Prepared statement being customized * @param ctx Statement context associated with the statement being customized * @throws SQLException go ahead and percolate it for jDBI to handle */ void beforeExecution(PreparedStatement stmt, StatementContext ctx) throws SQLException; /** * This will be invoked after execution of the prepared statement, but before any results * are accessed. * * @param stmt Prepared statement being customized * @param ctx Statement context associated with the statement being customized * @throws SQLException go ahead and percolate it for jDBI to handle */ void afterExecution(PreparedStatement stmt, StatementContext ctx) throws SQLException; /** * Invoked at cleanup time to clean resources used by this statement. * * @param ctx Statement context associated with the statement being customized * @throws SQLException go ahead and percolate it for jDBI to handle */ void cleanup(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/main/java/org/skife/jdbi/v2/tweak/StatementLocator.java
jdbi/src/main/java/org/skife/jdbi/v2/tweak/StatementLocator.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.tweak; import org.skife.jdbi.v2.StatementContext; /** * Used for finding the actual SQL for named statements.. */ public interface StatementLocator { /** * Use this to map from a named statement to SQL. The SQL returned will be passed to * a StatementRewriter, so this can include stuff like named params and whatnot. * * @param name The name of the statement, as provided to a Handle * @return the SQL to execute, after it goes through a StatementRewriter * @throws Exception if anything goes wrong, jDBI will percolate expected exceptions */ String locate(String name, StatementContext ctx) 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/main/java/org/skife/jdbi/v2/tweak/BeanMapperFactory.java
jdbi/src/main/java/org/skife/jdbi/v2/tweak/BeanMapperFactory.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.tweak; import org.skife.jdbi.v2.BeanMapper; import org.skife.jdbi.v2.BuiltInArgumentFactory; import org.skife.jdbi.v2.ResultSetMapperFactory; import org.skife.jdbi.v2.StatementContext; public class BeanMapperFactory implements ResultSetMapperFactory { @Override public boolean accepts(Class type, StatementContext ctx) { if (BuiltInArgumentFactory.canAccept(type)) { // don't interfere with built-ins return false; } return true; } @Override public ResultSetMapper mapperFor(Class type, StatementContext ctx) { return new BeanMapper(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/main/java/org/skife/jdbi/v2/tweak/transactions/SerializableTransactionRunner.java
jdbi/src/main/java/org/skife/jdbi/v2/tweak/transactions/SerializableTransactionRunner.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.tweak.transactions; import java.sql.SQLException; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.TransactionCallback; import org.skife.jdbi.v2.TransactionIsolationLevel; import org.skife.jdbi.v2.tweak.TransactionHandler; /** * A TransactionHandler that automatically retries transactions that fail due to * serialization failures, which can generally be resolved by automatically * retrying the transaction. Any TransactionCallback used under this runner * should be aware that it may be invoked multiple times. */ public class SerializableTransactionRunner extends DelegatingTransactionHandler implements TransactionHandler { /* http://www.postgresql.org/docs/9.1/static/errcodes-appendix.html */ private static final String SQLSTATE_TXN_SERIALIZATION_FAILED = "40001"; private final Configuration configuration; public SerializableTransactionRunner() { this(new Configuration(), new LocalTransactionHandler()); } public SerializableTransactionRunner(Configuration configuration, TransactionHandler delegate) { super(delegate); this.configuration = configuration; } @Override public <ReturnType> ReturnType inTransaction(Handle handle, TransactionCallback<ReturnType> callback) { int retriesRemaining = configuration.maxRetries; while (true) { try { return getDelegate().inTransaction(handle, callback); } catch (RuntimeException e) { if (!isSqlState(configuration.serializationFailureSqlState, e) || --retriesRemaining <= 0) { throw e; } } } } @Override public <ReturnType> ReturnType inTransaction(Handle handle, TransactionIsolationLevel level, TransactionCallback<ReturnType> callback) { final TransactionIsolationLevel initial = handle.getTransactionIsolationLevel(); try { handle.setTransactionIsolation(level); return inTransaction(handle, callback); } finally { handle.setTransactionIsolation(initial); } } /** * Returns true iff the Throwable or one of its causes is an SQLException whose SQLState begins * with the passed state. */ protected boolean isSqlState(String expectedSqlState, Throwable throwable) { do { if (throwable instanceof SQLException) { String sqlState = ((SQLException) throwable).getSQLState(); if (sqlState != null && sqlState.startsWith(expectedSqlState)) { return true; } } } while ( (throwable = throwable.getCause()) != null); return false; } public static class Configuration { private final int maxRetries; private final String serializationFailureSqlState; public Configuration() { this(5, SQLSTATE_TXN_SERIALIZATION_FAILED); } private Configuration(int maxRetries, String serializationFailureSqlState) { this.maxRetries = maxRetries; this.serializationFailureSqlState = serializationFailureSqlState; } public Configuration withMaxRetries(int maxRetries) { return new Configuration(maxRetries, serializationFailureSqlState); } public Configuration withSerializationFailureSqlState(String serializationFailureSqlState) { return new Configuration(maxRetries, serializationFailureSqlState); } } }
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/main/java/org/skife/jdbi/v2/tweak/transactions/DelegatingTransactionHandler.java
jdbi/src/main/java/org/skife/jdbi/v2/tweak/transactions/DelegatingTransactionHandler.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.tweak.transactions; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.TransactionCallback; import org.skife.jdbi.v2.TransactionIsolationLevel; import org.skife.jdbi.v2.tweak.TransactionHandler; public class DelegatingTransactionHandler implements TransactionHandler { private final TransactionHandler delegate; public DelegatingTransactionHandler(TransactionHandler delegate) { this.delegate = delegate; } protected TransactionHandler getDelegate() { return delegate; } @Override public void begin(Handle handle) { delegate.begin(handle); } @Override public void commit(Handle handle) { delegate.commit(handle); } @Override public void rollback(Handle handle) { delegate.rollback(handle); } @Override public void rollback(Handle handle, String name) { delegate.rollback(handle, name); } @Override public boolean isInTransaction(Handle handle) { return delegate.isInTransaction(handle); } @Override public void checkpoint(Handle handle, String name) { delegate.checkpoint(handle, name); } @Override public void release(Handle handle, String checkpointName) { delegate.release(handle, checkpointName); } @Override public <ReturnType> ReturnType inTransaction(Handle handle, TransactionCallback<ReturnType> callback) { return delegate.inTransaction(handle, callback); } @Override public <ReturnType> ReturnType inTransaction(Handle handle, TransactionIsolationLevel level, TransactionCallback<ReturnType> callback) { return delegate.inTransaction(handle, level, callback); } }
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/main/java/org/skife/jdbi/v2/tweak/transactions/LocalTransactionHandler.java
jdbi/src/main/java/org/skife/jdbi/v2/tweak/transactions/LocalTransactionHandler.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.tweak.transactions; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.TransactionCallback; import org.skife.jdbi.v2.TransactionIsolationLevel; import org.skife.jdbi.v2.TransactionStatus; import org.skife.jdbi.v2.exceptions.TransactionException; import org.skife.jdbi.v2.exceptions.TransactionFailedException; import org.skife.jdbi.v2.exceptions.UnableToRestoreAutoCommitStateException; import org.skife.jdbi.v2.tweak.TransactionHandler; import java.sql.Connection; import java.sql.SQLException; import java.sql.Savepoint; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; /** * This <code>TransactionHandler</code> uses local JDBC transactions * demarcated explicitly on the handle and passed through to be handled * directly on the JDBC Connection instance. */ public class LocalTransactionHandler implements TransactionHandler { private final ConcurrentHashMap<Handle, LocalStuff> localStuff = new ConcurrentHashMap<Handle, LocalStuff>(); /** * Called when a transaction is started */ @Override public void begin(Handle handle) { try { if (!localStuff.containsKey(handle)) { boolean initial = handle.getConnection().getAutoCommit(); localStuff.putIfAbsent(handle, new LocalStuff(initial)); handle.getConnection().setAutoCommit(false); } } catch (SQLException e) { throw new TransactionException("Failed to start transaction", e); } } /** * Called when a transaction is committed */ @Override public void commit(Handle handle) { try { handle.getConnection().commit(); } catch (SQLException e) { throw new TransactionException("Failed to commit transaction", e); } finally { restoreAutoCommitState(handle); } } /** * Called when a transaction is rolled back */ @Override public void rollback(Handle handle) { try { handle.getConnection().rollback(); } catch (SQLException e) { throw new TransactionException("Failed to rollback transaction", e); } finally { restoreAutoCommitState(handle); } } /** * Create a new checkpoint (savepoint in JDBC terminology) * * @param handle the handle on which the transaction is being checkpointed * @param name The name of the chckpoint, used to rollback to or release late */ @Override public void checkpoint(Handle handle, String name) { final Connection conn = handle.getConnection(); try { final Savepoint savepoint = conn.setSavepoint(name); localStuff.get(handle).getCheckpoints().put(name, savepoint); } catch (SQLException e) { throw new TransactionException(String.format("Unable to create checkpoint %s", name), e); } } @Override public void release(Handle handle, String name) { final Connection conn = handle.getConnection(); try { final Savepoint savepoint = localStuff.get(handle).getCheckpoints().remove(name); if (savepoint == null) { throw new TransactionException(String.format("Attempt to rollback to non-existant savepoint, '%s'", name)); } conn.releaseSavepoint(savepoint); } catch (SQLException e) { throw new TransactionException(String.format("Unable to create checkpoint %s", name), e); } } /** * Roll back to a named checkpoint * * @param handle the handle the rollback is being performed on * @param name the name of the checkpoint to rollback to */ @Override public void rollback(Handle handle, String name) { final Connection conn = handle.getConnection(); try { final Savepoint savepoint = localStuff.get(handle).getCheckpoints().remove(name); if (savepoint == null) { throw new TransactionException(String.format("Attempt to rollback to non-existant savepoint, '%s'", name)); } conn.rollback(savepoint); } catch (SQLException e) { throw new TransactionException(String.format("Unable to create checkpoint %s", name), e); } } /** * Called to test if a handle is in a transaction */ @Override public boolean isInTransaction(Handle handle) { try { return !handle.getConnection().getAutoCommit(); } catch (SQLException e) { throw new TransactionException("Failed to test for transaction status", e); } } @Override public <ReturnType> ReturnType inTransaction(Handle handle, TransactionCallback<ReturnType> callback) { final AtomicBoolean failed = new AtomicBoolean(false); TransactionStatus status = new TransactionStatus() { @Override public void setRollbackOnly() { failed.set(true); } }; final ReturnType returnValue; try { handle.begin(); returnValue = callback.inTransaction(handle, status); if (!failed.get()) { handle.commit(); } } catch (RuntimeException e) { handle.rollback(); throw e; } catch (Exception e) { handle.rollback(); throw new TransactionFailedException("Transaction failed do to exception being thrown " + "from within the callback. See cause " + "for the original exception.", e); } if (failed.get()) { handle.rollback(); throw new TransactionFailedException("Transaction failed due to transaction status being set " + "to rollback only."); } else { return returnValue; } } @Override public <ReturnType> ReturnType inTransaction(Handle handle, TransactionIsolationLevel level, TransactionCallback<ReturnType> callback) { final TransactionIsolationLevel initial = handle.getTransactionIsolationLevel(); try { handle.setTransactionIsolation(level); return inTransaction(handle, callback); } finally { handle.setTransactionIsolation(initial); } } private void restoreAutoCommitState(final Handle handle) { try { final LocalStuff stuff = localStuff.remove(handle); if (stuff != null) { handle.getConnection().setAutoCommit(stuff.getInitialAutocommit()); stuff.getCheckpoints().clear(); } } catch (SQLException e) { throw new UnableToRestoreAutoCommitStateException(e); } finally { // prevent memory leak if rollback throws an exception localStuff.remove(handle); } } private static class LocalStuff { private final Map<String, Savepoint> checkpoints = new HashMap<String, Savepoint>(); private final boolean initialAutocommit; public LocalStuff(boolean initial) { this.initialAutocommit = initial; } public Map<String, Savepoint> getCheckpoints() { return checkpoints; } public boolean getInitialAutocommit() { return initialAutocommit; } } }
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/main/java/org/skife/jdbi/v2/tweak/transactions/CMTTransactionHandler.java
jdbi/src/main/java/org/skife/jdbi/v2/tweak/transactions/CMTTransactionHandler.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.tweak.transactions; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.TransactionCallback; import org.skife.jdbi.v2.TransactionIsolationLevel; import org.skife.jdbi.v2.TransactionStatus; import org.skife.jdbi.v2.exceptions.TransactionException; import org.skife.jdbi.v2.tweak.TransactionHandler; import java.sql.SQLException; /** * Handler designed to behave properly in a J2EE CMT environment. It will never * explicitely begin or commit a transaction, and will throw a runtime exception * when rollback is called to force rollback. */ public class CMTTransactionHandler implements TransactionHandler { /** * Called when a transaction is started */ @Override public void begin(Handle handle) { // noop } /** * Called when a transaction is committed */ @Override public void commit(Handle handle) { // noop } /** * Called when a transaction is rolled back * Will throw a RuntimeException to force transactional rollback */ @Override public void rollback(Handle handle) { throw new TransactionException("Rollback called, this runtime exception thrown to halt the transaction"); } /** * Roll back to a named checkpoint * * @param handle the handle the rollback is being performed on * @param name the name of the checkpoint to rollback to */ @Override public void rollback(Handle handle, String name) { throw new UnsupportedOperationException("Checkpoints not implemented"); } /** * Called to test if a handle is in a transaction */ @Override public boolean isInTransaction(Handle handle) { try { return ! handle.getConnection().getAutoCommit(); } catch (SQLException e) { throw new TransactionException("Failed to check status of transaction", e); } } /** * Create a new checkpoint (savepoint in JDBC terminology) * * @param handle the handle on which the transaction is being checkpointed * @param name The name of the chckpoint, used to rollback to or release late */ @Override public void checkpoint(Handle handle, String name) { throw new UnsupportedOperationException("Checkpoints not implemented"); } /** * Release a previously created checkpoint * * @param handle the handle on which the checkpoint is being released * @param checkpointName the checkpoint to release */ @Override public void release(Handle handle, String checkpointName) { throw new TransactionException("Rollback called, this runtime exception thrown to halt the transaction"); } private class ExplodingTransactionStatus implements TransactionStatus { private final Handle handle; ExplodingTransactionStatus(Handle handle) { this.handle = handle; } @Override public void setRollbackOnly() { rollback(handle); } } @Override public <ReturnType> ReturnType inTransaction(final Handle handle, TransactionCallback<ReturnType> callback) { try { return callback.inTransaction(handle, new ExplodingTransactionStatus(handle)); } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } throw new TransactionException(e); } } @Override public <ReturnType> ReturnType inTransaction(Handle handle, TransactionIsolationLevel level, TransactionCallback<ReturnType> callback) { return inTransaction(handle, callback); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false