auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void MessageWall_016_CloseThread() { MessageWallPageObject wall = new MessageWallPageObject(driver); String timeStamp = wall.getTimeStamp(); String title = PageContent.messageWallTitlePrefix + timeStamp; String message = PageContent.messageWallMessagePrefix + timeStamp; wall.openWikiPage(); CommonFunctions.logInCookie(Properties.userNameStaff, Properties.passwordStaff); wall.openMessageWall(Properties.userNameStaff); wall.writeMessage(title, message); wall.clickPostButton(); wall.verifyPostedMessageWithTitle(title, message); wall.closeThread("reason"); CommonFunctions.logOut(driver); }

Target:
public void MessageWall_016_CloseThread() { MessageWallPageObject wall = new MessageWallPageObject(driver); timeStamp = wall.getTimeStamp(); title = PageContent.messageWallTitlePrefix + timeStamp; message = PageContent.messageWallMessagePrefix + timeStamp; wall.openWikiPage(); CommonFunctions.logInCookie(Properties.userNameStaff, Properties.passwordStaff); wall.openMessageWall(Properties.userNameStaff); wall.writeMessage(title, message); wall.clickPostButton(); wall.verifyPostedMessageWithTitle(title, message); wall.closeThread(PageContent.messageWallCloseReopenReason); CommonFunctions.logOut(driver); }
Source:
public Shell getShells () { checkDevice (); int index = 0; Shell result = new Shell [16]; for (int i = 0; i < widgetTable.length; i++) { Widget widget = widgetTable [i]; if (!(widget instanceof Shell)) { continue; } if (!widget.isDisposed()) { int j = 0; while (j < index) { if (result [j] == widget) break; j++; } if (j == index) { if (index == result.length) { Shell newResult = new Shell [index + 16]; System.arraycopy (result, 0, newResult, 0, index); result = newResult; } result [index++] = (Shell) widget; } } else { System.err.println ("SWT ERROR: disposed shell detected in the table" + debugInfoForIndex(index)); for (int j = i; i < widgetTable.length; i++) { if(widgetTable[j] == widget) { widgetTable[j] = null; } } } } if (index == result.length) return result; Shell newResult = new Shell [index]; System.arraycopy (result, 0, newResult, 0, index); return newResult; }

Target:
public Shell getShells () { checkDevice (); int index = 0; Shell result = new Shell [16]; for (int i = 0; i < widgetTable.length; i++) { Widget widget = widgetTable [i]; if (!(widget instanceof Shell)) { continue; } if (!widget.isDisposed()) { int j = 0; while (j < index) { if (result [j] == widget) break; j++; } if (j == index) { if (index == result.length) { Shell newResult = new Shell [index + 16]; System.arraycopy (result, 0, newResult, 0, index); result = newResult; } result [index++] = (Shell) widget; } } else { System.err.println ("SWT ERROR: disposed shell detected in the table" + debugInfoForIndex(index)); for (int j = i; j < widgetTable.length; j++) { if(widgetTable[j] == widget) { widgetTable[j] = null; } } } } if (index == result.length) return result; Shell newResult = new Shell [index]; System.arraycopy (result, 0, newResult, 0, index); return newResult; }
Source:
private static int getSupport( final Unit unit, final Set<List<UnitSupportAttachment>> supportsAvailable, final IntegerMap<UnitSupportAttachment> supportLeft, final Map<UnitSupportAttachment, IntegerMap<Unit>> supportUnitsLeft, final Map<Unit, IntegerMap<Unit>> unitSupportMap, final Predicate<UnitSupportAttachment> ruleFilter) { int givenSupport = 0; for (final List<UnitSupportAttachment> bonusType : supportsAvailable) { final int bonusTypeCount = bonusType.get(0).getBonusType().getFirst(); int maxPerBonusType = bonusTypeCount >= 1 ? bonusTypeCount : Integer.MAX_VALUE; for (final UnitSupportAttachment rule : bonusType) { if (!ruleFilter.test(rule)) { continue; } final Set<UnitType> types = rule.getUnitType(); if (types != null && types.contains(unit.getType()) && supportLeft.getInt(rule) > 0) { final int numSupportToApply = Math.min( maxPerBonusType, Math.min(supportLeft.getInt(rule), supportUnitsLeft.get(rule).size())); for (int i = 0; i < numSupportToApply; i++) { givenSupport += rule.getBonus(); supportLeft.add(rule, -1); final Set<Unit> supporters = supportUnitsLeft.get(rule).keySet(); final Unit u = supporters.iterator().next(); supportUnitsLeft.get(rule).add(u, -1); if (supportUnitsLeft.get(rule).getInt(u) <= 0) { supportUnitsLeft.get(rule).removeKey(u); } unitSupportMap.computeIfAbsent(u, j -> new IntegerMap<>()).add(unit, rule.getBonus()); } maxPerBonusType -= numSupportToApply; if (maxPerBonusType <= 0) { break; } } } } return givenSupport; }

Target:
private static int getSupport( final Unit unit, final Set<List<UnitSupportAttachment>> supportsAvailable, final IntegerMap<UnitSupportAttachment> supportLeft, final Map<UnitSupportAttachment, IntegerMap<Unit>> supportUnitsLeft, final Map<Unit, IntegerMap<Unit>> unitSupportMap, final Predicate<UnitSupportAttachment> ruleFilter) { int givenSupport = 0; for (final List<UnitSupportAttachment> bonusType : supportsAvailable) { int maxPerBonusType = bonusType.get(0).getBonusType().getCount(); for (final UnitSupportAttachment rule : bonusType) { if (!ruleFilter.test(rule)) { continue; } final Set<UnitType> types = rule.getUnitType(); if (types != null && types.contains(unit.getType()) && supportLeft.getInt(rule) > 0) { final int numSupportToApply = Math.min( maxPerBonusType, Math.min(supportLeft.getInt(rule), supportUnitsLeft.get(rule).size())); for (int i = 0; i < numSupportToApply; i++) { givenSupport += rule.getBonus(); supportLeft.add(rule, -1); final Set<Unit> supporters = supportUnitsLeft.get(rule).keySet(); final Unit u = supporters.iterator().next(); supportUnitsLeft.get(rule).add(u, -1); if (supportUnitsLeft.get(rule).getInt(u) <= 0) { supportUnitsLeft.get(rule).removeKey(u); } unitSupportMap.computeIfAbsent(u, j -> new IntegerMap<>()).add(unit, rule.getBonus()); } maxPerBonusType -= numSupportToApply; if (maxPerBonusType <= 0) { break; } } } } return givenSupport; }
Source:
public <S extends T> Iterable<S> saveAll(Iterable<S> entities) { Assert.notNull(entities, "Cannot insert 'null' as a List."); Iterator<S> iterator = entities.iterator(); if (iterator.hasNext()) { S entity = iterator.next(); operations.save(entities, getIndexCoordinates()); operations.getIndexOperations(entity.getClass()).refresh(); } return entities; }

Target:
public <S extends T> Iterable<S> saveAll(Iterable<S> entities) { Assert.notNull(entities, "Cannot insert 'null' as a List."); IndexCoordinates indexCoordinates = getIndexCoordinates(); operations.save(entities, indexCoordinates); operations.indexOps(indexCoordinates).refresh(); return entities; }
Source:
private Trigger postNewTriggerWithForm( @NonNull TriggeredCommandForm form, @NonNull Predicate predicate, @Nullable TriggerOptions options) throws ThingIFException { if (this.target == null) { throw new IllegalStateException("Can not perform this action before onboarding"); } if (form == null) { throw new IllegalArgumentException("form is null."); } if (predicate == null) { throw new IllegalArgumentException("predicate is null."); } Schema schema = this.getSchema(form.getSchemaName(), form.getSchemaVersion()); JSONObject requestBody = options != null ? JsonUtils.newJson(GsonRepository.gson().toJson(options)) : new JSONObject(); try { requestBody.put("triggersWhat", TriggersWhat.COMMAND.name()); requestBody.put("predicate", JsonUtils.newJson( GsonRepository.gson(schema).toJson(predicate))); JSONObject command = JsonUtils.newJson( GsonRepository.gson(schema).toJson(form)); command.put("issuer", this.owner.getTypedID()); if (form.getTargetID() == null) { command.put("target", this.target.getTypedID().toString()); } requestBody.put("command", command); } catch (JSONException e) { throw new RuntimeException(e); } return postNewTrigger(requestBody); }

Target:
private Trigger postNewTriggerWithForm( @NonNull TriggeredCommandForm form, @NonNull Predicate predicate, @Nullable TriggerOptions options) throws ThingIFException { if (this.target == null) { throw new IllegalStateException("Can not perform this action before onboarding"); } if (form == null) { throw new IllegalArgumentException("form is null."); } if (predicate == null) { throw new IllegalArgumentException("predicate is null."); } JSONObject requestBody = options != null ? JsonUtils.newJson(GsonRepository.gson().toJson(options)) : new JSONObject(); try { requestBody.put("triggersWhat", TriggersWhat.COMMAND.name()); requestBody.put("predicate", JsonUtils.newJson( GsonRepository.gson().toJson(predicate))); JSONObject command = JsonUtils.newJson( GsonRepository.gson( this.getSchema( form.getSchemaName(), form.getSchemaVersion())).toJson(form)); command.put("issuer", this.owner.getTypedID()); if (form.getTargetID() == null) { command.put("target", this.target.getTypedID().toString()); } requestBody.put("command", command); } catch (JSONException e) { throw new RuntimeException(e); } return postNewTrigger(requestBody); }
Source:
public void completed(AbstractBuild r) { if (skipOnMatrixChildren(r)) { return; } String key = BuildKey.format(r); AbstractProject<?, ?> project = r.getProject(); AbstractBuild<?, ?> previousBuild = project.getLastBuild(); if (null != previousBuild) { do { previousBuild = previousBuild.getPreviousCompletedBuild(); } while (null != previousBuild && previousBuild.getResult() == Result.ABORTED); if (null != previousBuild) { log.info(key, "found #%d as previous completed, non-aborted build", previousBuild.getNumber()); } else { log.debug(key, "did not find previous completed, non-aborted build"); } NotificationConditions conditions = NotificationConditions.create(notifier, log); if (conditions.test(new Context(r, previousBuild))) { String message = getBuildStatusMessage(r, notifier.getIncludeTestSummary(), notifier.getIncludeFailedTests(), notifier.getIncludeCustomMessage()); if (notifier.getCommitInfoChoice().showAnything()) { message = message + "\n" + getCommitList(r); } slackFactory.apply(r).publish(message, getBuildColor(r)); } } }

Target:
public void completed(AbstractBuild r) { if (skipOnMatrixChildren(r)) { return; } String key = BuildKey.format(r); AbstractProject<?, ?> project = r.getProject(); AbstractBuild<?, ?> previousBuild = project.getLastBuild(); if (null != previousBuild) { do { previousBuild = previousBuild.getPreviousCompletedBuild(); } while ((null != previousBuild && previousBuild.getResult() == Result.ABORTED) || (null != previousBuild && previousBuild.getNumber() == r.getNumber())); if (null != previousBuild) { log.info(key, "found #%d as previous completed, non-aborted build", previousBuild.getNumber()); } else { log.debug(key, "did not find previous completed, non-aborted build"); } NotificationConditions conditions = NotificationConditions.create(notifier, log); if (conditions.test(new Context(r, previousBuild))) { String message = getBuildStatusMessage(r, notifier.getIncludeTestSummary(), notifier.getIncludeFailedTests(), notifier.getIncludeCustomMessage()); if (notifier.getCommitInfoChoice().showAnything()) { message = message + "\n" + getCommitList(r); } slackFactory.apply(r).publish(message, getBuildColor(r)); } } }
Source:
protected void internalReceiveCommand(final String itemName, final Command command) { if (this.logger.isDebugEnabled()) { this.logger.debug("internalReceiveCommand({},{}) is called!", itemName, command); } ISYBindingConfig config = getBindingConfigByName(itemName); if (config != null) { processCommand(config, command); } else { this.logger.warn( "No configured Insteon address found for item [{}]", itemName); } }

Target:
protected void internalReceiveCommand(final String itemName, final Command command) { this.logger.debug("internalReceiveCommand({},{}) is called!", itemName, command); ISYBindingConfig config = getBindingConfigByName(itemName); if (config != null) { processCommand(config, command); } else { this.logger.warn( "No configured Insteon address found for item [{}]", itemName); } }
Source:
private static void watch(String path) { FileWatcher watcher; FileWatcherCallback callback = new FileWatcherCallback() { public void pathChanged(Type type, String changedPath) { System.out.printf("Change detected: %s / '%s'%n", type, changedPath); } }; if (Platform.current().isMacOs()) { watcher = createMacOsFileWatcher(path, callback); } else if (Platform.current().isWindows()) { watcher = createWindowsFileWatcher(path, callback); } else { throw new RuntimeException("Only Windows and macOS are supported for file watching"); } try { System.out.println("Waiting - type ctrl-d to exit ..."); while (true) { int ch = System.in.read(); if (ch < 0) { break; } } watcher.close(); } catch (Exception e) { throw new RuntimeException(e); } finally { try { watcher.close(); } catch (IOException e) { e.printStackTrace(); } } System.out.println("Done"); }

Target:
private static void watch(String path) { FileWatcher watcher; FileWatcherCallback callback = new FileWatcherCallback() { public void pathChanged(Type type, String changedPath) { System.out.printf("Change detected: %s / '%s'%n", type, changedPath); } }; if (Platform.current().isMacOs()) { watcher = createMacOsFileWatcher(path, callback); } else if (Platform.current().isWindows()) { watcher = createWindowsFileWatcher(path, callback); } else { throw new RuntimeException("Only Windows and macOS are supported for file watching"); } try { System.out.println("Waiting - type ctrl-d to exit ..."); while (true) { int ch = System.in.read(); if (ch < 0) { break; } } } catch (Exception e) { throw new RuntimeException(e); } finally { try { watcher.close(); } catch (IOException e) { e.printStackTrace(); } } System.out.println("Done"); }
Source:
public boolean canExecute() { return true; }

Target:
public boolean canExecute() { if (selection != null && selection.size() > 1) { for (EObject tool : selection) { if (!(tool instanceof AbstractToolDescription)) { return false; } } } return true; }
Source:
private Path getCurrentLoadPath() throws IOException, SemanticException { Path loadPathBase = new Path(conf.getVar(HiveConf.ConfVars.REPLDIR), Base64.getEncoder().encodeToString(sourceDbNameOrPattern.toLowerCase() .getBytes(StandardCharsets.UTF_8.name()))); final FileSystem fs = loadPathBase.getFileSystem(conf); loadPathBase = fs.makeQualified(loadPathBase); if (!fs.exists(loadPathBase)) { LOG.error("File not found " + loadPathBase.toUri().toString()); throw new FileNotFoundException(ErrorMsg.REPL_LOAD_PATH_NOT_FOUND.getMsg()); } FileStatus[] statuses = loadPathBase.getFileSystem(conf).listStatus(loadPathBase); if (statuses.length > 0) { FileStatus latestUpdatedStatus = statuses[0]; for (FileStatus status : statuses) { if (status.getModificationTime() > latestUpdatedStatus.getModificationTime()) { latestUpdatedStatus = status; } } Path hiveDumpPath = new Path(latestUpdatedStatus.getPath(), ReplUtils.REPL_HIVE_BASE_DIR); if (loadPathBase.getFileSystem(conf).exists(hiveDumpPath)) { if (loadPathBase.getFileSystem(conf).exists(new Path(hiveDumpPath, ReplUtils.DUMP_ACKNOWLEDGEMENT)) && !loadPathBase.getFileSystem(conf).exists(new Path(hiveDumpPath, ReplUtils.LOAD_ACKNOWLEDGEMENT))) { return hiveDumpPath; } } } return null; }

Target:
private Path getCurrentLoadPath() throws IOException, SemanticException { Path loadPathBase = new Path(conf.getVar(HiveConf.ConfVars.REPLDIR), Base64.getEncoder().encodeToString(sourceDbNameOrPattern.toLowerCase() .getBytes(StandardCharsets.UTF_8.name()))); final FileSystem fs = loadPathBase.getFileSystem(conf); loadPathBase = fs.makeQualified(loadPathBase); if (!fs.exists(loadPathBase)) { LOG.error("File not found " + loadPathBase.toUri().toString()); throw new FileNotFoundException(ErrorMsg.REPL_LOAD_PATH_NOT_FOUND.getMsg()); } FileStatus[] statuses = loadPathBase.getFileSystem(conf).listStatus(loadPathBase); if (statuses.length > 0) { FileStatus latestUpdatedStatus = statuses[0]; for (FileStatus status : statuses) { if (status.getModificationTime() > latestUpdatedStatus.getModificationTime()) { latestUpdatedStatus = status; } } Path hiveDumpPath = new Path(latestUpdatedStatus.getPath(), ReplUtils.REPL_HIVE_BASE_DIR); if (loadPathBase.getFileSystem(conf).exists(new Path(hiveDumpPath, ReplUtils.DUMP_ACKNOWLEDGEMENT)) && !loadPathBase.getFileSystem(conf).exists(new Path(hiveDumpPath, ReplUtils.LOAD_ACKNOWLEDGEMENT))) { return hiveDumpPath; } } return null; }
Source:
public void uploadSnapshotTest_fromCurrentLive() throws IOException, InterruptedException, ExecutionException{ String indexName = getLiveIndex(); File snapshot = null; try { snapshot = esIndexAPI.createSnapshot(ESIndexAPI.BACKUP_REPOSITORY, "backup", indexName); esIndexAPI.closeIndex(indexName); esIndexAPI.delete(indexName); ZipFile file = new ZipFile(snapshot.getAbsolutePath()); String pathToRepo = Config.getStringProperty("es.path.repo","test-resources"); File tempDir = new File(pathToRepo); boolean response = esIndexAPI.uploadSnapshot(file, tempDir.getAbsolutePath(), "backup"); assertTrue(response); } catch (DotStateException | IllegalArgumentException | IOException e) { e.printStackTrace(); }finally{ snapshot.delete(); } }

Target:
public void uploadSnapshotTest_fromCurrentLive() throws IOException, InterruptedException, ExecutionException{ String indexName = getLiveIndex(); File snapshot = null; snapshot = esIndexAPI.createSnapshot(ESIndexAPI.BACKUP_REPOSITORY, "backup", indexName); esIndexAPI.closeIndex(indexName); ZipFile file = new ZipFile(snapshot.getAbsolutePath()); String pathToRepo = Config.getStringProperty("es.path.repo","test-resources"); File tempDir = new File(pathToRepo); boolean response = esIndexAPI.uploadSnapshot(file, tempDir.getAbsolutePath()); assertTrue(response); if(snapshot!=null){ snapshot.delete(); } }
Source:
ResolutionScreen(MenuLayout menuLayout, GameOptions gameOptions) { displayDimensions = SolApplication.displayDimensions; resolutionControl = new SolUiControl(menuLayout.buttonRect(-1, 1), true); resolutionControl.setDisplayName("Resolution"); controls.add(resolutionControl); fullscreenControl = new SolUiControl(menuLayout.buttonRect(-1, 2), true); fullscreenControl.setDisplayName("Fullscreen"); controls.add(fullscreenControl); nuiUIScaleControl = new SolUiControl(menuLayout.buttonRect(-1, 3), true); nuiUIScaleControl.setDisplayName("Map Pan Speed"); controls.add(nuiUIScaleControl); closeControl = new SolUiControl(menuLayout.buttonRect(-1, 4), true, gameOptions.getKeyEscape()); closeControl.setDisplayName("Back"); controls.add(closeControl); backgroundTexture = Assets.getAtlasRegion("engine:mainMenuBg", Texture.TextureFilter.Linear); }

Target:
ResolutionScreen(MenuLayout menuLayout, GameOptions gameOptions) { displayDimensions = SolApplication.displayDimensions; resolutionControl = new SolUiControl(menuLayout.buttonRect(-1, 1), true); resolutionControl.setDisplayName("Resolution"); controls.add(resolutionControl); fullscreenControl = new SolUiControl(menuLayout.buttonRect(-1, 2), true); fullscreenControl.setDisplayName("Fullscreen"); controls.add(fullscreenControl); nuiUIScaleControl = new SolUiControl(menuLayout.buttonRect(-1, 3), true); nuiUIScaleControl.setDisplayName("NUI UI scale"); controls.add(nuiUIScaleControl); closeControl = new SolUiControl(menuLayout.buttonRect(-1, 4), true, gameOptions.getKeyEscape()); closeControl.setDisplayName("Back"); controls.add(closeControl); backgroundTexture = Assets.getAtlasRegion("engine:mainMenuBg", Texture.TextureFilter.Linear); }
Source:
protected void createPreparedStatement(Connection db) throws SQLException { findDefaultAutoIncrementingColumn(db); ColumnId incrementingColumn = null; if (incrementingColumnName != null && !incrementingColumnName.isEmpty()) { incrementingColumn = new ColumnId(tableId, incrementingColumnName); } ExpressionBuilder builder = dialect.expressionBuilder(); switch (mode) { case TABLE: builder.append("SELECT * FROM "); builder.append(tableId); break; case QUERY: builder.append(query); break; default: throw new ConnectException("Unknown mode encountered when preparing query: " + mode); } criteria = dialect.criteriaFor(incrementingColumn, timestampColumns, suffix); criteria.whereClause(builder); String queryString = builder.toString(); recordQuery(queryString); log.debug("{} prepared SQL query: {}", this, queryString); stmt = dialect.createPreparedStatement(db, queryString); }

Target:
protected void createPreparedStatement(Connection db) throws SQLException { findDefaultAutoIncrementingColumn(db); ColumnId incrementingColumn = null; if (incrementingColumnName != null && !incrementingColumnName.isEmpty()) { incrementingColumn = new ColumnId(tableId, incrementingColumnName); } ExpressionBuilder builder = dialect.expressionBuilder(); switch (mode) { case TABLE: builder.append("SELECT * FROM "); builder.append(tableId); break; case QUERY: builder.append(query); break; default: throw new ConnectException("Unknown mode encountered when preparing query: " + mode); } criteria = dialect.criteriaFor(incrementingColumn, timestampColumns); criteria.whereClause(builder); addSuffixIfPresent(builder); String queryString = builder.toString(); recordQuery(queryString); log.debug("{} prepared SQL query: {}", this, queryString); stmt = dialect.createPreparedStatement(db, queryString); }
Source:
public static Wallet fromKeys(NetworkParameters params, List<ECKey> keys) { for (ECKey key : keys) checkArgument(key.getClass().equals(ECKey.class)); KeyChainGroup group = new KeyChainGroup(params); group.importKeys(keys); return new Wallet(params, group); }

Target:
public static Wallet fromKeys(NetworkParameters params, List<ECKey> keys) { for (ECKey key : keys) checkArgument(!(key instanceof DeterministicKey)); KeyChainGroup group = new KeyChainGroup(params); group.importKeys(keys); return new Wallet(params, group); }
Source:
public static String isRetrospectiveVisit(Visit visit) { String retrospective = "false"; for (Encounter e : visit.getEncounters()) { if (e.getEncounterType().getUuid().equals(MetadataConstants.HIV_RETROSPECTIVE_ENCOUNTER_TYPE_UUID)) { retrospective = "true"; break; } } return retrospective; }

Target:
public static boolean isRetrospectiveVisit(Visit visit) { boolean retrospective = false; for (Encounter e : visit.getEncounters()) { if (e.getEncounterType().getUuid().equals(MetadataConstants.HIV_RETROSPECTIVE_ENCOUNTER_TYPE_UUID)) { retrospective = true; break; } } return retrospective; }
Source:
private String _cleanLongFilename(String fname) { int namemax = 136; int pathmax = 1024; int dirlen = fname.length(); int remaining = pathmax - dirlen; namemax = min(remaining, namemax); assert(namemax>0); if (fname.length() > namemax) { int lastSlash = fname.indexOf("/"); int lastDot = fname.indexOf("."); if (lastDot == -1 || lastDot < lastSlash) { fname = fname.substring(0, namemax); } else { String ext = fname.substring(lastDot+1); String head = fname.substring(0, lastDot); int headmax = namemax - ext.length(); head = head.substring(0, headmax); fname = head + ext; assert (fname.length() <= namemax); } } return fname; }

Target:
private String _cleanLongFilename(String fname) { int namemax = 136; int pathmax = 1024; int dirlen = fname.length(); int remaining = pathmax - dirlen; namemax = min(remaining, namemax); Assert.that(namemax>0, "The media directory is maximally long. There is no more length available for file name."); if (fname.length() > namemax) { int lastSlash = fname.indexOf("/"); int lastDot = fname.indexOf("."); if (lastDot == -1 || lastDot < lastSlash) { fname = fname.substring(0, namemax); } else { String ext = fname.substring(lastDot+1); String head = fname.substring(0, lastDot); int headmax = namemax - ext.length(); head = head.substring(0, headmax); fname = head + ext; Assert.that (fname.length() <= namemax, "The length of the file is greater than the maximal name value."); } } return fname; }
Source:
private OnHeapValueHolder<V> internalGet(final K key, final boolean updateAccess) throws CacheAccessException { getObserver.begin(); try { final AtomicReference<OnHeapValueHolder<V>> expiredValue = new AtomicReference<OnHeapValueHolder<V>>(null); OnHeapValueHolder<V> result = map.computeIfPresent(key, new BiFunction<K, OnHeapValueHolder<V>, OnHeapValueHolder<V>>() { @Override public OnHeapValueHolder<V> apply(K mappedKey, OnHeapValueHolder<V> mappedValue) { final long now = timeSource.getTimeMillis(); if (mappedValue.isExpired(now, TimeUnit.MILLISECONDS)) { onExpiration(mappedKey, mappedValue); expiredValue.set(mappedValue); return null; } if (updateAccess) { return setAccessTimeAndExpiryThenReturnMapping(key, mappedValue, now, false); } return mappedValue; } }); if (result == null) { getObserver.end(StoreOperationOutcomes.GetOutcome.MISS); if (byteSized && expiredValue.get() != null) { decrementCurrentUsageInBytesIfRequired(getSizeOfKeyWithOffset(key) + getSizeOfValueWithOffset(expiredValue.get().value()) + sizeOfEngine.getCHMOffset()); } } else { getObserver.end(StoreOperationOutcomes.GetOutcome.HIT); } return result; } catch (RuntimeException re) { handleRuntimeException(re); return null; } }

Target:
private OnHeapValueHolder<V> internalGet(final K key, final boolean updateAccess) throws CacheAccessException { getObserver.begin(); try { final AtomicReference<OnHeapValueHolder<V>> expiredValue = new AtomicReference<OnHeapValueHolder<V>>(null); OnHeapValueHolder<V> result = map.computeIfPresent(key, new BiFunction<K, OnHeapValueHolder<V>, OnHeapValueHolder<V>>() { @Override public OnHeapValueHolder<V> apply(K mappedKey, OnHeapValueHolder<V> mappedValue) { final long now = timeSource.getTimeMillis(); if (mappedValue.isExpired(now, TimeUnit.MILLISECONDS)) { onExpiration(mappedKey, mappedValue); expiredValue.set(mappedValue); return null; } if (updateAccess) { return setAccessTimeAndExpiryThenReturnMapping(key, mappedValue, now, false); } return mappedValue; } }); if (result == null) { getObserver.end(StoreOperationOutcomes.GetOutcome.MISS); if (expiredValue.get() != null) { decrementCurrentUsageInBytesIfRequired(expiredValue.get().size()); } } else { getObserver.end(StoreOperationOutcomes.GetOutcome.HIT); } return result; } catch (RuntimeException re) { handleRuntimeException(re); return null; } }
Source:
private void initNetworkModels() { Map<String, LogicalNetworkModel> networkModels = new HashMap<>(); for (Network network : allNetworks) { ReportedConfigurations reportedConfigurations = reportedConfigurationByNetworkId(network.getId()); LogicalNetworkModel networkModel = new LogicalNetworkModel(network, reportedConfigurations, this); networkModels.put(network.getName(), networkModel); if (networkModel.isManagement()) { managementNetworkModel = networkModel; } if (!network.isExternal()) { String label = network.getLabel(); if (label != null) { networkLabelMap.get(label).getNetworks().add(networkModel); } } } setNetworks(networkModels); }

Target:
private void initNetworkModels() { Map<String, LogicalNetworkModel> networkModels = new HashMap<>(); for (Network network : allNetworks) { LogicalNetworkModel networkModel = new LogicalNetworkModel(network, this); networkModels.put(network.getName(), networkModel); if (networkModel.isManagement()) { managementNetworkModel = networkModel; } if (!network.isExternal()) { String label = network.getLabel(); if (label != null) { networkLabelMap.get(label).getNetworks().add(networkModel); } } } setNetworks(networkModels); }
Source:
protected void addAddRedeployLinksSteps(CommandContext ctx, ModelNode steps, String overlay, String serverGroup, String[] links, boolean regexp) throws CommandLineException { boolean warn = false; for(String link : links) { final ModelNode op = new ModelNode(); final ModelNode address = op.get(Util.ADDRESS); if(serverGroup != null) { address.add(Util.SERVER_GROUP, serverGroup); } address.add(Util.DEPLOYMENT_OVERLAY, overlay); address.add(Util.DEPLOYMENT, link); op.get(Util.OPERATION).set(Util.ADD); steps.add(op); if (redeployAffected.isPresent(ctx.getParsedCommandLine())) { final List<String> matchingDeployments = Util.getMatchingDeployments(ctx.getModelControllerClient(), link, serverGroup, true); if (!matchingDeployments.isEmpty()) { if (serverGroup == null) { for (String deployment : matchingDeployments) { final ModelNode step = new ModelNode(); final ModelNode addr = step.get(Util.ADDRESS); addr.add(Util.DEPLOYMENT, deployment); step.get(Util.OPERATION).set(Util.REDEPLOY); steps.add(step); } } else { for (String deployment : matchingDeployments) { final ModelNode step = new ModelNode(); final ModelNode addr = step.get(Util.ADDRESS); addr.add(Util.SERVER_GROUP, serverGroup); addr.add(Util.DEPLOYMENT, deployment); step.get(Util.OPERATION).set(Util.REDEPLOY); steps.add(step); } } } } else { warn = true; } } if (warn) { String warningMsg = serverGroup == null ? "WARNING: redeployment is required on deployment " + Arrays.toString(links) : "WARNING: redeployment is required on deployment " + Arrays.toString(links) + " in server group " + serverGroup; ctx.printLine(warningMsg); } }

Target:
protected void addAddRedeployLinksSteps(CommandContext ctx, ModelNode steps, String overlay, String serverGroup, String[] links, boolean regexp) throws CommandLineException { boolean warn = false; for(String link : links) { final ModelNode op = new ModelNode(); final ModelNode address = op.get(Util.ADDRESS); if(serverGroup != null) { address.add(Util.SERVER_GROUP, serverGroup); } address.add(Util.DEPLOYMENT_OVERLAY, overlay); address.add(Util.DEPLOYMENT, link); op.get(Util.OPERATION).set(Util.ADD); steps.add(op); if (redeployAffected.isPresent(ctx.getParsedCommandLine())) { final List<String> matchingDeployments = Util.getMatchingDeployments(ctx.getModelControllerClient(), link, serverGroup, true); if (!matchingDeployments.isEmpty()) { if (serverGroup == null) { for (String deployment : matchingDeployments) { final ModelNode step = new ModelNode(); final ModelNode addr = step.get(Util.ADDRESS); addr.add(Util.DEPLOYMENT, deployment); step.get(Util.OPERATION).set(Util.REDEPLOY); steps.add(step); } } else { for (String deployment : matchingDeployments) { final ModelNode step = new ModelNode(); final ModelNode addr = step.get(Util.ADDRESS); addr.add(Util.SERVER_GROUP, serverGroup); addr.add(Util.DEPLOYMENT, deployment); step.get(Util.OPERATION).set(Util.REDEPLOY); steps.add(step); } } } } else { warn = true; } } if (warn) { String warningMsg = serverGroup == null ? WARN_MSG + Arrays.toString(links) : WARN_MSG + Arrays.toString(links) + " in server group " + serverGroup; ctx.printLine(warningMsg); } }
Source:
public ClientResponse<InputStream> handleResponse(HttpResponse response, TrafficCop trafficCop) { ChannelBufferInputStream channelStream = null; try { channelStream = new ChannelBufferInputStream(response.getContent()); queue.put(channelStream); } catch (InterruptedException e) { log.error(e, "Queue appending interrupted"); Thread.currentThread().interrupt(); throw new RuntimeException(e); } finally { if (channelStream != null) { try { channelStream.close(); } catch (IOException e) { log.error(e, "Unable to close the channel buffer"); } } } byteCount.addAndGet(response.getContent().readableBytes()); return ClientResponse.finished( new SequenceInputStream( new Enumeration<InputStream>() { @Override public boolean hasMoreElements() { synchronized (done) { return !done.get() || !queue.isEmpty(); } } @Override public InputStream nextElement() { try { return queue.take(); } catch (InterruptedException e) { log.warn(e, "Thread interrupted while taking from queue"); Thread.currentThread().interrupt(); throw new RuntimeException(e); } } } ) ); }

Target:
public ClientResponse<InputStream> handleResponse(HttpResponse response, TrafficCop trafficCop) { ChannelBufferInputStream channelStream = null; try { channelStream = new ChannelBufferInputStream(response.getContent()); queue.put(channelStream); } catch (InterruptedException e) { log.error(e, "Queue appending interrupted"); Thread.currentThread().interrupt(); throw new RuntimeException(e); } finally { CloseQuietly.close(channelStream); } byteCount.addAndGet(response.getContent().readableBytes()); return ClientResponse.finished( new SequenceInputStream( new Enumeration<InputStream>() { @Override public boolean hasMoreElements() { synchronized (done) { return !done.get() || !queue.isEmpty(); } } @Override public InputStream nextElement() { try { return queue.take(); } catch (InterruptedException e) { log.warn(e, "Thread interrupted while taking from queue"); Thread.currentThread().interrupt(); throw new RuntimeException(e); } } } ) ); }
Source:
public ErrorEntityWriterTestResourceConfig() { super(true, new MetricRegistry()); register(DefaultLoggingExceptionMapper.class); register(DefaultJacksonMessageBodyProvider.class); register(ExceptionResource.class); register(new ErrorEntityWriter<ErrorMessage, String>(MediaType.TEXT_HTML_TYPE, String.class) { @Override protected String getRepresentation(ErrorMessage entity) { return "Uh oh: " + entity.getMessage(); } }); }

Target:
public ErrorEntityWriterTestResourceConfig() { super(true, new MetricRegistry()); register(DefaultLoggingExceptionMapper.class); register(DefaultJacksonMessageBodyProvider.class); register(ExceptionResource.class); register(new ErrorEntityWriter<ErrorMessage, String>(MediaType.TEXT_HTML_TYPE, String.class) { @Override protected String getRepresentation(ErrorMessage entity) { return "<!DOCTYPE html><html><body>" + entity.getMessage() + "</body></html>"; } }); }
Source:
private void showUsageReportingDialog(RestApi restApi) { final DialogInterface.OnClickListener listener = (dialog, which) -> { if (restApi == null) { Toast.makeText(MainActivity.this, R.string.syncthing_terminated, Toast.LENGTH_SHORT).show(); return; } try { switch (which) { case DialogInterface.BUTTON_POSITIVE: restApi.setUsageReporting(true); restApi.restart(); break; case DialogInterface.BUTTON_NEGATIVE: restApi.setUsageReporting(false); restApi.restart(); break; case DialogInterface.BUTTON_NEUTRAL: Uri uri = Uri.parse("<LINK_0>"); startActivity(new Intent(Intent.ACTION_VIEW, uri)); break; } } catch (Exception e) { Log.e(TAG, "showUsageReportingDialog:OnClickListener", e); } }; if (restApi == null) { return; } restApi.getUsageReport(report -> { @SuppressLint("InflateParams") View v = LayoutInflater.from(MainActivity.this) .inflate(R.layout.dialog_usage_reporting, null); TextView tv = v.findViewById(R.id.example); tv.setText(report); new AlertDialog.Builder(MainActivity.this) .setTitle(R.string.usage_reporting_dialog_title) .setView(v) .setPositiveButton(R.string.yes, listener) .setNegativeButton(R.string.no, listener) .setNeutralButton(R.string.open_website, listener) .show(); }); }

Target:
private void showUsageReportingDialog(RestApi restApi) { final DialogInterface.OnClickListener listener = (dialog, which) -> { try { switch (which) { case DialogInterface.BUTTON_POSITIVE: restApi.setUsageReporting(true); restApi.saveConfigAndRestart(); break; case DialogInterface.BUTTON_NEGATIVE: restApi.setUsageReporting(false); restApi.saveConfigAndRestart(); break; case DialogInterface.BUTTON_NEUTRAL: Uri uri = Uri.parse("<LINK_0>"); startActivity(new Intent(Intent.ACTION_VIEW, uri)); break; } } catch (Exception e) { Log.e(TAG, "showUsageReportingDialog:OnClickListener", e); } }; restApi.getUsageReport(report -> { @SuppressLint("InflateParams") View v = LayoutInflater.from(MainActivity.this) .inflate(R.layout.dialog_usage_reporting, null); TextView tv = v.findViewById(R.id.example); tv.setText(report); new AlertDialog.Builder(MainActivity.this) .setTitle(R.string.usage_reporting_dialog_title) .setView(v) .setPositiveButton(R.string.yes, listener) .setNegativeButton(R.string.no, listener) .setNeutralButton(R.string.open_website, listener) .show(); }); }
Source:
public boolean retainAll(Collection<?> c) { boolean changed = false; Object[] retainAll = c.toArray(); outer: for (Iterator<E> iterator = iterator(); iterator.hasNext();) { E element = iterator.next(); for (Object retainAll1 : retainAll) { if (element == retainAll1) { continue outer; } } iterator.remove(); changed = true; } return changed; }

Target:
public boolean retainAll(Collection<?> c) { boolean changed = false; outer: for (Iterator<E> iterator = iterator(); iterator.hasNext();) { E element = iterator.next(); for (Object retain : c) { if (element == retain) { continue outer; } } iterator.remove(); changed = true; } return changed; }
Source:
@Override public void onKernalStop(boolean cancel) { cacheStartedLatch.countDown(); GridCachePartitionExchangeManager<Object, Object> exch = context().exchange(); exch.onKernalStop(cancel); for (GridCacheAdapter<?, ?> cache : caches.values()) { GridCacheAffinityManager aff = cache.context().affinity(); if (aff != null) aff.onKernalStop(true); } for (String cacheName : stopSeq) { GridCacheAdapter<?, ?> cache = caches.remove(maskNull(cacheName)); if (cache != null) { stoppedCaches.put(maskNull(cacheName), cache); onKernalStop(cache, cancel); } } for (Map.Entry<String, GridCacheAdapter<?, ?>> entry : caches.entrySet()) { GridCacheAdapter<?, ?> cache = entry.getValue(); if (cache == caches.remove(entry.getKey())) { stoppedCaches.put(entry.getKey(), cache); onKernalStop(entry.getValue(), cancel); } } cancelFutures(); List<? extends GridCacheSharedManager<?, ?>> sharedMgrs = sharedCtx.managers(); for (ListIterator<? extends GridCacheSharedManager<?, ?>> it = sharedMgrs.listIterator(sharedMgrs.size()); it.hasPrevious();) { GridCacheSharedManager<?, ?> mgr = it.previous(); if (mgr != exch) mgr.onKernalStop(cancel); } }

Target:
@Override public void onKernalStop(boolean cancel) { cacheStartedLatch.countDown(); GridCachePartitionExchangeManager<Object, Object> exch = context().exchange(); exch.onKernalStop(cancel); for (GridCacheAdapter<?, ?> cache : caches.values()) { GridCacheAffinityManager aff = cache.context().affinity(); if (aff != null) aff.cancelFutures(); } for (String cacheName : stopSeq) { GridCacheAdapter<?, ?> cache = caches.remove(maskNull(cacheName)); if (cache != null) { stoppedCaches.put(maskNull(cacheName), cache); onKernalStop(cache, cancel); } } for (Map.Entry<String, GridCacheAdapter<?, ?>> entry : caches.entrySet()) { GridCacheAdapter<?, ?> cache = entry.getValue(); if (cache == caches.remove(entry.getKey())) { stoppedCaches.put(entry.getKey(), cache); onKernalStop(entry.getValue(), cancel); } } cancelFutures(); List<? extends GridCacheSharedManager<?, ?>> sharedMgrs = sharedCtx.managers(); for (ListIterator<? extends GridCacheSharedManager<?, ?>> it = sharedMgrs.listIterator(sharedMgrs.size()); it.hasPrevious();) { GridCacheSharedManager<?, ?> mgr = it.previous(); if (mgr != exch) mgr.onKernalStop(cancel); } }
Source:
public void addSiteMapEntries(SiteMapGeneratorConfiguration smgc, SiteMapBuilder siteMapBuilder) { if (smgc instanceof CategorySiteMapGeneratorConfiguration) { CategorySiteMapGeneratorConfiguration categorySMGC = (CategorySiteMapGeneratorConfiguration) smgc; Long rootCategoryId = categorySMGC.getRootCategory().getId(); Category rootCategory = categoryDao.readCategoryById(rootCategoryId); addCategorySiteMapEntries(rootCategory, 0, categorySMGC, siteMapBuilder); } }

Target:
public void addSiteMapEntries(SiteMapGeneratorConfiguration smgc, SiteMapBuilder siteMapBuilder) { if (CategorySiteMapGeneratorConfiguration.class.isAssignableFrom(smgc.getClass())) { CategorySiteMapGeneratorConfiguration categorySMGC = (CategorySiteMapGeneratorConfiguration) smgc; Long rootCategoryId = categorySMGC.getRootCategory().getId(); Category rootCategory = categoryDao.readCategoryById(rootCategoryId); addCategorySiteMapEntries(rootCategory, 0, categorySMGC, siteMapBuilder); } }
Source:
private void createPath(String parentPath, boolean removeParentsIfCreated) { try { curator.create().creatingParentsIfNeeded().forPath(parentPath); if (removeParentsIfCreated) { parentsIBuilt.add(parentPath); } } catch (Exception e) { log.info(e, "Problem creating parentPath[%s], someone else created it first?", parentPath); } }

Target:
private void createPath(String parentPath, boolean removeParentsIfCreated) { try { curator.create().creatingParentsIfNeeded().forPath(parentPath); if (removeParentsIfCreated) { parentsIBuilt.add(parentPath); } log.debug("Created parentPath[%s], %s remove on stop.", parentPath, removeParentsIfCreated ? "will" : "will not"); } catch (Exception e) { log.info(e, "Problem creating parentPath[%s], someone else created it first?", parentPath); } }
Source:
public AnnotationCommandHandlerAdapter(Object annotatedCommandHandler, ParameterResolverFactory parameterResolverFactory) { this(annotatedCommandHandler, parameterResolverFactory, new ClasspathHandlerDefinition(Thread.currentThread().getContextClassLoader())); }

Target:
public AnnotationCommandHandlerAdapter(Object annotatedCommandHandler, ParameterResolverFactory parameterResolverFactory) { this(annotatedCommandHandler, parameterResolverFactory, ClasspathHandlerDefinition.forClass(annotatedCommandHandler.getClass())); }
Source:
public Map<BaggageField, String> mergeState(Map<BaggageField, String> state, BaggageField field, String value) { if (equal(value, state.get(field))) return state; if (value == null) { if (!state.containsKey(field)) return state; if (state.size() == 1) return null; } LinkedHashMap<BaggageField, String> mergedState = new LinkedHashMap<>(state); if (value != null) { mergedState.put(field, value); } else { mergedState.remove(field); } return mergedState; }

Target:
public Map<BaggageField, String> mergeState(Map<BaggageField, String> state, BaggageField field, String value) { if (equal(value, state.get(field))) return state; if (value == null) { if (!state.containsKey(field)) return state; if (state.size() == 1) return null; } LinkedHashMap<BaggageField, String> mergedState = new LinkedHashMap<>(state); mergedState.put(field, value); return mergedState; }
Source:
public static String getDecryptedData(String message) { String[] lines = splitIntoLines(message, true); int charCount = 0; for (int i = 0; i < key; ++i) { while (lines[i].contains("?")) { String letter = String.valueOf(message.charAt(charCount)); lines[i] = lines[i].replaceFirst("\\?", letter); charCount++; } } String result = ""; int lineCount = 0; int direction = -1; for (int i = 0; i < message.length(); ++i) { String letter = String.valueOf(lines[lineCount].charAt(0)); lines[lineCount] = lines[lineCount].substring(1); result += letter; direction *= lineCount == 0 || lineCount == key - 1 ? -1 : 1; lineCount += direction; } return result; }

Target:
String getDecryptedData(String message) { String[] lines = splitIntoLines(message, true); int charCount = 0; for (int i = 0; i < key; ++i) { while (lines[i].contains("?")) { String letter = String.valueOf(message.charAt(charCount)); lines[i] = lines[i].replaceFirst("\\?", letter); charCount++; } } StringBuilder result = new StringBuilder(); int lineCount = 0; int direction = -1; for (int i = 0; i < message.length(); ++i) { String letter = String.valueOf(lines[lineCount].charAt(0)); lines[lineCount] = lines[lineCount].substring(1); result.append(letter); direction *= lineCount == 0 || lineCount == key - 1 ? -1 : 1; lineCount += direction; } return result.toString(); }
Source:
public MqttWillAndTestament(String topic, byte[] payload, int qos, boolean retain) { this.topic = topic; this.payload = payload; this.qos = qos; this.retain = retain; if (StringUtils.isBlank(this.topic)) { throw new IllegalArgumentException("Topic must be set"); } }

Target:
public MqttWillAndTestament(String topic, byte[] payload, int qos, boolean retain) { if (StringUtils.isBlank(topic)) { throw new IllegalArgumentException("Topic must be set"); } this.topic = topic; this.payload = payload; this.qos = qos; this.retain = retain; }
Source:
public void commit() { if (!newObjects.isEmpty() || !objectsToDelete.isEmpty()) { repository().write(writer -> { writer.putAll(newObjects); writer.removeAll(objectsToDelete); writer.commit(); return null; }); if (!newObjects.isEmpty()) { WhiteListNotification.added(newObjects.keySet()).publish(service(IEventBus.class)); } else if (!objectsToDelete.isEmpty()) { WhiteListNotification.removed(Iterables.getOnlyElement(objectsToDelete.values())).publish(service(IEventBus.class)); } } }

Target:
public void commit() { if (!newObjects.isEmpty() || !objectsToDelete.isEmpty()) { repository().write(writer -> { writer.putAll(newObjects); writer.removeAll(objectsToDelete); writer.commit(); return null; }); if (!newObjects.isEmpty()) { WhiteListNotification.added(newObjects.keySet()).publish(service(IEventBus.class)); } if (!objectsToDelete.isEmpty()) { WhiteListNotification.removed(Iterables.getOnlyElement(objectsToDelete.values())).publish(service(IEventBus.class)); } } }
Source:
protected RelationState resolveState(List<BinaryRelation> knownRelations) { if (hasSameOperand()) { return relationStateForSameOperand(); } List<BinaryRelation> allRelations = deduce(knownRelations); for (BinaryRelation relation : allRelations) { RelationState result = relation.implies(this); if (result.isDetermined()) { return result; } } return RelationState.UNDETERMINED; }

Target:
protected RelationState resolveState(List<BinaryRelation> knownRelations) { if (hasSameOperand()) { return relationStateForSameOperand(); } Set<BinaryRelation> allRelations = new HashSet<>(knownRelations); Deque<BinaryRelation> workList = new ArrayDeque<>(knownRelations); int iterations = 0; while (!workList.isEmpty()) { if (allRelations.size() > MAX_DEDUCED_RELATIONS || iterations > MAX_ITERATIONS) { throw new TransitiveRelationExceededException("Used relations: " + allRelations.size() + ". Iterations " + iterations); } iterations++; BinaryRelation relation = workList.pop(); RelationState result = relation.implies(this); if (result.isDetermined()) { return result; } List<BinaryRelation> newRelations = allRelations.stream() .map(relation::deduceTransitiveOrSimplified) .filter(Objects::nonNull) .filter(r -> !allRelations.contains(r)) .collect(Collectors.toList()); allRelations.addAll(newRelations); workList.addAll(newRelations); } return RelationState.UNDETERMINED; }
Source:
public void compute(final IterableInterval<T> input, final DoubleType output) { final double[][] matrix = getCooccurrenceMatrix(input); final double[] pxminusy = coocPXMinusYFunc.calculate(matrix); double m = 0.0; for (int i = 0; i < numGreyLevels; i++) { m += i * pxminusy[i]; } double sum = 0.0d; for (int k = 0; k < numGreyLevels; k++) { sum += Math.pow(k - m, 2) * pxminusy[k]; } output.set(sum); }

Target:
public void compute(final IterableInterval<T> input, final DoubleType output) { final double[][] matrix = getCooccurrenceMatrix(input); final double[] pxminusy = coocPXMinusYFunc.calculate(matrix); double mu = 0.0; for (int i = 0; i < numGreyLevels; i++) { mu += i * pxminusy[i]; } double sum = 0.0d; for (int k = 0; k < numGreyLevels; k++) { sum += Math.pow(k - mu, 2) * pxminusy[k]; } output.set(sum); }
Source:
public void testMerge() throws Exception { cache.put("A", "B"); cache.merge("A", "C", (oldValue, newValue) -> "" + oldValue + newValue); assertEquals("BC", cache.get("A")); cache.merge("A", "C", (oldValue, newValue) -> null); assertNull(cache.get("A")); cache.merge("F", "42", (oldValue, newValue) -> "" + oldValue + newValue); assertEquals("42", cache.get("F")); cache.put("A", "B"); RuntimeException mergeRaisedException = new RuntimeException("hi there"); expectException(RuntimeException.class, "hi there", () -> cache.merge("A", "C", (k, v) -> { throw mergeRaisedException; })); }

Target:
public void testMerge() throws Exception { cache.put("A", "B"); cache.merge("A", "C", (oldValue, newValue) -> "" + oldValue + newValue); assertEquals("BC", cache.get("A")); cache.merge("A", "C", (oldValue, newValue) -> null); assertEquals(null, cache.get("A")); cache.merge("F", "42", (oldValue, newValue) -> "" + oldValue + newValue); assertEquals("42", cache.get("F")); cache.put("A", "B"); RuntimeException mergeRaisedException = new RuntimeException("hi there"); expectException(RuntimeException.class, "hi there", () -> cache.merge("A", "C", (k, v) -> { throw mergeRaisedException; })); }