auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static void parseAndReact(@NonNull Activity activity, @NonNull JSONObject paramsJson) throws JSONException { logger.debug("DeepLink received. JSON Details:\n" + paramsJson); final Router router = new Router(); final boolean isLoggedIn = new LoginPrefs(activity).getUsername() != null; if (!isLoggedIn) { activity.startActivity(router.getLogInIntent()); } else { @ScreenDef final String screenName = paramsJson.getString(KEY_SCREEN_NAME); switch (screenName) { case Screen.COURSE_DASHBOARD: { final String courseId = paramsJson.getString(KEY_COURSE_ID); router.showCourseDashboardTabs(activity, null, courseId, false); break; } case Screen.COURSE_VIDEOS: { final String courseId = paramsJson.getString(KEY_COURSE_ID); router.showCourseDashboardTabs(activity, null, courseId, false, screenName); break; } } } }

Target:
public static void parseAndReact(@NonNull Activity activity, @NonNull JSONObject paramsJson) throws JSONException { logger.debug("DeepLink received. JSON Details:\n" + paramsJson); final Router router = new Router(); final boolean isLoggedIn = new LoginPrefs(activity).getUsername() != null; if (!isLoggedIn) { activity.startActivity(router.getLogInIntent()); } else { @ScreenDef final String screenName = paramsJson.getString(KEY_SCREEN_NAME); switch (screenName) { case Screen.COURSE_DASHBOARD: case Screen.COURSE_VIDEOS: { final String courseId = paramsJson.getString(KEY_COURSE_ID); router.showCourseDashboardTabs(activity, null, courseId, false, screenName); break; } } } }
Source:
public void checkPermissions() { int permission = ContextCompat.checkSelfPermission(MainActivity.this, reqPermission[0]); if (permission == PackageManager.PERMISSION_GRANTED) { setPeData(); } else { ActivityCompat.requestPermissions(MainActivity.this, reqPermission, requestCode); } }

Target:
private void checkPermissions() { int permission = ContextCompat.checkSelfPermission(MainActivity.this, reqPermission[0]); if (permission == PackageManager.PERMISSION_GRANTED) { setPeData(); } else { ActivityCompat.requestPermissions(MainActivity.this, reqPermission, requestCode); } }
Source:
public void authorizeResource(String resource, String action, String entityType, String entityName, UserGroupInformation authenticatedUGI) throws AuthorizationException, EntityNotRegisteredException { Validate.notEmpty(resource, "Resource cannot be empty or null"); Validate.isTrue(RESOURCES.contains(resource), "Illegal resource: " + resource); Validate.notEmpty(action, "Action cannot be empty or null"); try { if (isSuperUser(authenticatedUGI)) { return; } if ("admin".equals(resource)) { if (!("version".equals(action) || "clearuser".equals(action) || "getuser".equals(action))) { authorizeAdminResource(authenticatedUGI, action); } } else if ("entities".equals(resource) || "instance".equals(resource)) { authorizeEntityResource(authenticatedUGI, entityName, entityType, action, "entities".equals(resource) && LIST_OPERATION.equals(action)); } else if ("metadata".equals(resource)) { authorizeMetadataResource(authenticatedUGI, action); } } catch (IOException e) { throw new AuthorizationException(e); } }

Target:
public void authorizeResource(String resource, String action, String entityType, String entityName, UserGroupInformation authenticatedUGI) throws AuthorizationException, EntityNotRegisteredException { Validate.notEmpty(resource, "Resource cannot be empty or null"); Validate.isTrue(RESOURCES.contains(resource), "Illegal resource: " + resource); Validate.notEmpty(action, "Action cannot be empty or null"); try { if (isSuperUser(authenticatedUGI)) { return; } if ("admin".equals(resource)) { if (!("version".equals(action) || "clearuser".equals(action) || "getuser".equals(action))) { authorizeAdminResource(authenticatedUGI, action); } } else if ("entities".equals(resource) || "instance".equals(resource)) { if ("entities".equals(resource) && LIST_OPERATION.equals(action)) { LOG.info("Skipping authorization for entity list operations"); } else { authorizeEntityResource(authenticatedUGI, entityName, entityType, action); } } else if ("metadata".equals(resource)) { authorizeMetadataResource(authenticatedUGI, action); } } catch (IOException e) { throw new AuthorizationException(e); } }
Source:
public Response getSelfDiscovered() { return Response.ok(Collections.singletonMap("selfDiscovered", selfDiscovered.getAsBoolean())).build(); }

Target:
public Response getSelfDiscovered() { if (selfDiscovered.getAsBoolean()) { return Response.ok().build(); } else { return Response.status(HttpStatus.SERVICE_UNAVAILABLE_503).build(); } }
Source:
public JsonNode toJson() { ObjectNode healthCheckResponse = factory.objectNode(); for (Map.Entry<String, HealthCheck.Result> result : healthCheckResults.entrySet()) { ObjectNode resultResponse = factory.objectNode(); resultResponse.put("healthy", result.getValue().isHealthy()); resultResponse.put("message", result.getValue().getMessage()); healthCheckResponse.put(result.getKey(), resultResponse); } return healthCheckResponse; }

Target:
public JsonNode toJson() { ObjectNode healthCheckResponse = factory.objectNode(); for (Map.Entry<String, HealthCheck.Result> result : healthCheckResults.entrySet()) { ObjectNode resultResponse = factory.objectNode(); resultResponse.put("healthy", result.getValue().isHealthy()); resultResponse.put("message", result.getValue().getMessage()); if (result.getValue().getDetails() != null) { for (Map.Entry<String, Object> entry : result.getValue().getDetails().entrySet()) { if(null != entry.getValue()) { if(entry.getValue() instanceof ObjectNode) { resultResponse.put(entry.getKey(), (ObjectNode)entry.getValue()); } else { resultResponse.put(entry.getKey(), entry.getValue().toString()); } } } } healthCheckResponse.put(result.getKey(), resultResponse); } return healthCheckResponse; }
Source:
public Dialog onCreateDialog(Bundle savedInstanceState) { setRetainInstance(true); return new BottomSheetDialog(requireContext(), getTheme()); }

Target:
public Dialog onCreateDialog(Bundle savedInstanceState) { return new BottomSheetDialog(requireContext(), getTheme()); }
Source:
public ScriptRunner getNextValScript() throws IOException { return new ScriptRunner(); }

Target:
public ScriptRunner getNextValScript() throws IOException { return ScriptRunner.NOOP; }
Source:
public String getText() { return text; }

Target:
@NonNull public String getText() { return StringUtils.defaultString(text); }
Source:
public IStatus handleDrop(CommonDropAdapter aDropAdapter, DropTargetEvent aDropTargetEvent, Object aTarget) { IStatus status = Status.CANCEL_STATUS; IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); final IWorkbenchPage activePage = window.getActivePage(); final IEditorPart activeEditor = activePage.getActiveEditor(); if (activeEditor instanceof SessionEditor) { Session session = ((SessionEditor) activeEditor).getSession(); Collection<File> droppedEObjects = extractDragSource(aDropTargetEvent.data); if (!droppedEObjects.isEmpty()) { try { new ProgressMonitorDialog(window.getShell()).run(false, false, monitor -> { session.getTransactionalEditingDomain().getCommandStack().execute(new RecordingCommand(session.getTransactionalEditingDomain()) { @Override protected void doExecute() { for (Iterator<File> iterator = droppedEObjects.iterator(); iterator.hasNext(); ) { File file = iterator.next(); session.addSemanticResource(URI.createPlatformResourceURI(file.getFullPath().toString(), true), monitor); } } }); }); status = Status.OK_STATUS; } catch (InvocationTargetException | InterruptedException e) { SessionEditorPlugin.getPlugin().getLog().log(new Status(IStatus.ERROR, SiriusEditPlugin.ID, e.getMessage(), e)); status = Status.CANCEL_STATUS; } } } return status; }

Target:
public IStatus handleDrop(CommonDropAdapter aDropAdapter, DropTargetEvent aDropTargetEvent, Object aTarget) { IStatus status = Status.CANCEL_STATUS; IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); final IWorkbenchPage activePage = window.getActivePage(); final IEditorPart activeEditor = activePage.getActiveEditor(); if (activeEditor instanceof SessionEditor) { Session session = ((SessionEditor) activeEditor).getSession(); Collection<File> droppedEObjects = extractDragSource(aDropTargetEvent.data); if (!droppedEObjects.isEmpty()) { try { new ProgressMonitorDialog(window.getShell()).run(false, false, monitor -> { session.getTransactionalEditingDomain().getCommandStack().execute(new RecordingCommand(session.getTransactionalEditingDomain()) { @Override protected void doExecute() { for (Iterator<File> iterator = droppedEObjects.iterator(); iterator.hasNext(); ) { File file = iterator.next(); session.addSemanticResource(URI.createPlatformResourceURI(file.getFullPath().toString(), true), monitor); } } }); }); status = Status.OK_STATUS; } catch (InvocationTargetException | InterruptedException e) { SessionEditorPlugin.getPlugin().error(e.getMessage(), e); } } } return status; }
Source:
public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) { ChannelModelImpl wih = (ChannelModelImpl) value; writer.addAttribute("name", wih.getName()); writer.addAttribute("type", wih.getType()); }

Target:
public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) { ChannelModelImpl channel = (ChannelModelImpl) value; writer.addAttribute("name", channel.getName()); writer.addAttribute("type", channel.getType()); }
Source:
private Constraints bytesToConstraints(byte[] bytes, String path) { try { return objectMapper.readValue(bytes, Constraints.class); } catch (Exception e) { logger.error("Cannot read data from node: {}", path, e); return null; } }

Target:
private Optional<Constraints> bytesToConstraints(byte[] bytes, String path) { try { return Optional.ofNullable(objectMapper.readValue(bytes, Constraints.class)); } catch (Exception e) { logger.error("Cannot read data from node: {}", path, e); return Optional.empty(); } }
Source:
public void shouldGetPublicRouterId() throws JSONException { String response = "{\"routers\": [{\"status\": \"ACTIVE\", \"external_gateway_info\": {\"network_id\": \"e8892de7-38f9-4002-90f9-eedf0e72f5fc\"}, \"name\": \"router-1137229409\", \"admin_state_up\": false, " + "\"tenant_id\": \"00000000000000000000000000000017\", \"routes\": [], \"id\": \"2fe38e4d-a4cb-4c0a-b1b9-e87e0d147f9c\"}, {\"status\": \"ACTIVE\", " + "\"external_gateway_info\": {\"network_id\": \"e5892de7-38f9-4002-90f9-eedf0e72f5fc\", \"enable_snat\": true}, \"name\": \"ext-rt\", \"admin_state_up\": " + " true, \"tenant_id\": \"00000000000000000000000000000001\", \"routes\": [], \"id\": \"35da5189-03f8-4167-868d-932637d83105\"}]}"; String routerId = openStackUtil.getPublicRouterId(response, "00000000000000000000000000000001", "e5892de7-38f9-4002-90f9-eedf0e72f5fc"); assertEquals(routerId, "35da5189-03f8-4167-868d-932637d83105"); }

Target:
public void shouldGetPublicRouterId() throws JSONException { String response = "{\"routers\": [{\"status\": \"ACTIVE\", \"external_gateway_info\":" + " {\"network_id\": \"e8892de7-38f9-4002-90f9-eedf0e72f5fc\"}, \"name\": " + "\"router-1137229409\", \"admin_state_up\": false, " + "\"tenant_id\": \"00000000000000000000000000000017\", \"routes\": [], " + "\"id\": \"2fe38e4d-a4cb-4c0a-b1b9-e87e0d147f9c\"}, {\"status\": \"ACTIVE\", " + "\"external_gateway_info\": {\"network_id\": \"e5892de7-38f9-4002-90f9-eedf0e72f5fc\"," + " \"enable_snat\": true}, \"name\": \"ext-rt\", \"admin_state_up\": " + " true, \"tenant_id\": \"00000000000000000000000000000001\", \"routes\": [], \"id\":" + "\"35da5189-03f8-4167-868d-932637d83105\"}]}"; String routerId = openStackUtil.getPublicRouterId(response, "00000000000000000000000000000001", "e5892de7-38f9-4002-90f9-eedf0e72f5fc"); assertEquals(routerId, "35da5189-03f8-4167-868d-932637d83105"); }
Source:
private void createLabel(Composite parent) { this.image = this.widgetFactory.createLabel(parent, "", SWT.NONE); this.text = this.widgetFactory.createHyperlink(parent, "", SWT.NONE); GridData gridData = new GridData(); gridData.grabExcessHorizontalSpace = true; gridData.horizontalAlignment = SWT.FILL; this.text.setLayoutData(gridData); }

Target:
private void createLabel(Composite parent) { this.image = this.widgetFactory.createLabel(parent, "", SWT.NONE); GridData gridData = new GridData(); gridData.grabExcessHorizontalSpace = true; gridData.horizontalAlignment = SWT.FILL; String onClickExpression = Optional.ofNullable(this.description.getOnClickExpression()).orElse(""); if (onClickExpression.isEmpty()) { this.text = this.widgetFactory.createLabel(parent, "", SWT.NONE); this.text.setLayoutData(gridData); } else { this.hyperlink = this.widgetFactory.createHyperlink(parent, "", SWT.NONE); this.hyperlink.setLayoutData(gridData); } }
Source:
public void run() { boolean confirmationResult = MessageDialog.openConfirm(new Shell(), "Confirm deletion", "Do you want to proceed ?"); if (confirmationResult) { TreeItem[] items = fTree.getSelection(); if (items.length != 0) { for (TreeItem item : items) { File deletedFile = new File(fItemsPaths.get(item).toString()); deleteFile(deletedFile); } update(); } } }

Target:
public void run() { boolean confirmationResult = false; TreeItem[] selectedItems = fTree.getSelection(); boolean oneOfSelectedIsDirectory = false; for (TreeItem item : selectedItems) { if (fItemsPaths.get(item).toFile().isDirectory()) { oneOfSelectedIsDirectory = true; } } if (oneOfSelectedIsDirectory) { confirmationResult = MessageDialog.openConfirm(new Shell(), Messages.XMLExplorerView_DeleteDirectoryHandler_Title, Messages.XMLExplorerView_DeleteDirectoryHandler_Confirmation_Question); } else { confirmationResult = MessageDialog.openConfirm(new Shell(), Messages.XMLExplorerView_DeleteXmlHandler_Title, Messages.XMLExplorerView_DeleteXmlHandler_Confirmation_Question); } if (confirmationResult) { TreeItem[] items = fTree.getSelection(); if (items.length != 0) { for (TreeItem item : items) { File deletedFile = new File(fItemsPaths.get(item).toString()); deleteFile(deletedFile); } update(); } } }
Source:
public void testClusterStats() throws Exception { Cache<String, Serializable> cache1 = manager(0).getCache(cachename); MBeanServer mBeanServer = PerThreadMBeanServerLookup.getThreadMBeanServer(); ObjectName nodeStats = getCacheManagerObjectName(JMX_DOMAIN, "DefaultCacheManager", CacheContainerStats.OBJECT_NAME); cache1.put("a1", "b1"); cache1.put("a2", "b2"); cache1.put("a3", "b3"); cache1.put("a4", "b4"); assertAttributeValue(mBeanServer, nodeStats, "NumberOfEntries", 4); assertAttributeValue(mBeanServer, nodeStats, "Stores", 4); assertAttributeValue(mBeanServer, nodeStats, "Evictions", 0); assertAttributeValueGreaterThan(mBeanServer, nodeStats, "AverageWriteTime", 0); cache1.remove("a1"); assertAttributeValue(mBeanServer, nodeStats, "RemoveHits", 1); }

Target:
public void testClusterStats() throws Exception { Cache<String, Serializable> cache1 = manager(0).getCache(cachename); MBeanServer mBeanServer = PerThreadMBeanServerLookup.getThreadMBeanServer(); ObjectName nodeStats = getCacheManagerObjectName(JMX_DOMAIN, "DefaultCacheManager", CacheContainerStats.OBJECT_NAME); cache1.put("a1", "b1"); cache1.put("a2", "b2"); cache1.put("a3", "b3"); cache1.put("a4", "b4"); assertAttributeValue(mBeanServer, nodeStats, "NumberOfEntries", 4); assertAttributeValue(mBeanServer, nodeStats, "Stores", 4); assertAttributeValue(mBeanServer, nodeStats, "Evictions", 0); assertAttributeValueGreaterThan(mBeanServer, nodeStats, "AverageWriteTime", 0); cache1.remove("a1"); assertAttributeValue(mBeanServer, nodeStats, "RemoveHits", 1); Cache<String, Serializable> cache3 = manager(0).getCache(cachename2); cache3.put("a10", "b1"); cache3.put("a11", "b2"); cache3.put("a12", "b3"); cache3.put("a13", "b4"); assertAttributeValue(mBeanServer, nodeStats, "NumberOfEntries", 7); assertAttributeValue(mBeanServer, nodeStats, "Stores", 8); assertAttributeValue(mBeanServer, nodeStats, "Evictions", 0); assertAttributeValueGreaterThan(mBeanServer, nodeStats, "AverageWriteTime", 0); }
Source:
private ItemStack getRubberBoots(Entity entity) { if (entity instanceof EntityPlayer) { EntityPlayer player = ((EntityPlayer) entity); ItemStack feet = player.getItemStackFromSlot(EntityEquipmentSlot.FEET); if (feet != null && (ModItems.RUBBER_BOOTS.isEqual(feet, false, false) || ModItems.STATIC_BOOTS.isEqual(feet, false, false))) return feet; } return null; }

Target:
private ItemStack getRubberBoots(Entity entity) { if (entity instanceof EntityPlayer) { EntityPlayer player = ((EntityPlayer) entity); ItemStack feet = player.getItemStackFromSlot(EntityEquipmentSlot.FEET); if (!InvTools.isEmpty(feet) && (ModItems.RUBBER_BOOTS.isEqual(feet, false, false) || ModItems.STATIC_BOOTS.isEqual(feet, false, false)) && !((EntityPlayer) entity).capabilities.isCreativeMode) return feet; } return InvTools.emptyStack(); }
Source:
public void testCreateFromJSONFunctionExtension() throws InterruptedException { log.info("CreateFromJSONFunctionExtension TestCase"); SiddhiManager siddhiManager = new SiddhiManager(); siddhiManager.setExtension("str:concat",ConcatFunctionExtension.class); String inStreamDefinition = "\ndefine stream inputStream (symbol string, price long, volume long);"; String query = ("@info(name = 'query1') from inputStream select " + "map:createFromJSON(\"{'symbol':'IBM','price':100,'volume':100 }\") as hashMap insert into outputStream;"); ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(inStreamDefinition + query); executionPlanRuntime.addCallback("outputStream",new StreamCallback() { @Override public void receive(Event[] inEvents) { EventPrinter.print(inEvents); for (Event event : inEvents) { count.incrementAndGet(); if (count.get() == 1) { HashMap map = (HashMap) event.getData(0); Assert.assertEquals("IBM",map.get("symbol")); eventArrived = true; } } } }); InputHandler inputHandler = executionPlanRuntime.getInputHandler("inputStream"); executionPlanRuntime.start(); inputHandler.send(new Object[]{"IBM",100,100l}); inputHandler.send(new Object[]{"WSO2",200,200l}); inputHandler.send(new Object[]{"XYZ",300,200l}); SiddhiTestHelper.waitForEvents(100,3,count,60000); Assert.assertEquals(3,count.get()); Assert.assertTrue(eventArrived); executionPlanRuntime.shutdown(); }

Target:
public void testCreateFromJSONFunctionExtension() throws InterruptedException { log.info("CreateFromJSONFunctionExtension TestCase"); SiddhiManager siddhiManager = new SiddhiManager(); siddhiManager.setExtension("str:concat", ConcatFunctionExtension.class); String inStreamDefinition = "\ndefine stream inputStream (symbol string, price long, volume long);"; String query = ("@info(name = 'query1') from inputStream select " + "map:createFromJSON(\"{'symbol':'IBM'," + "'price':100, 'volume':100 }\") as hashMap insert into outputStream;"); ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(inStreamDefinition + query); executionPlanRuntime.addCallback("outputStream", new StreamCallback() { @Override public void receive(Event[] inEvents) { EventPrinter.print(inEvents); for (Event event : inEvents) { count.incrementAndGet(); if (count.get() == 1) { HashMap map = (HashMap) event.getData(0); Assert.assertEquals("IBM", map.get("symbol")); eventArrived = true; } } } }); InputHandler inputHandler = executionPlanRuntime.getInputHandler("inputStream"); executionPlanRuntime.start(); inputHandler.send(new Object[]{"IBM", 100, 100l}); inputHandler.send(new Object[]{"WSO2", 200, 200l}); inputHandler.send(new Object[]{"XYZ", 300, 200l}); SiddhiTestHelper.waitForEvents(100, 3, count, 60000); Assert.assertEquals(3, count.get()); Assert.assertTrue(eventArrived); executionPlanRuntime.shutdown(); }
Source:
private void readNext() { final long index = getNextIndex(); Indexed cachedEntry = cache.get(index); if (cachedEntry != null) { this.nextEntry = cachedEntry; buffer.skip(memory.position() + cachedEntry.size() + Bytes.INTEGER + Bytes.INTEGER); memory.clear().limit(0); return; } else if (cache.index() < index) { this.nextEntry = null; return; } if (memory.remaining() < maxEntrySize) { buffer.skip(memory.position()) .mark() .read(memory.clear().limit(maxEntrySize * 2)) .reset(); memory.flip(); } memory.mark(); try { final int length = memory.readInt(); if (length <= 0 || length > maxEntrySize) { memory.reset().limit(memory.position()); nextEntry = null; return; } long checksum = memory.readUnsignedInt(); byte[] bytes = new byte[length]; memory.read(bytes); final Checksum crc32 = new CRC32(); crc32.update(bytes, 0, length); if (checksum == crc32.getValue()) { E entry = serializer.decode(bytes); nextEntry = new Indexed<>(index, entry, length); } else { memory.reset().limit(memory.position()); nextEntry = null; } } catch (BufferUnderflowException e) { memory.reset().limit(memory.position()); nextEntry = null; } }

Target:
private void readNext() { final long index = getNextIndex(); Indexed cachedEntry = cache.get(index); if (cachedEntry != null) { this.nextEntry = cachedEntry; buffer.skip(memory.position() + cachedEntry.size() + Bytes.INTEGER + Bytes.INTEGER); memory.clear().limit(0); return; } else if (cache.index() > 0 && cache.index() < index) { this.nextEntry = null; return; } if (memory.remaining() < maxEntrySize) { buffer.skip(memory.position()) .mark() .read(memory.clear().limit(maxEntrySize * 2)) .reset(); memory.flip(); } memory.mark(); try { final int length = memory.readInt(); if (length <= 0 || length > maxEntrySize) { memory.reset().limit(memory.position()); nextEntry = null; return; } long checksum = memory.readUnsignedInt(); byte[] bytes = new byte[length]; memory.read(bytes); final Checksum crc32 = new CRC32(); crc32.update(bytes, 0, length); if (checksum == crc32.getValue()) { E entry = serializer.decode(bytes); nextEntry = new Indexed<>(index, entry, length); } else { memory.reset().limit(memory.position()); nextEntry = null; } } catch (BufferUnderflowException e) { memory.reset().limit(memory.position()); nextEntry = null; } }
Source:
public CandlepinQuery<ProductLegacyDTO> listProducts( @Verify(Owner.class) @PathParam("owner_key") String ownerKey, @QueryParam("product") List<String> productIds) { Owner owner = this.getOwnerByKey(ownerKey); CandlepinQuery<Product> query = productIds != null && !productIds.isEmpty() ? this.ownerProductCurator.getProductsByIds(owner, productIds) : this.ownerProductCurator.getProductsByOwner(owner); return this.translator.translateQuery(query, ProductLegacyDTO.class); }

Target:
public CandlepinQuery<ProductDTO> listProducts( @Verify(Owner.class) @PathParam("owner_key") String ownerKey, @QueryParam("product") List<String> productIds) { Owner owner = this.getOwnerByKey(ownerKey); CandlepinQuery<Product> query = productIds != null && !productIds.isEmpty() ? this.ownerProductCurator.getProductsByIds(owner, productIds) : this.ownerProductCurator.getProductsByOwner(owner); return this.translator.translateQuery(query, ProductDTO.class); }
Source:
private void createAndUpsertTable(String tableName, String indexName, Properties props) throws SQLException { String ddl = "CREATE TABLE " + tableName + " (k INTEGER NOT NULL PRIMARY KEY, v1 VARCHAR, v2 VARCHAR)"; try(Connection conn = DriverManager.getConnection(getUrl(), props)) { conn.setAutoCommit(true); try (Statement statement = conn.createStatement()) { statement.execute(ddl); if (indexName != null) { String indexDdl1 = "CREATE INDEX " + indexName + " ON " + tableName + "(v1,v2)"; statement.execute(indexDdl1); } } conn.createStatement().execute( "upsert into " + tableName + " values (1, 'foo', 'foo1')"); conn.createStatement().execute( "upsert into " + tableName + " values (2, 'bar', 'bar1')"); conn.commit(); } }

Target:
private void createAndUpsertTable(String tableName, String indexName, Properties props) throws SQLException { String ddl = "CREATE TABLE " + tableName + " (k INTEGER NOT NULL PRIMARY KEY, v1 VARCHAR, v2 VARCHAR)"; try(Connection conn = DriverManager.getConnection(getUrl(), props)) { conn.setAutoCommit(true); try (Statement statement = conn.createStatement()) { statement.execute(ddl); if (indexName != null) { String indexDdl1 = "CREATE INDEX " + indexName + " ON " + tableName + "(v1,v2)"; statement.execute(indexDdl1); } statement.execute( "upsert into " + tableName + " values (1, 'foo', 'foo1')"); statement.execute( "upsert into " + tableName + " values (2, 'bar', 'bar1')"); conn.commit(); } } }
Source:
void propertyChangedInternal() { propertyChanged(); deriveAndSet(); }

Target:
void propertyChangedInternal() { deriveAndSet(); propertyChanged(); }
Source:
private Set<Table> getTablesToRestore(Set<String> savedTableNames, StringBuilder commaSeparatedViewNamesToDisable, List<String> include, List<String> exclude) { Set<Table> tables_to_restore = new HashSet<Table>(); if(include.size() > 0) { Set<String> newSet = new HashSet<>(); for(String s : include) { newSet.add(s); } savedTableNames = newSet; } else if(exclude.size() > 0) { for (String s : exclude) { if(savedTableNames.contains(s)) { savedTableNames.remove(s); } else { SNAP_LOG.info("Table: " + s + " does not match any savefile data"); } } } for (Table table : m_database.getTables()) { if (savedTableNames.contains(table.getTypeName())) { if (CatalogUtil.isSnapshotablePersistentTableView(m_database, table)) { commaSeparatedViewNamesToDisable.append(table.getTypeName()).append(","); } tables_to_restore.add(table); } else if (!CatalogUtil.isTableExportOnly(m_database, table)) { SNAP_LOG.info("Table: " + table.getTypeName() + " does not have any savefile data and so will not be loaded from disk."); } } if (commaSeparatedViewNamesToDisable.length() > 0) { commaSeparatedViewNamesToDisable.setLength(commaSeparatedViewNamesToDisable.length() - 1); } return tables_to_restore; }

Target:
private Set<Table> getTablesToRestore(Set<String> savedTableNames, StringBuilder commaSeparatedViewNamesToDisable, List<String> include, List<String> exclude) { Set<Table> tables_to_restore = new HashSet<Table>(); if(include.size() > 0) { Set<String> newSet = new HashSet<>(); for(String s : include) { newSet.add(s); } savedTableNames = newSet; } else if(exclude.size() > 0) { for (String s : exclude) { if(savedTableNames.contains(s)) { savedTableNames.remove(s); } else { SNAP_LOG.info("Table: " + s + " does not exist in the saved snapshot."); } } } for (Table table : m_database.getTables()) { if (savedTableNames.contains(table.getTypeName())) { if (CatalogUtil.isSnapshotablePersistentTableView(m_database, table)) { commaSeparatedViewNamesToDisable.append(table.getTypeName()).append(","); } tables_to_restore.add(table); } else if (!CatalogUtil.isTableExportOnly(m_database, table)) { SNAP_LOG.info("Table: " + table.getTypeName() + " does not have any savefile data and so will not be loaded from disk."); } } if (commaSeparatedViewNamesToDisable.length() > 0) { commaSeparatedViewNamesToDisable.setLength(commaSeparatedViewNamesToDisable.length() - 1); } return tables_to_restore; }
Source:
protected void buildAndPublishNotification(CaseCommentEvent event) { if (publishers.isEmpty()) { logger.debug("No publishers available, skipping comment notifications"); return; } CommentInstance comment = event.getComment(); List<String> mentionedRoles = extractMentionedRoles(comment.getComment()); if (mentionedRoles.isEmpty()) { logger.debug("No one has been mentioned in the comment, skipping comment notification"); return; } logger.debug("Found mentiones in comment {}", mentionedRoles, comment.getId()); StringBuilder commentContent = new StringBuilder(comment.getComment()); Set<OrganizationalEntity> recipients = collectOrgEntitiesByRole(mentionedRoles, event, commentContent); String notificationSubject = MessageFormat.format(subject, event.getCaseId()); Map<String, Object> parameters = buildParams(event, commentContent); for (NotificationPublisher publisher : publishers) { if (!publisher.isActive()) { logger.debug("Publisher is not active, skipping it", publisher); continue; } try { publisher.publish(sender, notificationSubject, recipients, template, parameters); } catch (IllegalArgumentException e) { publisher.publish(sender, notificationSubject, recipients, commentContent.toString()); } } }

Target:
protected void buildAndPublishNotification(CaseCommentEvent event) { if (publishers.isEmpty()) { logger.debug("No publishers available, skipping comment notifications"); return; } CommentInstance comment = event.getComment(); List<String> mentionedRoles = extractMentionedRoles(comment.getComment()); if (mentionedRoles.isEmpty()) { logger.debug("No one has been mentioned in the comment, skipping comment notification"); return; } logger.debug("Found mentions in comment {}", mentionedRoles, comment.getId()); StringBuilder commentContent = new StringBuilder(comment.getComment()); Set<OrganizationalEntity> recipients = collectOrgEntitiesByRole(mentionedRoles, event, commentContent); String notificationSubject = MessageFormat.format(subject, event.getCaseId()); Map<String, Object> parameters = buildParams(event, commentContent); for (NotificationPublisher publisher : publishers) { if (!publisher.isActive()) { logger.debug("Publisher is not active, skipping it", publisher); continue; } try { publisher.publish(sender, notificationSubject, recipients, template, parameters); } catch (IllegalArgumentException e) { publisher.publish(sender, notificationSubject, recipients, commentContent.toString()); } } }
Source:
private void createClientFactory() { ClientFactoryBuilder<Wfs> clientFactoryBuilder = clientFactory.getClientFactoryBuilder(); if (BASIC.equals(authenticationType) && StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) { factory = clientFactoryBuilder .endpointUrl(wfsUrl) .interfaceClass(Wfs.class) .entityProviders(initProviders()) .interceptor(new MarkableStreamInterceptor()) .disableCnCheck(disableCnCheck) .allowRedirects(false) .connectionTimeout(connectionTimeout) .receiveTimeout(receiveTimeout) .username(username) .password(password) .useSamlEcp(true) .build(); } else if (StringUtils.isNotBlank(getCertAlias()) && StringUtils.isNotBlank(getKeystorePath())) { factory = clientFactoryBuilder .endpointUrl(wfsUrl) .interfaceClass(Wfs.class) .entityProviders(initProviders()) .interceptor(new MarkableStreamInterceptor()) .disableCnCheck(disableCnCheck) .allowRedirects(false) .connectionTimeout(connectionTimeout) .receiveTimeout(receiveTimeout) .clientKeyInfo(getCertAlias(), getKeystorePath()) .sslProtocol(sslProtocol) .useSamlEcp(true) .build(); } else { factory = clientFactoryBuilder .endpointUrl(wfsUrl) .interfaceClass(Wfs.class) .entityProviders(initProviders()) .interceptor(new MarkableStreamInterceptor()) .disableCnCheck(disableCnCheck) .allowRedirects(false) .connectionTimeout(connectionTimeout) .receiveTimeout(receiveTimeout) .useSamlEcp(true) .build(); } }

Target:
private void createClientFactory() { ClientBuilder<Wfs> clientBuilder = clientBuilderFactory.getClientBuilder(); try { if (BASIC.equals(authenticationType) && StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) { factory = clientBuilder .endpoint(new URI(wfsUrl)) .interfaceClass(Wfs.class) .entityProviders(initProviders()) .interceptor(new MarkableStreamInterceptor()) .disableCnCheck(disableCnCheck) .allowRedirects(false) .connectionTimeout(connectionTimeout) .receiveTimeout(receiveTimeout) .username(username) .password(password) .useSamlEcp(true) .build(); } else if (StringUtils.isNotBlank(getCertAlias()) && StringUtils.isNotBlank(getKeystorePath())) { factory = clientBuilder .endpoint(new URI(wfsUrl)) .interfaceClass(Wfs.class) .entityProviders(initProviders()) .interceptor(new MarkableStreamInterceptor()) .disableCnCheck(disableCnCheck) .allowRedirects(false) .connectionTimeout(connectionTimeout) .receiveTimeout(receiveTimeout) .clientKeyInfo(getCertAlias(), Paths.get(getKeystorePath())) .sslProtocol(sslProtocol) .useSamlEcp(true) .build(); } else { factory = clientBuilder .endpoint(new URI(wfsUrl)) .interfaceClass(Wfs.class) .entityProviders(initProviders()) .interceptor(new MarkableStreamInterceptor()) .disableCnCheck(disableCnCheck) .allowRedirects(false) .connectionTimeout(connectionTimeout) .receiveTimeout(receiveTimeout) .useSamlEcp(true) .build(); } } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } }
Source:
private List<Project> readModelsForManipulation( File executionRoot, final List<PomPeek> peeked ) throws ManipulationException { final List<Project> projects = new ArrayList<>(); final HashMap<Project, ProjectVersionRef> projectToParent = new HashMap<>( ); for ( final PomPeek peek : peeked ) { final File pom = peek.getPom(); Model raw; try ( InputStream in = new FileInputStream( pom ) ) { raw = new MavenXpp3Reader().read( in ); } catch ( final IOException | XmlPullParserException e ) { throw new ManipulationException( "Failed to build model for POM: %s.%n--> %s", e, pom, e.getMessage() ); } if ( raw == null ) { continue; } final Project project = new Project( pom, raw ); projectToParent.put( project, peek.getParentKey() ); project.setInheritanceRoot( peek.isInheritanceRoot() ); if ( executionRoot.equals( pom ) ) { if ( logger.isDebugEnabled() ) { logger.debug( "Setting execution root to with file {}", project, pom, ( project.isInheritanceRoot() ? " and is the inheritance root." : "" ) ); } project.setExecutionRoot(); try { if ( FileUtils.readFileToString( pom, raw.getModelEncoding() ).contains( MODIFIED_BY ) ) { project.setIncrementalPME( true ); } } catch ( final IOException e ) { throw new ManipulationException( "Failed to read POM: %s", e, pom ); } } projects.add( project ); } for ( Project p : projects ) { ProjectVersionRef pvr = projectToParent.get( p ); p.setProjectParent( getParent( projects, pvr ) ); } return projects; }

Target:
private List<Project> readModelsForManipulation( File executionRoot, final List<PomPeek> peeked ) throws ManipulationException { final List<Project> projects = new ArrayList<>(); final HashMap<Project, ProjectVersionRef> projectToParent = new HashMap<>( ); for ( final PomPeek peek : peeked ) { final File pom = peek.getPom(); Model raw; try ( InputStream in = new FileInputStream( pom ) ) { raw = new MavenXpp3Reader().read( in ); } catch ( final IOException | XmlPullParserException e ) { throw new ManipulationException( "Failed to build model for POM: " + pom + "." + System.lineSeparator() + "--> " + e.getMessage(), e ); } if ( raw == null ) { continue; } final Project project = new Project( pom, raw ); projectToParent.put( project, peek.getParentKey() ); project.setInheritanceRoot( peek.isInheritanceRoot() ); if ( executionRoot.equals( pom )) { if (logger.isDebugEnabled()) { logger.debug("Setting execution root to with file {}" + (project.isInheritanceRoot() ? " and is the inheritance root. " : ""), project, pom); } project.setExecutionRoot (); try { if ( FileUtils.readFileToString( pom, raw.getModelEncoding() ).contains( MODIFIED_BY ) ) { project.setIncrementalPME (true); } } catch ( final IOException e ) { throw new ManipulationException( "Failed to read POM: " + pom, e ); } } projects.add( project ); } for ( Project p : projects ) { ProjectVersionRef pvr = projectToParent.get( p ); p.setProjectParent( getParent( projects, pvr ) ); } return projects; }
Source:
public void exactSequence() { Flowable.range(1, 5) .doOnRequest(this) .doOnCancel(this) .limit(5) .test() .assertResult(1, 2, 3, 4, 5); assertEquals(2, requests.size()); assertEquals(5, requests.get(0).intValue()); assertEquals(-100, requests.get(1).intValue()); }

Target:
public void exactSequence() { Flowable.range(1, 5) .doOnRequest(this) .doOnCancel(this) .limit(5) .test() .assertResult(1, 2, 3, 4, 5); assertEquals(2, requests.size()); assertEquals(5, requests.get(0).intValue()); assertEquals(CANCELLED, requests.get(1)); }
Source:
static com.azure.ai.textanalytics.models.TextAnalyticsError toTextAnalyticsError( TextAnalyticsError textAnalyticsError) { return new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString(textAnalyticsError.getInnerError().getCode().toString()), textAnalyticsError.getInnerError().getMessage(), textAnalyticsError.getInnerError().getTarget()); }

Target:
static com.azure.ai.textanalytics.models.TextAnalyticsError toTextAnalyticsError( TextAnalyticsError textAnalyticsError) { if (textAnalyticsError.getInnerError() == null) { return new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString(textAnalyticsError.getCode().toString()), textAnalyticsError.getMessage(), textAnalyticsError.getTarget()); } return new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString(textAnalyticsError.getInnerError().getCode().toString()), textAnalyticsError.getInnerError().getMessage(), textAnalyticsError.getInnerError().getTarget()); }
Source:
public void set(T value) { optional = Optional.of(value); }

Target:
public void set(T value) { if (optional.isPresent()) { throw new IllegalStateException( String.format("Multiple values for Optional type: ['%s','%s',...]", optional.get(), value)); } optional = Optional.of(value); }
Source:
private static void debugLogFileSystemClose(String methodName, String additionalInfo) { StackTraceElement callingMethod = new Throwable().fillInStackTrace().getStackTrace()[2]; LOGGER.debug( "FileSystem." + methodName + "() called by method: " + callingMethod.getClassName() + "." + callingMethod.getMethodName() + "(" + callingMethod.getFileName() + ":" + callingMethod.getLineNumber() + "); " + (additionalInfo != null ? additionalInfo : "")); }

Target:
private static void debugLogFileSystemClose(String methodName, String additionalInfo) { if (LOGGER.isDebugEnabled()) { Throwable throwable = new Throwable().fillInStackTrace(); LOGGER.debug("FileSystem.{}() by method: {}); {}", methodName, throwable.getStackTrace()[2], additionalInfo); if (LOGGER.isTraceEnabled()) { LOGGER.trace("FileSystem.{}() full stack trace:", methodName, throwable); } } }
Source:
public boolean show(ShowInContext context) { if (context == null) return false; ISelection selection = context.getSelection(); if (selection != null && !selection.isEmpty() && selection instanceof IStructuredSelection) { selectReveal(selection); if (commonViewer.getSelection() != null && !commonViewer.getSelection().isEmpty()) { return true; } } Object input = context.getInput(); if (input instanceof IEditorInput) { LinkHelperService lhs = getLinkHelperService(); selection = lhs.getSelectionFor((IEditorInput) input); if (selection != null) { selectReveal(selection); return true; } } if (input != null) { selectReveal(new StructuredSelection(input)); return true; } return false; }

Target:
public boolean show(ShowInContext context) { if (context == null) return false; ISelection selection = context.getSelection(); if (selection != null && !selection.isEmpty() && selection instanceof IStructuredSelection) { selectReveal(selection); selection = commonViewer.getSelection(); if (selection != null && !selection.isEmpty()) { return true; } } Object input = context.getInput(); if (input instanceof IEditorInput) { LinkHelperService lhs = getLinkHelperService(); selection = lhs.getSelectionFor((IEditorInput) input); if (selection != null) { selectReveal(selection); return true; } } if (input != null) { selectReveal(new StructuredSelection(input)); return true; } return false; }
Source:
public void testObtainHandleViaOpen() throws Exception { assertThatCode(dbRule.getJdbi()::open).doesNotThrowAnyException(); }

Target:
public void testObtainHandleViaOpen() throws Exception { assertThatCode(() -> { try (Handle h = dbRule.getJdbi().open()) { } }).doesNotThrowAnyException(); }
Source:
public void addOrUpdateProperties(String bundle, String version, String filename, Properties newProperties, Properties defaultProperties) throws IOException { Properties toPersist; if (ConfigSource.UI.equals(configSource)) { toPersist = new Properties(); for (Map.Entry<Object, Object> entry : newProperties.entrySet()) { if (defaultProperties == null || !defaultProperties.containsKey(entry.getKey()) || (!defaultProperties.get(entry.getKey()).equals(newProperties.get(entry.getKey())))) { toPersist.put(entry.getKey(), entry.getValue()); } } } else { toPersist = newProperties; checkDifferencesAndSaveFile(bundle, filename, toPersist); } ModulePropertiesRecord properties = new ModulePropertiesRecord(toPersist, bundle, version, filename, false); if (bundlePropertiesService != null) { addOrUpdateBundleRecord(properties); } }

Target:
public void addOrUpdateProperties(String bundle, String version, String filename, Properties newProperties, Properties defaultProperties) throws IOException { Properties toPersist; if (ConfigSource.UI.equals(configSource)) { toPersist = new Properties(); for (Map.Entry<Object, Object> entry : newProperties.entrySet()) { if (defaultProperties == null || !defaultProperties.containsKey(entry.getKey()) || (!defaultProperties.get(entry.getKey()).equals(newProperties.get(entry.getKey())))) { toPersist.put(entry.getKey(), entry.getValue()); } } } else { toPersist = newProperties; checkDifferencesAndSaveFile(bundle, filename, toPersist); } ModulePropertiesRecord properties = new ModulePropertiesRecord(toPersist, bundle, version, filename, false); if (bundlePropertiesDataService != null) { addOrUpdateBundleRecord(properties); } }
Source:
public XmlEntry(int baseQuark, int displayQuark, ITmfTrace trace, String name, long startTime, long endTime, EntryDisplayType type, @NonNull ITmfStateSystem ss, Element entryElement) { super(name, startTime, endTime); fTrace = trace; fType = type; fBaseQuark = baseQuark; fDisplayQuark = displayQuark; fSs = ss; fElement = entryElement; List<Element> elements = XmlUtils.getChildElements(fElement, TmfXmlUiStrings.PARENT_ELEMENT); if (elements.size() > 0) { fParentId = getFirstValue(elements.get(0)); } else { fParentId = EMPTY_STRING; } elements = XmlUtils.getChildElements(fElement, TmfXmlUiStrings.NAME_ELEMENT); if (elements.size() > 0) { String nameFromSs = getFirstValue(elements.get(0)); if (!nameFromSs.equals(EMPTY_STRING)) { setName(nameFromSs); } } elements = XmlUtils.getChildElements(fElement, TmfXmlUiStrings.ID_ELEMENT); if (elements.size() > 0) { fId = getFirstValue(elements.get(0)); } else { fId = name; } }

Target:
public XmlEntry(int baseQuark, int displayQuark, ITmfTrace trace, String name, long startTime, long endTime, EntryDisplayType type, @NonNull ITmfStateSystem ss, Element entryElement) { super(name, startTime, endTime); fTrace = trace; fType = type; fBaseQuark = baseQuark; fDisplayQuark = displayQuark; fSs = ss; fElement = entryElement; List<Element> elements = XmlUtils.getChildElements(fElement, TmfXmlUiStrings.PARENT_ELEMENT); if (elements.size() > 0) { fParentId = getFirstValue(elements.get(0)); } else { fParentId = EMPTY_STRING; } elements = XmlUtils.getChildElements(fElement, TmfXmlUiStrings.NAME_ELEMENT); if (elements.size() > 0) { String nameFromSs = getFirstValue(elements.get(0)); if (!nameFromSs.isEmpty()) { setName(nameFromSs); } } elements = XmlUtils.getChildElements(fElement, TmfXmlUiStrings.ID_ELEMENT); if (elements.size() > 0) { fId = getFirstValue(elements.get(0)); } else { fId = name; } }
Source:
public void checkEnvironmentStatus(Stack stack, Set<EnvironmentStatus> desiredStatuses) { if (stack.getEnvironmentCrn() != null) { DetailedEnvironmentResponse environmentResponse = environmentClientService.getByCrn(stack.getEnvironmentCrn()); if (!desiredStatuses.contains(environmentResponse.getEnvironmentStatus())) { throw new BadRequestException("This action is require to Environment be available, but the status is " + environmentResponse.getEnvironmentStatus().getDescription()); } } }

Target:
public void checkEnvironmentStatus(Stack stack, Set<EnvironmentStatus> desiredStatuses) { if (stack.getEnvironmentCrn() != null) { DetailedEnvironmentResponse environmentResponse = environmentClientService.getByCrn(stack.getEnvironmentCrn()); if (!desiredStatuses.contains(environmentResponse.getEnvironmentStatus())) { throw new BadRequestException("This action requires the Environment to be available, but the status is " + environmentResponse.getEnvironmentStatus().getDescription()); } } }
Source:
public static void serializeBlobProperties(ByteBuffer outputBuffer, BlobProperties properties) { outputBuffer.putShort(currentVersion); outputBuffer.putLong(properties.getTimeToLiveInSeconds()); outputBuffer.put(properties.isPrivate() ? (byte) 1 : (byte) 0); outputBuffer.putLong(properties.getCreationTimeInMs()); outputBuffer.putLong(properties.getBlobSize()); Utils.serializeNullableString(outputBuffer, properties.getContentType()); Utils.serializeNullableString(outputBuffer, properties.getOwnerId()); Utils.serializeNullableString(outputBuffer, properties.getServiceId()); outputBuffer.putShort(properties.getAccountId()); outputBuffer.putShort(properties.getContainerId()); }

Target:
public static void serializeBlobProperties(ByteBuffer outputBuffer, BlobProperties properties) { if (outputBuffer.remaining() < getBlobPropertiesSerDeSize(properties)) { throw new IllegalArgumentException("Outut buffer does not have sufficient space to serialize blob properties"); } outputBuffer.putShort(CURRENT_VERSION); outputBuffer.putLong(properties.getTimeToLiveInSeconds()); outputBuffer.put(properties.isPrivate() ? (byte) 1 : (byte) 0); outputBuffer.putLong(properties.getCreationTimeInMs()); outputBuffer.putLong(properties.getBlobSize()); Utils.serializeNullableString(outputBuffer, properties.getContentType()); Utils.serializeNullableString(outputBuffer, properties.getOwnerId()); Utils.serializeNullableString(outputBuffer, properties.getServiceId()); outputBuffer.putShort(properties.getAccountId()); outputBuffer.putShort(properties.getContainerId()); }
Source:
public <T, E1 extends Exception, E2 extends Exception> T transactionWithLocalRetry(RetryableTransactionActionWithExceptions<T, D, E1, E2> action, Class<E1> exClass1, Class<E2> exClass2) throws E1, E2 { try { return transactionRetryExecutor.runInterruptible(() -> { TransactionState ts = new TransactionState(); while (true) { Handle savedNestedTransaction = currentTransaction.get(); try (Handle handle = dbi.open()) { handle.begin(); currentTransaction.set(handle); T retval; try { retval = action.call(handle, handle.attach(daoIface), ts); } catch (Exception ex) { try { handle.rollback(); } catch (Exception rollback) { ex.addSuppressed(rollback); } Throwables.propagateIfInstanceOf(ex, exClass1); Throwables.propagateIfInstanceOf(ex, exClass2); Throwables.propagateIfPossible(ex); throw new TransactionFailedException( "Transaction failed due to exception being thrown " + "from within the callback. See cause " + "for the original exception.", ex); } if (!ts.retryNext) { validateTransactionAndCommit(handle); return retval; } ts.retryNext = false; ts.retryCount += 1; } finally { currentTransaction.set(savedNestedTransaction); } } }); } catch (RetryGiveupException ex) { Throwable innerException = ex.getCause(); Throwables.propagateIfInstanceOf(innerException, exClass1); Throwables.propagateIfInstanceOf(innerException, exClass2); throw Throwables.propagate(innerException); } catch (InterruptedException ex) { throw Throwables.propagate(ex); } }

Target:
public <T, E1 extends Exception, E2 extends Exception> T transactionWithLocalRetry(RetryableTransactionActionWithExceptions<T, D, E1, E2> action, Class<E1> exClass1, Class<E2> exClass2) throws E1, E2 { try { return transactionRetryExecutor.runInterruptible(() -> { TransactionState ts = new TransactionState(); while (true) { Handle savedNestedTransaction = currentTransaction.get(); try (Handle handle = dbi.open()) { handle.begin(); currentTransaction.set(handle); T retval; try { retval = action.call(handle, handle.attach(daoIface), ts); } catch (Exception ex) { try { handle.rollback(); } catch (Exception rollback) { ex.addSuppressed(rollback); } Throwables.propagateIfInstanceOf(ex, exClass1); Throwables.propagateIfInstanceOf(ex, exClass2); Throwables.propagateIfPossible(ex); throw new TransactionFailedException( "Transaction failed due to exception being thrown " + "from within the callback. See cause " + "for the original exception.", ex); } if (!ts.retryNext) { validateTransactionAndCommit(handle); return retval; } ts.retryNext = false; ts.retryCount += 1; } finally { currentTransaction.set(savedNestedTransaction); } } }); } catch (RetryGiveupException ex) { Throwable innerException = ex.getCause(); Throwables.propagateIfInstanceOf(innerException, exClass1); Throwables.propagateIfInstanceOf(innerException, exClass2); throw Throwables.propagate(innerException); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw Throwables.propagate(ex); } }