auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void removeMember(Patient patient) { List<CohortMembership> memberToRemoveList = getMembers().stream() .filter(m -> m.getPatient() == patient).collect(Collectors.toList()); memberToRemoveList.forEach(this::removeMembership); }

Target:
public void removeMember(Patient patient) { List<CohortMembership> memberToRemoveList = getMembers().stream() .filter(m -> m.getPatient().getPatientId().equals(patient.getPatientId())).collect(Collectors.toList()); memberToRemoveList.forEach(m -> m.setEndDate(new Date())); }
Source:
private boolean hasCharacteristic(int characteristics, int characteristic) { return (characteristics & characteristic) == characteristic; }

Target:
private static boolean hasCharacteristic(int characteristics, int characteristic) { return (characteristics & characteristic) == characteristic; }
Source:
protected static Method getMethod(Class<?> clz, String name, Object value) throws NoSuchMethodException { Method method = null; try { method = getMethod(clz, name); } catch (NoSuchMethodException nsme) { method = clz.getMethod("is" + name); } return method; }

Target:
protected static Method getMethod(Class<?> clz, String name, Object value) throws NoSuchMethodException { Method method = null; try { method = getMethod(clz, name); } catch (NoSuchMethodException nsme) { if (Boolean.class.equals(value.getClass())) { method = clz.getMethod("is" + name); } else { throw nsme; } } return method; }
Source:
public List<String> getIndices(ElasticsearchTableDescription tableDescription) { if (tableDescription.getIndexExactMatch()) { return ImmutableList.of(tableDescription.getIndex()); } TransportClient client = clients.get(tableDescription.getClusterName()); verify(client != null, "TransportClient should not be null"); String[] indices = client.admin() .indices() .getIndex(new GetIndexRequest()) .actionGet(timeout.toMillis()) .getIndices(); return Arrays.stream(indices) .filter(index -> index.startsWith(tableDescription.getIndex())) .collect(toImmutableList()); }

Target:
public List<String> getIndices(ElasticsearchTableDescription tableDescription) { if (tableDescription.getIndexExactMatch()) { return ImmutableList.of(tableDescription.getIndex()); } TransportClient client = clients.get(tableDescription.getClusterName()); verify(client != null, "client is null"); String[] indices = client.admin() .indices() .getIndex(new GetIndexRequest()) .actionGet(timeout.toMillis()) .getIndices(); return Arrays.stream(indices) .filter(index -> index.startsWith(tableDescription.getIndex())) .collect(toImmutableList()); }
Source:
public void before() { commandUp = spy(new CommandUp()); reset(commandUp); when(commandUp.execute()).thenReturn(mock(MesosCluster.class)); commandDestroy = spy(new CommandDestroy()); reset(commandDestroy); doNothing().when(commandDestroy).execute(); commandInfo = spy(new CommandInfo()); reset(commandInfo); doNothing().when(commandInfo).execute(); commandState = spy(new CommandState()); reset(commandState); doNothing().when(commandState).execute(); commandInstall = spy(new CommandInstall()); reset(commandInstall); doNothing().when(commandInstall).execute(); main = new Main(); main.setCommandUp(commandUp); main.setCommandDestroy(commandDestroy); main.setCommandInfo(commandInfo); main.setCommandState(commandState); main.setCommandInstall(commandInstall); main.setCommandHelp(new CommandHelp()); }

Target:
public void before() { outputStream = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(outputStream, true); commandUp = spy(new CommandUp()); doReturn(mock(MesosCluster.class)).when(commandUp).execute(); commandDestroy = spy(new CommandDestroy()); doNothing().when(commandDestroy).execute(); commandInfo = spy(new CommandInfo(ps)); doNothing().when(commandInfo).execute(); commandState = spy(new CommandState(ps)); doNothing().when(commandState).execute(); commandInstall = spy(new CommandInstall()); doNothing().when(commandInstall).execute(); main = new Main(); main.setOutput(ps); main.setCommandUp(commandUp); main.setCommandDestroy(commandDestroy); main.setCommandInfo(commandInfo); main.setCommandState(commandState); main.setCommandInstall(commandInstall); main.setCommandHelp(new CommandHelp()); }
Source:
public void shouldNotSendEventIfActionEventParameterCanNotBeConvertedToInteger() throws Exception { setTriggerEvent(); setActionEvent(); when(taskService.findActiveTasksForTriggerSubject(TRIGGER_SUBJECT)).thenReturn(tasks); when(taskService.getActionEventFor(task.getActions().get(0))).thenReturn(actionEvent); task.getActions().get(0).getValues().put("phone", "1234 d"); handler.handle(createEvent()); ArgumentCaptor<TaskHandlerException> captor = ArgumentCaptor.forClass(TaskHandlerException.class); verify(taskService).save(task); verify(taskService).findActiveTasksForTriggerSubject(TRIGGER_SUBJECT); verify(taskService).getActionEventFor(task.getActions().get(0)); verify(taskActivityService).addError(eq(task), captor.capture()); ArgumentCaptor<MotechEvent> captorEvent = ArgumentCaptor.forClass(MotechEvent.class); verify(eventRelay).sendEventMessage(captorEvent.capture()); verify(taskActivityService, never()).addSuccess(task); assertEquals(createHandlerFailureSubject(task.getName(), TRIGGER), captorEvent.getValue().getSubject()); assertEquals("task.error.convertToInteger", captor.getValue().getMessage()); }

Target:
public void shouldNotSendEventIfActionEventParameterCanNotBeConvertedToInteger() throws Exception { setTriggerEvent(); setActionEvent(); when(taskService.findActiveTasksForTriggerSubject(TRIGGER_SUBJECT)).thenReturn(tasks); when(taskService.getActionEventFor(task.getActions().get(0))).thenReturn(actionEvent); task.getActions().get(0).getValues().put("phone", "1234 d"); handler.handle(createEvent()); verify(taskService).save(task); verify(taskService).findActiveTasksForTriggerSubject(TRIGGER_SUBJECT); verify(taskService).getActionEventFor(task.getActions().get(0)); verify(taskActivityService).addError(eq(task), exceptionCaptor.capture(), eq(createEventParameters())); ArgumentCaptor<MotechEvent> captorEvent = ArgumentCaptor.forClass(MotechEvent.class); verify(eventRelay).sendEventMessage(captorEvent.capture()); verify(taskActivityService, never()).addSuccess(task); assertEquals(createHandlerFailureSubject(task.getName(), TRIGGER), captorEvent.getValue().getSubject()); assertEquals("task.error.convertToInteger", exceptionCaptor.getValue().getMessage()); }
Source:
HomeView( Binder uiBinder, PriceWidgetFactory priceWidgetFactory, PlaceManager placeManager, TokenFormatter tokenFormatter, AppMessages appMessages) { this.placeManager = placeManager; this.tokenFormatter = tokenFormatter; this.appMessages = appMessages; products = new ArrayList<>(); ProductDto shirt = new ProductDto(); shirt.setBrandName(appMessages.brandName(Brand.ARCBEES)); shirt.setPrice(55); shirt.setProductName("Shirt"); ProductDto bag = new ProductDto(); bag.setBrandName(appMessages.brandName(Brand.ARCBEES)); bag.setPrice(35); bag.setProductName("Bag"); shirtPrice = priceWidgetFactory.create(shirt); bagPrice = priceWidgetFactory.create(bag); products.add(shirtPrice); products.add(bagPrice); initWidget(uiBinder.createAndBindUi(this)); }

Target:
HomeView( Binder uiBinder, PriceWidgetFactory priceWidgetFactory, PlaceManager placeManager, TokenFormatter tokenFormatter, AppMessages appMessages) { this.priceWidgetFactory = priceWidgetFactory; this.placeManager = placeManager; this.tokenFormatter = tokenFormatter; this.appMessages = appMessages; products = new ArrayList<>(); createInitialProducts(Brand.getDefaultValue()); initWidget(uiBinder.createAndBindUi(this)); }
Source:
public void run() { try { if(ESReindexationProcessStatus.inFullReindexation()) return; } catch (DotDataException e2) { Logger.warn(this, "can't determine if we're in full reindex",e2); } int days = Config.getIntProperty("DIST_REINDEX_JOURNAL_CLEANUP_DAYS", 1); try { Logger.debug(this, "About to delete dist_reindex_journal entries older than "+ days +" day(s)"); HibernateUtil.startTransaction(); APILocator.getDistributedJournalAPI().distReindexJournalCleanup(days, false, false, DateType.DAY); HibernateUtil.closeAndCommitTransaction(); } catch (Exception e) { Logger.error(this, "Error ocurred while trying to delete dist_reindex_journal entries older than "+ days +" day(s)", e); try { HibernateUtil.rollbackTransaction(); } catch (DotHibernateException e1) { Logger.error(this, e1.getMessage(), e1); } } finally { try { HibernateUtil.closeSession(); } catch (DotHibernateException e) { Logger.error(this, e.getMessage(), e); } } }

Target:
public void run() { try { if(ESReindexationProcessStatus.inFullReindexation()) return; } catch (DotDataException e2) { Logger.warn(this, "can't determine if we're in full reindex",e2); } int days = Config.getIntProperty("DIST_REINDEX_JOURNAL_CLEANUP_DAYS", 1); try { Logger.debug(this, "About to delete dist_reindex_journal entries older than "+ days +" day(s)"); HibernateUtil.startTransaction(); APILocator.getDistributedJournalAPI().distReindexJournalCleanup(days, false, false, DateType.DAY); HibernateUtil.closeAndCommitTransaction(); } catch (Exception e) { Logger.error(this, "Error ocurred while trying to delete dist_reindex_journal entries older than "+ days +" day(s)", e); try { HibernateUtil.rollbackTransaction(); } catch (DotHibernateException e1) { Logger.error(this, e1.getMessage(), e1); } } finally { try { HibernateUtil.closeSession(); } catch (DotHibernateException e) { Logger.error(this, e.getMessage(), e); } DbConnectionFactory.closeConnection(); } }
Source:
public void shouldExecuteStatements() throws Exception { TransitionalPeriodTransactionMessContainer kernel = mockKernel(); QueryExecutionEngine executionEngine = mock( QueryExecutionEngine.class ); Result executionResult = mock( Result.class ); TransactionalContext transactionalContext = prepareKernelWithQuerySession( kernel ); when( executionEngine.executeQuery( "query", map(), transactionalContext ) ).thenReturn( executionResult ); TransactionRegistry registry = mock( TransactionRegistry.class ); when( registry.begin( any( TransactionHandle.class ) ) ).thenReturn( 1337L ); TransactionHandle handle = getTransactionHandle( kernel, executionEngine, registry ); ExecutionResultSerializer output = mock( ExecutionResultSerializer.class ); handle.execute( statements( new Statement( "query", map(), false, (ResultDataContent[]) null ) ), output, mock( HttpServletRequest.class ) ); verify( executionEngine ).executeQuery( "query", map(), transactionalContext ); InOrder outputOrder = inOrder( output ); outputOrder.verify( output ).transactionCommitUri( uriScheme.txCommitUri( 1337 ) ); outputOrder.verify( output ).statementResult( executionResult, false, (ResultDataContent[])null ); outputOrder.verify( output ).notifications( anyCollection() ); outputOrder.verify( output ).transactionStatus( anyLong() ); outputOrder.verify( output ).errors( MockitoHamcrest.argThat( hasNoErrors() ) ); outputOrder.verify( output ).finish(); verifyNoMoreInteractions( output ); }

Target:
public void shouldExecuteStatements() throws Exception { TransitionalPeriodTransactionMessContainer kernel = mockKernel(); QueryExecutionEngine executionEngine = mock( QueryExecutionEngine.class ); Result executionResult = mock( Result.class ); TransactionalContext transactionalContext = prepareKernelWithQuerySession( kernel ); when( executionEngine.executeQuery( "query", map(), transactionalContext ) ).thenReturn( executionResult ); TransactionRegistry registry = mock( TransactionRegistry.class ); when( registry.begin( any( TransactionHandle.class ) ) ).thenReturn( 1337L ); TransactionHandle handle = getTransactionHandle( kernel, executionEngine, registry ); ExecutionResultSerializer output = mock( ExecutionResultSerializer.class ); handle.execute( statements( new Statement( "query", map(), false, (ResultDataContent[]) null ) ), output, mock( HttpServletRequest.class ) ); verify( executionEngine ).executeQuery( "query", map(), transactionalContext ); InOrder outputOrder = inOrder( output ); outputOrder.verify( output ).transactionCommitUri( uriScheme.txCommitUri( 1337 ) ); outputOrder.verify( output ).statementResult( executionResult, false, (ResultDataContent[])null ); outputOrder.verify( output ).notifications( anyCollection() ); outputOrder.verify( output ).transactionStatus( anyLong() ); outputOrder.verify( output ).errors( argThat( hasNoErrors() ) ); outputOrder.verify( output ).finish(); verifyNoMoreInteractions( output ); }
Source:
private int positionedReadInternal(long pos, byte[] b, int off, int len) throws IOException { if (pos < 0 || pos >= mLength) { return -1; } LOG.info("AMDEBUG pread len ", len); if (len < 2 * Constants.MB) { LOG.info("AMDEBUG set for pread len ", len); mOptions.setPositionShort(true); } int lenCopy = len; CountingRetry retry = new CountingRetry(mBlockWorkerClientReadRetry); IOException lastException = null; while (len > 0 && retry.attempt()) { if (pos >= mLength) { break; } long blockId = mStatus.getBlockIds().get(Math.toIntExact(pos / mBlockSize)); try { if (mCachedPositionedReadStream == null) { mCachedPositionedReadStream = mBlockStore.getInStream(blockId, mOptions, mFailedWorkers); } else if (mCachedPositionedReadStream.getId() != blockId) { closeBlockInStream(mCachedPositionedReadStream); mCachedPositionedReadStream = mBlockStore.getInStream(blockId, mOptions, mFailedWorkers); } long offset = pos % mBlockSize; int bytesRead = mCachedPositionedReadStream.positionedRead(offset, b, off, (int) Math.min(mBlockSize - offset, len)); Preconditions.checkState(bytesRead > 0, "No data is read before EOF"); pos += bytesRead; off += bytesRead; len -= bytesRead; retry.reset(); lastException = null; triggerAsyncCaching(mCachedPositionedReadStream); } catch (UnavailableException | DeadlineExceededException | ConnectException e) { lastException = e; if (mCachedPositionedReadStream != null) { handleRetryableException(mCachedPositionedReadStream, e); mCachedPositionedReadStream = null; } } } if (lastException != null) { throw lastException; } return lenCopy - len; }

Target:
private int positionedReadInternal(long pos, byte[] b, int off, int len) throws IOException { if (pos < 0 || pos >= mLength) { return -1; } if (len < mContext.getPathConf(new AlluxioURI(mStatus.getPath())) .getBytes(PropertyKey.USER_FILE_SEQUENTIAL_PREAD_THRESHOLD)) { mOptions.setPositionShort(true); } int lenCopy = len; CountingRetry retry = new CountingRetry(mBlockWorkerClientReadRetry); IOException lastException = null; while (len > 0 && retry.attempt()) { if (pos >= mLength) { break; } long blockId = mStatus.getBlockIds().get(Math.toIntExact(pos / mBlockSize)); try { if (mCachedPositionedReadStream == null) { mCachedPositionedReadStream = mBlockStore.getInStream(blockId, mOptions, mFailedWorkers); } else if (mCachedPositionedReadStream.getId() != blockId) { closeBlockInStream(mCachedPositionedReadStream); mCachedPositionedReadStream = mBlockStore.getInStream(blockId, mOptions, mFailedWorkers); } long offset = pos % mBlockSize; int bytesRead = mCachedPositionedReadStream.positionedRead(offset, b, off, (int) Math.min(mBlockSize - offset, len)); Preconditions.checkState(bytesRead > 0, "No data is read before EOF"); pos += bytesRead; off += bytesRead; len -= bytesRead; retry.reset(); lastException = null; triggerAsyncCaching(mCachedPositionedReadStream); } catch (UnavailableException | DeadlineExceededException | ConnectException e) { lastException = e; if (mCachedPositionedReadStream != null) { handleRetryableException(mCachedPositionedReadStream, e); mCachedPositionedReadStream = null; } } } if (lastException != null) { throw lastException; } return lenCopy - len; }
Source:
public MavenDependencyResolver includeDependenciesFromPom(String path) throws ResolutionException { try { Validate.isReadable(path, "Path to the pom.xml file must be defined and accessible"); } catch (IllegalArgumentException e) { path = this.getLocalResourcePathFromResourceName(path); Validate.isReadable(path, "temp pom.xml file must be defined and accessible"); } Model model = system.loadPom(new File(path), settings, session); ArtifactTypeRegistry stereotypes = system.getArtifactTypeRegistry(session); for (org.apache.maven.model.Dependency dependency : model.getDependencies()) { dependencies.push(MavenConverter.fromDependency(dependency, stereotypes)); } return this; }

Target:
public MavenDependencyResolver includeDependenciesFromPom(String path) throws ResolutionException { path = resolvePathByQualifier(path); Validate.isReadable(path, "Path to the pom.xml file must be defined and accessible"); Model model = system.loadPom(new File(path), settings, session); ArtifactTypeRegistry stereotypes = system.getArtifactTypeRegistry(session); for (org.apache.maven.model.Dependency dependency : model.getDependencies()) { dependencies.push(MavenConverter.fromDependency(dependency, stereotypes)); } return this; }
Source:
public void add(String nodeKey, String propertyName, Object[] values) { CheckArg.isNotNull(nodeKey, "nodeKey"); CheckArg.isNotNull(propertyName, "propertyName"); CheckArg.isNotNull(values, "values"); EsIndexColumn column = columns.column(propertyName); assert column != null : "Unexpected column for the index " + name(); try { EsDocument doc = findOrCreateDoc(nodeKey); putValues(doc, column, values); client.storeDocument(name(), workspace, nodeKey, doc); client.refresh(name()); } catch (IOException e) { throw new EsIndexException(e); } }

Target:
public void add(String nodeKey, String propertyName, Object[] values) { CheckArg.isNotNull(nodeKey, "nodeKey"); CheckArg.isNotNull(propertyName, "propertyName"); CheckArg.isNotNull(values, "values"); EsIndexColumn column = columns.column(propertyName); assert column != null : "Unexpected column for the index " + name(); try { EsRequest doc = findOrCreateDoc(nodeKey); putValues(doc, column, values); client.storeDocument(name(), workspace, nodeKey, doc); } catch (IOException e) { throw new EsIndexException(e); } }
Source:
public String getUid() { return dataHandler.getAsString(BlogXPath.contributorUserid); }

Target:
public String getUid() { return dataHandler.getAsString(ForumsXPath.contributorUserid); }
Source:
public String[] getSupportedTypes() { return new String[] { SiteRest.CATEGORY + "." + SiteRest.NAME }; }

Target:
public String[] getSupportedTypes() { return new String[] {SiteRest.CATEGORY + "." + SiteRest.NAME, EPersonRest.CATEGORY + "." + EPersonRest.NAME}; }
Source:
private void displayHeader(Collection<String> labels) { table.resizeColumns(2 + labels.size()); final CellFormatter fmt = table.getCellFormatter(); int col = 0; table.setText(0, col, Util.C.approvalTableReviewer()); fmt.setStyleName(0, col, Gerrit.RESOURCES.css().header()); col++; table.clearCell(0, col); fmt.setStyleName(0, col, Gerrit.RESOURCES.css().header()); col++; List<String> sorted_labels = new ArrayList<String>(); sorted_labels.addAll(labels); Collections.sort(sorted_labels); for (String name : sorted_labels) { table.setText(0, col, name); fmt.setStyleName(0, col, Gerrit.RESOURCES.css().header()); col++; } fmt.addStyleName(0, col - 1, Gerrit.RESOURCES.css().rightmost()); }

Target:
private void displayHeader(Collection<String> labels) { table.resizeColumns(2 + labels.size()); final CellFormatter fmt = table.getCellFormatter(); int col = 0; table.setText(0, col, Util.C.approvalTableReviewer()); fmt.setStyleName(0, col, Gerrit.RESOURCES.css().header()); col++; table.clearCell(0, col); fmt.setStyleName(0, col, Gerrit.RESOURCES.css().header()); col++; for (String name : labels) { table.setText(0, col, name); fmt.setStyleName(0, col, Gerrit.RESOURCES.css().header()); col++; } fmt.addStyleName(0, col - 1, Gerrit.RESOURCES.css().rightmost()); }
Source:
protected void openLinkInNewTab(WebElement link) { String oldTab = driver.getWindowHandle(); waitForLinkOpenedInNewTab(link); switchToNewTab(oldTab); }

Target:
protected void openLinkInNewTab(WebElement link) { String currentTab = driver.getWindowHandle(); waitForLinkOpenedInNewTab(link); switchToNewTab(currentTab); }
Source:
public void aboutToBeShown() { super.aboutToBeShown(); this.selectionListener = new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { IStructuredSelection selection = radioGroupViewer.getStructuredSelection(); Object newValue = selection.getFirstElement(); controller.updateValue(newValue); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }; this.radioGroup.addSelectionListener(this.selectionListener); this.controller.onNewValue(new IConsumer<Object>() { @Override public void apply(Object value) { if (!radioGroup.isDisposed()) { final ISelection selection; if (value != null) { selection = new StructuredSelection(value); } else { selection = null; } radioGroupViewer.setSelection(selection); if (isEnabled() && !radioGroup.isEnabled()) { radioGroup.setEnabled(true); } } } }); this.controller.onNewCandidates(new IConsumer<List<Object>>() { @Override public void apply(List<Object> candidates) { if (!radioGroup.isDisposed()) { if (candidates != null) { radioGroupViewer.setInput(candidates.toArray()); } else { radioGroupViewer.setInput(null); } if (isEnabled() && !radioGroup.isEnabled()) { radioGroup.setEnabled(true); } radioGroupViewer.refresh(true); } } }); }

Target:
public void aboutToBeShown() { super.aboutToBeShown(); this.selectionListener = new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { IStructuredSelection selection = radioGroupViewer.getStructuredSelection(); Object newValue = selection.getFirstElement(); controller.updateValue(newValue); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }; this.radioGroup.addSelectionListener(this.selectionListener); this.controller.onNewValue(new IConsumer<Object>() { @Override public void apply(Object value) { if (!radioGroup.isDisposed()) { final ISelection selection; if (value != null) { selection = new StructuredSelection(value); } else { selection = null; } radioGroupViewer.setSelection(selection); if (!radioGroup.isEnabled()) { radioGroup.setEnabled(true); } } } }); this.controller.onNewCandidates(new IConsumer<List<Object>>() { @Override public void apply(List<Object> candidates) { if (!radioGroup.isDisposed()) { if (candidates != null) { radioGroupViewer.setInput(candidates.toArray()); } else { radioGroupViewer.setInput(null); } if (!radioGroup.isEnabled()) { radioGroup.setEnabled(true); } radioGroupViewer.refresh(true); } } }); }
Source:
public void shouldReflectChangesInASecretFile() throws Exception { Path temporarySecretFile = Files.createTempFile("vault", null); Path vaultDirectory = temporarySecretFile.getParent(); String secretName = temporarySecretFile.getFileName().toString(); PlainTextVaultProvider provider = new PlainTextVaultProvider(vaultDirectory); Files.write(temporarySecretFile, "secret1".getBytes()); VaultRawSecret secret1 = provider.obtainSecret(secretName); Files.write(temporarySecretFile, "secret2".getBytes()); VaultRawSecret secret2 = provider.obtainSecret(secretName); assertEquals("secret1", new String(secret1.getRawSecret().get().array())); assertEquals("secret2", new String(secret2.getRawSecret().get().array())); }

Target:
public void shouldReflectChangesInASecretFile() throws Exception { Path temporarySecretFile = Files.createTempFile("vault", null); Path vaultDirectory = temporarySecretFile.getParent(); String secretName = temporarySecretFile.getFileName().toString(); PlainTextVaultProvider provider = new PlainTextVaultProvider(vaultDirectory, "ignored") { @Override protected Path resolveSecretPath(String vaultSecretId) { return vaultDirectory.resolve(vaultSecretId); } }; String secret1AsString = null; String secret2AsString = null; Files.write(temporarySecretFile, "secret1".getBytes()); try (VaultRawSecret secret1 = provider.obtainSecret(secretName)) { secret1AsString = StandardCharsets.UTF_8.decode(secret1.getRawSecret().get()).toString(); } Files.write(temporarySecretFile, "secret2".getBytes()); try (VaultRawSecret secret2 = provider.obtainSecret(secretName)) { secret2AsString = StandardCharsets.UTF_8.decode(secret2.getRawSecret().get()).toString(); } assertEquals("secret1", secret1AsString); assertEquals("secret2", secret2AsString); }
Source:
public void reportTrace(EvaluationTrace trace) { traceRoot.reportSubtrace(trace); }

Target:
public void reportTrace(EvaluationTrace trace) { if (traceRoot != null) { traceRoot.reportSubtrace(trace); } }
Source:
protected void handleArgumentCommand(String command, String parameter, Iterator<String> args) { switch (command) { case "-a": parameter = args.next(); case "--algorithms": algorithms = new ArrayList<>(); for (String algorithm : parameter.split(",")) { algorithms.add(algorithm); } break; case "-b": case "--batch-mode": batchMode = true; break; case "-f": parameter = args.next(); case "--users-file": usersFileName = parameter; break; case "-p": parameter = args.next(); case "--password": password = parameter; break; case "-c": case "--clear-text": plainText = true; break; case "-e": case "--encrypted": plainText = false; break; case "-g": parameter = args.next(); case "--groups": for (String group : parameter.split(",")) { addGroups.add(group); } break; case "-w": parameter = args.next(); case "--groups-file": groupsFileName = parameter; break; case "-r": parameter = args.next(); case "--realm": realm = parameter; break; case "-s": parameter = args.next(); case "--server-root": serverRoot = new File(parameter); break; case "-u": parameter = args.next(); case "--user": username = parameter; break; default: throw new IllegalArgumentException(); } }

Target:
protected void handleArgumentCommand(String command, String parameter, Iterator<String> args) { switch (command) { case "-a": parameter = args.next(); case "--algorithms": algorithms = Arrays.stream(parameter.split(",")).collect(Collectors.toList()); break; case "-b": case "--batch-mode": batchMode = true; break; case "-f": parameter = args.next(); case "--users-file": usersFileName = parameter; break; case "-p": parameter = args.next(); case "--password": password = parameter; break; case "-c": case "--clear-text": plainText = true; break; case "-e": case "--encrypted": plainText = false; break; case "-g": parameter = args.next(); case "--groups": for (String group : parameter.split(",")) { addGroups.add(group); } break; case "-w": parameter = args.next(); case "--groups-file": groupsFileName = parameter; break; case "-r": parameter = args.next(); case "--realm": realm = parameter; break; case "-s": parameter = args.next(); case "--server-root": serverRoot = new File(parameter); break; case "-u": parameter = args.next(); case "--user": username = parameter; break; default: throw new IllegalArgumentException(); } }
Source:
public final Session session( AccessMode mode ) { assertOpen(); Session session = sessionFactory.newInstance( mode ); if ( closed.get() ) { closeResources(); throw new DriverClosedException(); } return session; }

Target:
public final Session session( AccessMode mode ) { assertOpen(); Session session = sessionFactory.newInstance( mode ); if ( closed.get() ) { closeResources(); throw driverCloseException(); } return session; }
Source:
private void validateContractInput(String containerIdentifier, InputDefinition inputDefinition) { validateContractInputName(inputDefinition.getName()); if (inputDefinition.hasChildren() && (inputDefinition.getType() != null && !inputDefinition.getType().equals(Type.FILE))) { addError("Can't have a type set on the contract input <" + inputDefinition.getName() + "> of contract of " + containerIdentifier + " because it has children"); } if (!inputDefinition.hasChildren() && inputDefinition.getType() == null) { addError("Type not set on the contract input <" + inputDefinition.getName() + "> of contract of " + containerIdentifier); } if (inputDefinition.hasChildren()) { for (InputDefinition definition : inputDefinition.getInputs()) { validateContractInput(containerIdentifier, definition); } } }

Target:
private void validateContractInput(String containerIdentifier, InputDefinition inputDefinition) { validateContractInputName(inputDefinition.getName()); if (inputDefinition.hasChildren() && (inputDefinition.getType() != null && !inputDefinition.getType().equals(Type.FILE))) { addError("Can't have a type set on the contract input <" + inputDefinition.getName() + "> on " + containerIdentifier + " because it has children"); } if (!inputDefinition.hasChildren() && inputDefinition.getType() == null) { addError("Type not set on the contract input <" + inputDefinition.getName() + "> on " + containerIdentifier); } if (inputDefinition.hasChildren()) { for (InputDefinition definition : inputDefinition.getInputs()) { validateContractInput(containerIdentifier, definition); } } }
Source:
public void hasMetrics() { List<MetricName> expected = Arrays.asList("nuxeo.cache.defaultCache.read", "nuxeo.cache.defaultCache.read-hit", "nuxeo.cache.defaultCache.read-hit-ratio", "nuxeo.cache.defaultCache.read-miss", "nuxeo.cache.defaultCache.write", "nuxeo.cache.defaultCache.invalidate-all", "nuxeo.cache.defaultCache.size").stream().map(MetricName::build).collect(Collectors.toList()); SharedMetricRegistries.getOrCreate(MetricsService.class.getName()).getNames() .containsAll(expected); }

Target:
public void hasMetrics() { List<MetricName> expected = Arrays.asList("nuxeo.cache.read", "nuxeo.cache.hit", "nuxeo.cache.hit.ratio", "nuxeo.cache.invalidation", "nuxeo.cache.size") .stream() .map(name -> MetricName.build(name).tagged("cache", "default-test-cache")) .collect(Collectors.toList()); Assert.assertTrue( SharedMetricRegistries.getOrCreate(MetricsService.class.getName()).getNames().containsAll(expected)); }
Source:
public QueryRequestSessionContext(CreateQuerySession createQuerySession, HttpServletRequest servletRequest) { this.createQuerySession = requireNonNull(createQuerySession, "createQuerySession is null"); checkArgument(!isNullOrEmpty(createQuerySession.getUser()), "User must be set"); this.identity = new Identity(createQuerySession.getUser(), Optional.ofNullable(servletRequest.getUserPrincipal())); this.remoteUserAddress = servletRequest.getRemoteAddr(); ImmutableMap.Builder<String, String> systemProperties = ImmutableMap.builder(); Map<String, ImmutableMap.Builder<String, String>> catalogSessionProperties = new HashMap<>(); if (createQuerySession.getProperties() != null && !createQuerySession.getProperties().isEmpty()) { for (Map.Entry<String, String> entry : createQuerySession.getProperties().entrySet()) { String fullPropertyName = entry.getKey(); String propertyValue = entry.getValue(); List<String> nameParts = PROPERTY_NAME_SPLITTER.splitToList(fullPropertyName); if (nameParts.size() == 1) { String propertyName = nameParts.get(0); checkArgument(!propertyName.isEmpty(), "propertyName is empty"); systemProperties.put(propertyName, propertyValue); } else if (nameParts.size() == 2) { String catalogName = nameParts.get(0); String propertyName = nameParts.get(1); checkArgument(!catalogName.isEmpty(), "catalogName is empty"); checkArgument(!propertyName.isEmpty(), "propertyName is empty"); catalogSessionProperties.computeIfAbsent(catalogName, id -> ImmutableMap.builder()).put(propertyName, propertyValue); } else { throw new IllegalArgumentException("Invalid property name: " + fullPropertyName); } } } this.systemProperties = systemProperties.build(); this.catalogSessionProperties = catalogSessionProperties.entrySet().stream() .collect(toImmutableMap(Map.Entry::getKey, entry -> entry.getValue().build())); }

Target:
public QueryRequestSessionContext(CreateQuerySession createQuerySession, HttpServletRequest servletRequest) { assertRequest(createQuerySession != null, "createQuerySession is null"); this.createQuerySession = createQuerySession; assertRequest(!isNullOrEmpty(createQuerySession.getUser()), "User must be set"); this.identity = new Identity(createQuerySession.getUser(), Optional.ofNullable(servletRequest.getUserPrincipal())); this.remoteUserAddress = servletRequest.getRemoteAddr(); if (createQuerySession.getProperties() != null && !createQuerySession.getProperties().isEmpty()) { SystemAndCatalogProperties systemAndCatalogProperties = parseSessionProperties(createQuerySession.getProperties(), "Invalid properties object"); this.systemProperties = systemAndCatalogProperties.getSystemProperties(); this.catalogSessionProperties = systemAndCatalogProperties.getCatalogProperties(); } else { this.systemProperties = ImmutableMap.of(); this.catalogSessionProperties = ImmutableMap.of(); } this.transactionId = Optional.ofNullable(createQuerySession.getTransactionId()).map(TransactionId::valueOf); }
Source:
private void blanketApproveDisbursementVoucherDocument(CuDisbursementVoucherDocument dv) throws WorkflowException { try { getDocumentService().blanketApproveDocument(dv, "Auto blanket approve from Batch Job", null); } catch (WorkflowException e) { LOG.error("approveDisbursementVoucherDocument: Unable to blanket approve DV Document ID::" + dv.getDocumentNumber() + "the exception was: ", e); throw e; } }

Target:
private void blanketApproveDisbursementVoucherDocument(CuDisbursementVoucherDocument dv) throws WorkflowException { try { getDocumentService().blanketApproveDocument(dv, "Auto blanket approve from Batch Job", null); } catch (WorkflowException e) { LOG.error("blanketApproveDisbursementVoucherDocument: Unable to blanket approve DV Document ID::" + dv.getDocumentNumber() + "the exception was: ", e); throw e; } }
Source:
private SelectedGpxFile getSelectedFileByLoadedFileName(String path) { List<SelectedGpxFile> newList = new ArrayList<>(selectedGPXFiles); for (SelectedGpxFile s : newList) { if (path.endsWith("/" + s.getLoadedName())) { return s; } } return null; }

Target:
private SelectedGpxFile getSelectedFileByLoadedFileName(String path) { List<SelectedGpxFile> newList = new ArrayList<>(selectedGPXFiles); for (SelectedGpxFile s : newList) { if (path.endsWith("/" + s.getLoadingFileName())) { return s; } } return null; }
Source:
public Map<String, Object> getQueueInfo(String queueName) throws JMSException { log.debug("Getting info about queue {}", queueName); List<Map<String, Object>> mm = runQuery("_object_id", singularMap("_object_name", queueName)); if (mm.size() == 0) { throw new RuntimeException("Couldn't find a queue in Qpid: " + queueName); } if (mm.size() > 1) { throw new RuntimeException("Found unexpected amount of information about queue: " + queueName); } return mm.get(0); }

Target:
private Map<String, Object> getQueueInfo(String queueName) throws JMSException { log.debug("Getting info about queue {}", queueName); List<Map<String, Object>> mm = runQuery("_object_id", singularMap("_object_name", queueName)); if (mm.size() == 0) { throw new RuntimeException("Couldn't find a queue in Qpid: " + queueName); } if (mm.size() > 1) { throw new RuntimeException("Found unexpected amount of information about queue: " + queueName); } return mm.get(0); }
Source:
private static Termios convertToTermios(TerminalSettings settings) { Termios result = new Termios(); result.c_iflag = settings.c_iflag; result.c_oflag = settings.c_oflag; result.c_cflag = settings.c_cflag; System.arraycopy(settings.c_cc, 0, result.c_cc, 0, settings.c_cc.length); result.c_ispeed = settings.c_ispeed; result.c_ospeed = settings.c_ospeed; return result; }

Target:
private static Termios convertToTermios(TerminalSettings settings) { Termios result = new Termios(); result.c_iflag = settings.c_iflag; result.c_oflag = settings.c_oflag; result.c_cflag = settings.c_cflag; result.c_lflag = settings.c_lflag; System.arraycopy(settings.c_cc, 0, result.c_cc, 0, settings.c_cc.length); result.c_ispeed = settings.c_ispeed; result.c_ospeed = settings.c_ospeed; return result; }
Source:
public void handlePost(ActionParameters params) throws ActionException { params.requireLoggedInUser(); MyPlaceCategory category = new MyPlaceCategory(); category.setUuid(params.getUser().getUuid()); category.setName(params.getRequiredParam(PARAM_NAME)); category.getWFSLayerOptions() .setDefaultFeatureStyle(JSONHelper.createJSONObject(params.getHttpParam(PARAM_STYLE))); try { layerService.insert(Collections.singletonList(category)); LOG.info("Inserted category:", category.getId()); } catch (ServiceException e) { LOG.warn(e); throw new ActionException("Failed to insert layers"); } AuditLog.user(params.getClientIp(), params.getUser()) .withParam("id", category.getId()) .withParam("name", category.getName()) .added(AuditLog.ResourceType.MYPLACES_LAYER); JSONObject response = toLayerJSON(category); ResponseHelper.writeResponse(params, 200, response); }

Target:
public void handlePost(ActionParameters params) throws ActionException { MyPlaceCategory category = new MyPlaceCategory(); category.setUuid(params.getUser().getUuid()); category.setName(params.getRequiredParam(PARAM_NAME)); category.getWFSLayerOptions() .setDefaultFeatureStyle(JSONHelper.createJSONObject(params.getHttpParam(PARAM_STYLE))); try { layerService.insert(Collections.singletonList(category)); LOG.info("Inserted category:", category.getId()); } catch (ServiceException e) { LOG.warn(e); throw new ActionException("Failed to insert layers"); } AuditLog.user(params.getClientIp(), params.getUser()) .withParam("id", category.getId()) .withParam("name", category.getName()) .added(AuditLog.ResourceType.MYPLACES_LAYER); JSONObject response = toLayerJSON(category); ResponseHelper.writeResponse(params, 200, response); }
Source:
private double calcTimeoutToFence(int vmCount, VdsSpmStatus spmStatus) { int spmIndicator = 0; if (spmStatus == VdsSpmStatus.SPM) { spmIndicator = 1; } return TimeUnit.SECONDS.toMillis((int)( Config.<Integer> GetValue(ConfigValues.TimeoutToResetVdsInSeconds) + (Config.<Double> GetValue(ConfigValues.DelayResetForSpmInSeconds) * spmIndicator) + (Config.<Double> GetValue(ConfigValues.DelayResetPerVmInSeconds) * vmCount))); }

Target:
private double calcTimeoutToFence(int vmCount, VdsSpmStatus spmStatus) { int spmIndicator = 0; if (spmStatus != VdsSpmStatus.None) { spmIndicator = 1; } return TimeUnit.SECONDS.toMillis((int)( Config.<Integer> GetValue(ConfigValues.TimeoutToResetVdsInSeconds) + (Config.<Double> GetValue(ConfigValues.DelayResetForSpmInSeconds) * spmIndicator) + (Config.<Double> GetValue(ConfigValues.DelayResetPerVmInSeconds) * vmCount))); }
Source:
public static void testFormula() { try { GeopointParser.parse("N 12° 23.345′ E 123° 34.5AB′"); fail(); } catch (final Geopoint.ParseException e) { } try { GeopointParser.parse("N 12° 23′ E 123° 3A′"); fail(); } catch (final Geopoint.ParseException e) { } try { GeopointParser.parse("N 12° E 12A°"); fail(); } catch (final Geopoint.ParseException e) { } try { GeopointParser.parse("N 12° 23′ 34″ E 123° 34′ 5A″"); fail(); } catch (final Geopoint.ParseException e) { } try { GeopointParser.parse("N 12° 23′ 34.56″ E 123° 34′ 56.7A″"); fail(); } catch (final Geopoint.ParseException e) { } try { GeopointParser.parse("-12.345678° 23.4ABCDE°"); fail(); } catch (final Geopoint.ParseException e) { } }

Target:
public static void testFormula() { assertParsingFails("N 12° 23.345′ E 123° 34.5AB′"); assertParsingFails("N 12° 23′ E 123° 3A′"); assertParsingFails("N 12° E 12A°"); assertParsingFails("N 12° 23′ 34″ E 123° 34′ 5A″"); assertParsingFails("N 12° 23′ 34.56″ E 123° 34′ 56.7A″"); assertParsingFails("-12.345678° 23.4ABCDE°"); }
Source:
public void testWorkdirIsDotGit_CreateRepositoryFromWorkDirOnly() throws Exception { File workdir = getFile("workdir", "repo"); Repository repo = new Repository(null, workdir); assertTrue(repo.getDirectory().getName().equals(Constants.DOT_GIT)); }

Target:
public void testWorkdirIsDotGit_CreateRepositoryFromWorkDirOnly() throws Exception { File workdir = getFile("workdir", "repo"); Repository repo = new Repository(null, workdir); assertGitdirPath(repo, "workdir", "repo", Constants.DOT_GIT); }
Source:
public boolean performNextOperation(int completedChildCount) { if (getParameters().getNextStep() == null) { return false; } switch (getParameters().getNextStep()) { case GEO_REP: GlusterVolumeGeoRepSessionParameters parameters = new GlusterVolumeGeoRepSessionParameters(getSession().getMasterVolumeId(), getSession().getId()); parameters.setEndProcedure(EndProcedure.COMMAND_MANAGED); parameters.setParentCommand(getActionType()); parameters.setParentParameters(getParameters()); getParameters().setNextStep(DRStep.REMOVE_TMP_SNAPSHOTS); CommandCoordinatorUtil.executeAsyncCommand(VdcActionType.GlusterStorageGeoRepSyncInternal, parameters, cloneContextAndDetachFromParent()); persistCommandIfNeeded(); break; case REMOVE_TMP_SNAPSHOTS: removeDRSnapshots(); getParameters().setNextStep(null); persistCommandIfNeeded(); break; } return true; }

Target:
public boolean performNextOperation(int completedChildCount) { if (getParameters().getNextStep() == null) { return false; } switch (getParameters().getNextStep()) { case GEO_REP: GlusterVolumeGeoRepSessionParameters parameters = new GlusterVolumeGeoRepSessionParameters(getSession().getMasterVolumeId(), getSession().getId()); parameters.setEndProcedure(EndProcedure.COMMAND_MANAGED); parameters.setParentCommand(getActionType()); parameters.setParentParameters(getParameters()); getParameters().setNextStep(DRStep.REMOVE_TMP_SNAPSHOTS); runInternalActionWithTasksContext(VdcActionType.GlusterStorageGeoRepSyncInternal, parameters); persistCommandIfNeeded(); break; case REMOVE_TMP_SNAPSHOTS: removeDRSnapshots(); getParameters().setNextStep(null); persistCommandIfNeeded(); break; } return true; }
Source:
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { if (args.length > 0 && args[0].contains("lock") && user.isAuthorized("essentials.jump.lock")) { if (user.isFlyClickJump()) { user.setRightClickJump(false); user.sendMessage(tl("jumpEasterDisable")); } else { user.setRightClickJump(true); user.sendMessage(tl("jumpEasterEnable")); } return; } Location loc; final Location cloc = user.getLocation(); try { loc = LocationUtil.getTarget(user.getBase()); loc.setYaw(cloc.getYaw()); loc.setPitch(cloc.getPitch()); loc.setY(loc.getY() + 1); } catch (NullPointerException ex) { throw new Exception(tl("jumpError"), ex); } final Trade charge = new Trade(this.getName(), ess); charge.isAffordableFor(user); user.getTeleport().teleport(loc, charge, TeleportCause.COMMAND); throw new NoChargeException(); }

Target:
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { if (args.length > 0 && args[0].contains("lock") && user.isAuthorized("essentials.jump.lock")) { if (user.isFlyClickJump()) { user.setRightClickJump(false); user.sendMessage(tl("jumpEasterDisable")); } else { user.setRightClickJump(true); user.sendMessage(tl("jumpEasterEnable")); } return; } Location loc; final Location cloc = user.getLocation(); try { loc = LocationUtil.getTarget(user.getBase()); loc.setYaw(cloc.getYaw()); loc.setPitch(cloc.getPitch()); loc.setY(loc.getY() + 1); } catch (NullPointerException ex) { throw new Exception(tl("jumpError"), ex); } final Trade charge = new Trade(this.getName(), ess); charge.isAffordableFor(user); user.getAsyncTeleport().teleport(loc, charge, TeleportCause.COMMAND, getNewExceptionFuture(user.getSource(), commandLabel)); }
Source:
public List<Pool> createAndEnrichPools(Pool masterPool, List<Pool> existingPools) { List<Pool> pools = new LinkedList<Pool>(); masterPool.setQuantity(calculateQuantity(masterPool.getQuantity(), masterPool.getProduct(), masterPool.getUpstreamPoolId())); String virtOnly = masterPool.getProductAttribute(Product.Attributes.VIRT_ONLY); if (virtOnly != null && !virtOnly.isEmpty()) { masterPool.setAttribute(Pool.Attributes.VIRT_ONLY, virtOnly); } log.info("Checking if pools need to be created for: {}", masterPool); if (!hasMasterPool(existingPools)) { if (masterPool.getSourceSubscription() != null && masterPool.getSourceSubscription().getSubscriptionSubKey().contentEquals("derived")) { throw new IllegalStateException("Cannot create master pool from bonus pool"); } pools.add(masterPool); log.info("Creating new master pool: {}", masterPool); } Pool bonusPool = createBonusPool(masterPool, existingPools); if (bonusPool != null) { pools.add(bonusPool); } return pools; }

Target:
public List<Pool> createAndEnrichPools(Pool masterPool, List<Pool> existingPools) { List<Pool> pools = new LinkedList<Pool>(); masterPool.setQuantity(calculateQuantity(masterPool.getQuantity(), masterPool.getProduct(), masterPool.getUpstreamPoolId())); String virtOnly = masterPool.getProductAttributeValue(Product.Attributes.VIRT_ONLY); if (virtOnly != null && !virtOnly.isEmpty()) { masterPool.setAttribute(Pool.Attributes.VIRT_ONLY, virtOnly); } log.info("Checking if pools need to be created for: {}", masterPool); if (!hasMasterPool(existingPools)) { if (masterPool.getSourceSubscription() != null && masterPool.getSourceSubscription().getSubscriptionSubKey().contentEquals("derived")) { throw new IllegalStateException("Cannot create master pool from bonus pool"); } pools.add(masterPool); log.info("Creating new master pool: {}", masterPool); } Pool bonusPool = createBonusPool(masterPool, existingPools); if (bonusPool != null) { pools.add(bonusPool); } return pools; }
Source:
public void TestStartNewWikiButton_001 () { HomePageObject homePage = new HomePageObject(driver); homePage.getUrl(urlBuilder.getUrlForWiki("muppet")); homePage.getVenusGlobalNav().clickStartNewWiki(); Assertion.assertTrue(driver.getCurrentUrl().contains("Special:CreateNewWiki")); }

Target:
public void TestStartNewWikiButton_001 () { HomePageObject homePage = new HomePageObject(driver); homePage.getUrl(urlBuilder.getUrlForWiki("muppet")); CreateNewWikiPageObjectStep1 createNewWikiPage = homePage.getVenusGlobalNav().clickStartNewWiki(); Assertion.assertTrue(createNewWikiPage.verifyPage()); }
Source:
private void cacheServiceMetrics(Service srvc, String srvcName) { Map<GridServiceMethodReflectKey, HistogramMetricImpl> srvcHistograms = invocationHistograms.get(srvcName); if (srvcHistograms != null) return; srvcHistograms = new HashMap<>(); for (Class<?> itf : allInterfaces(srvc.getClass())) { for (Method mtd : itf.getMethods()) { if (metricIgnored(mtd.getDeclaringClass())) continue; HistogramMetricImpl histogram = createHistogram(srvcName, mtd); srvcHistograms.put(new GridServiceMethodReflectKey(mtd.getName(), mtd.getParameterTypes()), histogram); } } invocationHistograms.put(srvcName, srvcHistograms); }

Target:
private void cacheServiceMetrics(Service srvc, String srvcName) { Map<GridServiceMethodReflectKey, HistogramMetricImpl> srvcHistograms = invocationHistograms.get(srvcName); if (srvcHistograms != null) return; srvcHistograms = new HashMap<>(); for (Class<?> itf : allInterfaces(srvc.getClass())) { for (Method mtd : itf.getMethods()) { if (metricIgnored(mtd.getDeclaringClass())) continue; HistogramMetricImpl histogram = createHistogram(srvcName, mtd); srvcHistograms.put(new GridServiceMethodReflectKey(mtd.getName(), mtd.getParameterTypes()), histogram); } } invocationHistograms.put(srvcName, Collections.unmodifiableMap(srvcHistograms)); }