auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testStartStreaming() throws InterruptedException { Mockito.when(client.initializeState(StreamFrom.BEGINNING, StreamTo.NOW)).thenReturn(Completable.complete()); Mockito.when(client.startStreaming(Mockito.<Short[]>anyVararg())).thenReturn(Completable.complete()); SessionState sessionState = Mockito.mock(SessionState.class); Mockito.when(sessionState.isAtEnd()).thenReturn(false, false, true); Mockito.when(client.sessionState()).thenReturn(sessionState); BlockingQueue<ByteBuf> resultsQueue = new ArrayBlockingQueue<>(3); streamingConnection.startStreaming(resultsQueue); Assert.assertTrue(streamingConnection.isStreaming()); Thread.sleep(4 * 500); Mockito.verify(client, Mockito.times(3)).sessionState(); }

Target:
public void testStartStreaming() throws InterruptedException { Mockito.when(client.initializeState(StreamFrom.BEGINNING, StreamTo.NOW)).thenReturn(Completable.complete()); Mockito.when(client.startStreaming(Mockito.<Short[]>anyVararg())).thenReturn(Completable.complete()); SessionState sessionState = Mockito.mock(SessionState.class); Mockito.when(sessionState.isAtEnd()).thenReturn(false, false, true); Mockito.when(client.sessionState()).thenReturn(sessionState); BlockingQueue<ByteBuf> resultsQueue = new ArrayBlockingQueue<>(3); streamingConnection.startStreaming(resultsQueue); Assert.assertTrue(streamingConnection.isStreaming()); Thread.sleep(2000); Mockito.verify(client, Mockito.times(3)).sessionState(); }
Source:
int runCmd(CommandLine cmdLine) throws Exception { final String includingBookieId = cmdLine.getOptionValue("missingreplica"); final String excludingBookieId = cmdLine.getOptionValue("excludingmissingreplica"); Predicate<List<String>> predicate = null; if (!StringUtils.isBlank(includingBookieId) && !StringUtils.isBlank(excludingBookieId)) { predicate = replicasList -> (replicasList.contains(includingBookieId) && !replicasList.contains(excludingBookieId)); } else if (!StringUtils.isBlank(includingBookieId)) { predicate = replicasList -> replicasList.contains(includingBookieId); } else if (!StringUtils.isBlank(excludingBookieId)) { predicate = replicasList -> !replicasList.contains(excludingBookieId); } LedgerManagerFactory mFactory = null; try { mFactory = LedgerManagerFactory.newLedgerManagerFactory( bkConf, new ZkLayoutManager( ZooKeeperClient.newBuilder() .connectString(bkConf.getZkServers()) .sessionTimeoutMs(bkConf.getZkTimeout()) .build(), bkConf.getZkLedgersRootPath(), ZkUtils.getACLs(bkConf))); LedgerUnderreplicationManager underreplicationManager = mFactory.newLedgerUnderreplicationManager(); Iterator<Long> iter = underreplicationManager.listLedgersToRereplicate(predicate); while (iter.hasNext()) { System.out.println(ledgerIdFormatter.formatLedgerId(iter.next())); } } finally { if (mFactory != null) { mFactory.uninitialize(); } } return 0; }

Target:
int runCmd(CommandLine cmdLine) throws Exception { final String includingBookieId = cmdLine.getOptionValue("missingreplica"); final String excludingBookieId = cmdLine.getOptionValue("excludingmissingreplica"); Predicate<List<String>> predicate = null; if (!StringUtils.isBlank(includingBookieId) && !StringUtils.isBlank(excludingBookieId)) { predicate = replicasList -> (replicasList.contains(includingBookieId) && !replicasList.contains(excludingBookieId)); } else if (!StringUtils.isBlank(includingBookieId)) { predicate = replicasList -> replicasList.contains(includingBookieId); } else if (!StringUtils.isBlank(excludingBookieId)) { predicate = replicasList -> !replicasList.contains(excludingBookieId); } try (RegistrationManager rm = RegistrationManager.instantiateRegistrationManager(bkConf)) { try (LedgerManagerFactory mFactory = LedgerManagerFactory.newLedgerManagerFactory(bkConf, rm.getLayoutManager())) { LedgerUnderreplicationManager underreplicationManager = mFactory.newLedgerUnderreplicationManager(); Iterator<Long> iter = underreplicationManager.listLedgersToRereplicate(predicate); while (iter.hasNext()) { System.out.println(ledgerIdFormatter.formatLedgerId(iter.next())); } } } return 0; }
Source:
public void testWriteAndReadBCFWithIndex() throws IOException { final File bcfOutputFile = File.createTempFile("testWriteAndReadVCF.", ".bcf", tempDir); Tribble.indexFile(bcfOutputFile).deleteOnExit(); final VCFHeader header = createFakeHeader(); try (final VariantContextWriter writer = new VariantContextWriterBuilder() .setOutputFile(bcfOutputFile).setReferenceDictionary(header.getSequenceDictionary()) .setOptions(EnumSet.of(Options.INDEX_ON_THE_FLY)) .build()) { writer.writeHeader(header); writer.add(createVC(header)); writer.add(createVC(header)); } VariantContextTestProvider.VariantContextContainer container = VariantContextTestProvider .readAllVCs(bcfOutputFile, new BCF2Codec()); int counter = 0; final Iterator<VariantContext> it = container.getVCs().iterator(); while (it.hasNext()) { it.next(); counter++; } Assert.assertEquals(counter, 2); }

Target:
public void testWriteAndReadBCFWithIndex() throws IOException { final File bcfOutputFile = File.createTempFile("testWriteAndReadVCF.", ".bcf", tempDir); bcfOutputFile.deleteOnExit(); Tribble.indexFile(bcfOutputFile).deleteOnExit(); final VCFHeader header = createFakeHeader(); try (final VariantContextWriter writer = new VariantContextWriterBuilder() .setOutputFile(bcfOutputFile).setReferenceDictionary(header.getSequenceDictionary()) .setOptions(EnumSet.of(Options.INDEX_ON_THE_FLY)) .build()) { writer.writeHeader(header); writer.add(createVC(header)); writer.add(createVC(header)); } VariantContextTestProvider.VariantContextContainer container = VariantContextTestProvider .readAllVCs(bcfOutputFile, new BCF2Codec()); int counter = 0; final Iterator<VariantContext> it = container.getVCs().iterator(); while (it.hasNext()) { it.next(); counter++; } Assert.assertEquals(counter, 2); }
Source:
public void testGenerateInstructorJoinEmail() throws IOException { ______TS("instructor new account email"); String instructorEmail = "instructor@email.tmt"; String shortName = "Instr"; String regkey = "skxxxxxxxxxks"; @SuppressWarnings("deprecation") InstructorAttributes receiver = new InstructorAttributes("googleId", "courseId", "Instructor Name", instructorEmail); receiver.key = regkey; AccountAttributes sender = new AccountAttributes(); sender.email = "instructor-joe@gmail.com"; sender.name = "Joe Wilson"; String joinLink = Config.getAppUrl(Const.ActionURIs.INSTRUCTOR_COURSE_JOIN) .withRegistrationKey(StringHelper.encrypt(regkey)) .withInstructorInstitution("Test Institute") .toAbsoluteString(); EmailWrapper email = new EmailGenerator() .generateNewInstructorAccountJoinEmail(instructorEmail, shortName, joinLink); String subject = String.format(EmailType.NEW_INSTRUCTOR_ACCOUNT.getSubject(), shortName); verifyEmail(email, instructorEmail, subject, "/instructorNewAccountEmail.html"); assertEquals(email.getBcc(), Config.SUPPORT_EMAIL); ______TS("instructor course join email"); CourseAttributes course = new CourseAttributes("course-id", "Course Name", "UTC"); email = new EmailGenerator().generateInstructorCourseJoinEmail(sender, receiver, course); subject = String.format(EmailType.INSTRUCTOR_COURSE_JOIN.getSubject(), course.getName(), course.getId()); verifyEmail(email, receiver.email, subject, "/instructorCourseJoinEmail.html"); }

Target:
public void testGenerateInstructorJoinEmail() throws IOException { ______TS("instructor new account email"); String instructorEmail = "instructor@email.tmt"; String shortName = "Instr"; String regkey = "skxxxxxxxxxks"; @SuppressWarnings("deprecation") InstructorAttributes instructor = new InstructorAttributes("googleId", "courseId", "Instructor Name", instructorEmail); instructor.key = regkey; AccountAttributes inviter = new AccountAttributes(); inviter.email = "instructor-joe@gmail.com"; inviter.name = "Joe Wilson"; String joinLink = Config.getAppUrl(Const.ActionURIs.INSTRUCTOR_COURSE_JOIN) .withRegistrationKey(StringHelper.encrypt(regkey)) .withInstructorInstitution("Test Institute") .toAbsoluteString(); EmailWrapper email = new EmailGenerator() .generateNewInstructorAccountJoinEmail(instructorEmail, shortName, joinLink); String subject = String.format(EmailType.NEW_INSTRUCTOR_ACCOUNT.getSubject(), shortName); verifyEmail(email, instructorEmail, subject, "/instructorNewAccountEmail.html"); assertEquals(email.getBcc(), Config.SUPPORT_EMAIL); ______TS("instructor course join email"); CourseAttributes course = new CourseAttributes("course-id", "Course Name", "UTC"); email = new EmailGenerator().generateInstructorCourseJoinEmail(inviter, instructor, course); subject = String.format(EmailType.INSTRUCTOR_COURSE_JOIN.getSubject(), course.getName(), course.getId()); verifyEmail(email, instructor.email, subject, "/instructorCourseJoinEmail.html"); }
Source:
void report(LeaderElectionStatistics statistics) { long count = statistics.getCount().longValue(); weightedGaugeMean.update(statistics.getMean(), count); weightedGaugeP95.update(statistics.getP95(), count); weightedGaugeP99.update(statistics.getP99(), count); lastElectionTime.setValue( statistics.getPerceivedTime().map(SafeLong::longValue).orElse(0L)); }

Target:
void report(LeaderElectionStatistics statistics) { long count = statistics.getCount().longValue(); weightedGaugeMean.update(statistics.getMean(), count); weightedGaugeP95.update(statistics.getP95(), count); weightedGaugeP99.update(statistics.getP99(), count); leaderElectionEstimate.setValue( statistics.getDurationEstimate().map(SafeLong::longValue).orElse(0L)); }
Source:
public SafeHtmlCell getCell() { return new SafeHtmlCell() { @Override public void render(Context context, SafeHtml value, SafeHtmlBuilder sb, String id) { if (value != null) { String divStyle = "display:table-cell;width:100%;padding:0px 4px;vertical-align:middle;vertical-align:middle;"; sb.append(AssetProvider.getTemplates().divWithStringStyle(divStyle, id, value)); } } }; }

Target:
public SafeHtmlCell getCell() { return new SafeHtmlCell() { @Override public void render(Context context, SafeHtml value, SafeHtmlBuilder sb, String id) { if (value != null) { String divStyle = "display:table-cell;width:100%;padding:0px 4px;vertical-align:middle;"; sb.append(AssetProvider.getTemplates().divWithStringStyle(divStyle, id, value)); } } }; }
Source:
public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); requireActivity().setTitle(R.string.fui_title_register_email); FragmentActivity activity = getActivity(); mListener = (AnonymousUpgradeListener) activity; }

Target:
public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); FragmentActivity activity = requireActivity(); activity.setTitle(R.string.fui_title_register_email); if (!(activity instanceof AnonymousUpgradeListener)) { throw new IllegalStateException("Activity must implement CheckEmailListener"); } mListener = (AnonymousUpgradeListener) activity; }
Source:
public byte[] read(Path path, BiConsumer<Long, Long> progressConsumer) { FileWrapper wrapper = getPath(path); long size = wrapper.getFileProperties().size; if (wrapper.getFileProperties().isDirectory) { return null; } ProgressConsumer<Long> monitor = (readBytes) -> progressConsumer.accept(readBytes, size); AsyncReader in = wrapper.getInputStream(userContext.network, userContext.crypto, size, monitor).join(); return Serialize.readFully(in, size).join(); }

Target:
public byte[] read(Path path, BiConsumer<Long, Long> progressConsumer) { FileWrapper wrapper = getPath(path); long size = wrapper.getFileProperties().size; ProgressConsumer<Long> monitor = (readBytes) -> progressConsumer.accept(readBytes, size); AsyncReader in = wrapper.getInputStream(userContext.network, userContext.crypto, size, monitor).join(); return Serialize.readFully(in, size).join(); }
Source:
protected void configureDispatch() { bind(ClientActionHandlerRegistry.class).to(builder.clientActionHandlerRegistryType).asEagerSingleton(); bind(RpcDispatchCallFactory.class).to(DefaultRpcDispatchCallFactory.class).in(Singleton.class); bind(DispatchAsync.class).to(getDispatchAsyncClass()).in(Singleton.class); bind(RpcInterceptorRegistry.class).to(builder.getInterceptorRegistry()).in(Singleton.class); bind(RpcDispatchHooks.class).to(builder.getDispatchHooks()).in(Singleton.class); }

Target:
protected void configureDispatch() { bind(ClientActionHandlerRegistry.class).to(builder.clientActionHandlerRegistryType).asEagerSingleton(); bind(RpcDispatchCallFactory.class).to(builder.getDispatchCallFactory()).in(Singleton.class); bind(DispatchAsync.class).to(builder.getDispatchAsync()).in(Singleton.class); bind(RpcInterceptorRegistry.class).to(builder.getInterceptorRegistry()).in(Singleton.class); bind(RpcDispatchHooks.class).to(builder.getDispatchHooks()).in(Singleton.class); }
Source:
public void testExplainProc() throws IOException, ProcCallException { Client client = getClient(); VoltTable vt = null; vt = client.callProcedure("@ExplainProc", "T1.insert" ).getResults()[0]; while (vt.advanceRow()) { System.out.println(vt); String name = vt.getString(0); String sql = vt.getString(1); String plan = vt.getString(2); assertTrue( name.contains("sql0")); assertTrue( sql.contains( "INSERT INTO T1 VALUES (?, ?, ?)" )); assertTrue( plan.contains( "INSERT into \"T1\"" )); assertTrue( plan.contains( "MATERIALIZE TUPLE from parameters and/or literals" )); } vt = client.callProcedure("@ExplainProc", "CreateStoredProcedure").getResults()[0]; for (int i = 0; i < 2; i++) { vt.advanceRow(); String name = vt.getString(0); String task = vt.getString(1); String plan = vt.getString(2); if (i == 0) { assertEquals("insert", name); assertEquals("insert into t4 values(?);", task); } else if (i == 1) { assertEquals("select", name); assertEquals("select * from t4 where A>=?;", task); } if (i == 0) { assertTrue(plan.contains("RECEIVE FROM ALL PARTITIONS")); assertTrue(plan.contains("SEND PARTITION RESULTS TO COORDINATOR")); assertTrue(plan.contains("INSERT into \"T4\"")); assertTrue(plan.contains("MATERIALIZE TUPLE from parameters and/or literals")); } else if (i == 1) { assertTrue(plan.contains("RETURN RESULTS TO STORED PROCEDURE")); assertTrue(plan.contains("SEQUENTIAL SCAN of \"T4\"")); } } }

Target:
public void testExplainProc() throws IOException, ProcCallException { Client client = getClient(); VoltTable vt = null; vt = client.callProcedure("@ExplainProc", "T1.insert" ).getResults()[0]; while (vt.advanceRow()) { System.out.println(vt); String name = vt.getString(0); String sql = vt.getString(1); String plan = vt.getString(2); assertEquals("sql0", name); assertEquals("INSERT INTO T1 VALUES (?, ?, ?);", sql); assertTrue(plan.contains("INSERT into \"T1\"")); assertTrue(plan.contains("MATERIALIZE TUPLE from parameters and/or literals")); } vt = client.callProcedure("@ExplainProc", "JavaProcedure").getResults()[0]; for (int i = 0; i < 2; i++) { vt.advanceRow(); String name = vt.getString(0); String task = vt.getString(1); String plan = vt.getString(2); if (i == 0) { assertEquals("insert", name); assertEquals("insert into t4 values(?);", task); assertTrue(plan.contains("RECEIVE FROM ALL PARTITIONS")); assertTrue(plan.contains("SEND PARTITION RESULTS TO COORDINATOR")); assertTrue(plan.contains("INSERT into \"T4\"")); assertTrue(plan.contains("MATERIALIZE TUPLE from parameters and/or literals")); } else { assertEquals("select", name); assertEquals("select * from t4 where A>=?;", task); assertTrue(plan.contains("RETURN RESULTS TO STORED PROCEDURE")); assertTrue(plan.contains("SEQUENTIAL SCAN of \"T4\"")); } } }
Source:
public static String getDownloadUrl( final Path path, final String clientId ) { return URLHelper.getServletUrl( clientId ) + "?" + FileManagerFields.FORM_FIELD_PATH + "=" + URL.encode( path.toURI() ); }

Target:
public static String getDownloadUrl( final Path path, final String clientId ) { return URLHelper.getServletUrl( clientId ) + "&" + FileManagerFields.FORM_FIELD_PATH + "=" + URL.encode( path.toURI() ); }
Source:
public void hook(ExtensionHook extensionHook) { extensionHook.addOptionsParamSet(getRuleConfigParam()); extensionHook.getHookView().addOptionPanel(getOptionsRuleConfigPanel()); API.getInstance().registerApiImplementor(new RuleConfigAPI(this)); }

Target:
public void hook(ExtensionHook extensionHook) { extensionHook.addOptionsParamSet(getRuleConfigParam()); if (extensionHook.getView() != null) { extensionHook.getHookView().addOptionPanel(getOptionsRuleConfigPanel()); } API.getInstance().registerApiImplementor(new RuleConfigAPI(this)); }
Source:
protected void executeCommand() { VDSReturnValue returnValue = runVdsCommand(VDSCommandType.StopGlusterVolumeProfile, new GlusterVolumeVDSParameters(upServer.getId(), getGlusterVolumeName())); setSucceeded(returnValue.getSucceeded()); if (!getSucceeded()) { handleVdsError(AuditLogType.GLUSTER_VOLUME_PROFILE_STOP_FAILED, returnValue.getVdsError().getMessage()); return; } }

Target:
protected void executeCommand() { VDSReturnValue returnValue = runVdsCommand(VDSCommandType.StopGlusterVolumeProfile, new GlusterVolumeVDSParameters(upServer.getId(), getGlusterVolumeName())); setSucceeded(returnValue.getSucceeded()); if (!getSucceeded()) { handleVdsError(AuditLogType.GLUSTER_VOLUME_PROFILE_STOP_FAILED, returnValue.getVdsError().getMessage()); } }
Source:
private int getClosingBracketStartOffset(int startOffset, boolean isCDATA) { int counter = startOffset + 1; while (startOffset < content.length()) { if (content.charAt(counter) == '>' && (!isCDATA || content.charAt(counter - 1) == ']')) { return counter; } counter++; } throw new IllegalStateException("No \">\" found."); }

Target:
private int getClosingBracketStartOffset(int startOffset, boolean isCDATA) { int counter = startOffset + 1; while (startOffset < content.length()) { if (content.charAt(counter) == '>' && bracketsBefore(isCDATA, counter)) { return counter; } counter++; } throw new IllegalStateException("No \">\" found."); }
Source:
private PlannerContext( final DruidOperatorTable operatorTable, final ExprMacroTable macroTable, final PlannerConfig plannerConfig, final DateTime localNow, final Map<String, Object> queryContext, final List<TypedValue> parameters, final AuthenticationResult authenticationResult ) { this.operatorTable = operatorTable; this.macroTable = macroTable; this.plannerConfig = Preconditions.checkNotNull(plannerConfig, "plannerConfig"); this.queryContext = queryContext != null ? new HashMap<>(queryContext) : new HashMap<>(); this.parameters = parameters != null ? parameters : ImmutableList.of(); this.localNow = Preconditions.checkNotNull(localNow, "localNow"); this.authenticationResult = Preconditions.checkNotNull(authenticationResult, "authenticationResult"); String sqlQueryId = (String) this.queryContext.get(CTX_SQL_QUERY_ID); if (Strings.isNullOrEmpty(sqlQueryId)) { sqlQueryId = UUID.randomUUID().toString(); } this.sqlQueryId = sqlQueryId; }

Target:
private PlannerContext( final DruidOperatorTable operatorTable, final ExprMacroTable macroTable, final PlannerConfig plannerConfig, final DateTime localNow, final Map<String, Object> queryContext, final List<TypedValue> parameters, final AuthenticationResult authenticationResult ) { this.operatorTable = operatorTable; this.macroTable = macroTable; this.plannerConfig = Preconditions.checkNotNull(plannerConfig, "plannerConfig"); this.queryContext = queryContext != null ? new HashMap<>(queryContext) : new HashMap<>(); this.parameters = Preconditions.checkNotNull(parameters); this.localNow = Preconditions.checkNotNull(localNow, "localNow"); this.authenticationResult = Preconditions.checkNotNull(authenticationResult, "authenticationResult"); String sqlQueryId = (String) this.queryContext.get(CTX_SQL_QUERY_ID); if (Strings.isNullOrEmpty(sqlQueryId)) { sqlQueryId = UUID.randomUUID().toString(); } this.sqlQueryId = sqlQueryId; }
Source:
protected boolean promptForInputChange(String requestPreviewMessage, IProgressMonitor monitor) { List<IResource> relevantResources = getRelevantResources(); boolean showPrompt = false; for (IResource resource : relevantResources) if (hasChanged(resource)) { showPrompt = true; break; } if(showPrompt) return super.promptForInputChange(requestPreviewMessage, monitor); return false; }

Target:
protected boolean promptForInputChange(String requestPreviewMessage, IProgressMonitor monitor) { List<IResource> relevantResources = getRelevantResources(); for (IResource resource : relevantResources) if (hasChanged(resource)) return super.promptForInputChange(requestPreviewMessage, monitor); return false; }
Source:
public List<TransactionReportRow> getTransactionDetailsForLot(final Integer lotId) { final List<TransactionReportRow> transactions = new ArrayList<>(); try { final String sql = "SELECT i.userid,i.lotid,i.trndate," + "(CASE WHEN trnstat = 0 THEN '" + TransactionStatus.PENDING.getValue() + "' WHEN trnstat = 1 THEN '" + TransactionStatus.CONFIRMED.getValue() + "' WHEN trnstat = 2 THEN '" + TransactionStatus.CANCELLED.getValue() + "' END) as trnStatus, " + " i.trnqty,i.sourceid,l.listname, i.comments," + "(CASE WHEN trntype = 0 THEN '" + TransactionType.DEPOSIT.getValue() + "' WHEN trntype = 1 THEN '" + TransactionType.WITHDRAWAL.getValue() + "' WHEN trntype = 2 THEN '" + TransactionType.DISCARD.getValue() + "' WHEN trntype = 3 THEN '" + TransactionType.ADJUSTMENT.getValue() + "' END) as trntype " + "FROM ims_transaction i LEFT JOIN listnms l ON l.listid = i.sourceid " + " INNER JOIN ims_lot lot ON lot.lotid = i.lotid " + "WHERE i.lotid = :lotId AND i.trnstat <> 9 ORDER BY i.trnid"; final Query query = this.getSession().createSQLQuery(sql); query.setParameter("lotId", lotId); this.createTransactionRow(transactions, query); } catch (final Exception e) { final String message = "Error with ggetTransactionDetailsForLot(" + lotId + ") query from Transaction: " + e.getMessage(); LOG.error(message, e); throw new MiddlewareQueryException(message, e); } return transactions; }

Target:
public List<TransactionReportRow> getTransactionDetailsForLot(final Integer lotId) { final List<TransactionReportRow> transactions = new ArrayList<>(); try { final String sql = "SELECT i.userid,i.lotid,i.trndate," + "(CASE WHEN trnstat = " + TransactionStatus.PENDING.getIntValue() + " THEN '" + TransactionStatus.PENDING.getValue() + "' WHEN trnstat = " + TransactionStatus.CONFIRMED.getIntValue() + " THEN '" + TransactionStatus.CONFIRMED.getValue() + "' WHEN trnstat = " + TransactionStatus.CANCELLED.getIntValue() + " THEN '" + TransactionStatus.CANCELLED.getValue() + "' END) as trnStatus, " + " i.trnqty,i.sourceid,l.listname, i.comments," + "(CASE WHEN trntype = " + TransactionType.DEPOSIT.getId() + " THEN '" + TransactionType.DEPOSIT.getValue() + "' WHEN trntype = " + TransactionType.WITHDRAWAL.getId() + " THEN '" + TransactionType.WITHDRAWAL.getValue() + "' WHEN trntype = " + TransactionType.DISCARD.getId() + " THEN '" + TransactionType.DISCARD.getValue() + "' WHEN trntype = " + TransactionType.ADJUSTMENT.getId() + " THEN '" + TransactionType.ADJUSTMENT.getValue() + "' END) as trntype " + "FROM ims_transaction i LEFT JOIN listnms l ON l.listid = i.sourceid " + " INNER JOIN ims_lot lot ON lot.lotid = i.lotid " + "WHERE i.lotid = :lotId ORDER BY i.trnid"; final Query query = this.getSession().createSQLQuery(sql); query.setParameter("lotId", lotId); this.createTransactionRow(transactions, query); } catch (final Exception e) { final String message = "Error with ggetTransactionDetailsForLot(" + lotId + ") query from Transaction: " + e.getMessage(); LOG.error(message, e); throw new MiddlewareQueryException(message, e); } return transactions; }
Source:
public final I_C_Invoice creditInvoice(@NonNull final I_C_Invoice invoice, final InvoiceCreditContext creditCtx) { Check.errorIf(isCreditMemo(invoice), "Param 'invoice'={} may not be a credit memo"); Check.assume(invoice.getGrandTotal().signum() != 0, "GrandTotal!=0 for {}", invoice); if (creditCtx.isCreditedInvoiceReinvoicable()) { Check.errorIf(invoice.isPaid(), "Param 'invoice'={} may not yet be paid"); final BigDecimal openAmt = Services.get(IAllocationDAO.class).retrieveOpenAmt(invoice, false); Check.assume(openAmt.signum() != 0, "OpenAmt != zero for {}", invoice); } final Properties ctx = InterfaceWrapperHelper.getCtx(invoice); final DocTypeId targetDocTypeId = getTarget_DocType_ID(ctx, invoice, creditCtx.getDocTypeId()); final I_C_Invoice creditMemo = InterfaceWrapperHelper.create( copyFrom(invoice, SystemTime.asTimestamp(), targetDocTypeId.getRepoId(), invoice.isSOTrx(), false, creditCtx.isReferenceOriginalOrder(), creditCtx.isReferenceInvoice(), true, new CreditMemoInvoiceCopyHandler(creditCtx)), I_C_Invoice.class); return creditMemo; }

Target:
public final I_C_Invoice creditInvoice(@NonNull final I_C_Invoice invoice, final InvoiceCreditContext creditCtx) { Check.errorIf(isCreditMemo(invoice), "Param 'invoice'={} may not be a credit memo"); Check.assume(invoice.getGrandTotal().signum() != 0, "GrandTotal!=0 for {}", invoice); if (creditCtx.isReferenceInvoice()) { if (invoice.isPaid()) { throw new AdempiereException( MSG_InvoiceMayNotBePaid, new Object[] { invoice.getDocumentNo() }); } final BigDecimal openAmt = Services.get(IAllocationDAO.class).retrieveOpenAmt(invoice, false); if (openAmt.signum() == 0) { throw new AdempiereException( MSG_InvoiceMayNotHaveOpenAmtZero, new Object[] { invoice.getDocumentNo() }); } } final Properties ctx = InterfaceWrapperHelper.getCtx(invoice); final DocTypeId targetDocTypeId = getTarget_DocType_ID(ctx, invoice, creditCtx.getDocTypeId()); final I_C_Invoice creditMemo = InterfaceWrapperHelper.create( copyFrom(invoice, SystemTime.asTimestamp(), targetDocTypeId.getRepoId(), invoice.isSOTrx(), false, creditCtx.isReferenceOriginalOrder(), creditCtx.isReferenceInvoice(), true, new CreditMemoInvoiceCopyHandler(creditCtx)), I_C_Invoice.class); return creditMemo; }
Source:
public double sumDouble(int columnIndex) { double result = 0; for (int i = 0; i < partitionCount; i++) { openPartition(i); final int base = getColumnBase(i); final int index = getPrimaryColumnIndex(base, columnIndex); final ReadOnlyColumn column = columns.getQuick(index); if (column != null) { for (int pageIndex = 0, pageCount = column.getPageCount(); pageIndex < pageCount; pageIndex++) { long a = column.getPageAddress(pageIndex); long count = column.getPageSize(pageIndex) / Double.BYTES; result += Vect.sumDoubleNeumaier(a, count); } } } return result; }

Target:
public double sumDouble(int columnIndex) { double result = 0; for (int i = 0; i < partitionCount; i++) { openPartition(i); final int base = getColumnBase(i); final int index = getPrimaryColumnIndex(base, columnIndex); final ReadOnlyColumn column = columns.getQuick(index); if (column != null) { for (int pageIndex = 0, pageCount = column.getPageCount(); pageIndex < pageCount; pageIndex++) { long a = column.getPageAddress(pageIndex); long count = column.getPageSize(pageIndex) / Double.BYTES; result += Vect.sumDouble(a, count); } } } return result; }
Source:
Boolean isHierhicalStateMachine() { return hiearhical; }

Target:
Boolean isHierhicalStateMachine() { return hierarchical; }
Source:
public List<IndirectCostRecoveryAccount> getActiveIndirectCostRecoveryAccounts() { List<IndirectCostRecoveryAccount> activeList = new ArrayList(); for (IndirectCostRecoveryAccount icr : getIndirectCostRecoveryAccounts()) { if (icr.isActive()) { activeList.add(IndirectCostRecoveryAccount.copyICRAccount(icr)); } } return activeList; }

Target:
public List<IndirectCostRecoveryAccount> getActiveIndirectCostRecoveryAccounts() { List<IndirectCostRecoveryAccount> activeList = new ArrayList<>(); for (IndirectCostRecoveryAccount icr : getIndirectCostRecoveryAccounts()) { if (icr.isActive()) { activeList.add(IndirectCostRecoveryAccount.copyICRAccount(icr)); } } return activeList; }
Source:
public void endRequestMonitoring() { if (!ended) { ended = true; activeRequests.dec(); context.stop(); } else { LOGGER.warn("Request already ended"); } }

Target:
public void endRequestMonitoring() { if (!ended) { ended = true; activeRequests.dec(); context.stop(); } else { LOGGER.warn("Request already ended for :: " + metricNamespace); } }
Source:
public <T extends Resource> T getResource(String href, Class<T> clazz, Map<String, Object> queryParameters) { Assert.hasText(href, "href argument cannot be null or empty."); Assert.notNull(clazz, "Resource class argument cannot be null."); SanitizedQuery sanitized = QuerySanitizer.sanitize(href, queryParameters); return getResource(sanitized.getHrefWithoutQuery(), clazz, sanitized.getQuery()); }

Target:
public <T extends Resource> T getResource(String href, Class<T> clazz, Map<String, Object> queryParameters) { ResourceDataResult result = getResourceData(href, clazz, queryParameters); return instantiate(clazz, result.getData(), result.getUri().getQuery()); }
Source:
private void setupHistory() throws IOException { if (this.history != null) { return; } this.history = new FileHistory(new File(getOpts().getHistoryFile())); ShutdownHookManager.addShutdownHook(new Runnable() { @Override public void run() { try { history.flush(); } catch (IOException e) { error(e); } finally { close(); } } }); }

Target:
private void setupHistory() throws IOException { if (this.history != null) { return; } this.history = new FileHistory(new File(getOpts().getHistoryFile())); }
Source:
public synchronized List<Sample<T>> finishSampling(int count) { List<Sample<T>> results = Collections.EMPTY_LIST; if (enabled) { enabled = false; results = summary.topK(count) .stream() .map(c -> new Sample<T>(c.getItem(), c.getCount(), c.getError())) .collect(Collectors.toList()); } return results; }

Target:
public synchronized List<Sample<T>> finishSampling(int count) { List<Sample<T>> results = Collections.emptyList(); if (endTimeMillis != -1) { endTimeMillis = -1; results = summary.topK(count) .stream() .map(c -> new Sample<T>(c.getItem(), c.getCount(), c.getError())) .collect(Collectors.toList()); } return results; }
Source:
public void doWrite(Server server, Query query, Iterable<Result> results) throws Exception { if (createDatabase) influxDB.createDatabase(database); BatchPoints.Builder batchPointsBuilder = BatchPoints.database(database).retentionPolicy(retentionPolicy) .tag(TAG_HOSTNAME, server.getSource()); for(Map.Entry<String,String> tag : tags.entrySet()) { batchPointsBuilder.tag(tag.getKey(),tag.getValue()); } BatchPoints batchPoints = batchPointsBuilder.consistency(writeConsistency).build(); for (Result result : results) { log.debug("Query result: {}", result); Map<String, Object> resultValues = result.getValues(); HashMap<String, Object> filteredValues = newHashMap(); for (Map.Entry<String, Object> values : resultValues.entrySet()) { Object value = values.getValue(); if (isValidNumber(value)) { String key; if(typeNamesAsTags) { key = KeyUtils.getPrefixedKeyString(query, result, values, Collections.<String>emptyList(), values.getKey()); } else { key = KeyUtils.getPrefixedKeyString(query, result, values, typeNames, values.getKey()); } filteredValues.put(key, value); } } if (!filteredValues.isEmpty()) { filteredValues.put("_jmx_port", Integer.parseInt(server.getPort())); Map<String, String> resultTagsToApply = buildResultTagMap(result); Point point = Point.measurement(result.getKeyAlias()).time(result.getEpoch(), MILLISECONDS) .tag(resultTagsToApply).fields(filteredValues).build(); log.debug("Point: {}", point); batchPoints.point(point); } } influxDB.write(batchPoints); }

Target:
public void doWrite(Server server, Query query, Iterable<Result> results) throws Exception { if (createDatabase) influxDB.createDatabase(database); BatchPoints.Builder batchPointsBuilder = BatchPoints.database(database).retentionPolicy(retentionPolicy) .tag(TAG_HOSTNAME, server.getSource()); for(Map.Entry<String,String> tag : tags.entrySet()) { batchPointsBuilder.tag(tag.getKey(),tag.getValue()); } BatchPoints batchPoints = batchPointsBuilder.consistency(writeConsistency).build(); for (Result result : results) { log.debug("Query result: {}", result); Map<String, Object> resultValues = result.getValues(); HashMap<String, Object> filteredValues = newHashMap(); for (Map.Entry<String, Object> values : resultValues.entrySet()) { Object value = values.getValue(); if (isValidNumber(value)) { typeNames = typeNamesAsTags ? typeNames : Collections.<String>emptyList(); String key = KeyUtils.getPrefixedKeyString(query, result, values, typeNames, values.getKey()); filteredValues.put(key, value); } } if (!filteredValues.isEmpty()) { filteredValues.put("_jmx_port", Integer.parseInt(server.getPort())); Map<String, String> resultTagsToApply = buildResultTagMap(result); Point point = Point.measurement(result.getKeyAlias()).time(result.getEpoch(), MILLISECONDS) .tag(resultTagsToApply).fields(filteredValues).build(); log.debug("Point: {}", point); batchPoints.point(point); } } influxDB.write(batchPoints); }
Source:
public void run() { AccountTransaction accountTransaction = transaction.getTransaction(); if (AccountTransaction.Type.DEPOSIT.equals(accountTransaction.getType()) || AccountTransaction.Type.FEES_REFUND.equals(accountTransaction.getType()) || AccountTransaction.Type.TAX_REFUND.equals(accountTransaction.getType()) || AccountTransaction.Type.INTEREST.equals(accountTransaction.getType())) accountTransaction.setType(AccountTransaction.Type.TAX_REFUND); else if (AccountTransaction.Type.REMOVAL.equals(accountTransaction.getType()) || AccountTransaction.Type.FEES.equals(accountTransaction.getType()) || AccountTransaction.Type.TAXES.equals(accountTransaction.getType()) || AccountTransaction.Type.INTEREST_CHARGE.equals(accountTransaction.getType())) accountTransaction.setType(AccountTransaction.Type.TAXES); else throw new IllegalArgumentException(); client.markDirty(); }

Target:
public void run() { AccountTransaction accountTransaction = transaction.getTransaction(); if (AccountTransaction.Type.DEPOSIT.equals(accountTransaction.getType()) || AccountTransaction.Type.FEES_REFUND.equals(accountTransaction.getType()) || AccountTransaction.Type.INTEREST.equals(accountTransaction.getType())) accountTransaction.setType(AccountTransaction.Type.TAX_REFUND); else if (AccountTransaction.Type.REMOVAL.equals(accountTransaction.getType()) || AccountTransaction.Type.FEES.equals(accountTransaction.getType()) || AccountTransaction.Type.INTEREST_CHARGE.equals(accountTransaction.getType())) accountTransaction.setType(AccountTransaction.Type.TAXES); else throw new IllegalArgumentException(); client.markDirty(); }
Source:
private void execute(String signature, SquidClassLoader classLoader) { BytecodeCFGMethodVisitor cfgVisitor = new BytecodeCFGMethodVisitor(); MethodLookup lookup = MethodLookup.lookup(signature, classLoader, cfgVisitor); if (lookup == null) { LOG.debug("Method lookup failed for %s", signature); return; } methodBehavior.setDeclaredExceptions(lookup.declaredExceptions); methodBehavior.setVarArgs(lookup.isVarArgs); BytecodeCFG bytecodeCFG = cfgVisitor.getCfg(); if (bytecodeCFG == null || methodIsBlacklisted(signature)) { return; } steps = 0; for (ProgramState startingState : startingStates(signature, ProgramState.EMPTY_STATE, lookup.isStatic)) { enqueue(new ProgramPoint(bytecodeCFG.entry()), startingState); } while (!workList.isEmpty()) { steps++; if (steps > maxSteps()) { throw new ExplodedGraphWalker.MaximumStepsReachedException("Too many steps resolving "+methodBehavior.signature()); } setNode(workList.removeFirst()); if (programPosition.block.successors().isEmpty()) { endOfExecutionPath.add(node); continue; } if (programPosition.i < programPosition.block.elements().size()) { executeInstruction((Instruction) programPosition.block.elements().get(programPosition.i)); } else { handleBlockExit(programPosition); } } handleEndOfExecutionPath(); executeCheckEndOfExecution(); methodBehavior.completed(); workList = null; node = null; programState = null; constraintManager = null; }

Target:
private void execute(String signature, SquidClassLoader classLoader) { BytecodeCFGMethodVisitor cfgVisitor = new BytecodeCFGMethodVisitor(); MethodLookup lookup = MethodLookup.lookup(signature, classLoader, cfgVisitor); if (lookup == null) { LOG.debug("Method body not found: %s", signature); return; } methodBehavior.setDeclaredExceptions(lookup.declaredExceptions); methodBehavior.setVarArgs(lookup.isVarArgs); BytecodeCFG bytecodeCFG = cfgVisitor.getCfg(); if (bytecodeCFG == null) { return; } steps = 0; for (ProgramState startingState : startingStates(signature, ProgramState.EMPTY_STATE, lookup.isStatic)) { enqueue(new ProgramPoint(bytecodeCFG.entry()), startingState); } while (!workList.isEmpty()) { steps++; if (steps > maxSteps()) { throw new ExplodedGraphWalker.MaximumStepsReachedException("Too many steps resolving "+methodBehavior.signature()); } setNode(workList.removeFirst()); if (programPosition.block.successors().isEmpty()) { endOfExecutionPath.add(node); continue; } if (programPosition.i < programPosition.block.elements().size()) { executeInstruction((Instruction) programPosition.block.elements().get(programPosition.i)); } else { handleBlockExit(programPosition); } } handleEndOfExecutionPath(); executeCheckEndOfExecution(); methodBehavior.completed(); workList = null; node = null; programState = null; constraintManager = null; }
Source:
public List<String> getUserRoles(String userName) { LOGGER.debug("Invoking LightblueLdapRoleProvider#getUserRoles"); List<String> userRoles = new ArrayList<>(); try { List<String> userRolesFromCache = getUserRolesFromCache(userName); if( userRolesFromCache != null && userRolesFromCache.isEmpty() ) { userRoles.addAll(userRolesFromCache); } if (userRoles.isEmpty()) { SearchResult searchResult = new LdapFindUserByUidCommand(ldapContext, ldapSearchBase, userName).execute(); userRoles.addAll(getUserRolesFromLdap(searchResult)); } } catch (NamingException ne) { LOGGER.error("Naming problem with LDAP for user: " + userName, ne); } catch (HystrixRuntimeException ce) { LOGGER.error("Not found in cache, returns an empty list " + userName, ce); } return userRoles; }

Target:
public List<String> getUserRoles(String userName) { LOGGER.debug("Invoking LightblueLdapRoleProvider#getUserRoles"); List<String> userRoles = new ArrayList<>(); try { List<String> userRolesFromCache = getUserRolesFromCache(userName); if( userRolesFromCache != null && !userRolesFromCache.isEmpty() ) { userRoles.addAll(userRolesFromCache); } if (userRoles.isEmpty()) { SearchResult searchResult = new LdapFindUserByUidCommand(ldapContext, ldapSearchBase, userName).execute(); userRoles.addAll(getUserRolesFromLdap(searchResult)); } } catch (NamingException ne) { LOGGER.error("Naming problem with LDAP for user: " + userName, ne); } catch (HystrixRuntimeException ce) { LOGGER.error("Not found in cache, returns an empty list " + userName, ce); } return userRoles; }
Source:
public PlanNode visitSpatialJoin(SpatialJoinNode node, RewriteContext<Set<Symbol>> context) { Set<Symbol> expectedFilterInputs = ImmutableSet.<Symbol>builder() .addAll(SymbolsExtractor.extractUnique(node.getFilter())) .addAll(context.get()) .build(); PlanNode left = context.rewrite(node.getLeft(), expectedFilterInputs); PlanNode right = context.rewrite(node.getRight(), expectedFilterInputs); Set<Symbol> seenSymbol = new HashSet<>(); List<Symbol> outputSymbols = node.getOutputSymbols().stream() .filter(context.get()::contains) .filter(seenSymbol::add) .collect(toImmutableList()); return new SpatialJoinNode(node.getId(), node.getType(), left, right, outputSymbols, node.getFilter()); }

Target:
public PlanNode visitSpatialJoin(SpatialJoinNode node, RewriteContext<Set<Symbol>> context) { Set<Symbol> requiredInputs = ImmutableSet.<Symbol>builder() .addAll(SymbolsExtractor.extractUnique(node.getFilter())) .addAll(context.get()) .build(); PlanNode left = context.rewrite(node.getLeft(), requiredInputs); PlanNode right = context.rewrite(node.getRight(), requiredInputs); List<Symbol> outputSymbols = node.getOutputSymbols().stream() .filter(context.get()::contains) .distinct() .collect(toImmutableList()); return new SpatialJoinNode(node.getId(), node.getType(), left, right, outputSymbols, node.getFilter()); }
Source:
public void customExhangeTestBean() { ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(Config.class, CustomExchangeTestBean.class); final Collection<org.springframework.amqp.core.Exchange> exchanges = context .getBeansOfType(org.springframework.amqp.core.Exchange.class).values(); assertThat(exchanges, hasSize(1)); assertThat(exchanges.iterator().next(), instanceOf(CustomExchange.class)); final CustomExchange customExchange = (CustomExchange) exchanges.iterator().next(); assertEquals("my_custom_exchange", customExchange.getName()); assertEquals("custom_type", customExchange.getType()); context.close(); }

Target:
public void customExhangeTestBean() { ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(Config.class, CustomExchangeTestBean.class); final Collection<CustomExchange> exchanges = context.getBeansOfType(CustomExchange.class).values(); assertThat(exchanges, hasSize(1)); final CustomExchange exchange = exchanges.iterator().next(); assertEquals("my_custom_exchange", exchange.getName()); assertEquals("custom_type", exchange.getType()); context.close(); }
Source:
public Tag build() { validate(); if (tagBytes != null) { return new ArrayBackedTag(tagType, tagBytes); } else { return new ByteBufferTag(tagType, tagBuffer, -Tag.INFRASTRUCTURE_SIZE, tagBuffer.capacity() + Tag.INFRASTRUCTURE_SIZE); } }

Target:
public Tag build() { validate(); return new ArrayBackedTag(tagType, tagBytes); }
Source:
public SuccessResponse addTable(String tableConfigStr) { TableConfig tableConfig; try { tableConfig = JsonUtils.stringToObject(tableConfigStr, TableConfig.class); TableConfigUtils.validate(tableConfig); } catch (Exception e) { throw new ControllerApplicationException(LOGGER, e.getMessage(), Response.Status.BAD_REQUEST, e); } String tableName = tableConfig.getTableName(); try { ensureMinReplicas(tableConfig); verifyTableConfigs(tableConfig); _pinotHelixResourceManager.addTable(tableConfig); return new SuccessResponse("Table " + tableName + " Successfully added"); } catch (Exception e) { _controllerMetrics.addMeteredGlobalValue(ControllerMeter.CONTROLLER_TABLE_ADD_ERROR, 1L); if (e instanceof PinotHelixResourceManager.InvalidTableConfigException) { String errStr = String.format("Invalid table config for table %s: %s", tableName, e.getMessage()); throw new ControllerApplicationException(LOGGER, errStr, Response.Status.BAD_REQUEST, e); } else if (e instanceof PinotHelixResourceManager.TableAlreadyExistsException) { throw new ControllerApplicationException(LOGGER, e.getMessage(), Response.Status.CONFLICT, e); } else { throw new ControllerApplicationException(LOGGER, e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR, e); } } }

Target:
public SuccessResponse addTable(String tableConfigStr) { TableConfig tableConfig; try { tableConfig = JsonUtils.stringToObject(tableConfigStr, TableConfig.class); TableConfigUtils.validate(tableConfig); } catch (Exception e) { throw new ControllerApplicationException(LOGGER, e.getMessage(), Response.Status.BAD_REQUEST, e); } String tableName = tableConfig.getTableName(); try { ensureMinReplicas(tableConfig); verifyTableConfigs(tableConfig); _pinotHelixResourceManager.addTable(tableConfig); return new SuccessResponse("Table " + tableName + " succesfully added"); } catch (Exception e) { _controllerMetrics.addMeteredGlobalValue(ControllerMeter.CONTROLLER_TABLE_ADD_ERROR, 1L); if (e instanceof PinotHelixResourceManager.InvalidTableConfigException) { String errStr = String.format("Invalid table config for table %s: %s", tableName, e.getMessage()); throw new ControllerApplicationException(LOGGER, errStr, Response.Status.BAD_REQUEST, e); } else if (e instanceof PinotHelixResourceManager.TableAlreadyExistsException) { throw new ControllerApplicationException(LOGGER, e.getMessage(), Response.Status.CONFLICT, e); } else { throw new ControllerApplicationException(LOGGER, e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR, e); } } }
Source:
public void startBackgroundTasks() { scheduler.schedule( fiveUpdater(FiveUpdater.TimeFrame.ALL) .withName("Five Updater") , DAILY ); log.info("Installed Five updater"); scheduler.schedule( fiveUpdater(FiveUpdater.TimeFrame.TODAY) .withName("Five Today Updater") , RepetitionRules.NEVER ); log.info("Installed FiveToday updater"); scheduler.schedule( fiveUpdater(FiveUpdater.TimeFrame.PLUS_MINUS_7_DAYS) .withName("Five +-7 Days Updater") , RepetitionRules.NEVER ); log.info("Installed FivePlusMinusSevenDays updater"); }

Target:
public void startBackgroundTasks() { scheduler.schedule( fiveUpdaterDelegate(FiveUpdater.TimeFrame.ALL) .withName("Five Updater"), DAILY ); log.info("Installed Five updater"); scheduler.schedule( fiveUpdaterDelegate(FiveUpdater.TimeFrame.TODAY) .withName("Five Today Updater"), RepetitionRules.NEVER ); log.info("Installed FiveToday updater"); scheduler.schedule( fiveUpdaterDelegate(FiveUpdater.TimeFrame.PLUS_MINUS_7_DAYS) .withName("Five +-7 Days Updater"), RepetitionRules.NEVER ); log.info("Installed FivePlusMinusSevenDays updater"); }
Source:
public DocumentModel run(DocumentModel input) { IdRef idRef = new IdRef(input.getId()); DocumentModel lastVersion = session.getLastDocumentVersion(idRef); return lastVersion; }

Target:
public DocumentModel run(DocumentModel input) { IdRef idRef = new IdRef(input.getId()); return session.getLastDocumentVersion(idRef); }
Source:
public static void handleRequest(RestRequestInfo restRequestInfo) throws RestServiceException { RestResponseHandler responseHandler = restRequestInfo.getRestResponseHandler(); if (restRequestInfo.getRestRequestContent() == null) { String echoStr = echo(restRequestInfo.getRestRequestMetadata()).toString(); responseHandler.setContentType("text/plain"); responseHandler.addToResponseBody(echoStr.getBytes(), true); } else if (restRequestInfo.getRestRequestContent().isLast()) { responseHandler.flush(); responseHandler.close(); } }

Target:
public static void handleRequest(RestRequestInfo restRequestInfo) throws RestServiceException { RestResponseHandler responseHandler = restRequestInfo.getRestResponseHandler(); if (restRequestInfo.getRestRequestContent() == null) { String echoStr = echo(restRequestInfo.getRestRequestMetadata()).toString(); responseHandler.setContentType("application/json"); responseHandler.addToResponseBody(echoStr.getBytes(), true); } else if (restRequestInfo.getRestRequestContent().isLast()) { responseHandler.flush(); responseHandler.onRequestComplete(null, false); } }
Source:
public void execute(DiagnosticContext context) { logger.info("Getting Elasticsearch Version."); try { DiagnosticInputs diagnosticInputs = context.getDiagnosticInputs(); RestClient restClient = context.getEsRestClient(); RestResult res = restClient.execQuery("/"); if(res.getStatus() != 200)){ throw new DiagnosticException("Unrecoverable ES query error."); } String result = res.toString(); JsonNode root = JsonYamlUtils.createJsonNodeFromString(result); String versionNumber = root.path("version").path("number").asText(); Version version = new Version(versionNumber); context.setVersion(version); } catch (Exception e) { logger.error("Could not retrieve the Elasticsearch version - unable to continue."); throw new DiagnosticException("Undetermined error", e); } }

Target:
public void execute(DiagnosticContext context) { logger.info("Getting Elasticsearch Version."); try { RestClient restClient = context.getEsRestClient(); RestResult res = restClient.execQuery("/"); if (! res.isValid()) { throw new DiagnosticException( res.formatStatusMessage( "Could not retrieve the Elasticsearch version - unable to continue.")); } String result = res.toString(); JsonNode root = JsonYamlUtils.createJsonNodeFromString(result); String versionNumber = root.path("version").path("number").asText(); Version version = new Version(versionNumber); context.setVersion(version); } catch (DiagnosticException de) { throw de; } catch (Throwable t) { logger.log(SystemProperties.DIAG, "Unanticipated error:", t); throw new DiagnosticException(String.format("Could not retrieve the Elasticsearch version due to a system or network error - unable to continue. %s", Constants.CHECK_LOG)); } }
Source:
public Mono<MatchResult> matches(ServerWebExchange exchange) { return Mono.just(exchange.getRequest()) .map(r -> (r.getMethod() != null ? r.getMethod() : Mono.empty())) .filter(m -> ALLOWED_METHODS.contains(m)) .flatMap(m -> MatchResult.notMatch()) .switchIfEmpty(MatchResult.match()); }

Target:
public Mono<MatchResult> matches(ServerWebExchange exchange) { return Mono.just(exchange.getRequest()) .flatMap(r -> Mono.justOrEmpty(r.getMethod())) .filter(m -> ALLOWED_METHODS.contains(m)) .flatMap(m -> MatchResult.notMatch()) .switchIfEmpty(MatchResult.match()); }