auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void onUnimprovedStepCountLimitInputChange( ChangeEvent event ) { try { Integer value = unimprovedStepCountLimitInput.getValue().isEmpty() ? null : Integer.parseInt( unimprovedStepCountLimitInput.getValue() ); presenter.onUnimprovedStepCountLimitChange( value ); } catch ( NumberFormatException e ) { } }

Target:
public void onUnimprovedStepCountLimitInputChange( ChangeEvent event ) { boolean isNumeric = unimprovedStepCountLimitInput.getValue().matches( "\\d+" ); if (isNumeric) { presenter.onUnimprovedStepCountLimitChange( Integer.parseInt( unimprovedStepCountLimitInput.getValue() ) ); } else { presenter.onUnimprovedStepCountLimitChange( 0 ); unimprovedStepCountLimitInput.setValue( "0" ); } }
Source:
public static List<Path> getPaths(List<String> uriStrings) throws RuntimeException { return uriStrings.stream().map(s -> { try { return IOUtil.getPath(s); } catch (IOException e) { throw new RuntimeException(e); } }).collect(Collectors.toList()); }

Target:
public static List<Path> getPaths(List<String> uriStrings) throws RuntimeIOException { return uriStrings.stream().map(s -> { try { return IOUtil.getPath(s); } catch (IOException e) { throw new RuntimeIOException(e); } }).collect(Collectors.toList()); }
Source:
public TranslationSystemImpl(Context context) { config = context.get(Config.class).getSystem(); AssetManager assetManager = context.get(AssetManager.class); Set<ResourceUrn> urns = assetManager.getAvailableAssets(Translation.class); for (ResourceUrn urn : urns) { Optional<Translation> asset = assetManager.getAsset(urn, Translation.class); if (asset.isPresent()) { Translation trans = asset.get(); Uri uri = trans.getProjectUri(); if (uri.isValid()) { TranslationProject proj = projects.computeIfAbsent(uri, e -> new StandardTranslationProject()); proj.add(trans); trans.subscribe(this::onAssetChanged); logger.info("Discovered " + trans); } else { logger.warn("Ignoring invalid project uri: {}", uri); } } } }

Target:
public TranslationSystemImpl(Context context) { config = context.get(Config.class).getSystem(); assetManager = context.get(AssetManager.class); refresh(); }
Source:
public void disable() { for (CustomSpeedController motor : motors) { motor.disable(); } }

Target:
public void disable() { for (SpeedController motor : motors) { motor.disable(); } }
Source:
public synchronized ILogData previous() { final QueuedStreamContext context = getCurrentContext(); final long oldPointer = context.getGlobalPointer(); log.trace("previous[{}]: max={} min={}", this, context.maxResolution, context.minResolution); if (context.getGlobalPointer() == Address.NEVER_READ) { return null; } Long prevAddress = context .resolvedQueue.lower(context.getGlobalPointer()); if (prevAddress == null && Address.isAddress(context.minResolution) || prevAddress != null && prevAddress <= context.minResolution) { context.setGlobalPointer(prevAddress == null ? Address.NEVER_READ : prevAddress - 1L); remainingUpTo(context.minResolution); context.minResolution = Address.NON_ADDRESS; context.setGlobalPointer(oldPointer); prevAddress = context .resolvedQueue.lower(context.getGlobalPointer()); log.trace("previous[{}]: updated resolved queue {}", this, context.resolvedQueue); } context.readQueue.clear(); if (prevAddress != null) { log.trace("previous[{}]: updated read queue {}", this, context.readQueue); context.setGlobalPointer(prevAddress); return read(prevAddress); } log.trace("previous[{}]: reached the beginning of the stream resetting" + " the stream pointer to {}", this, Address.NON_ADDRESS); context.setGlobalPointer(Address.NON_ADDRESS); return null; }

Target:
public synchronized ILogData previous() { final QueuedStreamContext context = getCurrentContext(); final long oldPointer = context.getGlobalPointer(); log.trace("previous[{}]: max={} min={}", this, context.maxResolution, context.minResolution); if (context.getGlobalPointer() == Address.NEVER_READ) { return null; } compactionMarkCheck(oldPointer - 1L); Long prevAddress = context .resolvedQueue.lower(context.getGlobalPointer()); if (prevAddress == null && Address.isAddress(context.minResolution) || prevAddress != null && prevAddress <= context.minResolution) { context.setGlobalPointer(prevAddress == null ? Address.NEVER_READ : prevAddress - 1L); remainingUpTo(context.minResolution); context.minResolution = Address.NON_ADDRESS; context.setGlobalPointer(oldPointer); prevAddress = context .resolvedQueue.lower(context.getGlobalPointer()); log.trace("previous[{}]: updated resolved queue {}", this, context.resolvedQueue); } context.readQueue.clear(); if (prevAddress != null) { compactionMarkCheck(prevAddress); log.trace("previous[{}]: updated read queue {}", this, context.readQueue); context.setGlobalPointer(prevAddress); return read(prevAddress, prevAddress); } log.trace("previous[{}]: reached the beginning of the stream resetting" + " the stream pointer to {}", this, Address.NON_ADDRESS); context.setGlobalPointer(Address.NON_ADDRESS); return null; }
Source:
public void handleCommand(ChannelUID channelUID, Command command) { if (command instanceof OnOffType) { Integer ioChannel = Integer.valueOf(channelUID.getId().substring(channelUID.getId().length() - 1)); if (ioChannel != null && ioChannel < ((AbstractDigitalOwDevice) sensors.get(0)).getChannelCount()) { Bridge bridge = getBridge(); if (bridge != null) { OwBaseBridgeHandler bridgeHandler = (OwBaseBridgeHandler) bridge.getHandler(); if (bridgeHandler != null) { if (!((AbstractDigitalOwDevice) sensors.get(0)).writeChannel(bridgeHandler, ioChannel, command)) { logger.info("writing to channel in thing not permitted (input channel)", channelUID, this.thing.getUID()); } } else { logger.info("bridge handler not found"); } } else { logger.info("bridge not found"); } } } super.handleCommand(channelUID, command); }

Target:
public void handleCommand(ChannelUID channelUID, Command command) { if (command instanceof OnOffType) { Integer ioChannel = Integer.valueOf(channelUID.getId().substring(channelUID.getId().length() - 1)); if (ioChannel != null && ioChannel < ((AbstractDigitalOwDevice) sensors.get(0)).getChannelCount()) { Bridge bridge = getBridge(); if (bridge != null) { OwBaseBridgeHandler bridgeHandler = (OwBaseBridgeHandler) bridge.getHandler(); if (bridgeHandler != null) { if (!((AbstractDigitalOwDevice) sensors.get(0)).writeChannel(bridgeHandler, ioChannel, command)) { logger.debug("writing to channel in thing not permitted (input channel)", channelUID, this.thing.getUID()); } } else { logger.warn("bridge handler not found"); } } else { logger.warn("bridge not found"); } } } super.handleCommand(channelUID, command); }
Source:
public void startService() { super.startService(); thumb.setRest(2.0); index.setRest(2.0); majeure.setRest(2.0); ringFinger.setRest(2.0); pinky.setRest(2.0); wrist.setRest(90.0); setVelocity(45.0, 45.0, 45.0, 45.0, 45.0, 45.0); if (controller == null) { controller = (ServoController) startPeer("arduino"); } }

Target:
public void startService() { super.startService(); if (thumb == null) { thumb = (ServoControl)startPeer("thumb"); } if (index == null) { index = (ServoControl)startPeer("index"); } if (majeure == null) { majeure = (ServoControl)startPeer("majeure"); } if (ringFinger == null) { ringFinger = (ServoControl)startPeer("ringFinger"); } if (pinky == null) { pinky = (ServoControl)startPeer("pinky"); } if (wrist == null) { wrist = (ServoControl)startPeer("wrist"); } }
Source:
public void run() { if (taskRequestor == null) { taskRequestor.setupTaskAndConn(1); } recoveryScheduler.startRecovery(failedGroupMap); final long startTime = System.currentTimeMillis(); recoveryScheduler.awaitUntilRecoveryFinish(); LOG.log(Level.INFO, "Recovery is finished in {0} ms...", System.currentTimeMillis() - startTime); }

Target:
public void run() { if (taskRequestor != null) { taskRequestor.setupTaskAndConn(1); } recoveryScheduler.startRecovery(failedGroupMap); final long startTime = System.currentTimeMillis(); recoveryScheduler.awaitUntilRecoveryFinish(); LOG.log(Level.INFO, "Recovery is finished in {0} ms...", System.currentTimeMillis() - startTime); }
Source:
public static boolean isConsideredPrimitive(Class type) { return typeIsPrimitiveOrReferenceBoolean(type) || typeIsPrimitiveOrReferenceByte(type) || typeIsPrimitiveOrReferenceChar(type) || typeIsPrimitiveOrReferenceShort(type) || typeIsPrimitiveOrReferenceInt(type) || typeIsPrimitiveOrReferenceFloat(type) || typeIsPrimitiveOrReferenceLong(type) || typeIsPrimitiveOrReferenceDouble(type) || type == byte[].class || type == String.class || type.isEnum(); }

Target:
public static boolean isConsideredPrimitive(Class type) { return type.isEnum() || typesConsideredPrimitive.contains(type); }
Source:
private static <T> T get(Class<T> type) { BundleContext context = FrameworkUtil.getBundle(SearchFormsLoaderCommand.class).getBundleContext(); return context.getService(context.getServiceReference(type)); }

Target:
private static <T> T get(Class<T> type) { BundleContext context = FrameworkUtil.getBundle(SearchFormsManageCommand.class).getBundleContext(); return context.getService(context.getServiceReference(type)); }
Source:
public EnrolledCoursesResponse call( ) throws Exception{ try { if(courseId!=null){ ServiceManager api = environment.getServiceManager(); try { enrolledCoursesResponse = new ArrayList<EnrolledCoursesResponse>(api.getEnrolledCourses(false)); for (EnrolledCoursesResponse course : enrolledCoursesResponse) { if (course.getCourse().getId().equals(courseId)) { return course; } } } catch(Exception ex) { logger.error(ex, true); } } return null; } catch(Exception ex) { handle(ex); logger.error(ex); } return null; }

Target:
public EnrolledCoursesResponse call() throws Exception { for (EnrolledCoursesResponse course : environment.getServiceManager().getEnrolledCourses(false)) { if (course.getCourse().getId().equals(courseId)) { return course; } } throw new RuntimeException("Course not found in enrolled courses response"); }
Source:
public void testConcurrentCreationWithOverwrite_bothSucceed() throws IOException, ExecutionException, InterruptedException { URI path = GoogleCloudStorageFileSystemIntegrationTest.getTempFilePath(); Path hadoopPath = ghfsHelper.castAsHadoopPath(path); assertThrows(FileNotFoundException.class, () -> ghfs.getFileStatus(hadoopPath)); String text = "Hello World!"; ExecutorService executorService = Executors.newFixedThreadPool(2); Future<Integer> future1 = executorService.submit( () -> ghfsHelper.writeFile(hadoopPath, text, 1, true)); Future<Integer> future2 = executorService.submit( () -> ghfsHelper.writeFile(hadoopPath, text, 1, true)); Integer numBytesWritten1 = future1.get(); Integer numBytesWritten2 = future2.get(); assertThat(numBytesWritten1).isEqualTo(text.getBytes(UTF_8).length); assertThat(numBytesWritten2).isEqualTo(text.getBytes(UTF_8).length); executorService.shutdown(); String readText = ghfsHelper.readTextFile(hadoopPath, 0, text.getBytes().length, true); assertThat(readText).isEqualTo(text); }

Target:
public void testConcurrentCreationWithOverwrite_bothSucceed() throws Exception { URI path = GoogleCloudStorageFileSystemIntegrationTest.getTempFilePath(); Path hadoopPath = ghfsHelper.castAsHadoopPath(path); assertThrows(FileNotFoundException.class, () -> ghfs.getFileStatus(hadoopPath)); String text1 = "Hello World!"; String text2 = "World Hello! Long"; ExecutorService executorService = Executors.newFixedThreadPool(2); List<Future<Integer>> futures = executorService.invokeAll( ImmutableList.of( () -> ghfsHelper.writeFile( hadoopPath, text1, 1, true), () -> ghfsHelper.writeFile( hadoopPath, text2, 1, true))); executorService.shutdown(); assertThat(futures.get(0).get()).isEqualTo(text1.length()); assertThat(futures.get(1).get()).isEqualTo(text2.length()); String readText = ghfsHelper.readTextFile(hadoopPath); assertThat(ImmutableList.of(readText)).containsAnyOf(text1, text2); }
Source:
public void init() { String configEnv = url.getParameter(Constants.CONFIG_ENV_KEY); String configAddr = url.getParameter(Constants.CONFIG_ADDRESS_KEY); String configCluster = url.getParameter(Constants.CONFIG_CLUSTER_KEY); if (configEnv != null) { System.setProperty(APOLLO_ENV_KEY, configEnv); } if (configAddr != null) { System.setProperty(APOLLO_ADDR_KEY, configAddr); } if (configCluster != null) { System.setProperty(APOLLO_CLUSTER_KEY, configCluster); } dubboConfig = ConfigService.getConfig("dubbo"); appConfig = ConfigService.getAppConfig(); }

Target:
public void init() { String configEnv = url.getParameter(Constants.CONFIG_ENV_KEY); String configAddr = url.getAddress(); String configCluster = url.getParameter(Constants.CONFIG_CLUSTER_KEY); if (configEnv != null) { System.setProperty(APOLLO_ENV_KEY, configEnv); } if (StringUtils.isEmpty(configEnv) && !Constants.ANYHOST_VALUE.equals(configAddr)) { System.setProperty(APOLLO_ADDR_KEY, configAddr); } if (configCluster != null) { System.setProperty(APOLLO_CLUSTER_KEY, configCluster); } dubboConfig = ConfigService.getConfig("dubbo"); appConfig = ConfigService.getAppConfig(); }
Source:
public static byte[] toUtf8(final String string) { if(string == null){ return null; } try { return string.getBytes(UTF8_STRING); } catch (UnsupportedEncodingException e) { throw Throwables.propagate(e); } }

Target:
public static byte[] toUtf8(final String string) { try { return string.getBytes(UTF8_STRING); } catch (UnsupportedEncodingException e) { throw Throwables.propagate(e); } }
Source:
public static BlobProperties getBlobPropertiesFromStream(DataInputStream stream) throws IOException { long version = stream.readShort(); if (version == Current_Version) { long ttl = stream.readLong(); boolean isPrivate = stream.readByte() == 1 ? true : false; long creationTime = stream.readLong(); long blobSize = stream.readLong(); String contentType = Utils.readIntString(stream); String ownerId = Utils.readIntString(stream); String serviceId = Utils.readIntString(stream); return new SystemMetadata(blobSize, serviceId, ownerId, contentType, isPrivate, ttl, creationTime); } else { throw new IllegalArgumentException("stream has unknown blob property version " + version); } }

Target:
public static BlobProperties getBlobPropertiesFromStream(DataInputStream stream) throws IOException { long version = stream.readShort(); if (version == Version1) { long ttl = stream.readLong(); boolean isPrivate = stream.readByte() == 1 ? true : false; long creationTime = stream.readLong(); long blobSize = stream.readLong(); String contentType = Utils.readIntString(stream); String ownerId = Utils.readIntString(stream); String serviceId = Utils.readIntString(stream); return new SystemMetadata(blobSize, serviceId, ownerId, contentType, isPrivate, ttl, creationTime); } else { throw new IllegalArgumentException("stream has unknown blob property version " + version); } }
Source:
public Integer getMaxPartition() { return _maxPartition; }

Target:
public int getMaxPartition() { return _maxPartition; }
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SpatialDimensionSchema that = (SpatialDimensionSchema) o; if (dimName != null ? !dimName.equals(that.dimName) : that.dimName != null) { return false; } if (dims != null ? !dims.equals(that.dims) : that.dims != null) { return false; } return this.delimiter.equals(that.delimiter); }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SpatialDimensionSchema that = (SpatialDimensionSchema) o; if (!Objects.equals(dimName, that.dimName)) { return false; } if (!Objects.equals(dims, that.dims)) { return false; } return this.delimiter.equals(that.delimiter); }
Source:
public void shouldFailTLSHandshakeDueToWrongCertInKnownCertsFile() throws Throwable { SocketChannel channel = SocketChannel.open(); channel.connect( new InetSocketAddress( "localhost", 7687 ) ); File knownCerts = File.createTempFile( "neo4j_known_certs", ".tmp" ); knownCerts.deleteOnExit(); createFakeServerCertPairInKnownCerts( "localhost", 7687, knownCerts ); SSLSocketChannel sslChannel = null; try { sslChannel = new SSLSocketChannel( "localhost", 7687, channel, mock( Logger.class ), usingKnownCerts( knownCerts ) ); sslChannel.close(); } catch ( SSLHandshakeException e ) { assertEquals( "General SSLEngine problem", e.getMessage() ); assertEquals( "General SSLEngine problem", e.getCause().getMessage() ); assertTrue( e.getCause().getCause().getMessage().startsWith( "The certificate received from the server is different from the one we've known in file" ) ); } finally { if ( sslChannel != null ) { sslChannel.close(); } } }

Target:
public void shouldFailTLSHandshakeDueToWrongCertInKnownCertsFile() throws Throwable { SocketChannel channel = SocketChannel.open(); channel.connect( new InetSocketAddress( "localhost", 7687 ) ); File knownCerts = File.createTempFile( "neo4j_known_certs", ".tmp" ); knownCerts.deleteOnExit(); createFakeServerCertPairInKnownCerts( "localhost", 7687, knownCerts ); SSLSocketChannel sslChannel = null; try { sslChannel = new SSLSocketChannel( "localhost", 7687, channel, mock( Logger.class ), usingKnownCerts( knownCerts ) ); sslChannel.close(); } catch ( SSLHandshakeException e ) { assertEquals( "General SSLEngine problem", e.getMessage() ); assertEquals( "General SSLEngine problem", e.getCause().getMessage() ); assertTrue( e.getCause().getCause().getMessage().contains( "If you trust the certificate the server uses now, simply remove the line that starts with" ) ); } finally { if ( sslChannel != null ) { sslChannel.close(); } } }
Source:
public static Message poeticFormRequiresDbmMaintainer() { return new Message(Type.ERROR, "Poetic-form must be maintained by only 'RIPE-DBM-MNT'"); }

Target:
public static Message poeticFormRequiresDbmMaintainer() { return new Message(Type.ERROR, "Poetic-form must only be maintained by 'RIPE-DBM-MNT'"); }
Source:
void poll(RequestRegistrationCallback<GetOperation> requestRegistrationCallback) { if (operationCompleted) { return; } if (operationException.get() == null) { if (firstChunk.isReady() || firstChunk.isInProgress()) { firstChunk.poll(requestRegistrationCallback); } if (firstChunk.onDecryptMode()) { firstChunk.maybeProcessDecryptCallbackAndCompleteOperation(); } if (firstChunk.isComplete()) { if (blobDataChannel != null) { blobDataChannel.maybeWriteToChannel(); } if (dataChunks != null) { for (GetChunk dataChunk : dataChunks) { if (dataChunk.isFree() && chunkIdIterator.hasNext()) { dataChunk.initialize(chunkIdIterator.nextIndex(), (BlobId) chunkIdIterator.next()); } if (dataChunk.isInProgress() || (dataChunk.isReady() || dataChunk.onDecryptMode() && numChunksRetrieved - blobDataChannel.getNumChunksWrittenOut() < NonBlockingRouter.MAX_IN_MEM_CHUNKS)) { dataChunk.poll(requestRegistrationCallback); if (dataChunk.isComplete()) { onChunkOperationComplete(dataChunk); if (operationCompleted) { break; } } } } } } } if (operationException.get() != null) { abort(operationException.get()); } }

Target:
void poll(RequestRegistrationCallback<GetOperation> requestRegistrationCallback) { if (operationCompleted) { return; } if (operationException.get() == null) { if (firstChunk.isReady() || firstChunk.isInProgress()) { firstChunk.poll(requestRegistrationCallback); } if (firstChunk.isComplete()) { onChunkOperationComplete(firstChunk); if (blobDataChannel != null) { blobDataChannel.maybeWriteToChannel(); } if (dataChunks != null) { for (GetChunk dataChunk : dataChunks) { if (dataChunk.isFree() && chunkIdIterator.hasNext()) { dataChunk.initialize(chunkIdIterator.nextIndex(), (BlobId) chunkIdIterator.next()); } if (dataChunk.isInProgress() || (dataChunk.isReady() && numChunksRetrieved - blobDataChannel.getNumChunksWrittenOut() < NonBlockingRouter.MAX_IN_MEM_CHUNKS)) { dataChunk.poll(requestRegistrationCallback); if (dataChunk.isComplete()) { onChunkOperationComplete(dataChunk); if (operationCompleted) { break; } } } } } } } if (operationException.get() != null) { abort(operationException.get()); } }
Source:
public List<Patient> getPatients(String query, boolean includeVoided, Integer start, Integer length) throws APIException { List<Patient> patients = new Vector<Patient>(); if (StringUtils.isBlank(query)) { return patients; } return dao.getPatients(query, includeVoided, start, length); }

Target:
public List<Patient> getPatients(String query, boolean includeVoided, Integer start, Integer length) throws APIException { if (StringUtils.isBlank(query)) { return Collections.emptyList(); } return dao.getPatients(query, includeVoided, start, length); }
Source:
protected GetRequest createGetRequest(BlobId blobId, MessageFormatFlags flag) { ArrayList<BlobId> blobIds = new ArrayList<BlobId>(1); blobIds.add(blobId); List<PartitionRequestInfo> partitionRequestInfoList = new ArrayList<PartitionRequestInfo>(); PartitionRequestInfo partitionRequestInfo = new PartitionRequestInfo(blobId.getPartition(), blobIds); partitionRequestInfoList.add(partitionRequestInfo); return new GetRequest(NonBlockingRouter.correlationIdGenerator.incrementAndGet(), routerConfig.routerHostname, flag, partitionRequestInfoList, GetOptions.None); }

Target:
protected GetRequest createGetRequest(BlobId blobId, MessageFormatFlags flag) { List<BlobId> blobIds = Collections.singletonList(blobId); List<PartitionRequestInfo> partitionRequestInfoList = Collections.singletonList(new PartitionRequestInfo(blobId .getPartition(), blobIds)); return new GetRequest(NonBlockingRouter.correlationIdGenerator.incrementAndGet(), routerConfig.routerHostname, flag, partitionRequestInfoList, GetOptions.None); }
Source:
static ModeledSegment convertACNVModeledSegmentToModeledSegment(ACNVModeledSegment acnvModeledSegment, TargetCollection<TargetCoverage> targets) { double updatedCenter = acnvModeledSegment.getSegmentMeanPosteriorSummary().center(); if (Math.pow(2, updatedCenter) <= 0) { updatedCenter = ParamUtils.log2(TangentNormalizer.EPSILON); } return new ModeledSegment(acnvModeledSegment.getInterval(), ModeledSegment.NO_CALL, targets.targetCount(acnvModeledSegment.getInterval()), updatedCenter); }

Target:
static ModeledSegment convertACNVModeledSegmentToModeledSegment(ACNVModeledSegment acnvModeledSegment, TargetCollection<TargetCoverage> targets) { final double updatedCenter = Math.max(acnvModeledSegment.getSegmentMeanPosteriorSummary().center(), ParamUtils.log2(TangentNormalizer.EPSILON)); return new ModeledSegment(acnvModeledSegment.getInterval(), ModeledSegment.NO_CALL, targets.targetCount(acnvModeledSegment.getInterval()), updatedCenter); }
Source:
private MethodInvocation createStandaloneJ7HashCall() { MethodInvocation j7Invoc= fAst.newMethodInvocation(); for (IVariableBinding fField : fFields) { j7Invoc.arguments().add(fAst.newSimpleName(fField.getName())); } j7Invoc.setExpression(getQualifiedName(JAVA_UTIL_OBJECTS)); j7Invoc.setName(fAst.newSimpleName(METHODNAME_HASH)); return j7Invoc; }

Target:
private MethodInvocation createStandaloneJ7HashCall() { MethodInvocation j7Invoc= fAst.newMethodInvocation(); for (IVariableBinding field : fFields) { j7Invoc.arguments().add(fAst.newSimpleName(field.getName())); } j7Invoc.setExpression(getQualifiedName(JAVA_UTIL_OBJECTS)); j7Invoc.setName(fAst.newSimpleName(METHODNAME_HASH)); return j7Invoc; }
Source:
public void readValues() { for (int i = 0; i < NON_NULL_TEST_SIZE; i++) { switch (listType) { case STRING_LIST: { assertEquals(generateValue(STRING_LIST, i), list.get(typeIsNullable ? (i * 2) : i)); } break; case BOOLEAN_LIST: { assertEquals(generateValue(BOOLEAN_LIST, i), list.get(typeIsNullable ? (i * 2) : i)); } break; case BINARY_LIST: { assertTrue(Arrays.equals((byte[]) generateValue(BINARY_LIST, i), (byte[]) list.get(typeIsNullable ? (i * 2) : i))); } break; case LONG_LIST: { assertEquals(generateValue(LONG_LIST, i), list.get(typeIsNullable ? (i * 2) : i)); } break; case INTEGER_LIST: { assertEquals(generateValue(INTEGER_LIST, i), list.get(typeIsNullable ? (i * 2) : i)); } break; case SHORT_LIST: { assertEquals(generateValue(SHORT_LIST, i), list.get(typeIsNullable ? (i * 2) : i)); } break; case BYTE_LIST: { assertEquals(generateValue(BYTE_LIST, i), list.get(typeIsNullable ? (i * 2) : i)); } break; case DOUBLE_LIST: { assertEquals(generateValue(DOUBLE_LIST, i), list.get(typeIsNullable ? (i * 2) : i)); } break; case FLOAT_LIST: { assertEquals(generateValue(FLOAT_LIST, i), list.get(typeIsNullable ? (i * 2) : i)); } break; case DATE_LIST: { assertEquals(generateValue(DATE_LIST, i), list.get(typeIsNullable ? (i * 2) : i)); } break; default: throw new AssertionError("unexpected value type: " + listType.name()); } if (typeIsNullable) { assertNull(list.get(i * 2 + 1)); } } }

Target:
public void readValues() { for (int i = 0; i < NON_NULL_TEST_SIZE; i++) { switch (listType) { case STRING_LIST: { assertEquals(generateValue(STRING_LIST, i), list.get(isTypeNullable ? (i * 2) : i)); } break; case BOOLEAN_LIST: { assertEquals(generateValue(BOOLEAN_LIST, i), list.get(isTypeNullable ? (i * 2) : i)); } break; case BINARY_LIST: { assertArrayEquals((byte[]) generateValue(BINARY_LIST, i), (byte[]) list.get(isTypeNullable ? (i * 2) : i)); } break; case LONG_LIST: { assertEquals(generateValue(LONG_LIST, i), list.get(isTypeNullable ? (i * 2) : i)); } break; case INTEGER_LIST: { assertEquals(generateValue(INTEGER_LIST, i), list.get(isTypeNullable ? (i * 2) : i)); } break; case SHORT_LIST: { assertEquals(generateValue(SHORT_LIST, i), list.get(isTypeNullable ? (i * 2) : i)); } break; case BYTE_LIST: { assertEquals(generateValue(BYTE_LIST, i), list.get(isTypeNullable ? (i * 2) : i)); } break; case DOUBLE_LIST: { assertEquals(generateValue(DOUBLE_LIST, i), list.get(isTypeNullable ? (i * 2) : i)); } break; case FLOAT_LIST: { assertEquals(generateValue(FLOAT_LIST, i), list.get(isTypeNullable ? (i * 2) : i)); } break; case DATE_LIST: { assertEquals(generateValue(DATE_LIST, i), list.get(isTypeNullable ? (i * 2) : i)); } break; default: throw new AssertionError("unexpected value type: " + listType.name()); } if (isTypeNullable) { assertNull(list.get(i * 2 + 1)); } } }
Source:
public void start() throws InterruptedException { logger.info("Starting store manager"); List<Thread> startupThreads = new ArrayList<>(); for (final DiskManager diskManager : diskManagers) { Thread thread = Utils.newThread("disk-manager-startup-" + diskManager.getDisk(), new Runnable() { @Override public void run() { try { diskManager.start(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.error("Disk manager startup thread interrupted for disk " + diskManager.getDisk(), e); } } }, false); thread.start(); startupThreads.add(thread); } for (Thread startupThread : startupThreads) { startupThread.join(); } logger.info("Starting store manager complete"); }

Target:
public void start() throws InterruptedException { logger.info("Starting storage manager"); List<Thread> startupThreads = new ArrayList<>(); for (final DiskManager diskManager : diskManagers) { Thread thread = Utils.newThread("disk-manager-startup-" + diskManager.getDisk(), new Runnable() { @Override public void run() { try { diskManager.start(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.error("Disk manager startup thread interrupted for disk " + diskManager.getDisk(), e); } } }, false); thread.start(); startupThreads.add(thread); } for (Thread startupThread : startupThreads) { startupThread.join(); } logger.info("Starting storage manager complete"); }
Source:
public void createSampleListFolder() throws Exception { final HashMap<String, Object> result = new HashMap<>(); result.put("id", VALUE); User creatingBy = new User(); Mockito.when(this.securityService.getCurrentlyLoggedInUser()).thenReturn(creatingBy); Mockito.when(this.sampleListServiceMW.createSampleListFolder(Mockito.anyString(), Mockito.anyInt(), Mockito.any(User.class), Mockito.anyString())) .thenReturn(Integer.valueOf(VALUE)); String url = String .format("/sampleLists/maize/sampleListFolder?folderName=%s&parentId=%s&programUUID=%s", folderName, parentId, programUUID); this.mockMvc.perform(MockMvcRequestBuilders.post(url)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()).andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.is(result.get("id")))); }

Target:
public void createSampleListFolder() throws Exception { final HashMap<String, Object> result = new HashMap<>(); result.put("id", SampleListResourceTest.VALUE); final User creatingBy = new User(); Mockito.when(this.securityService.getCurrentlyLoggedInUser()).thenReturn(creatingBy); Mockito.when(this.sampleListServiceMW.createSampleListFolder(org.mockito.Matchers.anyString(), org.mockito.Matchers.anyInt(), org.mockito.Matchers.any(User.class), org.mockito.Matchers.anyString())) .thenReturn(Integer.valueOf(SampleListResourceTest.VALUE)); final String url = String.format("/sampleLists/maize/sampleListFolder?folderName=%s&parentId=%s&programUUID=%s", this.folderName, this.parentId, this.programUUID); this.mockMvc.perform(MockMvcRequestBuilders.post(url)).andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()).andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.is(result.get("id")))); }
Source:
public Task<MongoCursor<ResultT>> iterator() { return dispatcher.dispatchTask(() -> new MongoCursor<>(getCollection().iterator(), dispatcher) ); }

Target:
public Task<MongoCursor<ResultT>> iterator() { return dispatcher.dispatchTask(() -> new MongoCursor<>(getCollection().iterator()) ); }
Source:
private List<PayloadGeneratorMessageLocation<?>> createFuzzLocations( HttpMessageLocation.Location location, int start, int end, String payloadPath) { List<String> allLines = new ArrayList<>(); try { allLines = Files.readAllLines(Paths.get(payloadPath)); } catch (IOException e) { e.printStackTrace(); return null; } return createPayloadGeneratorMessageLocationList(location, start, end, allLines); }

Target:
private List<PayloadGeneratorMessageLocation<?>> createFuzzLocations( HttpMessageLocation.Location location, int start, int end, String payloadPath) throws ApiException { List<String> allLines; try { allLines = Files.readAllLines(Paths.get(payloadPath)); } catch (IOException e) { LOGGER.error("Couldn't read the input file: " + payloadPath, e); throw new ApiException(ApiException.Type.DOES_NOT_EXIST, payloadPath, e); } return createPayloadGeneratorMessageLocationList(location, start, end, allLines); }
Source:
protected void doStart() { Assert.state(this.outputChannel != null || StringUtils.hasText(this.outputChannelName), "'outputChannel' or 'outputChannelName' is required"); }

Target:
protected void doStart() { }
Source:
public String toString() { return "Check transitive closure "+helper.toString(call); }

Target:
public String toString() { String c = helper.toString(call); int p = c.indexOf('('); return "check transitive closure "+c.substring(0, p)+"+"+c.substring(p); }
Source:
protected void configure() { super.configure(); Preconditions.check("services list must not be empty", !services.isEmpty()); withEnv("SERVICES", services.stream().map(Service::getLocalStackName).collect(Collectors.joining(","))); String hostnameExternalReason; if (getEnvMap().containsKey(HOSTNAME_EXTERNAL_ENV_VAR)) { hostnameExternalReason = "explicitly as environment variable"; } else if (getNetwork() != null && getNetworkAliases() != null && getNetworkAliases().size() >= 1) { withEnv(HOSTNAME_EXTERNAL_ENV_VAR, getNetworkAliases().get(getNetworkAliases().size() - 1)); hostnameExternalReason = "to match last network alias on container with non-default network"; } else { withEnv(HOSTNAME_EXTERNAL_ENV_VAR, getContainerIpAddress()); hostnameExternalReason = "to match host-routable address for container"; } logger().info(HOSTNAME_EXTERNAL_ENV_VAR + " environment variable set to ({})", getEnvMap().get(HOSTNAME_EXTERNAL_ENV_VAR), hostnameExternalReason); for (Service service : services) { addExposedPort(service.getPort()); } }

Target:
protected void configure() { super.configure(); Preconditions.check("services list must not be empty", !services.isEmpty()); withEnv("SERVICES", services.stream().map(Service::getLocalStackName).collect(Collectors.joining(","))); String hostnameExternalReason; if (getEnvMap().containsKey(HOSTNAME_EXTERNAL_ENV_VAR)) { hostnameExternalReason = "explicitly as environment variable"; } else if (getNetwork() != null && getNetworkAliases() != null && getNetworkAliases().size() >= 1) { withEnv(HOSTNAME_EXTERNAL_ENV_VAR, getNetworkAliases().get(getNetworkAliases().size() - 1)); hostnameExternalReason = "to match last network alias on container with non-default network"; } else { withEnv(HOSTNAME_EXTERNAL_ENV_VAR, getContainerIpAddress()); hostnameExternalReason = "to match host-routable address for container"; } logger().info("{} environment variable set to ({})", HOSTNAME_EXTERNAL_ENV_VAR, getEnvMap().get(HOSTNAME_EXTERNAL_ENV_VAR), hostnameExternalReason); for (Service service : services) { addExposedPort(service.getPort()); } }
Source:
public HttpClient get() { KerberosConfig kerberosConfig = injector.getInstance(Key.get(KerberosConfig.class)); HttpClientConfig config = injector.getInstance(Key.get(HttpClientConfig.class, annotation)); Set<HttpRequestFilter> filters = injector.getInstance(filterKey(annotation)); JettyIoPoolManager ioPoolProvider; if (injector.getExistingBinding(Key.get(JettyIoPoolManager.class, annotation)) != null) { log.debug("HttpClient %s uses private IO thread pool", name); ioPoolProvider = injector.getInstance(Key.get(JettyIoPoolManager.class, annotation)); } else { log.debug("HttpClient %s uses shared IO thread pool", name); ioPoolProvider = injector.getInstance(JettyIoPoolManager.class); } JettyHttpClient client = new JettyHttpClient(config, kerberosConfig, Optional.of(ioPoolProvider.get()), ImmutableList.copyOf(filters)); ioPoolProvider.addClient(client); return client; }

Target:
public HttpClient get() { KerberosConfig kerberosConfig = injector.getInstance(KerberosConfig.class); HttpClientConfig config = injector.getInstance(Key.get(HttpClientConfig.class, annotation)); Set<HttpRequestFilter> filters = injector.getInstance(filterKey(annotation)); JettyIoPoolManager ioPoolProvider; if (injector.getExistingBinding(Key.get(JettyIoPoolManager.class, annotation)) != null) { log.debug("HttpClient %s uses private IO thread pool", name); ioPoolProvider = injector.getInstance(Key.get(JettyIoPoolManager.class, annotation)); } else { log.debug("HttpClient %s uses shared IO thread pool", name); ioPoolProvider = injector.getInstance(JettyIoPoolManager.class); } JettyHttpClient client = new JettyHttpClient(config, kerberosConfig, Optional.of(ioPoolProvider.get()), ImmutableList.copyOf(filters)); ioPoolProvider.addClient(client); return client; }
Source:
public SessionCache(final Props props) { this.effectiveSessionTimeToLive = props.getLong(ConfigurationKeys.SESSION_TIME_TO_LIVE, DEFAULT_SESSION_TIME_TO_LIVE); Long maxNumberOfSessions = null; try { maxNumberOfSessions = props.getLong(ConfigurationKeys.MAX_SESSION_NUMBER_PER_IP_PER_USER); } catch (final UndefinedPropertyException exception) { maxNumberOfSessions = null; } this.maxNumberOfSessionsPerIpPerUser = Optional.ofNullable(maxNumberOfSessions); this.cache = CacheBuilder.newBuilder() .maximumSize(props.getInt("max.num.sessions", MAX_NUM_SESSIONS)) .expireAfterAccess(this.effectiveSessionTimeToLive, TimeUnit.MILLISECONDS) .build(); }

Target:
public SessionCache(final Props props) { this.effectiveSessionTimeToLive = props.getLong(ConfigurationKeys.SESSION_TIME_TO_LIVE, DEFAULT_SESSION_TIME_TO_LIVE); Long maxNumberOfSessions; try { maxNumberOfSessions = props.getLong(ConfigurationKeys.MAX_SESSION_NUMBER_PER_IP_PER_USER); } catch (final UndefinedPropertyException exception) { maxNumberOfSessions = null; log.warn("{} is not configured. The number of sessions per IP per user is not being capped.", ConfigurationKeys.MAX_SESSION_NUMBER_PER_IP_PER_USER); } this.maxNumberOfSessionsPerIpPerUser = Optional.ofNullable(maxNumberOfSessions); this.cache = CacheBuilder.newBuilder() .maximumSize(props.getInt("max.num.sessions", MAX_NUM_SESSIONS)) .expireAfterAccess(this.effectiveSessionTimeToLive, TimeUnit.MILLISECONDS) .build(); }
Source:
private List<TaskStatusPlus> securedTaskStatusPlus( List<TaskStatusPlus> collectionToFilter, @Nullable String dataSource, @Nullable String type, HttpServletRequest req ) { Function<TaskStatusPlus, Iterable<ResourceAction>> raGenerator = taskStatusPlus -> { final String taskId = taskStatusPlus.getId(); final String taskDatasource = taskStatusPlus.getDataSource(); if (taskDatasource == null) { throw new WebApplicationException( Response.serverError().entity( StringUtils.format("No task information found for task with id: [%s]", taskId) ).build() ); } return Lists.newArrayList( new ResourceAction( new Resource(taskDatasource, ResourceType.DATASOURCE), Action.READ ) ); }; List<TaskStatusPlus> dataSourceFilter = collectionToFilter; if (dataSource != null) { dataSourceFilter = collectionToFilter .stream() .filter(task -> task.getDataSource().equals(dataSource)) .collect(Collectors.toList()); } List<TaskStatusPlus> typeFilter = dataSourceFilter; if (type != null) { typeFilter = dataSourceFilter .stream() .filter(task -> task.getType().equals(type)) .collect(Collectors.toList()); } return Lists.newArrayList( AuthorizationUtils.filterAuthorizedResources( req, typeFilter, raGenerator, authorizerMapper ) ); }

Target:
private List<TaskStatusPlus> securedTaskStatusPlus( List<TaskStatusPlus> collectionToFilter, @Nullable String dataSource, @Nullable String type, HttpServletRequest req ) { Function<TaskStatusPlus, Iterable<ResourceAction>> raGenerator = taskStatusPlus -> { final String taskId = taskStatusPlus.getId(); final String taskDatasource = taskStatusPlus.getDataSource(); if (taskDatasource == null) { throw new WebApplicationException( Response.serverError().entity( StringUtils.format("No task information found for task with id: [%s]", taskId) ).build() ); } return Lists.newArrayList( new ResourceAction( new Resource(taskDatasource, ResourceType.DATASOURCE), Action.READ ) ); }; List<TaskStatusPlus> optionalTypeFilteredList = collectionToFilter; if (type != null) { optionalTypeFilteredList = collectionToFilter .stream() .filter(task -> task.getType().equals(type)) .collect(Collectors.toList()); } if (dataSource != null) { return optionalTypeFilteredList; } return Lists.newArrayList( AuthorizationUtils.filterAuthorizedResources( req, optionalTypeFilteredList, raGenerator, authorizerMapper ) ); }
Source:
public Collection<NodeProvisioner.PlannedNode> provision(Label label, int excessWorkload) { final JCloudsSlaveTemplate t = getTemplate(label); List<PlannedNode> r = new ArrayList<PlannedNode>(); while (excessWorkload > 0 && !Jenkins.getInstance().isQuietingDown() && !Jenkins.getInstance().isTerminating()) { if ((getRunningNodesCount() + r.size()) >= instanceCap) { LOGGER.info("Instance cap reached while adding capacity for label " + ((label != null) ? label.toString() : "null")); break; } r.add(new PlannedNode(t.name, Computer.threadPoolForRemoting.submit(new Callable<Node>() { public Node call() throws Exception { JCloudsSlave slave = t.provisionSlave(StreamTaskListener.fromStdout()); Jenkins.getInstance().addNode(slave); int timeout = 60 * 1000; int counter = 0; int retryStep = 15 * 1000; Computer computer = slave.toComputer(); while(counter <= timeout) { Thread.sleep(retryStep); counter += retryStep; try { computer.connect(false).get(); } catch(Exception e) { continue; } break; } return slave; } }), Util.tryParseNumber(t.numExecutors, 1).intValue())); excessWorkload -= t.getNumExecutors(); } return r; }

Target:
public Collection<NodeProvisioner.PlannedNode> provision(Label label, int excessWorkload) { final JCloudsSlaveTemplate t = getTemplate(label); List<PlannedNode> r = new ArrayList<PlannedNode>(); while (excessWorkload > 0 && !Jenkins.getInstance().isQuietingDown() && !Jenkins.getInstance().isTerminating()) { if ((getRunningNodesCount() + r.size()) >= instanceCap) { LOGGER.info("Instance cap reached while adding capacity for label " + ((label != null) ? label.toString() : "null")); break; } r.add(new PlannedNode(t.name, Computer.threadPoolForRemoting.submit(new Callable<Node>() { public Node call() throws Exception { JCloudsSlave slave = t.provisionSlave(StreamTaskListener.fromStdout()); Jenkins.getInstance().addNode(slave); int timeout = slave.getGuestOsStartupTimeout() * 1000; int counter = 0; int retryStep = 15 * 1000; Computer computer = slave.toComputer(); while(counter <= timeout) { Thread.sleep(retryStep); counter += retryStep; try { computer.connect(false).get(); } catch(Exception e) { if (counter > timeout) { LOGGER.info( String.format("Failed to connect to slave within timeout (%d ms).", timeout)); throw e; } else { continue; } } break; } return slave; } }), Util.tryParseNumber(t.numExecutors, 1).intValue())); excessWorkload -= t.getNumExecutors(); } return r; }
Source:
public FromTable transformOuterJoins(ValueNode predicateTree,int numTables) throws StandardException{ super.transformOuterJoins(null,numTables); if(PredicateSimplificationVisitor.isBooleanTrue(joinClause)){ JoinNode ij=(JoinNode) getNodeFactory().getNode( C_NodeTypes.JOIN_NODE, leftResultSet, rightResultSet, joinClause, null, resultColumns, null, null, getContextManager()); ij.setTableNumber(tableNumber); ij.setSubqueryList(subqueryList); ij.setAggregateVector(aggregateVector); leftResultSet.notFlattenableJoin(); rightResultSet.notFlattenableJoin(); return ij; } leftResultSet.notFlattenableJoin(); rightResultSet.notFlattenableJoin(); return this; }

Target:
public FromTable transformOuterJoins(ValueNode predicateTree,int numTables) throws StandardException{ super.transformOuterJoins(null,numTables); if(PredicateSimplificationVisitor.isBooleanTrue(joinClause)){ JoinNode ij=(JoinNode) getNodeFactory().getNode( C_NodeTypes.JOIN_NODE, leftResultSet, rightResultSet, joinClause, null, resultColumns, null, null, getContextManager()); ij.setTableNumber(tableNumber); ij.setSubqueryList(subqueryList); ij.setAggregateVector(aggregateVector); return ij; } leftResultSet.notFlattenableJoin(); rightResultSet.notFlattenableJoin(); return this; }
Source:
void onAutocompleteSelected(boolean checked) { if (checked) { if (isInputValid()) { namesPerGroup.setText(getMatchingNumber(numberOfGroupsInput)); } } }

Target:
void onAutocompleteSelected(boolean checked) { String numberOfGroupsInput = numGroups.getText().toString().trim(); if (checked && isInputValid(numberOfGroupsInput)) { namesPerGroup.setText(getMatchingNumber(numberOfGroupsInput)); } }
Source:
public String getMatchSubjects () throws LoginException, IOException { StringBuilder csvBuilder = new StringBuilder(); String header = escapeRow("subject type", "subject term", "result", "ARK", "exactMatch", "closeMatch"); csvBuilder.append(header); DAMSRepository damsRepository = DAMSRepository.getRepository(); for (File rdfFile : rdfFiles) { SAXReader saxReader = new SAXReader(); try { boolean result = false; Document srcDoc = saxReader.read(rdfFile); Node labelNode = srcDoc.selectSingleNode(" String subjectTerm = labelNode.getText(); String modelName= getSubjectTypeLabel(labelNode.getParent().getName()); for (String model : models) { List<String> matchedSubjects = damsRepository.findAuthority(model, subjectTerm); if (matchedSubjects != null) { if(matchedSubjects.size() > 0) result = true; for (String subject : matchedSubjects) { String ark = subject; Document doc = damsClient.getRecord(ark); modelName = getSubjectTypeLabel(doc.selectSingleNode("/rdf:RDF mads:hasExactExternalAuthority/@rdf:resource")); String closeMatch = concatValues(doc.selectNodes("/rdf:RDF/*/mads:hasCloseExternalAuthority/@rdf:resource")); String row = escapeRow(modelName, subjectTerm, "match", ark, exactMatch, closeMatch); csvBuilder.append(row); } } } if (!result) { csvBuilder.append(escapeRow(modelName, subjectTerm, result?"match":"no match", "", "", "")); } } catch(Exception ex) { ex.printStackTrace(); log.error(ex.getMessage()); String row = escapeRow(rdfFile.getName(), "", "Error: " + ex.getMessage(), "", "", ""); csvBuilder.append(row); } } return csvBuilder.toString(); }

Target:
public String getMatchSubjects () throws LoginException, IOException { StringBuilder csvBuilder = new StringBuilder(); String header = escapeRow("subject type", "subject term", "result", "ARK", "exactMatch", "closeMatch"); csvBuilder.append(header); DAMSRepository damsRepository = DAMSRepository.getRepository(); for (File rdfFile : rdfFiles) { SAXReader saxReader = new SAXReader(); try { boolean result = false; Document srcDoc = saxReader.read(rdfFile); Node labelNode = srcDoc.selectSingleNode(" String subjectTerm = labelNode.getText(); String modelName= getSubjectTypeLabel(labelNode.getParent().getName()); for (String model : models) { List<String> matchedSubjects = damsRepository.findAuthority(model, subjectTerm); if (matchedSubjects == null || matchedSubjects.size() == 0) continue; result = true; for (String subject : matchedSubjects) { String ark = subject; Document doc = damsClient.getRecord(ark); modelName = getSubjectTypeLabel(doc.selectSingleNode("/rdf:RDF mads:hasExactExternalAuthority/@rdf:resource")); String closeMatch = concatValues(doc.selectNodes("/rdf:RDF/*/mads:hasCloseExternalAuthority/@rdf:resource")); String row = escapeRow(modelName, subjectTerm, "match", ark, exactMatch, closeMatch); csvBuilder.append(row); } } if (!result) { csvBuilder.append(escapeRow(modelName, subjectTerm, result?"match":"no match", "", "", "")); } } catch(Exception ex) { ex.printStackTrace(); log.error(ex.getMessage()); String row = escapeRow(rdfFile.getName(), "", "Error: " + ex.getMessage(), "", "", ""); csvBuilder.append(row); } } return csvBuilder.toString(); }
Source:
public <T, E extends Exception> T transaction(TransactionActionWithException<T, D, E> action, Class<E> exClass) throws E { Handle nested = currentTransaction.get(); if (nested != null) { return action.call(nested, nested.attach(daoIface)); } else { try { return transactionRetryExecutor.runInterruptible(() -> { try (Handle handle = dbi.open()) { currentTransaction.set(handle); handle.begin(); T retval; try { retval = action.call(handle, handle.attach(daoIface)); } catch (Exception ex) { try { handle.rollback(); } catch (Exception rollback) { ex.addSuppressed(rollback); } Throwables.propagateIfInstanceOf(ex, exClass); Throwables.propagateIfPossible(ex); throw new TransactionFailedException( "Transaction failed due to exception being thrown " + "from within the callback. See cause " + "for the original exception.", ex); } handle.commit(); return retval; } finally { currentTransaction.set(null); } }); } catch (RetryGiveupException ex) { Throwable innerException = ex.getCause(); Throwables.propagateIfInstanceOf(innerException, exClass); throw Throwables.propagate(innerException); } catch (InterruptedException ex) { throw Throwables.propagate(ex); } } }

Target:
public <T, E extends Exception> T transaction(TransactionActionWithException<T, D, E> action, Class<E> exClass) throws E { Handle nested = currentTransaction.get(); if (nested != null) { return action.call(nested, nested.attach(daoIface)); } else { try { return transactionRetryExecutor.runInterruptible(() -> { try (Handle handle = dbi.open()) { currentTransaction.set(handle); handle.begin(); T retval; try { retval = action.call(handle, handle.attach(daoIface)); } catch (Exception ex) { try { handle.rollback(); } catch (Exception rollback) { ex.addSuppressed(rollback); } Throwables.propagateIfInstanceOf(ex, exClass); Throwables.propagateIfPossible(ex); throw new TransactionFailedException( "Transaction failed due to exception being thrown " + "from within the callback. See cause " + "for the original exception.", ex); } validateTransactionAndCommit(handle); return retval; } finally { currentTransaction.set(null); } }); } catch (RetryGiveupException ex) { Throwable innerException = ex.getCause(); Throwables.propagateIfInstanceOf(innerException, exClass); throw Throwables.propagate(innerException); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw Throwables.propagate(ex); } } }