auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testAttachAndWrite() throws Exception { final int nEvents = index.getTotalEventCount(); final Index index = this.index; Socket socket = this.tcpInput.attach(); PrintStream output = new PrintStream(socket.getOutputStream()); output.print(createTimestamp() + " Boris the mad baboon!\r\n"); output.flush(); socket.close(); SplunkTestCase.assertEventuallyTrue(new EventuallyTrueBehavior() { public boolean predicate() { index.refresh(); return index.getTotalEventCount() == nEvents + 1; } }); }

Target:
public void testAttachAndWrite() { final int nEvents = index.getTotalEventCount(); final Index index = this.index; try { Socket socket = this.tcpInput.attach(); PrintStream output = new PrintStream(socket.getOutputStream()); output.print(createTimestamp() + " Boris the mad baboon!\r\n"); output.flush(); socket.close(); } catch (IOException e) { SplunkTestCase.fail("Got an IO exception in attaching."); } SplunkTestCase.assertEventuallyTrue(new EventuallyTrueBehavior() { public boolean predicate() { index.refresh(); return index.getTotalEventCount() == nEvents + 1; } }); }
Source:
private void doBackupCheck() { final int DAY_IN_MILLISEC= 60 * 60 * 24 *1000; AuditLogableBase alert = new AuditLogableBase(); EngineBackupHistory lastBackup = DbFacade.getInstance().getEngineBackupHistoryDAO().getLastSuccessfulEngineBackup(DB); if (lastBackup == null) { auditLogDirector.log(alert, AuditLogType.ENGINE_NO_BACKUP); } else { if (Config.<Boolean>getValue(ConfigValues.BackupAlertPeriodInDays)) { Integer backupAlertPeriodInDays = Config.<Integer> getValue(ConfigValues.BackupAlertPeriodInDays); Date dt = lastBackup.getDoneAt(); long diffInDays = (Calendar.getInstance().getTimeInMillis() - dt.getTime())/DAY_IN_MILLISEC; if (diffInDays > backupAlertPeriodInDays) { alert.addCustomValue("Date", lastBackup.getDoneAt().toString()); auditLogDirector.log(alert, AuditLogType.ENGINE_NO_WARM_BACKUP); } } } }

Target:
private void doBackupCheck() { AuditLogableBase alert = new AuditLogableBase(); EngineBackupLog lastBackup = engineBackupLogDAO.getLastSuccessfulEngineBackup(ENGINE_DB_ID); if (lastBackup == null) { auditLogDirector.log(alert, AuditLogType.ENGINE_NO_BACKUP); } else { if (Config.<Boolean>getValue(ConfigValues.BackupAlertPeriodInDays)) { Integer backupAlertPeriodInDays = Config.<Integer>getValue(ConfigValues.BackupAlertPeriodInDays); Date dt = lastBackup.getDoneAt(); long diffInDays = (Calendar.getInstance().getTimeInMillis() - dt.getTime()) / TimeUnit.DAYS.toMillis(1); if (diffInDays > backupAlertPeriodInDays) { alert.addCustomValue("Date", lastBackup.getDoneAt().toString()); auditLogDirector.log(alert, AuditLogType.ENGINE_NO_WARM_BACKUP); } } } }
Source:
private void teleportAAllPlayers(final Server server, final CommandSource sender, final User target) { sender.sendMessage(tl("teleportAAll")); for (User player : ess.getOnlineUsers()) { if (target == player) { continue; } if (!player.isTeleportEnabled()) { continue; } if (sender.equals(target.getBase()) && target.getWorld() != player.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !target.isAuthorized("essentials.worlds." + target.getWorld().getName())) { continue; } try { TPARequestEvent tpaEvent = new TPARequestEvent(sender, player, true); ess.getServer().getPluginManager().callEvent(tpaEvent); if(tpaEvent.isCancelled()) { return; } player.requestTeleport(target, true); player.sendMessage(tl("teleportHereRequest", target.getDisplayName())); player.sendMessage(tl("typeTpaccept")); if (ess.getSettings().getTpaAcceptCancellation() != 0) { player.sendMessage(tl("teleportRequestTimeoutInfo", ess.getSettings().getTpaAcceptCancellation())); } } catch (Exception ex) { ess.showError(sender, ex, getName()); } } }

Target:
private void teleportAAllPlayers(final Server server, final CommandSource sender, final User target) { sender.sendMessage(tl("teleportAAll")); for (User player : ess.getOnlineUsers()) { if (target == player) { continue; } if (!player.isTeleportEnabled()) { continue; } if (sender.equals(target.getBase()) && target.getWorld() != player.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !target.isAuthorized("essentials.worlds." + target.getWorld().getName())) { continue; } try { TPARequestEvent tpaEvent = new TPARequestEvent(sender, player, true); ess.getServer().getPluginManager().callEvent(tpaEvent); if (tpaEvent.isCancelled()) { sender.sendMessage(tl("teleportRequestCancelled", player.getDisplayName())); continue; } player.requestTeleport(target, true); player.sendMessage(tl("teleportHereRequest", target.getDisplayName())); player.sendMessage(tl("typeTpaccept")); if (ess.getSettings().getTpaAcceptCancellation() != 0) { player.sendMessage(tl("teleportRequestTimeoutInfo", ess.getSettings().getTpaAcceptCancellation())); } } catch (Exception ex) { ess.showError(sender, ex, getName()); } } }
Source:
private ORawBuffer readRecordIfNotLatest(final OCluster cluster, final ORecordId rid, final int recordVersion) throws ORecordNotFoundException { checkOpenness(); if (!rid.isPersistent()) throw new ORecordNotFoundException(rid, "Cannot read record " + rid + " since the position is invalid in database '" + name + '\''); if (transaction.get() != null) { return doReadRecordIfNotLatest(cluster, rid, recordVersion); } stateLock.acquireReadLock(); try { if (pessimisticLock) { acquireReadLock(rid); } ORawBuffer buff; checkOpenness(); buff = doReadRecordIfNotLatest(cluster, rid, recordVersion); return buff; } finally { if (pessimisticLock) { releaseReadLock(rid); } stateLock.releaseReadLock(); } }

Target:
private ORawBuffer readRecordIfNotLatest(final OCluster cluster, final ORecordId rid, final int recordVersion) throws ORecordNotFoundException { checkOpenness(); if (!rid.isPersistent()) throw new ORecordNotFoundException(rid, "Cannot read record " + rid + " since the position is invalid in database '" + name + '\''); if (transaction.get() != null) { return doReadRecordIfNotLatest(cluster, rid, recordVersion); } stateLock.acquireReadLock(); try { if (pessimisticLock) { acquireReadLock(rid); } ORawBuffer buff; checkOpenness(); buff = doReadRecordIfNotLatest(cluster, rid, recordVersion); return buff; } finally { try { if (pessimisticLock) { releaseReadLock(rid); } } finally { stateLock.releaseReadLock(); } } }
Source:
public static BlobColumn buildFromProtobuf(final ColumnMessage message, final int numTuples) { Preconditions.checkArgument( message.getType().ordinal() == ColumnMessage.Type.BLOB_VALUE, "Trying to construct Bytes from non-bytes ColumnMessage %s", message.getType()); Preconditions.checkArgument(message.hasBlobColumn(), "ColumnMessage is missing DateColumn"); final BlobColumnMessage BlobColumn = message.getBlobColumn(); ByteBuffer[] newData = new ByteBuffer[numTuples]; ByteBuffer data = BlobColumn.getData().asReadOnlyByteBuffer(); for (int i = 0; i < numTuples; i++) { newData[i] = ByteBuffer.allocate(data.capacity()); newData[i].put(data); } return new BlobColumnBuilder(newData, numTuples).build(); }

Target:
public static BlobColumn buildFromProtobuf(final ColumnMessage message, final int numTuples) { Preconditions.checkArgument( message.getType().ordinal() == ColumnMessage.Type.BLOB_VALUE, "Trying to construct BlobColumn from non-bytes ColumnMessage %s", message.getType()); Preconditions.checkArgument(message.hasBlobColumn(), "ColumnMessage is missing BlobColumn"); final BlobColumnMessage BlobColumn = message.getBlobColumn(); List<Integer> startIndices = BlobColumn.getStartIndicesList(); List<Integer> endIndices = BlobColumn.getEndIndicesList(); ByteBuffer[] newData = new ByteBuffer[numTuples]; ByteBuffer data = BlobColumn.getData().asReadOnlyByteBuffer(); for (int i = 0; i < numTuples; i++) { int length = endIndices.get(i) - startIndices.get(i); newData[i] = ByteBuffer.allocate(length); data.get(newData[i].array(), 0, length); } return new BlobColumnBuilder(newData, numTuples).build(); }
Source:
private void deleteOldPacks(Collection<PackFile> oldPacks, Collection<PackFile> newPacks, boolean ignoreErrors) throws IOException { int deleteOptions = FileUtils.RETRY | FileUtils.SKIP_MISSING; if (ignoreErrors) deleteOptions |= FileUtils.IGNORE_ERRORS; oldPackLoop: for (PackFile oldPack : oldPacks) { String oldName = oldPack.getPackName(); for (PackFile newPack : newPacks) if (oldName.equals(newPack.getPackName())) continue oldPackLoop; if (!nameFor(oldName, ".pack.keep").exists()) { oldPack.close(); FileUtils.delete(nameFor(oldName, ".pack"), deleteOptions); FileUtils.delete(nameFor(oldName, ".idx"), deleteOptions); } } repo.getObjectDatabase().close(); }

Target:
private void deleteOldPacks(Collection<PackFile> oldPacks, Collection<PackFile> newPacks, boolean ignoreErrors) throws IOException { int deleteOptions = FileUtils.RETRY | FileUtils.SKIP_MISSING; if (ignoreErrors) deleteOptions |= FileUtils.IGNORE_ERRORS; oldPackLoop: for (PackFile oldPack : oldPacks) { String oldName = oldPack.getPackName(); for (PackFile newPack : newPacks) if (oldName.equals(newPack.getPackName())) continue oldPackLoop; if (!oldPack.shouldBeKept()) { oldPack.close(); FileUtils.delete(nameFor(oldName, ".pack"), deleteOptions); FileUtils.delete(nameFor(oldName, ".idx"), deleteOptions); } } repo.getObjectDatabase().close(); }
Source:
public void messageFormatTtlUpdateRecordTest() throws IOException, MessageFormatException { StoreKey key = new MockId("id1"); short accountId = Utils.getRandomShort(TestUtils.RANDOM); short containerId = Utils.getRandomShort(TestUtils.RANDOM); long ttlUpdateTimeMs = SystemTime.getInstance().milliseconds() + TestUtils.RANDOM.nextInt(); long updatedExpiryMs = ttlUpdateTimeMs + TestUtils.RANDOM.nextInt(); MessageFormatInputStream messageFormatStream = new TtlUpdateMessageFormatInputStream(key, accountId, containerId, updatedExpiryMs, ttlUpdateTimeMs); long ttlUpdateRecordSize = MessageFormatRecord.Update_Format_V3.getRecordSize(UpdateRecord.Type.TTL_UPDATE); int headerSize = MessageFormatRecord.getHeaderSizeForVersion(MessageFormatRecord.headerVersionToUse); Assert.assertEquals(headerSize + ttlUpdateRecordSize + key.sizeInBytes(), messageFormatStream.getSize()); checkTtlUpdateMessage(messageFormatStream, ttlUpdateRecordSize, key, accountId, containerId, ttlUpdateTimeMs, updatedExpiryMs); }

Target:
public void messageFormatTtlUpdateRecordTest() throws IOException, MessageFormatException { StoreKey key = new MockId("id1"); short accountId = Utils.getRandomShort(TestUtils.RANDOM); short containerId = Utils.getRandomShort(TestUtils.RANDOM); long ttlUpdateTimeMs = SystemTime.getInstance().milliseconds() + TestUtils.RANDOM.nextInt(); long updatedExpiryMs = ttlUpdateTimeMs + TestUtils.RANDOM.nextInt(); MessageFormatInputStream messageFormatStream = new TtlUpdateMessageFormatInputStream(key, accountId, containerId, updatedExpiryMs, ttlUpdateTimeMs); long ttlUpdateRecordSize = MessageFormatRecord.Update_Format_V3.getRecordSize(UpdateRecord.Type.TTL_UPDATE); int headerSize = MessageFormatRecord.getHeaderSizeForVersion(MessageFormatRecord.headerVersionToUse); Assert.assertEquals(headerSize + ttlUpdateRecordSize + key.sizeInBytes(), messageFormatStream.getSize()); checkTtlUpdateMessage(messageFormatStream, ttlUpdateRecordSize, key, accountId, containerId, updatedExpiryMs, ttlUpdateTimeMs); }
Source:
protected boolean canDoAction() { if (getParameters().getDiskImage().getDiskStorageType() != DiskStorageType.IMAGE) { addCanDoActionMessage("$diskId " + getParameters().getDiskImage().getId()); addCanDoActionMessage("$storageType " + getParameters().getDiskImage().getDiskStorageType()); addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_UNSUPPORTED_DISK_STORAGE_TYPE); return false; } else { return true; } }

Target:
protected boolean canDoAction() { if (getParameters().getDiskImage().getDiskStorageType() != DiskStorageType.IMAGE) { addCanDoActionMessage("$diskId " + getParameters().getDiskImage().getId()); addCanDoActionMessage("$storageType " + getParameters().getDiskImage().getDiskStorageType()); addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_UNSUPPORTED_DISK_STORAGE_TYPE); return false; } else if (!validate(new StorageDomainValidator(getStorageDomain()).isDomainExistAndActive())) { addCanDoActionMessage("$diskId " + getParameters().getDiskImage().getId()); addCanDoActionMessage("$domainId " + getStorageDomainId()); addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_UNAVAILABLE); return false; } else if (getStorageDomain().getStorageDomainType() != StorageDomainType.Data) { addCanDoActionMessage("$domainId " + getParameters().getStorageDomainId()); addCanDoActionMessage("$domainType " + getStorageDomain().getStorageDomainType()); addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_TYPE_UNSUPPORTED); } return true; }
Source:
public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean b) { if(stack.hasTagCompound()) { if(!stack.stackTagCompound.getBoolean("Active")) { list.add(EnumChatFormatting.RED + "Inactive!"); } else { list.add("Mode: " + EnumChatFormatting.AQUA + MODES[stack.getItemDamage()]); } } }

Target:
public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean b) { if(stack.hasTagCompound()) { if(!stack.stackTagCompound.getBoolean("Active")) { list.add(EnumChatFormatting.RED + StatCollector.translateToLocal("pe.arcana.inactive")); } else { list.add(StatCollector.translateToLocal("pe.arcana.mode") + EnumChatFormatting.AQUA + StatCollector.translateToLocal("pe.arcana.mode." + stack.getItemDamage())); } } }
Source:
private void bounce(TaskIdWithUsage task, TaskCleanupType cleanupType, Optional<String> message) { taskManager.createTaskCleanup(new SingularityTaskCleanup( Optional.empty(), cleanupType, System.currentTimeMillis(), task.getTaskId(), message, Optional.of(UUID.randomUUID().toString()), Optional.empty(), Optional.empty() )); requestManager.addToPendingQueue(new SingularityPendingRequest( task.getTaskId().getRequestId(), task.getTaskId().getDeployId(), System.currentTimeMillis(), Optional.empty(), PendingType.TASK_BOUNCE, Optional.empty(), Optional.empty(), Optional.empty(), message, Optional.of(UUID.randomUUID().toString()) )); }

Target:
private void bounce(TaskIdWithUsage task, TaskCleanupType cleanupType, Optional<String> message) { String actionId = UUID.randomUUID().toString(); taskManager.createTaskCleanup(new SingularityTaskCleanup( Optional.empty(), cleanupType, System.currentTimeMillis(), task.getTaskId(), message, Optional.of(actionId), Optional.empty(), Optional.empty() )); requestManager.addToPendingQueue(new SingularityPendingRequest( task.getTaskId().getRequestId(), task.getTaskId().getDeployId(), System.currentTimeMillis(), Optional.empty(), PendingType.TASK_BOUNCE, Optional.empty(), Optional.empty(), Optional.empty(), message, Optional.of(actionId) )); }
Source:
private int getSize(Node item) throws NumberFormatException { Node val = item.getFirstChild(); assertNotNull(val); assertEquals(Node.TEXT_NODE, val.getNodeType()); try { return Integer.parseInt(val.getNodeValue().trim()); } catch (NumberFormatException ex) { if (DirectoryListing.DIRECTORY_SIZE_PLACEHOLDER.equals(val.getNodeValue().trim())) { return DIRECTORY_INTERNAL_SIZE; } return -1; } }

Target:
private int getSize(Node item) throws NumberFormatException { Node val = item.getFirstChild(); assertNotNull(val); assertEquals(Node.TEXT_NODE, val.getNodeType()); if (DirectoryListing.DIRECTORY_SIZE_PLACEHOLDER.equals(val.getNodeValue().trim())) { return DIRECTORY_INTERNAL_SIZE; } try { return Integer.parseInt(val.getNodeValue().trim()); } catch (NumberFormatException ex) { return INVALID_SIZE; } }
Source:
private VoltTable[] fastPath(List<QueuedSQL> batch) { final int batchSize = batch.size(); Object[] params = new Object[batchSize]; long[] fragmentIds = new long[batchSize]; String[] sqlTexts = new String[batchSize]; int succeededFragmentsCount = 0; int i = 0; for (final QueuedSQL qs : batch) { assert(qs.stmt.collector == null); fragmentIds[i] = qs.stmt.aggregator.id; if (qs.serialization != null) { params[i] = qs.serialization; } else { params[i] = qs.params; } sqlTexts[i] = qs.stmt.getText(); i++; } VoltTable[] results = null; getExecutionEngine().setPerFragmentTimingEnabled(m_perCallStats.samplingStmts()); try { results = m_site.executePlanFragments( batchSize, fragmentIds, null, params, sqlTexts, m_txnState.txnId, m_txnState.m_spHandle, m_txnState.uniqueId, m_isReadOnly); } catch (Throwable ex) { if (! m_isReadOnly) { m_site.truncateUndoLog(true, m_spBigBatchBeginToken >= 0 ? m_spBigBatchBeginToken: m_site.getLatestUndoToken(), m_txnState.m_spHandle, null); } throw ex; } finally { long[] executionTimes = null; if (m_perCallStats.samplingStmts()) { executionTimes = new long[batchSize]; } succeededFragmentsCount = getExecutionEngine().extractPerFragmentStats(batchSize, executionTimes); for (i = 0; i < batchSize; i++) { QueuedSQL qs = batch.get(i); boolean hasCoordinatorTask = false; boolean failed = i == succeededFragmentsCount; m_perCallStats.recordStatementStats(qs.stmt.getStmtName(), hasCoordinatorTask, failed, executionTimes == null ? 0 : executionTimes[i], results == null ? null : results[i], qs.params); if (failed) { break; } } } return results; }

Target:
private VoltTable[] fastPath(List<QueuedSQL> batch) { final int batchSize = batch.size(); Object[] params = new Object[batchSize]; long[] fragmentIds = new long[batchSize]; String[] sqlTexts = new String[batchSize]; int succeededFragmentsCount = 0; int i = 0; for (final QueuedSQL qs : batch) { assert(qs.stmt.collector == null); fragmentIds[i] = qs.stmt.aggregator.id; if (qs.serialization != null) { params[i] = qs.serialization; } else { params[i] = qs.params; } sqlTexts[i] = qs.stmt.getText(); i++; } VoltTable[] results = null; getExecutionEngine().setPerFragmentTimingEnabled(m_perCallStats.samplingStmts()); try { results = m_site.executePlanFragments( batchSize, fragmentIds, null, params, sqlTexts, m_txnState.txnId, m_txnState.m_spHandle, m_txnState.uniqueId, m_isReadOnly); } catch (Throwable ex) { if (! m_isReadOnly) { m_site.truncateUndoLog(true, m_spBigBatchBeginToken >= 0 ? m_spBigBatchBeginToken: m_site.getLatestUndoToken(), m_txnState.m_spHandle, null); } throw ex; } finally { long[] executionTimes = null; if (m_perCallStats.samplingStmts()) { executionTimes = new long[batchSize]; } succeededFragmentsCount = getExecutionEngine().extractPerFragmentStats(batchSize, executionTimes); for (i = 0; i < batchSize; i++) { QueuedSQL qs = batch.get(i); boolean isCoordinatorTask = false; boolean failed = i == succeededFragmentsCount; m_perCallStats.recordStatementStats(qs.stmt.getStmtName(), isCoordinatorTask, failed, executionTimes == null ? 0 : executionTimes[i], results == null ? null : results[i], qs.params); if (failed) { break; } } } return results; }
Source:
public SortedSet<DescriptorLanguage.FileType> getVersionsFileTypes(@Parameter(hidden = true, name = "user")@Auth Optional<User> user, @Parameter(name = "entryId", description = "Entry to retrieve the version from", required = true, in = ParameterIn.PATH) @PathParam("entryId") Long entryId, @Parameter(name = "versionId", description = "Version to retrieve the sourcefile types from", required = true, in = ParameterIn.PATH) @PathParam("versionId") Long versionId) { Entry<? extends Entry, ? extends Version> entry = toolDAO.getGenericEntryById(entryId); checkEntry(entry); if (!entry.getIsPublished()) { checkUser(user.get(), entry); } Version version = versionDAO.findVersionInEntry(entryId, versionId); if (version == null) { throw new CustomWebApplicationException("Version " + versionId + " does not exist for this entry", HttpStatus.SC_BAD_REQUEST); } SortedSet<DescriptorLanguage.FileType> fileTypes = new TreeSet<>(); SortedSet<SourceFile> sourceFiles = version.getSourceFiles(); fileTypes = sourceFiles.stream().map(sourceFile -> sourceFile.getType()).collect(Collectors.toCollection(TreeSet::new)); return fileTypes; }

Target:
public SortedSet<DescriptorLanguage.FileType> getVersionsFileTypes(@Parameter(hidden = true, name = "user")@Auth Optional<User> user, @Parameter(name = "entryId", description = "Entry to retrieve the version from", required = true, in = ParameterIn.PATH) @PathParam("entryId") Long entryId, @Parameter(name = "versionId", description = "Version to retrieve the sourcefile types from", required = true, in = ParameterIn.PATH) @PathParam("versionId") Long versionId) { Entry<? extends Entry, ? extends Version> entry = toolDAO.getGenericEntryById(entryId); checkEntry(entry); checkEntryPermissions(user, entry); Version version = versionDAO.findVersionInEntry(entryId, versionId); if (version == null) { throw new CustomWebApplicationException("Version " + versionId + " does not exist for this entry", HttpStatus.SC_BAD_REQUEST); } SortedSet<SourceFile> sourceFiles = version.getSourceFiles(); return sourceFiles.stream().map(sourceFile -> sourceFile.getType()).collect(Collectors.toCollection(TreeSet::new)); }
Source:
public void onGroupRebalanceFinished(int grpId) { Set<Integer> groupsToEnable = tmpDisabledWal.enable(grpId); if (F.isEmpty(groupsToEnable)) return; grpId = groupsToEnable.stream().findFirst().get(); CacheGroupContext grp = cctx.cache().cacheGroup(grpId); assert grp != null: "Can not find group with id: " + grpId; AffinityTopologyVersion lastGroupTop = grp.topology().readyTopologyVersion(); CheckpointProgress cpFut = triggerCheckpoint("wal-local-state-changed-rebalance-finished-" + lastGroupTop); assert cpFut != null; cpFut.futureFor(FINISHED).listen(new IgniteInClosureX<IgniteInternalFuture>() { @Override public void applyx(IgniteInternalFuture future) { if (X.hasCause(future.error(), NodeStoppingException.class)) return; for (Integer grpId0 : groupsToEnable) { try { cctx.database().walEnabled(grpId0, true, true); } catch (Exception e) { if (!X.hasCause(e, NodeStoppingException.class)) throw e; } CacheGroupContext grp = cctx.cache().cacheGroup(grpId0); if (grp != null) grp.topology().ownMoving(lastGroupTop); else if (log.isDebugEnabled()) log.debug("Cache group was destroyed before checkpoint finished, [grpId=" + grpId0 + ']'); } if (log.isDebugEnabled()) log.debug("Refresh partitions due to rebalance finished"); cctx.exchange().refreshPartitions(); } }); }

Target:
public void onGroupRebalanceFinished(int grpId) { Set<Integer> groupsToEnable = tmpDisabledWal.enable(grpId); if (F.isEmpty(groupsToEnable)) return; grpId = F.first(groupsToEnable); CacheGroupContext grp = cctx.cache().cacheGroup(grpId); assert grp != null : "Can not find group with id: " + grpId; AffinityTopologyVersion lastGroupTop = grp.topology().readyTopologyVersion(); CheckpointProgress cpFut = triggerCheckpoint("wal-local-state-changed-rebalance-finished-" + lastGroupTop); assert cpFut != null; cpFut.futureFor(FINISHED).listen(new IgniteInClosureX<IgniteInternalFuture>() { @Override public void applyx(IgniteInternalFuture future) { if (X.hasCause(future.error(), NodeStoppingException.class)) return; for (Integer grpId0 : groupsToEnable) { try { cctx.database().walEnabled(grpId0, true, true); } catch (Exception e) { if (!X.hasCause(e, NodeStoppingException.class)) throw e; } CacheGroupContext grp = cctx.cache().cacheGroup(grpId0); if (grp != null) grp.topology().ownMoving(lastGroupTop); else if (log.isDebugEnabled()) log.debug("Cache group was destroyed before checkpoint finished, [grpId=" + grpId0 + ']'); } if (log.isDebugEnabled()) log.debug("Refresh partitions due to rebalance finished"); cctx.exchange().refreshPartitions(); } }); }
Source:
void integrationTestTexGroup() throws IOException, ParseException { ParserResult result = parser.parse(new StringReader( "@comment{jabref-meta: grouping:" + OS.NEWLINE + "0 AllEntriesGroup:;" + OS.NEWLINE + "1 TexGroup:cited entries\\;0\\;paper.aux\\;1\\;0x8a8a8aff\\;\\;\\;;" + "}" + OS.NEWLINE + "@Comment{jabref-meta: databaseType:biblatex;}" + OS.NEWLINE + "@Comment{jabref-meta: fileDirectory:src/test/resources/org/jabref/model/groups;}" + OS.NEWLINE + "@Comment{jabref-meta: fileDirectory-" + System.getProperty("user.name") + "-" + InetAddress.getLocalHost().getHostName() + ":src/test/resources/org/jabref/model/groups;}" + OS.NEWLINE + "@Comment{jabref-meta: fileDirectoryLatex-" + System.getProperty("user.name") + "-" + InetAddress.getLocalHost().getHostName() + ":src/test/resources/org/jabref/model/groups;}" + OS.NEWLINE )); GroupTreeNode root = result.getMetaData().getGroups().get(); assertEquals("src/test/resources/org/jabref/model/groups/paper.aux", ((TexGroup) root.getChildren().get(0).getGroup()).getFilePath().toString()); }

Target:
void integrationTestTexGroup() throws Exception { ParserResult result = parser.parse(new StringReader( "@comment{jabref-meta: grouping:" + OS.NEWLINE + "0 AllEntriesGroup:;" + OS.NEWLINE + "1 TexGroup:cited entries\\;0\\;paper.aux\\;1\\;0x8a8a8aff\\;\\;\\;;" + "}" + OS.NEWLINE + "@Comment{jabref-meta: databaseType:biblatex;}" + OS.NEWLINE + "@Comment{jabref-meta: fileDirectory:src/test/resources/org/jabref/model/groups;}" + OS.NEWLINE + "@Comment{jabref-meta: fileDirectory-" + System.getProperty("user.name") + "-" + InetAddress.getLocalHost().getHostName() + ":src/test/resources/org/jabref/model/groups;}" + OS.NEWLINE + "@Comment{jabref-meta: fileDirectoryLatex-" + System.getProperty("user.name") + "-" + InetAddress.getLocalHost().getHostName() + ":src/test/resources/org/jabref/model/groups;}" + OS.NEWLINE )); GroupTreeNode root = result.getMetaData().getGroups().get(); assertEquals("src/test/resources/org/jabref/model/groups/paper.aux", ((TexGroup) root.getChildren().get(0).getGroup()).getFilePath().toString()); }
Source:
public void setDefaultGroupStore(AccountStore accountStore) { AccountStoreMappingList accountStoreMappingList = getAccountStoreMappings(); boolean needToCreateNewStore = true; for (AccountStoreMapping accountStoreMapping : accountStoreMappingList) { if (accountStoreMapping.getAccountStore().getHref().equals(accountStore.getHref())) { needToCreateNewStore = false; accountStoreMapping.setDefaultGroupStore(true); setProperty(DEFAULT_GROUP_STORE_MAPPING, accountStoreMapping); accountStoreMapping.save(); break; } } if (needToCreateNewStore) { AccountStoreMapping mapping = addAccountStore(accountStore); mapping.setDefaultGroupStore(true); setProperty(DEFAULT_GROUP_STORE_MAPPING, mapping); mapping.save(); } this.save(); }

Target:
public void setDefaultGroupStore(AccountStore accountStore) { AccountStoreMappingList accountStoreMappingList = getAccountStoreMappings(); boolean needToCreateNewStore = true; for (AccountStoreMapping accountStoreMapping : accountStoreMappingList) { if (accountStoreMapping.getAccountStore().getHref().equals(accountStore.getHref())) { needToCreateNewStore = false; accountStoreMapping.setDefaultGroupStore(true); accountStoreMapping.save(); setProperty(DEFAULT_GROUP_STORE_MAPPING, accountStoreMapping); break; } } if (needToCreateNewStore) { AccountStoreMapping mapping = addAccountStore(accountStore); mapping.setDefaultGroupStore(true); mapping.save(); setProperty(DEFAULT_GROUP_STORE_MAPPING, mapping); } save(); }
Source:
public void initiate(VeluxBridge bridge) { logger.trace("retrieve() called."); CheckLostNodes bcp = bridge.bridgeAPI().checkLostNodes(); if ((bridge.bridgeCommunicate(bcp)) && (bcp.isCommunicationSuccessful())) { logger.trace("retrieve() finished successfully."); } else { logger.trace("retrieve() finished with failure."); } return; }

Target:
public void initiate(VeluxBridge bridge) { logger.trace("initiate() called."); CheckLostNodes bcp = bridge.bridgeAPI().checkLostNodes(); if (bridge.bridgeCommunicate(bcp) && bcp.isCommunicationSuccessful()) { logger.trace("initiate() finished successfully."); } else { logger.trace("initiate() finished with failure."); } return; }
Source:
private void closeConnections() { int numThreads = connections.size() + 2; ExecutorService executor = Executors.newFixedThreadPool(numThreads, new ThreadFactoryBuilder().setDaemon(true).setNameFormat("connection-close-%d").build()); CompletionService<Void> completionService = new ExecutorCompletionService<>(executor); try { connections.stream().forEach(connection -> completionService.submit(() -> { try { if (connection != null && !connection.isClosed()) connection.close(); } catch (SQLException e) { } return null; })); int futures = 0; while(futures++ < connections.size()) { Future<Void> future = completionService.poll(10, TimeUnit.SECONDS); if (future == null) throw new TimeoutException(); future.get(); } return; } catch (InterruptedException e) { LOG.error("Interrupted while closing", e); Thread.currentThread().interrupt(); } catch (TimeoutException | ExecutionException e) { LOG.warn("Couldn't close gracefully", e); for(Connection connection : connections) { try { if (connection != null && !connection.isClosed()) { LOG.info("Aborting " + connection); connection.abort(executor); } } catch (SQLException sqle) { LOG.error("Couldn't abort connection", sqle); } } } finally { executor.shutdown(); try { if (!executor.awaitTermination(30, TimeUnit.SECONDS)) { executor.shutdownNow(); } } catch (InterruptedException e) { } } }

Target:
private void closeConnections() { try { List<Callable<Void>> callables = connections.stream().map(connection -> (Callable<Void>) () -> { try { if (connection != null && !connection.isClosed()) connection.close(); } catch (SQLException e) { LOG.error("Exception while closing connection", e); } return null; }).collect(Collectors.toList()); List<Future<Void>> results = executor.invokeAll(callables, 10, TimeUnit.SECONDS); List<Future<Void>> stillRunning = results.stream().filter(f -> f.isCancelled() || !f.isDone()).collect(Collectors.toList()); if (stillRunning.isEmpty()) { return; } stillRunning.stream().forEach(f -> f.cancel(true)); } catch (InterruptedException e) { LOG.error("Interrupted while closing", e); Thread.currentThread().interrupt(); } catch (Exception e) { LOG.warn("Exception while closing gracefully", e); } LOG.warn("Some tasks still running, aborting connections"); for(Connection connection : connections) { try { if (connection != null && !connection.isClosed()) { LOG.info("Aborting " + connection); connection.abort(executor); } } catch (SQLException sqle) { LOG.error("Couldn't abort connection", sqle); } } }
Source:
public Exchange<T> call() throws IOException { Kryo readSerde = new Kryo(); readSerde.setClassLoader(classLoader); Map<Object, T> bucketDataPerWindow = Maps.newHashMap(); Path dataFile = new Path(bucketRoot + PATH_SEPARATOR + window); FileSystem fs = FileSystem.newInstance(dataFile.toUri(), configuration); try { if(fs.exists(dataFile)){ FSDataInputStream stream = fs.open(dataFile); stream.seek(bucketPositions[bucketIdx].get(window)); Input input = new Input(stream); int length = stream.readInt(); for (int i = 0; i < length; i++) { Object key = readSerde.readObject(input, eventKeyClass); int partitionKey = key.hashCode() & partitionMask; boolean keyPasses = partitionKeys.contains(partitionKey); if (!writeEventKeysOnly) { int entrySize = input.readInt(); if (keyPasses) { T entry = readSerde.readObject(input, eventClass); bucketDataPerWindow.put(key, entry); } else { input.skip(entrySize); } } else if (keyPasses) { bucketDataPerWindow.put(key, null); } } input.close(); stream.close(); } } finally { fs.close(); } return new Exchange<T>(window, bucketDataPerWindow); }

Target:
public Exchange<T> call() throws IOException { Kryo readSerde = new Kryo(); readSerde.setClassLoader(classLoader); Map<Object, T> bucketDataPerWindow = Maps.newHashMap(); Path dataFile = new Path(bucketRoot + PATH_SEPARATOR + window); FileSystem fs = FileSystem.newInstance(dataFile.toUri(), configuration); try { FSDataInputStream stream = fs.open(dataFile); stream.seek(bucketPositions[bucketIdx].get(window)); Input input = new Input(stream); int length = stream.readInt(); for (int i = 0; i < length; i++) { Object key = readSerde.readObject(input, eventKeyClass); int partitionKey = key.hashCode() & partitionMask; boolean keyPasses = partitionKeys.contains(partitionKey); if (!writeEventKeysOnly) { int entrySize = input.readInt(); if (keyPasses) { T entry = readSerde.readObject(input, eventClass); bucketDataPerWindow.put(key, entry); } else { input.skip(entrySize); } } else if (keyPasses) { bucketDataPerWindow.put(key, null); } } input.close(); stream.close(); } finally { fs.close(); } return new Exchange<T>(window, bucketDataPerWindow); }
Source:
public void rememberExternalLibTimestamps() { IBuildpathEntry[] buildpath = this.resolvedBuildpath; if (buildpath == null) return; Map<IPath, Long> externalTimeStamps = ModelManager .getModelManager().deltaState.getExternalLibTimeStamps(); for (int i = 0, length = buildpath.length; i < length; i++) { IBuildpathEntry entry = buildpath[i]; if (entry.getEntryKind() == IBuildpathEntry.BPE_LIBRARY) { IPath path = entry.getPath(); if (externalTimeStamps.get(path) == null) { Object target = Model.getTarget(ResourcesPlugin .getWorkspace().getRoot(), path, true); if (target instanceof IFileHandle) { long timestamp = DeltaProcessor .getTimeStamp((IFileHandle) target); externalTimeStamps.put(path, Long.valueOf(timestamp)); } } } } Map<IPath, Long> customTimeStamps = ModelManager.getModelManager().deltaState .getCustomTimeStamps(); try { IScriptProject scriptProject = DLTKCore.create(project); IProjectFragment[] fragments = scriptProject .getAllProjectFragments(); for (int i = 0; i < fragments.length; i++) { if (fragments[i] instanceof IProjectFragmentTimestamp) { IProjectFragmentTimestamp stamp = (IProjectFragmentTimestamp) fragments[i]; long timeStamp = stamp.getTimeStamp(); customTimeStamps.put(fragments[i].getPath(), Long.valueOf( timeStamp)); } } } catch (ModelException e) { if (DLTKCore.DEBUG) { e.printStackTrace(); } } }

Target:
public void rememberExternalLibTimestamps() { IBuildpathEntry[] buildpath = this.resolvedBuildpath; if (buildpath == null) return; Map<IPath, Long> externalTimeStamps = ModelManager .getModelManager().deltaState.getExternalLibTimeStamps(); for (int i = 0, length = buildpath.length; i < length; i++) { IBuildpathEntry entry = buildpath[i]; if (entry.getEntryKind() == IBuildpathEntry.BPE_LIBRARY) { IPath path = entry.getPath(); if (externalTimeStamps.get(path) == null) { Object target = Model.getTarget(ResourcesPlugin .getWorkspace().getRoot(), path, true); if (target instanceof IFileHandle) { long timestamp = DeltaProcessor .getTimeStamp((IFileHandle) target); externalTimeStamps.put(path, new Long(timestamp)); } } } } Map<IPath, Long> customTimeStamps = ModelManager.getModelManager().deltaState .getCustomTimeStamps(); try { IScriptProject scriptProject = DLTKCore.create(project); IProjectFragment[] fragments = scriptProject .getAllProjectFragments(); for (int i = 0; i < fragments.length; i++) { if (fragments[i] instanceof IProjectFragmentTimestamp) { IProjectFragmentTimestamp stamp = (IProjectFragmentTimestamp) fragments[i]; long timeStamp = stamp.getTimeStamp(); customTimeStamps.put(fragments[i].getPath(), new Long( timeStamp)); } } } catch (ModelException e) { if (DLTKCore.DEBUG) { e.printStackTrace(); } } }
Source:
public void testUnmarshalSeralizedObjectInvalidByteArray() throws Exception { AttributeAdapter attributeAdapter = getObjectAttributeAdapter(); ObjectElement mockObjectElement = mock(ObjectElement.class); doReturn("name").when(mockObjectElement).getName(); doReturn(ImmutableList.of(new byte[] {-31, 0, 0, 0})).when(mockObjectElement).getValue(); Attribute result = attributeAdapter.unmarshal(mockObjectElement); assertThat("Unmarshalled byte array not returned", result.getValue() instanceof byte[]); }

Target:
public void testUnmarshalSeralizedObjectInvalidByteArray() throws Exception { AttributeAdapter attributeAdapter = getObjectAttributeAdapter(); ObjectElement mockObjectElement = mock(ObjectElement.class); doReturn("name").when(mockObjectElement).getName(); doReturn(ImmutableList.of(new byte[] {-31, 0, 0, 0})).when(mockObjectElement).getValue(); Attribute result = attributeAdapter.unmarshal(mockObjectElement); assertThat( "Unmarshalled byte array not returned", result.getValue(), is(instanceOf(byte[].class))); }
Source:
public void setMonitorEventTypes(String monitorEventTypes) { HazelcastIntegrationDefinitionValidator.validateEnumType( ClusterMonitorType.class, monitorEventTypes); final Set<String> monitorTypes = StringUtils .commaDelimitedListToSet(monitorEventTypes); Assert.notEmpty(monitorTypes, "'monitorTypes' must have elements"); this.monitorTypes = monitorTypes; }

Target:
public void setMonitorEventTypes(String monitorEventTypes) { final Set<String> monitorTypes = HazelcastIntegrationDefinitionValidator.validateEnumType( ClusterMonitorType.class, monitorEventTypes); Assert.notEmpty(monitorTypes, "'monitorTypes' must have elements"); this.monitorTypes = monitorTypes; }
Source:
public static <V> V runLocked(final Callable<V> callable, final InterProcessLock lock) throws Exception { try { lock.acquire(); return callable.call(); } finally { try { lock.release(); } catch (final Exception e) { LOG.warn("Error occurred when releasing ZK lock", e); } } }

Target:
public static <V> V runLocked(final Callable<V> callable, final InterProcessLock lock) throws Exception { lock.acquire(); try { return callable.call(); } finally { try { lock.release(); } catch (final Exception e) { LOG.warn("Error occurred when releasing ZK lock", e); } } }
Source:
private void writeNumericBinary(BigDecimal value) throws IOException { int weight = 0; List<Integer> groups = new ArrayList<>(); int scale = value.scale(); int signum = value.signum(); if (signum != 0) { BigInteger[] unscaled = new BigInteger[] {value.unscaledValue()}; if (signum < 0) { unscaled[0] = unscaled[0].negate(); } weight = -scale / MAX_GROUP_SCALE - 1; int remainder = 0; int scaleChunk = scale % MAX_GROUP_SCALE; if (scaleChunk > 0) { remainder = divide(unscaled, POWERS10[scaleChunk]) * POWERS10[MAX_GROUP_SCALE - scaleChunk]; if (remainder != 0) { weight--; } } if (remainder == 0) { while ((remainder = divide(unscaled, MAX_GROUP_SIZE)) == 0) { weight++; } } groups.add(remainder); while (unscaled[0].signum() != 0) { groups.add(divide(unscaled, MAX_GROUP_SIZE)); } } writeInt(8 + groups.size() * 2); writeShort(groups.size()); writeShort(groups.size() + weight); writeShort(signum < 0 ? 16384 : 0); writeShort(scale); for (int i = groups.size() - 1; i >= 0; i--) { writeShort(groups.get(i)); } }

Target:
private void writeNumericBinary(BigDecimal value) throws IOException { int weight = 0; List<Integer> groups = new ArrayList<>(); int scale = value.scale(); int signum = value.signum(); if (signum != 0) { BigInteger[] unscaled = {null}; if (scale < 0) { unscaled[0] = value.setScale(0).unscaledValue(); scale = 0; } else { unscaled[0] = value.unscaledValue(); } if (signum < 0) { unscaled[0] = unscaled[0].negate(); } weight = -scale / MAX_GROUP_SCALE - 1; int remainder = 0; int scaleChunk = scale % MAX_GROUP_SCALE; if (scaleChunk > 0) { remainder = divide(unscaled, POWERS10[scaleChunk]) * POWERS10[MAX_GROUP_SCALE - scaleChunk]; if (remainder != 0) { weight--; } } if (remainder == 0) { while ((remainder = divide(unscaled, MAX_GROUP_SIZE)) == 0) { weight++; } } groups.add(remainder); while (unscaled[0].signum() != 0) { groups.add(divide(unscaled, MAX_GROUP_SIZE)); } } int groupCount = groups.size(); if (groupCount + weight > Short.MAX_VALUE || scale > Short.MAX_VALUE) { throw DbException.get(ErrorCode.NUMERIC_VALUE_OUT_OF_RANGE_1, value.toString()); } writeInt(8 + groupCount * 2); writeShort(groupCount); writeShort(groupCount + weight); writeShort(signum < 0 ? 16384 : 0); writeShort(scale); for (int i = groupCount - 1; i >= 0; i--) { writeShort(groups.get(i)); } }
Source:
public void testPurchase() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); final Adjustments adjustmentsData = new Adjustments(); final Adjustment adjustmentData = TestUtils.createRandomAdjustment(); adjustmentData.setCurrency(null); adjustmentsData.add(adjustmentData); billingInfoData.setAccount(null); accountData.setBillingInfo(billingInfoData); try { final Purchase purchaseData = new Purchase(); purchaseData.setAccount(accountData); purchaseData.setAdjustments(adjustmentsData); purchaseData.setCollectionMethod("automatic"); purchaseData.setAdjustments(adjustmentsData); purchaseData.setCurrency("USD"); final Invoice invoice = recurlyClient.purchase(purchaseData); Assert.assertEquals(invoice.getLineItems().get(0).getProductCode(), adjustmentData.getProductCode()); } catch (Exception e) { System.out.println(e.getMessage()); System.out.println(e.getStackTrace()); } finally { recurlyClient.closeAccount(accountData.getAccountCode()); } }

Target:
public void testPurchase() throws Exception { final Account accountData = TestUtils.createRandomAccount(); final BillingInfo billingInfoData = TestUtils.createRandomBillingInfo(); final Adjustments adjustmentsData = new Adjustments(); final Adjustment adjustmentData = TestUtils.createRandomAdjustment(); adjustmentData.setCurrency(null); adjustmentsData.add(adjustmentData); billingInfoData.setAccount(null); accountData.setBillingInfo(billingInfoData); try { final Purchase purchaseData = new Purchase(); purchaseData.setAccount(accountData); purchaseData.setAdjustments(adjustmentsData); purchaseData.setCollectionMethod("automatic"); purchaseData.setAdjustments(adjustmentsData); purchaseData.setCurrency("USD"); final Invoice invoice = recurlyClient.purchase(purchaseData); Assert.assertEquals(invoice.getLineItems().get(0).getProductCode(), adjustmentData.getProductCode()); } finally { recurlyClient.closeAccount(accountData.getAccountCode()); } }
Source:
public Values(Object... vals) { super(vals != null ? vals.length : 0); if (vals != null && vals.length != 0 ) { for (Object o : vals) { add(o); } } else { add(null); } }

Target:
public Values(Object... vals) { super(vals != null ? vals.length : 1); if (vals != null ) { for (Object o : vals) { add(o); } } else { add(null); } }
Source:
public void update() throws BankException, LoginException, BankChoiceException, IOException { super.update(); if (username == null || password == null || username.length() == 0 || password.length() == 0) { throw new LoginException(res.getText(R.string.invalid_username_password).toString()); } urlopen = login(); try { response = urlopen.open("<LINK_0>"+((int)(System.currentTimeMillis() / 1000L))); Matcher matcher = reAccounts.matcher(response); int accId = 1; while (matcher.find()) { Account account = new Account(Html.fromHtml(matcher.group(1)).toString().trim(), Helpers.parseBalance(matcher.group(2)), ""+accId); account.setCurrency(matcher.group(3).trim()); accounts.add(account); accId++; } matcher = reBalance.matcher(response); if (matcher.find()) { balance = Helpers.parseBalance(matcher.group(1)); currency = matcher.group(2).trim(); if (accounts.isEmpty()) { Account account = new Account(currency, balance, "1"); account.setCurrency(currency); accounts.add(account); } } if (accounts.isEmpty()) { throw new BankException(res.getText(R.string.no_accounts_found).toString()); } } finally { super.updateComplete(); } }

Target:
public void update() throws BankException, LoginException, BankChoiceException, IOException { super.update(); if (username == null || password == null || username.length() == 0 || password.length() == 0) { throw new LoginException(res.getText(R.string.invalid_username_password).toString()); } urlopen = login(); response = urlopen.open("<LINK_0>"+((int)(System.currentTimeMillis() / 1000L))); Matcher matcher = reAccounts.matcher(response); int accId = 1; while (matcher.find()) { Account account = new Account(Html.fromHtml(matcher.group(1)).toString().trim(), Helpers.parseBalance(matcher.group(2)), ""+accId); account.setCurrency(matcher.group(3).trim()); accounts.add(account); accId++; } matcher = reBalance.matcher(response); if (matcher.find()) { balance = Helpers.parseBalance(matcher.group(1)); currency = matcher.group(2).trim(); if (accounts.isEmpty()) { Account account = new Account(currency, balance, "1"); account.setCurrency(currency); accounts.add(account); } } if (accounts.isEmpty()) { throw new BankException(res.getText(R.string.no_accounts_found).toString()); } super.updateComplete(); }
Source:
public void copyCurrentSelectionToClipboard() { terminalTextViewOverlay.copyCurrentSelectionToClipboard(); }

Target:
public void copyCurrentSelectionToClipboard() { if (terminalTextViewOverlay != null) { terminalTextViewOverlay.copyCurrentSelectionToClipboard(); } }
Source:
public void generate() { Path path = PathFactory.newPath( "test", "file:/ GlobalsModel globalsModel = mock( GlobalsModel.class ); when( ioService.exists( any( org.uberfire.java.nio.file.Path.class ) ) ).thenReturn( false ); globalsEditorService.generate( path, "test", globalsModel, "comment" ); verify( ioService, times( 1 ) ).write( any( org.uberfire.java.nio.file.Path.class ), anyString(), anyMap(), any( CommentedOption.class ) ); }

Target:
public void generate() { Path path = PathFactory.newPath( "test", "file:/ GlobalsModel globalsModel = mock( GlobalsModel.class ); when( ioService.exists( any( org.uberfire.java.nio.file.Path.class ) ) ).thenReturn( false ); Map<String, Object> metadataMap = new HashMap<String, Object>() { { put( GeneratedAttributesView.GENERATED_ATTRIBUTE_NAME, true ); } }; when( metadataService.configAttrs( anyMapOf( String.class, Object.class ), any( Metadata.class ) ) ).thenReturn( metadataMap ); globalsEditorService.generate( path, "test", globalsModel, "comment" ); ArgumentCaptor<Map> mapArgumentCaptor = ArgumentCaptor.forClass( Map.class ); verify( ioService, times( 1 ) ).write( any( org.uberfire.java.nio.file.Path.class ), anyString(), mapArgumentCaptor.capture(), any( CommentedOption.class ) ); Map capturedMap = mapArgumentCaptor.getValue(); assertEquals( metadataMap, capturedMap ); Object generatedAttribute = capturedMap.get( GeneratedAttributesView.GENERATED_ATTRIBUTE_NAME ); assertNotNull( generatedAttribute ); assertTrue( Boolean.parseBoolean( generatedAttribute.toString() ) ); }
Source:
public CharSequence safeApply(final Object value, final Options options) { String target = (String) options.param(0, null); String replacement = (String) options.param(1, null); return value.toString().replace(target, replacement); }

Target:
protected CharSequence safeApply(final Object value, final Options options) { return StringUtils.capitalize(value.toString()); }
Source:
public void allGaugesAreSetForUnknownSafetyAsUnsafe() { setLoggingSafety(ImmutableMap.of()); sweepMetricsManager.updateMetrics(SWEEP_RESULTS, TABLE_REF); assertRecordedCurrentValue(ImmutableMap.of( CELLS_EXAMINED, EXAMINED, CELLS_SWEPT, DELETED, TIME_SPENT_SWEEPING, TIME_SWEEPING, TABLE_BEING_SWEPT, UNSAFE_FULLY_QUALIFIED)); sweepMetricsManager.updateMetrics(OTHER_SWEEP_RESULTS, TABLE_REF2); assertRecordedCurrentValue(ImmutableMap.of( CELLS_EXAMINED, OTHER_EXAMINED, CELLS_SWEPT, OTHER_DELETED, TIME_SPENT_SWEEPING, OTHER_TIME_SWEEPING, TABLE_BEING_SWEPT, UNSAFE_FULLY_QUALIFIED)); }

Target:
public void allGaugesAreSetForUnknownSafetyAsUnsafe() { setLoggingSafety(ImmutableMap.of()); sweepMetricsManager.updateMetrics(SWEEP_RESULTS, TABLE_REF); assertRecordedExaminedDeletedTimeTableName(VALUES, UNSAFE_FULLY_QUALIFIED); sweepMetricsManager.updateMetrics(OTHER_SWEEP_RESULTS, TABLE_REF2); assertRecordedExaminedDeletedTimeTableName(OTHER_VALUES, UNSAFE_FULLY_QUALIFIED); }