auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean isEntryExist(String entryKey) throws LocalEntryAdminException { final Lock lock = getLock(); try { lock.lock(); assertKeyEmpty(entryKey); log.debug("Checking localEntry Exists : " + entryKey); return getSynapseConfiguration().getLocalRegistry().containsKey(entryKey); } catch (LocalEntryAdminException e) { throw e; } finally { lock.unlock(); } }

Target:
public boolean isEntryExist(String entryKey) throws LocalEntryAdminException { final Lock lock = getLock(); try { lock.lock(); assertKeyEmpty(entryKey); log.debug("Checking localEntry Exists : " + entryKey); return getSynapseConfiguration().getLocalRegistry().containsKey(entryKey); } finally { lock.unlock(); } }
Source:
protected boolean cleanState( String topologyName, SchedulerStateManagerAdaptor statemgr) { LOG.fine("Cleaning up topology state"); Boolean result; result = statemgr.deleteTMasterLocation(topologyName); if (result == null || !result) { LOG.warning("Failed to clear TMaster location. Check whether TMaster set it correctly."); } result = statemgr.deletePackingPlan(topologyName); if (result == null || !result) { LOG.warning("Failed to clear packing plan. Check whether TMaster set it correctly."); } result = statemgr.deletePhysicalPlan(topologyName); if (result == null || !result) { LOG.warning("Failed to clear physical plan. Check whether TMaster set it correctly."); } result = statemgr.deleteSchedulerLocation(topologyName); if (result == null || !result) { LOG.warning("Failed to clear scheduler location. Check whether Scheduler set it correctly."); } result = statemgr.deleteExecutionState(topologyName); if (result == null || !result) { LOG.severe("Failed to clear execution state"); return false; } result = statemgr.deleteTopology(topologyName); if (result == null || !result) { LOG.severe("Failed to clear topology definition"); return false; } LOG.fine("Cleaned up topology state"); return true; }

Target:
protected boolean cleanState( String topologyName, SchedulerStateManagerAdaptor statemgr) { LOG.fine("Cleaning up topology state"); Boolean result; result = statemgr.deleteTMasterLocation(topologyName); if (result == null || !result) { LOG.warning("Failed to clear TMaster location. Check whether TMaster set it correctly."); } result = statemgr.deletePackingPlan(topologyName); if (result == null || !result) { LOG.warning("Failed to clear packing plan. Check whether Launcher set it correctly."); } result = statemgr.deletePhysicalPlan(topologyName); if (result == null || !result) { LOG.warning("Failed to clear physical plan. Check whether TMaster set it correctly."); } result = statemgr.deleteSchedulerLocation(topologyName); if (result == null || !result) { LOG.warning("Failed to clear scheduler location. Check whether Scheduler set it correctly."); } result = statemgr.deleteExecutionState(topologyName); if (result == null || !result) { LOG.severe("Failed to clear execution state"); return false; } result = statemgr.deleteTopology(topologyName); if (result == null || !result) { LOG.severe("Failed to clear topology definition"); return false; } LOG.fine("Cleaned up topology state"); return true; }
Source:
ServerSocket createServerSocket(InetSocketAddress address, boolean portUnification, boolean sslQuorum) throws IOException { ServerSocket serverSocket; try { if (portUnification || sslQuorum) { serverSocket = new UnifiedServerSocket(self.getX509Util(), portUnification); } else { serverSocket = new ServerSocket(); } serverSocket.setReuseAddress(true); serverSocket.bind(address); return serverSocket; } catch (BindException e) { LOG.error("Couldn't bind to " + self.getQuorumAddress(), e); throw e; } }

Target:
Optional<ServerSocket> createServerSocket(InetSocketAddress address, boolean portUnification, boolean sslQuorum) { ServerSocket serverSocket; try { if (portUnification || sslQuorum) { serverSocket = new UnifiedServerSocket(self.getX509Util(), portUnification); } else { serverSocket = new ServerSocket(); } serverSocket.setReuseAddress(true); serverSocket.bind(address); return Optional.of(serverSocket); } catch (IOException e) { LOG.error("Couldn't bind to {}", address.toString(), e); } return Optional.empty(); }
Source:
void validateDevfile(Devfile devfile) throws DevfileFormatException { validateProjects(devfile); Set<String> toolNames = validateTools(devfile); validateCommands(devfile, toolNames); }

Target:
public void validateDevfile(Devfile devfile) throws DevfileFormatException { validateProjects(devfile); Set<String> toolNames = validateTools(devfile); validateCommands(devfile, toolNames); }
Source:
private static ServiceMessage toServiceMessage(MethodInfo methodInfo, Object... params) { if (methodInfo.parameterCount() != 0 && params[0] instanceof ServiceMessage) { return ServiceMessage.from((ServiceMessage) params[0]) .qualifier(methodInfo.serviceName(), methodInfo.methodName()) .build(); } return ServiceMessage.builder() .qualifier(methodInfo.serviceName(), methodInfo.methodName()) .data(methodInfo.parameterCount() != 0 ? params[0] : null) .build(); }

Target:
private ServiceMessage toServiceMessage(MethodInfo methodInfo, Object... params) { if (methodInfo.parameterCount() != 0 && params[0] instanceof ServiceMessage) { return ServiceMessage.from((ServiceMessage) params[0]) .qualifier(methodInfo.serviceName(), methodInfo.methodName()) .build(); } return ServiceMessage.builder() .qualifier(methodInfo.serviceName(), methodInfo.methodName()) .data(methodInfo.parameterCount() != 0 ? params[0] : null) .build(); }
Source:
@Override public MessageConsumer getMessageConsumer(Session session, Destination destination) throws JMSConnectorException { MessageConsumer messageConsumer = null; if (cachedMessageConsumer == null) { messageConsumer = createMessageConsumer(session, destination); } else { messageConsumer = cachedMessageConsumer; } return messageConsumer; }

Target:
public MessageConsumer getMessageConsumer(Session session, Destination destination) throws JMSConnectorException { MessageConsumer messageConsumer; if (cachedMessageConsumer == null) { messageConsumer = createMessageConsumer(session, destination); } else { messageConsumer = cachedMessageConsumer; } return messageConsumer; }
Source:
protected void addTaskCleanUpProcessListener(final KModuleDeploymentUnit unit, final InternalKieContainer kieContainer) { final DeploymentDescriptor descriptor = getDeploymentDescriptor(unit, kieContainer); descriptor.getBuilder().addEventListener( new NamedObjectModel( "mvel", "taskCleanup", "new org.jbpm.services.task.admin.listener.TaskCleanUpProcessEventListener(taskService)" ) ); unit.setDeploymentDescriptor(descriptor); }

Target:
protected void addTaskCleanUpProcessListener(final KModuleDeploymentUnit unit, final InternalKieContainer kieContainer) { final DeploymentDescriptor descriptor = getDeploymentDescriptor(unit, kieContainer); descriptor.getBuilder().addEventListener( new ObjectModel( "mvel", "new org.jbpm.services.task.admin.listener.TaskCleanUpProcessEventListener(taskService)" ) ); unit.setDeploymentDescriptor(descriptor); }
Source:
private Set<SupportedAdditionalClusterFeature> getAdditionalClusterFeaturesAdded() { Set<SupportedAdditionalClusterFeature> featuresSupported = new HashSet<SupportedAdditionalClusterFeature>(getVdsGroup().getAddtionalFeaturesSupported()); featuresSupported.removeAll(clusterFeatureDao.getSupportedFeaturesByClusterId(getVdsGroup().getId())); return featuresSupported; }

Target:
private Set<SupportedAdditionalClusterFeature> getAdditionalClusterFeaturesAdded() { Set<SupportedAdditionalClusterFeature> featuresSupported = new HashSet<>(getVdsGroup().getAddtionalFeaturesSupported()); featuresSupported.removeAll(clusterFeatureDao.getSupportedFeaturesByClusterId(getVdsGroup().getId())); return featuresSupported; }
Source:
protected void populateColumnDataTypes(HashSet<String> columnNamesSet) throws SQLException { ResultSet rsColumns; DatabaseMetaData meta = store.getConnection().getMetaData(); rsColumns = meta.getColumns(null, null, getTablename().toUpperCase(), null); if (!rsColumns.isBeforeFirst()) { rsColumns = meta.getColumns(null, null, getTablename().toLowerCase(), null); } int totalColumns = columnNamesSet.size(); if (totalColumns == 0) { while (rsColumns.next()) { columnNames.add(rsColumns.getString("COLUMN_NAME")); columnNullabilities.add(rsColumns.getInt("NULLABLE")); columnDataTypes.add(rsColumns.getInt("DATA_TYPE")); } } else { while ((totalColumns > 0) && rsColumns.next()) { if (columnNamesSet.contains(rsColumns.getString("COLUMN_NAME").toUpperCase())) { columnNames.add(rsColumns.getString("COLUMN_NAME")); columnNullabilities.add(rsColumns.getInt("NULLABLE")); columnDataTypes.add(rsColumns.getInt("DATA_TYPE")); totalColumns--; } } } }

Target:
protected void populateColumnDataTypes(HashSet<String> columnNamesSet) throws SQLException { ResultSet rsColumns; DatabaseMetaData meta = store.getConnection().getMetaData(); rsColumns = meta.getColumns(null, null, getTablename().toUpperCase(), null); if (!rsColumns.isBeforeFirst()) { rsColumns = meta.getColumns(null, null, getTablename().toLowerCase(), null); if (!rsColumns.isBeforeFirst()) { rsColumns = meta.getColumns(null, null, getTablename(), null); if (!rsColumns.isBeforeFirst()) { throw new RuntimeException("Table name not found"); } } } boolean readAllColumns = columnNamesSet.size() == 0 ? true : false; int remainingColumns = columnNamesSet.size(); while (rsColumns.next()) { if (readAllColumns || remainingColumns > 0) { if (readAllColumns || columnNamesSet.contains(rsColumns.getString("COLUMN_NAME").toUpperCase())) { columnNames.add(rsColumns.getString("COLUMN_NAME")); columnNullabilities.add(rsColumns.getInt("NULLABLE")); columnDataTypes.add(rsColumns.getInt("DATA_TYPE")); remainingColumns--; } } else { break; } } }
Source:
protected void assertColumn(CharSequence expected, CharSequence tableName, int index) { DefaultCairoConfiguration configuration = new DefaultCairoConfiguration(root); try (TableReader reader = new TableReader(configuration, tableName)) { final StringSink sink = new StringSink(); final RecordCursorPrinter printer = new RecordCursorPrinter(sink); sink.clear(); printer.printFullColumn(reader.getCursor(), reader.getMetadata(), index, false); TestUtils.assertEquals(expected, sink); reader.getCursor().toTop(); sink.clear(); printer.printFullColumn(reader.getCursor(), reader.getMetadata(), index, false); TestUtils.assertEquals(expected, sink); } }

Target:
protected void assertColumn(CharSequence expected, CharSequence tableName, int index) { try (TableReader reader = new TableReader(configuration, tableName)) { final StringSink sink = new StringSink(); final RecordCursorPrinter printer = new RecordCursorPrinter(sink); sink.clear(); printer.printFullColumn(reader.getCursor(), reader.getMetadata(), index, false); TestUtils.assertEquals(expected, sink); reader.getCursor().toTop(); sink.clear(); printer.printFullColumn(reader.getCursor(), reader.getMetadata(), index, false); TestUtils.assertEquals(expected, sink); } }
Source:
public List<String> removeAppLanguageCodes(@NonNull List<String> codes) { if (appLanguageCodes.size() > 1) { for (String code : codes) { appLanguageCodes.remove(code); } Prefs.setAppLanguageCodeCsv(StringUtil.listToCsv(appLanguageCodes)); } return appLanguageCodes; }

Target:
public List<String> removeAppLanguageCodes(@NonNull List<String> codes) { if (appLanguageCodes.size() > 1) { appLanguageCodes.removeAll(codes); if (appLanguageCodes.isEmpty()) { appLanguageCodes.addAll(getSystemLanguageCodes()); } Prefs.setAppLanguageCodeCsv(StringUtil.listToCsv(appLanguageCodes)); } return appLanguageCodes; }
Source:
private void refreshLabelAndIcon() { if (getFigure() instanceof SiriusWrapLabel) { SiriusWrapLabel siriusWrapLabel = (SiriusWrapLabel) getFigure(); DDiagramElement dDiagramElement = resolveDiagramElement(); EditPart parent = getParent(); if (siriusWrapLabel != null && dDiagramElement != null && parent instanceof IDiagramElementEditPart) { DiagramElementEditPartOperation.refreshFont((IDiagramElementEditPart) parent, dDiagramElement, siriusWrapLabel); StyleConfiguration styleConfiguration = IStyleConfigurationRegistry.INSTANCE.getStyleConfiguration(dDiagramElement.getDiagramElementMapping(), dDiagramElement.getStyle()); Image labelIcon = new StyleConfigurationQuery(styleConfiguration).getLabelIcon(dDiagramElement, this); siriusWrapLabel.setText(dDiagramElement.getName()); siriusWrapLabel.setIcon(labelIcon); if (dDiagramElement instanceof DNode) { styleConfiguration.adaptNodeLabel((DNode) dDiagramElement, siriusWrapLabel); } } } }

Target:
private void refreshLabelAndIcon() { if (getFigure() instanceof SiriusWrapLabel) { SiriusWrapLabel siriusWrapLabel = (SiriusWrapLabel) getFigure(); DDiagramElement dDiagramElement = resolveDiagramElement(); EditPart parent = getParent(); if (parent instanceof IDiagramElementEditPart) { DiagramElementEditPartOperation.refreshLabelAndIcon((IDiagramElementEditPart) parent, dDiagramElement, siriusWrapLabel); } } }
Source:
public PID getTransformedPid(PID originalPid) { return generateIds ? pidMinter.mintDepositRecordPid() : PIDs.get(DEPOSIT_RECORD_BASE, originalPid.getUUID().toLowerCase()); }

Target:
public PID getTransformedPid(PID originalPid) { return generateIds ? pidMinter.mintDepositRecordPid() : PIDs.get(DEPOSIT_RECORD_BASE, originalPid.getId().toLowerCase()); }
Source:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: Intent intent = new Intent(this, TopicActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(intent); return true; } return super.onOptionsItemSelected(item); }

Target:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); }
Source:
private PlanNodeStatsEstimate compute( PlanNodeStatsEstimate sourceStats, PlanNodeStatsEstimate filteringSourceStats, Symbol sourceJoinSymbol, Symbol filteringSourceJoinSymbol, BiFunction<SymbolStatsEstimate, SymbolStatsEstimate, Double> retainedNdvProvider) { SymbolStatsEstimate sourceJoinSymbolStats = sourceStats.getSymbolStatistics(sourceJoinSymbol); SymbolStatsEstimate filteringSourceJoinSymbolStats = filteringSourceStats.getSymbolStatistics(filteringSourceJoinSymbol); double retainedNDV = retainedNdvProvider.apply(sourceJoinSymbolStats, filteringSourceJoinSymbolStats); double filterFactor = sourceJoinSymbolStats.getValuesFraction() * retainedNDV / sourceJoinSymbolStats.getDistinctValuesCount(); SymbolStatsEstimate newSourceJoinSymbolStats = SymbolStatsEstimate.buildFrom(sourceJoinSymbolStats) .setNullsFraction(0) .setDistinctValuesCount(retainedNDV) .build(); PlanNodeStatsEstimate outputStats = sourceStats.mapSymbolColumnStatistics(sourceJoinSymbol, oldStats -> newSourceJoinSymbolStats); outputStats = outputStats.mapOutputRowCount(rowCount -> rowCount * filterFactor); return outputStats; }

Target:
private static PlanNodeStatsEstimate compute( PlanNodeStatsEstimate sourceStats, PlanNodeStatsEstimate filteringSourceStats, Symbol sourceJoinSymbol, Symbol filteringSourceJoinSymbol, BiFunction<SymbolStatsEstimate, SymbolStatsEstimate, Double> retainedNdvProvider) { SymbolStatsEstimate sourceJoinSymbolStats = sourceStats.getSymbolStatistics(sourceJoinSymbol); SymbolStatsEstimate filteringSourceJoinSymbolStats = filteringSourceStats.getSymbolStatistics(filteringSourceJoinSymbol); double retainedNdv = retainedNdvProvider.apply(sourceJoinSymbolStats, filteringSourceJoinSymbolStats); double filterFactor = sourceJoinSymbolStats.getValuesFraction() * retainedNdv / sourceJoinSymbolStats.getDistinctValuesCount(); SymbolStatsEstimate newSourceJoinSymbolStats = SymbolStatsEstimate.buildFrom(sourceJoinSymbolStats) .setNullsFraction(0) .setDistinctValuesCount(retainedNdv) .build(); PlanNodeStatsEstimate outputStats = PlanNodeStatsEstimate.buildFrom(sourceStats) .addSymbolStatistics(sourceJoinSymbol, newSourceJoinSymbolStats) .setOutputRowCount(sourceStats.getOutputRowCount() * filterFactor) .build(); return outputStats; }
Source:
@Test public void test2() { driver.setConnection(new ConnectionStateBuilder() .withAirplaneModeDisabled() .build()); ConnectionState state = driver.getConnection(); assertTrue(!state.isAirplaneModeEnabled() && !state.isWiFiEnabled() && !state.isDataEnabled()); driver.setConnection(new ConnectionStateBuilder() .withAirplaneModeEnabled() .build()); state = driver.getConnection(); assertTrue(state.isAirplaneModeEnabled() && !state.isWiFiEnabled() && !state.isDataEnabled()); }

Target:
public void test2() { ConnectionState state = driver.setConnection(new ConnectionStateBuilder() .withAirplaneModeDisabled() .build()); assertFalse(state.isAirplaneModeEnabled()); assertFalse(state.isWiFiEnabled()); assertFalse(state.isDataEnabled()); state = driver.setConnection(new ConnectionStateBuilder(state) .withAirplaneModeEnabled() .build()); assertTrue(state.isAirplaneModeEnabled()); }
Source:
private void deleteGeneratedMaps() { log.info("Deleting leftover generated maps..."); if (customMapsDirectory != null && customMapsDirectory.toFile().exists()) { try { Files.list(customMapsDirectory) .filter(Files::isDirectory) .filter(p -> GENERATED_MAP_PATTERN.matcher(p.getFileName().toString()).matches()) .forEach(p -> noCatch(() -> FileUtils.deleteRecursively(p))); } catch (IOException e) { log.error("Could not list custom maps directory for deleting leftover generated maps.", e); } } }

Target:
private void deleteGeneratedMaps() { log.info("Deleting leftover generated maps..."); if (customMapsDirectory != null && customMapsDirectory.toFile().exists()) { try (Stream<Path> listOfMapFiles = Files.list(customMapsDirectory)) { listOfMapFiles .filter(Files::isDirectory) .filter(p -> GENERATED_MAP_PATTERN.matcher(p.getFileName().toString()).matches()) .forEach(p -> noCatch(() -> FileUtils.deleteRecursively(p))); } catch (IOException e) { log.error("Could not list custom maps directory for deleting leftover generated maps.", e); } } }
Source:
public List<CaptureConfig> onPresetSession() { return new ArrayList<>(); }

Target:
public CaptureConfig onPresetSession() { return null; }
Source:
public void shouldFailRequestingARefund_whenAPartialRefundMakesTotalRefundedAmountBiggerThanChargeAmount() { Long firstRefundAmount = 80L; Long secondRefundAmount = 30L; ValidatableResponse validatableResponse = postRefundFor(defaultTestCharge.getExternalChargeId(), firstRefundAmount, defaultTestCharge.getAmount()); String firstRefundId = assertRefundResponseWith(firstRefundAmount, validatableResponse, ACCEPTED.getStatusCode()); List<Map<String, Object>> refundsFoundByChargeId = databaseTestHelper.getRefundsByChargeId(defaultTestCharge.getChargeId()); assertThat(refundsFoundByChargeId.size(), is(1)); assertThat(refundsFoundByChargeId, hasItems(aRefundMatching(firstRefundId, is(notNullValue()), defaultTestCharge.getChargeId(), firstRefundAmount, "REFUNDED"))); postRefundFor(defaultTestCharge.getExternalChargeId(), secondRefundAmount, defaultTestCharge.getAmount() - firstRefundAmount) .statusCode(400) .body("reason", is("amount_not_available")) .body("message", is("Not sufficient amount available for refund")); List<Map<String, Object>> refundsFoundByChargeId1 = databaseTestHelper.getRefundsByChargeId(defaultTestCharge.getChargeId()); assertThat(refundsFoundByChargeId1.size(), is(1)); assertThat(refundsFoundByChargeId1, hasItems(aRefundMatching(firstRefundId, is(notNullValue()), defaultTestCharge.getChargeId(), firstRefundAmount, "REFUNDED"))); assertRefundsHistoryInDBForSuccessfulOrPartialRefund(defaultTestCharge); }

Target:
public void shouldFailRequestingARefund_whenAPartialRefundMakesTotalRefundedAmountBiggerThanChargeAmount() { Long firstRefundAmount = 80L; Long secondRefundAmount = 30L; ValidatableResponse validatableResponse = postRefundFor(defaultTestCharge.getExternalChargeId(), firstRefundAmount, defaultTestCharge.getAmount()); String firstRefundId = assertRefundResponseWith(firstRefundAmount, validatableResponse, ACCEPTED.getStatusCode()); List<Map<String, Object>> refundsFoundByChargeId = databaseTestHelper.getRefundsByChargeId(defaultTestCharge.getChargeId()); assertThat(refundsFoundByChargeId.size(), is(1)); assertThat(refundsFoundByChargeId, hasItems(aRefundMatching(firstRefundId, is(notNullValue()), defaultTestCharge.getChargeId(), firstRefundAmount, "REFUNDED"))); postRefundFor(defaultTestCharge.getExternalChargeId(), secondRefundAmount, defaultTestCharge.getAmount() - firstRefundAmount) .statusCode(400) .body("reason", is("amount_not_available")) .body("message", is("Not sufficient amount available for refund")); List<Map<String, Object>> refundsFoundByChargeId1 = databaseTestHelper.getRefundsByChargeId(defaultTestCharge.getChargeId()); assertThat(refundsFoundByChargeId1.size(), is(1)); assertThat(refundsFoundByChargeId1, hasItems(aRefundMatching(firstRefundId, is(notNullValue()), defaultTestCharge.getChargeId(), firstRefundAmount, "REFUNDED"))); assertRefundsHistoryInOrderInDBForSuccessfulOrPartialRefund(defaultTestCharge); }
Source:
public Ds3DocSpecParserImpl(final NameMapper nameMapper) { this.objectMapper = initDs3DocSpec(); this.nameMapper = nameMapper; }

Target:
public Ds3DocSpecParserImpl(final NameMapper nameMapper) { this.nameMapper = nameMapper; }
Source:
public void issuerWhenTokenEndpointAuthMethodsNoneThenMethodIsNone() throws Exception { this.response.put("token_endpoint_auth_methods_supported", Arrays.asList("none")); ClientRegistration registration = registration("") .clientAuthenticationMethod(ClientAuthenticationMethod.NONE) .build(); assertThat(registration.getClientAuthenticationMethod()).isEqualTo(ClientAuthenticationMethod.NONE); }

Target:
public void issuerWhenTokenEndpointAuthMethodsNoneThenMethodIsNone() throws Exception { this.response.put("token_endpoint_auth_methods_supported", Arrays.asList("none")); ClientRegistration registration = registration("").build(); assertThat(registration.getClientAuthenticationMethod()).isEqualTo(ClientAuthenticationMethod.NONE); }
Source:
void initializeNewTasks() { if (!created.isEmpty()) { log.debug("Initializing {}s {}", taskTypeName, created.keySet()); } for (final Iterator<Map.Entry<TaskId, T>> it = created.entrySet().iterator(); it.hasNext(); ) { final Map.Entry<TaskId, T> entry = it.next(); try { if (!entry.getValue().initializeStateStores()) { log.debug("Transitioning to created", taskTypeName, entry.getKey()); ((AssignedStreamsTasks) this).addToRestoring((StreamTask) entry.getValue()); } else { transitionToRunning(entry.getValue()); } it.remove(); } catch (final LockException e) { log.trace("Could not create due to {}; will retry", taskTypeName, entry.getKey(), e.toString()); } } }

Target:
void initializeNewTasks() { if (!created.isEmpty()) { log.debug("Initializing {}s {}", taskTypeName, created.keySet()); } for (final Iterator<Map.Entry<TaskId, T>> it = created.entrySet().iterator(); it.hasNext(); ) { final Map.Entry<TaskId, T> entry = it.next(); try { if (!entry.getValue().initializeStateStores()) { log.debug("Transitioning to restoring", taskTypeName, entry.getKey()); ((AssignedStreamsTasks) this).addToRestoring((StreamTask) entry.getValue()); } else { transitionToRunning(entry.getValue()); } it.remove(); } catch (final LockException e) { log.debug("Could not create due to {}; will retry", taskTypeName, entry.getKey(), e.toString()); } } }
Source:
public void shouldRaiseAlertIfRequestParamsAppearAsCookieValue() throws URIException, NullPointerException { HttpMessage msg = createMessage(); msg.getRequestHeader().setURI(new URI("<LINK_0>", false)); msg.getResponseHeader().setHeader(HttpResponseHeader.SET_COOKIE, "Set-Cookie: aCookie=fred; Secure"); rule.scanHttpResponseReceive(msg, -1, createSource(msg)); assertThat(alertsRaised.size(), equalTo(1)); }

Target:
public void shouldRaiseAlertIfRequestParamsAppearAsCookieValue() throws Exception { HttpMessage msg = createMessage(); msg.getRequestHeader().setURI(new URI("<LINK_0>", false)); msg.getResponseHeader().setHeader(HttpResponseHeader.SET_COOKIE, "Set-Cookie: aCookie=fred; Secure"); rule.scanHttpResponseReceive(msg, -1, createSource(msg)); assertThat(alertsRaised.size(), equalTo(1)); assertThat(alertsRaised.get(0).getParam(), equalTo("name")); }
Source:
public static Object[] setUpLayoutElements(Context context, FormEntryPrompt prompt) { View answerView; CustomRangeSlider slider; TextView currentValue; TextView minValue; TextView maxValue; String appearance = prompt.getQuestion().getAppearanceAttr(); if (appearance != null && appearance.contains(VERTICAL_APPEARANCE)) { RangeWidgetVerticalBinding rangeWidgetVerticalBinding = RangeWidgetVerticalBinding .inflate(((Activity) context).getLayoutInflater()); answerView = rangeWidgetVerticalBinding.getRoot(); slider = rangeWidgetVerticalBinding.slider; currentValue = rangeWidgetVerticalBinding.currentValue; minValue = rangeWidgetVerticalBinding.minValue; maxValue = rangeWidgetVerticalBinding.maxValue; } else { RangeWidgetHorizontalBinding rangeWidgetHorizontalBinding = RangeWidgetHorizontalBinding .inflate(((Activity) context).getLayoutInflater()); answerView = rangeWidgetHorizontalBinding.getRoot(); slider = rangeWidgetHorizontalBinding.slider; currentValue = rangeWidgetHorizontalBinding.currentValue; minValue = rangeWidgetHorizontalBinding.minValue; maxValue = rangeWidgetHorizontalBinding.maxValue; } setUpWidgetParameters((RangeQuestion) prompt.getQuestion(), minValue, maxValue); if (prompt.isReadOnly()) { slider.setEnabled(false); } return new Object[] {answerView, slider, currentValue}; }

Target:
public static RangeWidgetLayoutElements setUpLayoutElements(Context context, FormEntryPrompt prompt) { View answerView; TrackingTouchSlider slider; TextView currentValue; TextView minValue; TextView maxValue; String appearance = prompt.getQuestion().getAppearanceAttr(); if (appearance != null && appearance.contains(VERTICAL_APPEARANCE)) { RangeWidgetVerticalBinding rangeWidgetVerticalBinding = RangeWidgetVerticalBinding .inflate(((Activity) context).getLayoutInflater()); answerView = rangeWidgetVerticalBinding.getRoot(); slider = rangeWidgetVerticalBinding.slider; currentValue = rangeWidgetVerticalBinding.currentValue; minValue = rangeWidgetVerticalBinding.minValue; maxValue = rangeWidgetVerticalBinding.maxValue; } else { RangeWidgetHorizontalBinding rangeWidgetHorizontalBinding = RangeWidgetHorizontalBinding .inflate(((Activity) context).getLayoutInflater()); answerView = rangeWidgetHorizontalBinding.getRoot(); slider = rangeWidgetHorizontalBinding.slider; currentValue = rangeWidgetHorizontalBinding.currentValue; minValue = rangeWidgetHorizontalBinding.minValue; maxValue = rangeWidgetHorizontalBinding.maxValue; } setUpWidgetParameters((RangeQuestion) prompt.getQuestion(), minValue, maxValue); if (prompt.isReadOnly()) { slider.setEnabled(false); } return new RangeWidgetLayoutElements(answerView, slider, currentValue); }
Source:
public IBigtableDataClient getClientWrapper() { if(options.useGCJClient()){ return dataGCJClient; } return new BigtableDataClientWrapper(dataClient, getDataRequestContext()); }

Target:
public IBigtableDataClient getClientWrapper() { if (options.useGCJClient()) { if (this.dataGCJClient == null) { synchronized (BigtableSession.this) { try { if (dataGCJClient == null) { BigtableDataSettings dataSettings = BigtableVeneerSettingsFactory.createBigtableDataSettings(options); this.dataGCJClient = new BigtableDataGCJClient( com.google.cloud.bigtable.data.v2.BigtableDataClient.create(dataSettings)); } } catch (IOException ioException) { throw new RuntimeException(ioException); } } } return dataGCJClient; } else { return new BigtableDataClientWrapper(dataClient, getDataRequestContext()); } }
Source:
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { final ItemStack stack = user.getBase().getItemInHand(); if (stack == null) { throw new Exception(tl("cantSpawnItem", "Air")); } if (stack.getAmount() >= ((user.isAuthorized("essentials.oversizedstacks")) ? ess.getSettings().getOversizedStackSize() : stack.getMaxStackSize())) { throw new Exception(tl("fullStack")); } final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""); if (!user.canSpawnItem(stack.getType())) { throw new Exception(tl("cantSpawnItem", itemname)); } if (args.length > 1) { int newAmount = stack.getAmount(); try { newAmount += Integer.parseInt(ChatColor.stripColor(args[1])); } catch(Exception e) { throw new Exception(tl("numberRequired")); } if (!user.isAuthorized("essentials.oversizedstacks")) { newAmount = stack.getMaxStackSize(); } else { if (newAmount > ess.getSettings().getOversizedStackSize()) { newAmount = ess.getSettings.getOversizedStackSize(); } } stack.setAmount(newAmount); } else { if (user.isAuthorized("essentials.oversizedstacks")) { stack.setAmount(ess.getSettings().getOversizedStackSize()); } else { stack.setAmount(stack.getMaxStackSize()); } } user.getBase().updateInventory(); }

Target:
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { final ItemStack stack = user.getBase().getItemInHand(); if (stack == null) { throw new Exception(tl("cantSpawnItem", "Air")); } if (stack.getAmount() >= ((user.isAuthorized("essentials.oversizedstacks")) ? ess.getSettings().getOversizedStackSize() : stack.getMaxStackSize())) { throw new Exception(tl("fullStack")); } final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""); if (!user.canSpawnItem(stack.getType())) { throw new Exception(tl("cantSpawnItem", itemname)); } if (args.length > 1) { int newAmount = stack.getAmount(); try { newAmount += Integer.parseInt(args[1]); } catch(NumberFormatException e) { throw new Exception(tl("numberRequired")); } if (!user.isAuthorized("essentials.oversizedstacks")) { newAmount = stack.getMaxStackSize(); } else { if (newAmount > ess.getSettings().getOversizedStackSize()) { newAmount = ess.getSettings().getOversizedStackSize(); } } stack.setAmount(newAmount); } else { if (user.isAuthorized("essentials.oversizedstacks")) { stack.setAmount(ess.getSettings().getOversizedStackSize()); } else { stack.setAmount(stack.getMaxStackSize()); } } user.getBase().updateInventory(); }
Source:
public void exportDataset(DatasetVersion version, JsonObject json, OutputStream outputStream) throws ExportException { try { Path cachedMetadataFilePath = Paths.get(version.getDataset().getFileSystemDirectory().toString(), "export_ddi" + ".cached"); File datafile = cachedMetadataFilePath.toFile(); DdiExportUtil.datasetHtmlDDI(datafile, outputStream); } catch (XMLStreamException xse) { throw new ExportException ("Caught XMLStreamException performing DDI export"); } }

Target:
public void exportDataset(DatasetVersion version, JsonObject json, OutputStream outputStream) throws ExportException { try { InputStream ddiInputStream; try { ddiInputStream = ExportService.getInstance(null).getExport(version.getDataset(), "ddi"); } catch(ExportException | IOException e) { throw new ExportException ("Cannot open export_ddi cached file"); } DdiExportUtil.datasetHtmlDDI(ddiInputStream, outputStream); } catch (XMLStreamException xse) { throw new ExportException ("Caught XMLStreamException performing DDI export"); } }
Source:
public Response performRemove(String id) { RemoveVmFromImportExportParamenters params = new RemoveVmFromImportExportParamenters( Guid.createGuidFromStringDefaultEmpty(id), storageDomainId, getDataCenterId(storageDomainId)); return performAction(VdcActionType.RemoveVmFromImportExport, params); }

Target:
public Response performRemove(String id) { RemoveVmFromImportExportParamenters params = new RemoveVmFromImportExportParamenters( GuidUtils.asGuid(id), storageDomainId, getDataCenterId(storageDomainId)); return performAction(VdcActionType.RemoveVmFromImportExport, params); }
Source:
public void testNodes() throws Exception { try(IgniteEx g1 = startGrid(0)) { SystemView<ClusterNodeView> nodes = g1.context().systemView().view(NODES_SYS_VIEW); assertEquals(1, nodes.size()); checkNodeView(nodes.iterator().next(), g1.localNode(), true); try(IgniteEx g2 = startGrid(1)) { awaitPartitionMapExchange(); assertEquals(2, nodes.size()); boolean found = false; for (ClusterNodeView node : nodes) { if (!node.nodeId().equals(g2.localNode().id())) continue; checkNodeView(node, g2.localNode(), false); found = true; break; } assertTrue(found); SystemView<ClusterNodeView> nodes2 = g2.context().systemView().view(NODES_SYS_VIEW); assertEquals(2, nodes2.size()); for (ClusterNodeView node : nodes2) { if(node.nodeId().equals(g2.localNode().id())) checkNodeView(node, g2.localNode(), true); else checkNodeView(node, g1.localNode(), false); } } } }

Target:
public void testNodes() throws Exception { try(IgniteEx g1 = startGrid(0)) { SystemView<ClusterNodeView> views = g1.context().systemView().view(NODES_SYS_VIEW); assertEquals(1, views.size()); try(IgniteEx g2 = startGrid(1)) { awaitPartitionMapExchange(); checkViewsState(views, g1.localNode(), g2.localNode()); checkViewsState(g2.context().systemView().view(NODES_SYS_VIEW), g2.localNode(), g1.localNode()); } assertEquals(1, views.size()); } }
Source:
public static void waitForBlocksToBeFreed(final BlockWorker bw, final Long... blockIds) throws TimeoutException { try { Whitebox.getInternalState(bw, BlockMasterSync.class).heartbeat(); CommonUtils.waitFor("blocks to be removed", () -> { if (blockIds.length == 0) { return true; } Set<Long> blocks = bw.getBlockStore().getBlockStoreMetaFull() .getBlockListByStorageLocation().values().stream().flatMap(List::stream) .collect(Collectors.toSet()); List<Long> bids = Lists.newArrayList(blockIds); return bids.stream().map(id -> !blocks.contains(id)).reduce((s1, s2) -> s1 && s2) .orElse(false); }, WaitForOptions.defaults().setTimeoutMs(100 * Constants.SECOND_MS)); Whitebox.getInternalState(bw, BlockMasterSync.class).heartbeat(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } }

Target:
public static void waitForBlocksToBeFreed(final BlockWorker bw, final Long... blockIds) throws TimeoutException { try { Whitebox.getInternalState(bw, BlockMasterSync.class).heartbeat(); CommonUtils.waitFor("blocks to be removed", () -> { Set<Long> blocks = bw.getBlockStore().getBlockStoreMetaFull() .getBlockListByStorageLocation().values().stream().flatMap(List::stream) .collect(Collectors.toSet()); blocks.retainAll(Sets.newHashSet(blockIds)); return blocks.isEmpty(); }, WaitForOptions.defaults().setTimeoutMs(100 * Constants.SECOND_MS)); Whitebox.getInternalState(bw, BlockMasterSync.class).heartbeat(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } }
Source:
private ConnectionCheck(String host, int port) { this.host = "127.0.0.1"; this.port = port; }

Target:
private ConnectionCheck(String host, int port) { this.host = host; this.port = port; }
Source:
protected @Nullable String generateStringOfCFGWithoutAnalysis( String inputFile, String method, String clas, boolean verbose) { @Nullable Map<String, Object> res = generateStringOfCFG(inputFile, method, clas, verbose, null); if (res != null) { return (String) res.get("stringGraph"); } else { return "null"; } }

Target:
protected String generateStringOfCFGWithoutAnalysis( String inputFile, String method, String clas, boolean verbose) { @Nullable Map<String, Object> res = generateStringOfCFG(inputFile, method, clas, verbose, null); if (res != null) { String stringGraph = (String) res.get("stringGraph"); if (stringGraph == null) { return "Unexpected output from generating string control flow graph, shouldn't be null."; } return stringGraph; } else { return "Unexpected output from generating string control flow graph, shouldn't be null."; } }
Source:
private static int largestNPandigitalPrime() { return Stream.rangeClosedBy(9, 1, -1) .flatMap(n -> nDigitPandigitalNumbers(n) .filter(Utils::isPrime) .sorted() .reverse()) .head(); }

Target:
private static int largestNPandigitalPrime() { return Stream.rangeClosedBy(9, 1, -1) .flatMap(n -> nDigitPandigitalNumbers(n) .filter(Utils::isPrime) .sorted(reverseOrder())) .head(); }
Source:
ExecutionContextBuilder(ExecutionContext other) { instrumentation = other.getInstrumentation(); executionId = other.getExecutionId(); instrumentationState = other.getInstrumentationState(); graphQLSchema = other.getGraphQLSchema(); queryStrategy = other.getQueryStrategy(); mutationStrategy = other.getMutationStrategy(); subscriptionStrategy = other.getSubscriptionStrategy(); context = other.getContext(); root = other.getRoot(); document = other.getDocument(); operationDefinition = other.getOperationDefinition(); variables = new LinkedHashMap<>(other.getVariables()); fragmentsByName = new LinkedHashMap<>(other.getFragmentsByName()); dataLoaderRegistry = other.getDataLoaderRegistry(); cacheControl = other.getCacheControl(); locale = other.getLocale(); errors = new ArrayList<>(other.getErrors()); valueUnboxer = other.getValueUnboxer(); this.executionInput = other.getExecutionInput(); }

Target:
ExecutionContextBuilder(ExecutionContext other) { instrumentation = other.getInstrumentation(); executionId = other.getExecutionId(); instrumentationState = other.getInstrumentationState(); graphQLSchema = other.getGraphQLSchema(); queryStrategy = other.getQueryStrategy(); mutationStrategy = other.getMutationStrategy(); subscriptionStrategy = other.getSubscriptionStrategy(); context = other.getContext(); localContext = other.getLocalContext(); root = other.getRoot(); document = other.getDocument(); operationDefinition = other.getOperationDefinition(); variables = new LinkedHashMap<>(other.getVariables()); fragmentsByName = new LinkedHashMap<>(other.getFragmentsByName()); dataLoaderRegistry = other.getDataLoaderRegistry(); cacheControl = other.getCacheControl(); locale = other.getLocale(); errors = new ArrayList<>(other.getErrors()); valueUnboxer = other.getValueUnboxer(); executionInput = other.getExecutionInput(); }
Source:
public void generatePassword(final WebContext ctx, String id) { UserAccount userAccount = findForTenant(UserAccount.class, id); assertNotNew(userAccount); if (!userAccount.isPasswordGenerationPossible()) { throw Exceptions.createHandled() .withNLSKey("UserAccountConroller.cannotGeneratePasswordForOwnUser") .handle(); } userAccount.getLogin().setGeneratedPassword(Strings.generatePassword()); oma.update(userAccount); auditLog.neutral("AuditLog.passwordGenerated") .causedByCurrentUser() .forUser(userAccount.getUniqueName(), userAccount.getLogin().getUsername()) .forTenant(String.valueOf(userAccount.getTenant().getId()), userAccount.getTenant().getValue().getName()) .forCurrentUser() .log(); if (userAccount.shouldSendGeneratedPassword()) { UserContext.message(Message.info(NLS.fmtr("UserAccountConroller.passwordGeneratedAndSent") .set(PARAM_EMAIL, userAccount.getEmail()) .format())); Context context = Context.create() .set(PARAM_PASSWORD, userAccount.getLogin().getGeneratedPassword()) .set(PARAM_NAME, userAccount.getPerson().getAddressableName()) .set(PARAM_USERNAME, userAccount.getLogin().getUsername()) .set(PARAM_URL, getBaseUrl()) .set(PARAM_ROOT, wondergemRoot); mails.createEmail() .to(userAccount.getEmail(), userAccount.getPerson().toString()) .subject(NLS.get("mail-password.subject")) .textTemplate("mail/useraccount/password.pasta", context) .htmlTemplate("mail/useraccount/password.html.pasta", context) .send(); } else { UserContext.message(Message.info(NLS.get("UserAccountConroller.passwordGenerated"))); } accounts(ctx); }

Target:
public void generatePassword(final WebContext ctx, String id) { UserAccount userAccount = findForTenant(UserAccount.class, id); assertNotNew(userAccount); if (!userAccount.isPasswordGenerationPossible()) { throw Exceptions.createHandled() .withNLSKey("UserAccountConroller.cannotGeneratePasswordForOwnUser") .handle(); } userAccount.getLogin().setGeneratedPassword(Strings.generatePassword()); oma.update(userAccount); auditLog.neutral("AuditLog.passwordGenerated") .causedByCurrentUser() .forUser(userAccount.getUniqueName(), userAccount.getLogin().getUsername()) .forTenant(String.valueOf(userAccount.getTenant().getId()), userAccount.getTenant().getValue().getName()) .log(); if (userAccount.shouldSendGeneratedPassword()) { UserContext.message(Message.info(NLS.fmtr("UserAccountConroller.passwordGeneratedAndSent") .set(PARAM_EMAIL, userAccount.getEmail()) .format())); Context context = Context.create() .set(PARAM_PASSWORD, userAccount.getLogin().getGeneratedPassword()) .set(PARAM_NAME, userAccount.getPerson().getAddressableName()) .set(PARAM_USERNAME, userAccount.getLogin().getUsername()) .set(PARAM_URL, getBaseUrl()) .set(PARAM_ROOT, wondergemRoot); mails.createEmail() .to(userAccount.getEmail(), userAccount.getPerson().toString()) .subject(NLS.get("mail-password.subject")) .textTemplate("mail/useraccount/password.pasta", context) .htmlTemplate("mail/useraccount/password.html.pasta", context) .send(); } else { UserContext.message(Message.info(NLS.get("UserAccountConroller.passwordGenerated"))); } accounts(ctx); }
Source:
public static ScheduledThreadPoolExecutor newScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory, RejectedExecutionHandler handler) { int positiveCorePoolSize = corePoolSize > 0 ? corePoolSize : 1; ScheduledThreadPoolExecutor ret = new ScheduledThreadPoolExecutor(positiveCorePoolSize, threadFactory, handler) { @Override public void execute(Runnable command) { super.execute(wrap(command)); } }; ret.setKeepAliveTime(DEFAULT_THREAD_POOL_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); return ret; }

Target:
public static ScheduledThreadPoolExecutor newScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory, RejectedExecutionHandler handler) { Preconditions.checkArgument(corePoolSize >= 0, "Cannot create a ScheduledThreadPoolExecutor with threads - thread count must not be negative!", SafeArg.of("corePoolSize", corePoolSize)); int positiveCorePoolSize = corePoolSize > 0 ? corePoolSize : 1; ScheduledThreadPoolExecutor ret = new ScheduledThreadPoolExecutor(positiveCorePoolSize, threadFactory, handler) { @Override public void execute(Runnable command) { super.execute(wrap(command)); } }; ret.setKeepAliveTime(DEFAULT_THREAD_POOL_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); return ret; }
Source:
private synchronized void scheduleUpdate() { scheduledFuture = updateScheduledExecutor.scheduleWithFixedDelay(() -> { synchronized (this) { if (future != null && !future.isDone()) { return; } } long count = infoUpdateExponentialWait ? min(abs(updateCount.get()), 10) : 1; if (nanosSince(lastUpdateNanos.get()).toMillis() >= updateIntervalMillis * count) { sendNextRequest(); } }, 0, 100, MILLISECONDS); }

Target:
private synchronized void scheduleUpdate() { scheduledFuture = updateScheduledExecutor.scheduleWithFixedDelay(() -> { synchronized (this) { if (future != null && !future.isDone()) { return; } } if (nanosSince(lastUpdateNanos.get()).toMillis() >= updateIntervalMillis) { sendNextRequest(); } }, 0, 100, MILLISECONDS); }
Source:
private void updateDiseaseOccurrenceValidationWeighting(DiseaseOccurrence occurrence, Set<DiseaseOccurrence> pendingSave) { Double expertWeighting = occurrence.getExpertWeighting(); double systemWeighting = occurrence.getSystemWeighting(); double weighting = (expertWeighting != null) ? expertWeighting : systemWeighting; if (occurrence.getValidationWeighting() == null || occurrence.getValidationWeighting() != weighting) { pendingSave.add(occurrence); occurrence.setValidationWeighting(weighting); } }

Target:
private void updateDiseaseOccurrenceValidationWeighting(DiseaseOccurrence occurrence, Set<DiseaseOccurrence> pendingSave) { Double expertWeighting = occurrence.getExpertWeighting(); double systemWeighting = occurrence.getSystemWeighting(); double weighting = (expertWeighting != null) ? expertWeighting : systemWeighting; if (hasWeightingChanged(occurrence.getValidationWeighting(), weighting)) { pendingSave.add(occurrence); occurrence.setValidationWeighting(weighting); } }
Source:
public void notifyEvents(Collection<Event> events) { if (distributed) { NotifyData nEvent = new NotifyData(currentNode, events, Event.class); Integer key = nEvent.hashCode(); if (log.isDebugEnabled()) { log.debugf("Sending events [%s]", nEvent); } dataCache.getAdvancedCache().withFlags(Flag.IGNORE_RETURN_VALUES) .putAsync(key, nEvent, LIFESPAN, TimeUnit.MILLISECONDS); } }

Target:
public void notifyEvents(Collection<Event> events) { if (distributed) { NotifyData nEvent = new NotifyData(currentNode, events, Event.class); Integer key = nEvent.hashCode(); log.debugf("Sending events [%s]", nEvent); dataCache.getAdvancedCache().withFlags(Flag.IGNORE_RETURN_VALUES) .putAsync(key, nEvent, LIFESPAN, TimeUnit.MILLISECONDS); } }
Source:
public void executeCommand(UICommand command) { if (command.getName().equalsIgnoreCase("export_to_pdf")) { GlusterVolumeProfileInfo profileInfo = getProfileInfo(); GlusterVolumeCreatePdfParameters pdfParameters = new GlusterVolumeCreatePdfParameters(profileInfo, "", "admin"); Frontend.getInstance().runAction(VdcActionType.GlusterVolumeProfilePdfExport, pdfParameters, true); } }

Target:
public void executeCommand(UICommand command) { if (command.getName().equalsIgnoreCase("export_to_pdf")) { GlusterVolumeProfileInfo profileInfo = getProfileInfo(); GlusterVolumeCreatePdfParameters pdfParameters = new GlusterVolumeCreatePdfParameters(profileInfo, "", "admin"); Frontend.getInstance().runAction(VdcActionType.GlusterVolumeProfilePdfExport, pdfParameters, new IFrontendActionAsyncCallback() { @Override public void executed(FrontendActionAsyncResult result) { VdcReturnValueBase returnValue = result.getReturnValue(); setWindow(null); ConfirmationModel cModel = new ConfirmationModel(); cModel.setMessage(returnValue.getDescription()); } }); } }
Source:
public Transformer<String, String, KeyValue<String, String>> get() { return new Transformer<String, String, KeyValue<String, String>>() { private ProcessorContext context; private KeyValueStore<String, Integer> kvStore; @Override @SuppressWarnings("unchecked") public void init(final ProcessorContext context) { this.context = context; this.context.schedule(Duration.ofSeconds(1), PunctuationType.STREAM_TIME, timestamp -> { try (final KeyValueIterator<String, Integer> iter = kvStore.all()) { System.out.println("----------- " + timestamp + " ----------- "); while (iter.hasNext()) { final KeyValue<String, Integer> entry = iter.next(); System.out.println("[" + entry.key + ", " + entry.value + "]"); context.forward(entry.key, entry.value.toString()); } } }); this.kvStore = (KeyValueStore<String, Integer>) context.getStateStore("Counts"); } @Override public KeyValue<String, String> transform(final String dummy, final String line) { final String[] words = line.toLowerCase(Locale.getDefault()).split(" "); for (final String word : words) { final Integer oldValue = this.kvStore.get(word); if (oldValue == null) { this.kvStore.put(word, 1); } else { this.kvStore.put(word, oldValue + 1); } } context.commit(); return null; } @Override public void close() }; }

Target:
public Transformer<String, String, KeyValue<String, String>> get() { return new Transformer<String, String, KeyValue<String, String>>() { private ProcessorContext context; private KeyValueStore<String, Integer> kvStore; @Override @SuppressWarnings("unchecked") public void init(final ProcessorContext context) { this.context = context; this.context.schedule(Duration.ofSeconds(1), PunctuationType.STREAM_TIME, timestamp -> { try (final KeyValueIterator<String, Integer> iter = kvStore.all()) { System.out.println("----------- " + timestamp + " ----------- "); while (iter.hasNext()) { final KeyValue<String, Integer> entry = iter.next(); System.out.println("[" + entry.key + ", " + entry.value + "]"); context.forward(entry.key, entry.value.toString()); } } }); this.kvStore = (KeyValueStore<String, Integer>) context.getStateStore("Counts"); } @Override public KeyValue<String, String> transform(final String dummy, final String line) { final String[] words = line.toLowerCase(Locale.getDefault()).split(" "); for (final String word : words) { final Integer oldValue = this.kvStore.get(word); if (oldValue == null) { this.kvStore.put(word, 1); } else { this.kvStore.put(word, oldValue + 1); } } return null; } @Override public void close() }; }