auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static Training parseTraining(@NonNull final JSONObject json) throws JSONException { final Training training = new Training(); <START> if (json.has("id")) training.setId(json.getInt("id")); <END> training.setMinistryId(json.getString("ministry_id")); training.setName(json.getString("name")); training.setDate(stringToDate(json.getString("date"))); training.setType(json.getString("type")); training.setMcc(json.getString("mcc")); training.setLastSynced(new Date()); try { training.setLatitude(json.getDouble("latitude")); training.setLongitude(json.getDouble("longitude")); } catch (Exception e) { Log.w("TrainingJsonParser", "Location is null"); } if (json.has("gcm_training_completions")) { training.setCompletions(parseCompletions(json.getJSONArray("gcm_training_completions"))); } return training; }</code><technical_language>want json.optInt("Id") instead. else I noticed is id is currently int, in order for internal android functions a long</technical_language>

Target:
public static Training parseTraining(@NonNull final JSONObject json) throws JSONException { final Training training = new Training(); training.setId(json.optLong("Id")); training.setMinistryId(json.getString("ministry_id")); training.setName(json.getString("name")); training.setDate(stringToDate(json.getString("date"))); training.setType(json.getString("type")); training.setMcc(json.getString("mcc")); training.setLastSynced(new Date()); try { training.setLatitude(json.getDouble("latitude")); training.setLongitude(json.getDouble("longitude")); } catch (Exception e) { Log.w("TrainingJsonParser", "Location is null"); } if (json.has("gcm_training_completions")) { training.setCompletions(parseCompletions(json.getJSONArray("gcm_training_completions"))); } return training; }
Source:
<code>public void sampleExtractTest() throws IOException { int status = -1; File inputFile = new File(mInputFileName); if (inputFile.exists()) { FileInputStream fileInput = new FileInputStream(inputFile); FileDescriptor fileDescriptor = fileInput.getFD(); Extractor extractor = new Extractor(); extractor.setUpExtractor(fileDescriptor); status = extractor.extractSample(mTrackId); extractor.deinitExtractor(); <START> extractor.dumpStatistics(mInputFileName); <END> fileInput.close(); } else { Log.i(TAG, "Test files not found."); } assertThat(status, is(equalTo(0))); }</code><technical_language>this print entire file path printing statistics? NDK version prints filename (excluding path). need preserve file name pass here</technical_language>

Target:
public void sampleExtractTest() throws IOException { int status = -1; File inputFile = new File(mInputFilePath + mInputFileName); if (inputFile.exists()) { FileInputStream fileInput = new FileInputStream(inputFile); FileDescriptor fileDescriptor = fileInput.getFD(); Extractor extractor = new Extractor(); extractor.setUpExtractor(fileDescriptor); status = extractor.extractSample(mTrackId); extractor.deinitExtractor(); extractor.dumpStatistics(mInputFileName); fileInput.close(); } else { Log.i(TAG, "Unable to open input file for reading."); } assertThat(status, is(equalTo(0))); }
Source:
<code>protected Object getEntity(int index) { <START> return null; <END> }</code><technical_language>reuse for application</technical_language>

Target:
public Applications getEntity(int index) { return null; }
Source:
<code>private List<T> executeQuery(SQLSerializer ser, Object... additionalParams) { List<Object> params = ser.getConstants(); params.addAll(Arrays.asList(additionalParams)); Object[] arrParams = params.toArray(); IgniteQuery qry = IgniteQueryGenerator.prepareQuery(type, ser.toString(), arrParams); <START> QueryCursor qryCursor = cache.query(QueryUtils.prepareQuery(qry, arrParams)); return (List<T>) QueryUtils.transformQueryCursor(qryCursor, arrParams, false, ReturnStrategy.LIST_OF_VALUES); <END> }</code><technical_language>I qryCursor wrapped try-with-resource in order close cursor query execution</technical_language>

Target:
private List<T> executeQuery(SQLSerializer ser, Object... additionalParams) { List<Object> params = ser.getConstants(); params.addAll(Arrays.asList(additionalParams)); Object[] arrParams = params.toArray(); IgniteQuery qry = IgniteQueryGenerator.prepareQuery(type, ser.toString(), arrParams); try (QueryCursor qryCursor = cache.query(QueryUtils.prepareQuery(qry, arrParams))) { return (List<T>) transformQueryCursor(qryCursor, arrParams, false, ReturnStrategy.LIST_OF_VALUES); } }
Source:
<code>protected Resource createResource(OperationContext context, ModelNode operation) { Resource delegate = super.createResource(context, operation); if(context.isDefaultRequiresRuntime()) { final ModClusterResource resource = new ModClusterResource(delegate, context.getCurrentAddress().getLastElement().getValue()); context.removeResource(PathAddress.EMPTY_ADDRESS); context.addResource(PathAddress.EMPTY_ADDRESS, resource); return resource; } return delegate; <START> } <END></code><technical_language>I this is simpler: if (context.isDefaultRequiresRuntime()) { // Wrap a standard Resource impl in custom variant understands runtime-only children Resource delegate = Resource.Factory.create(); Resource result = new ModClusterResource(delegate, context.getCurrentAddressValue()); context.addResource(PathAddress.EMPTY_ADDRESS, result); return result; } else { return super.createResource(context, operation); }</technical_language>

Target:
protected Resource createResource(OperationContext context, ModelNode operation) { if (context.isDefaultRequiresRuntime()) { Resource delegate = Resource.Factory.create(); Resource result = new ModClusterResource(delegate, context.getCurrentAddressValue()); context.addResource(PathAddress.EMPTY_ADDRESS, result); return result; } else { return super.createResource(context, operation); } }
Source:
<code>private StoragePoolIsoMapDAO getStoragePoolIsoMapDAO() { <START> return DbFacade.getInstance().getStoragePoolIsoMapDao(); <END> }</code><technical_language>getDbFacade</technical_language>

Target:
private StoragePoolIsoMapDAO getStoragePoolIsoMapDAO() { return getDbFacade().getStoragePoolIsoMapDao(); }
Source:
<code>public void baseSetup() throws Exception { System.setProperty("user.name", TEST_USER); masterPort = temporaryPorts.localPort("helios master"); masterAdminPort = temporaryPorts.localPort("helios master admin"); <START> String className = getClass().getName(); <END> masterEndpoint = "http://localhost:" + masterPort(); masterAdminEndpoint = "http://localhost:" + masterAdminPort(); zk = zooKeeperTestManager(); listThreads(); zk.ensure("/config"); zk.ensure("/status"); agentStateDirs = temporaryFolder.newFolder("helios-agents").toPath(); masterStateDirs = temporaryFolder.newFolder("helios-masters").toPath(); httpClient = HttpClients.createMinimal(); }</code><technical_language>className is needed. delete integrationMode, testHost, masterName</technical_language>

Target:
public void baseSetup() throws Exception { System.setProperty("user.name", TEST_USER); masterPort = temporaryPorts.localPort("helios master"); masterAdminPort = temporaryPorts.localPort("helios master admin"); masterEndpoint = "http://localhost:" + masterPort(); masterAdminEndpoint = "http://localhost:" + masterAdminPort(); zk = zooKeeperTestManager(); listThreads(); zk.ensure("/config"); zk.ensure("/status"); agentStateDirs = temporaryFolder.newFolder("helios-agents").toPath(); masterStateDirs = temporaryFolder.newFolder("helios-masters").toPath(); httpClient = HttpClients.createMinimal(); }
Source:
<code>public void onMessageReceived(RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); Log.d("DemoFirebaseService", "got new message: " + remoteMessage.getData()); CountlyPush.Message message = CountlyPush.decodeMessage(remoteMessage.getData()); if (message != null && message.has("typ")) { message.recordAction(getApplicationContext()); return; } Boolean result = CountlyPush.displayMessage(getApplicationContext(), message, R.drawable.notification_icon, null); if (result == null) { Log.i(TAG, "Message wasn't sent from Countly server, so it cannot be handled by Countly SDK"); } else if (result) { Log.i(TAG, "Message was handled by Countly SDK"); } else { <START> Log.i(TAG, "Message wasn't handled by Countly SDK because API level is too low for Notification support or because currentActivity is null (not enough lifecycle method calls)"); <END> } }</code><technical_language>I alle Log.d</technical_language>

Target:
public void onMessageReceived(RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); Log.d(TAG, "got new message: " + remoteMessage.getData()); CountlyPush.Message message = CountlyPush.decodeMessage(remoteMessage.getData()); Boolean result = CountlyPush.displayMessage(getApplicationContext(), message, R.drawable.notification_icon, null); if (result == null) { Log.d(TAG, "Message wasn't sent from Countly server, so it cannot be handled by Countly SDK"); } else if (result) { Log.d(TAG, "Message was handled by Countly SDK"); } else { Log.d(TAG, "Message wasn't handled by Countly SDK because API level is too low for Notification support or because currentActivity is null (not enough lifecycle method calls)"); } }
Source:
<code>public int compareTo(ItemProperty<?, ?> o) { if (o instanceof HarvestingProperty) { HarvestingProperty property = (HarvestingProperty) o; Set<BlockType> set = Sets.newHashSet(property.getValue()); for (BlockType harvest : this.getValue()) { if (set.contains(harvest)) { set.remove(harvest); } else { return 1; } } return set.size() > 0 ? -set.size() : 0; } <START> return 1; <END> }</code><technical_language>violating contract of Comparable here. default a comparison of classname</technical_language>

Target:
public int compareTo(ItemProperty<?, ?> o) { if (o instanceof HarvestingProperty) { HarvestingProperty property = (HarvestingProperty) o; Set<BlockType> set = Sets.newHashSet(property.getValue()); for (BlockType harvest : this.getValue()) { if (set.contains(harvest)) { set.remove(harvest); } else { return 1; } } return set.size() > 0 ? -set.size() : 0; } return this.getClass().getName().compareTo(o.getClass().getName()); }
Source:
<code>public CompletableFuture<Void> createConfigMap(KubernetesConfigMap configMap) { return CompletableFuture.runAsync( () -> { if (!getConfigMap(configMap.getName()).isPresent()) { this.internalClient.configMaps().create(configMap.getInternalResource()); } }, <START> kubeClientExecutorService); <END> }</code><technical_language>related this PR, I replace kubeClientExecutorService AbstractResourceManagerDriver#ioExecutor</technical_language>

Target:
public CompletableFuture<Void> createConfigMap(KubernetesConfigMap configMap) { final String configMapName = configMap.getName(); return CompletableFuture.runAsync( () -> this.internalClient.configMaps().inNamespace(namespace).create(configMap.getInternalResource()), kubeClientExecutorService) .exceptionally( throwable -> { throw new CompletionException( new KubernetesException("Failed to create ConfigMap " + configMapName, throwable)); }); }
Source:
<code>public void describeProcessGetRequestWorksWithCORS() throws IOException { String url = wpsUrl + "?Service=WPS&Request=DescribeProcess&Version=1.0.0&Identifier=" + "org.n52.wps.server.algorithm.test.EchoProcess"; method = new GetMethod(url); method.addRequestHeader("Origin", randomOrigin); int code = client.executeMethod(method); assertThat(code, is(equalTo(200))); Header acaoHeader = method.getResponseHeader("Access-Control-Allow-Origin"); <START> assertThat(acaoHeader.toString(), containsString(randomOrigin.toString())); <END> }</code><technical_language>If CORS is activated, this throws a NPE. I recommend add assertNotNull statement</technical_language>

Target:
public void describeProcessGetRequestWorksWithCORS() throws IOException { String url = wpsUrl + "?Service=WPS&Request=DescribeProcess&Version=1.0.0&Identifier=" + "org.n52.wps.server.algorithm.test.EchoProcess"; method = new GetMethod(url); method.addRequestHeader("Origin", randomOrigin); int code = client.executeMethod(method); assertThat(code, is(equalTo(200))); Header acaoHeader = method.getResponseHeader("Access-Control-Allow-Origin"); assertNotNull(acaoHeader); assertThat(acaoHeader.toString(), containsString(randomOrigin.toString())); }
Source:
<code>private Journal getParentJournal(Volume volume) { List<Journal> journals = hibernateTemplate.execute(session -> { Query query = session.createQuery("from Journal where :volume in elements(volumes)"); query.setParameter("volume", volume); return (List<Journal>) query.list(); }); <START> return journals.get(0); END> }</code><technical_language>Multiple parent journals possible. uniqueResult</technical_language>

Target:
private Journal getParentJournal(Volume volume) { return hibernateTemplate.execute(session -> { Query query = session.createQuery("from Journal where :volume in elements(volumes)"); query.setParameter("volume", volume); return (Journal) query.uniqueResult(); }); }
Source:
<code>private void doTestAutoInstallation(String id, String fullversion) throws Exception { <START> Assume.assumeTrue(Boolean.getBoolean("jenkins.testJDKInstaller")); <END> retrieveUpdateCenterData(); JDKInstaller installer = new JDKInstaller(id, true); JDK jdk = new JDK("test", tmp.getRoot().getAbsolutePath(), Arrays.asList( new InstallSourceProperty(Arrays.<ToolInstaller>asList(installer)))); j.jenkins.getJDKs().add(jdk); FreeStyleProject p = j.createFreeStyleProject(); p.setJDK(jdk); p.getBuildersList().add(new Shell("java -fullversion\necho $JAVA_HOME")); FreeStyleBuild b = j.buildAndAssertSuccess(p); @SuppressWarnings("deprecation") String log = b.getLog(); System.out.println(log); assertTrue(log.contains(fullversion)); assertTrue(log.contains(tmp.getRoot().getAbsolutePath())); }</code><technical_language>Place string description in assume</technical_language>

Target:
private void doTestAutoInstallation(String id, String fullversion) throws Exception { Assume.assumeTrue("this is a really time consuming test, so only run it when we really want", Boolean.getBoolean("jenkins.testJDKInstaller")); retrieveUpdateCenterData(); JDKInstaller installer = new JDKInstaller(id, true); JDK jdk = new JDK("test", tmp.getRoot().getAbsolutePath(), Arrays.asList( new InstallSourceProperty(Arrays.<ToolInstaller>asList(installer)))); j.jenkins.getJDKs().add(jdk); FreeStyleProject p = j.createFreeStyleProject(); p.setJDK(jdk); p.getBuildersList().add(new Shell("java -fullversion\necho $JAVA_HOME")); FreeStyleBuild b = j.buildAndAssertSuccess(p); @SuppressWarnings("deprecation") String log = b.getLog(); System.out.println(log); assertTrue(log.contains(fullversion)); assertTrue(log.contains(tmp.getRoot().getAbsolutePath())); }
Source:
<code>private OrcBatchRecordReader createRecordReader(boolean zstdJniDecompressionEnabled) throws IOException { OrcDataSource dataSource = new FileOrcDataSource(orcFile, new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), true); OrcReader orcReader = new OrcReader( dataSource, format.getOrcEncoding(), new StorageOrcFileTailSource(), new StorageStripeMetadataSource(), OrcReaderTestingUtils.createTestingReaderOptions(zstdJniDecompressionEnabled), <START> new HiveFileContext(false, Optional.empty())); <END> return orcReader.createBatchRecordReader( ImmutableMap.of(0, type), OrcPredicate.TRUE, UTC, newSimpleAggregatedMemoryContext(), INITIAL_BATCH_SIZE); }</code><technical_language>other places</technical_language>

Target:
private OrcBatchRecordReader createRecordReader(boolean zstdJniDecompressionEnabled) throws IOException { OrcDataSource dataSource = new FileOrcDataSource(orcFile, new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), true); OrcReader orcReader = new OrcReader( dataSource, format.getOrcEncoding(), new StorageOrcFileTailSource(), new StorageStripeMetadataSource(), OrcReaderTestingUtils.createTestingReaderOptions(zstdJniDecompressionEnabled), DEFAULT_HIVE_FILE_CONTEXT); return orcReader.createBatchRecordReader( ImmutableMap.of(0, type), OrcPredicate.TRUE, UTC, newSimpleAggregatedMemoryContext(), INITIAL_BATCH_SIZE); }
Source:
<code>public HashAggregationOperatorFactory( int operatorId, PlanNodeId planNodeId, List<? extends Type> groupByTypes, List<Integer> groupByChannels, List<Integer> globalAggregationGroupIds, Step step, List<AccumulatorFactory> accumulatorFactories, Optional<Integer> hashChannel, Optional<Integer> groupIdChannel, int expectedGroups, DataSize maxPartialMemory, JoinCompiler joinCompiler) { this(operatorId, planNodeId, groupByTypes, groupByChannels, globalAggregationGroupIds, step, false, accumulatorFactories, hashChannel, groupIdChannel, expectedGroups, maxPartialMemory, false, new DataSize(0, MEGABYTE), new DataSize(0, MEGABYTE), <START> (types, spillContext, memoryContextSupplier) -> { <END> throw new UnsupportedOperationException(); }, joinCompiler); }</code><technical_language>appears this change is unintended</technical_language>

Target:
public HashAggregationOperatorFactory( int operatorId, PlanNodeId planNodeId, List<? extends Type> groupByTypes, List<Integer> groupByChannels, List<Integer> globalAggregationGroupIds, Step step, List<AccumulatorFactory> accumulatorFactories, Optional<Integer> hashChannel, Optional<Integer> groupIdChannel, int expectedGroups, DataSize maxPartialMemory, JoinCompiler joinCompiler) { this(operatorId, planNodeId, groupByTypes, groupByChannels, globalAggregationGroupIds, step, false, accumulatorFactories, hashChannel, groupIdChannel, expectedGroups, maxPartialMemory, false, new DataSize(0, MEGABYTE), new DataSize(0, MEGABYTE), (types, spillContext, memoryContext) -> { throw new UnsupportedOperationException(); }, joinCompiler); }
Source:
<code>public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View layout = inflater.inflate(R.layout.signup_magic_link, container, false); mTryAgainButton = layout.findViewById(R.id.signup_magic_link_button); <START> mTryAgainButton.setOnClickListener(new View.OnClickListener() { <END> @Override public void onClick(View view) { if (mLoginListener != null) { mLoginListener.openEmailClient(); } } }); if (savedInstanceState == null) { sendMagicLinkEmail(); } return layout; }</code><technical_language>super clear, wdyt renaming mTryAgainButton match new functionality</technical_language>

Target:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View layout = inflater.inflate(R.layout.signup_magic_link, container, false); mOpenMailButton = layout.findViewById(R.id.signup_magic_link_button); mOpenMailButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mLoginListener != null) { mLoginListener.openEmailClient(); } } }); if (savedInstanceState == null) { sendMagicLinkEmail(); } return layout; }
Source:
<code>public static boolean setDiskAlias(BaseDisk disk, VM vm) { if (disk == null) { log.errorFormat("Disk object is null"); return false; } String vmName = ""; int count = 1; if (vm != null) { <START> vmName = vm.getvm_name(); <END> count = vm.getDiskMapCount() + 1; } disk.setDiskAlias(getSuggestedDiskAlias(disk, vmName, count)); return true; }</code><technical_language>If vm is null, vmName remains "" - disk alias correct? is a point setting a disk alias if vm is null</technical_language>

Target:
public static boolean setDiskAlias(BaseDisk disk, VM vm) { if (disk == null) { log.errorFormat("Disk object is null"); return false; } String vmName = ""; int count = 1; if (vm != null) { vmName = vm.getVmName(); count = vm.getDiskMapCount() + 1; } disk.setDiskAlias(getSuggestedDiskAlias(disk, vmName, count)); return true; }
Source:
<code>public boolean adjustSelection(final SelectionExtension direction, final boolean isShiftKeyDown) { final boolean hasSelectionChanged = super.adjustSelection(direction, isShiftKeyDown); if (hasSelectionChanged) { if (getModel().getSelectedCells().size() > 0) { final GridData.SelectedCell selectedCell = getModel().getSelectedCells().get(0); doAfterSelectionChange(selectedCell.getRowIndex(), ColumnIndexUtilities.findUiColumnIndex(getModel().getColumns(), selectedCell.getColumnIndex())); } <START> if (getModel().getSelectedHeaderCells().size() > 0) { <END> final GridData.SelectedCell selectedHeraderCell = getModel().getSelectedHeaderCells().get(0); doAfterHeaderSelectionChange(selectedHeraderCell.getRowIndex(), ColumnIndexUtilities.findUiColumnIndex(getModel().getColumns(), selectedHeraderCell.getColumnIndex())); } } return hasSelectionChanged; }</code><technical_language>Is ..} else if(getModel().getSelectedHeaderCells().size() > 0) {... better</technical_language>

Target:
public boolean adjustSelection(final SelectionExtension direction, final boolean isShiftKeyDown) { final boolean isSelectionChanged = super.adjustSelection(direction, isShiftKeyDown); if (isSelectionChanged) { if (getModel().getSelectedCells().size() > 0) { final GridData.SelectedCell selectedCell = getModel().getSelectedCells().get(0); doAfterSelectionChange(selectedCell.getRowIndex(), ColumnIndexUtilities.findUiColumnIndex(getModel().getColumns(), selectedCell.getColumnIndex())); } else if (getModel().getSelectedHeaderCells().size() > 0) { final GridData.SelectedCell selectedHeraderCell = getModel().getSelectedHeaderCells().get(0); doAfterHeaderSelectionChange(selectedHeraderCell.getRowIndex(), ColumnIndexUtilities.findUiColumnIndex(getModel().getColumns(), selectedHeraderCell.getColumnIndex())); } } return isSelectionChanged; }
Source:
<code><START> public FetchCommand setRemote(String remote) { <END> this.remote = remote; return this; }</code><technical_language>Missing checkCallable()</technical_language>

Target:
public FetchCommand setRemote(String remote) { checkCallable(); this.remote = remote; return this; }
Source:
<code>private Runner createRunner() { <START> return new Runner(glueSupplier.get(), eventBus, backendSupplier.get(), runtimeOptions); <END> }</code><technical_language>is new test cucumber.runtime.junit.CucumberTest#cucumber_can_run_pickles_in_parallel is failing. I understand problem moment - this another day this I I reckon this do it</technical_language>

Target:
private Runner createRunner() { return new Runner(glueSupplier.get(), new TestCaseEventBus(eventBus), backendSupplier.get(), runtimeOptions); }
Source:
<code>private void resetCache() { if (cachedMessageConsumer != null) { try { cachedMessageConsumer.close(); } catch (JMSException e) { } cachedMessageConsumer = null; } if (cachedMessageProducer != null) { try { cachedMessageProducer.close(); <START> } catch (JMSException e) { <END> } cachedMessageProducer = null; } if (cachedSession != null) { try { cachedSession.close(); } catch (JMSException e) { } cachedSession = null; } if (cachedConnection != null) { try { cachedConnection.close(); } catch (JMSException e) { } cachedConnection = null; } }</code><technical_language>here. Bad practice. caller know</technical_language>

Target:
private void resetCache() throws JMSException { if (cachedMessageConsumer != null) { cachedMessageConsumer.close(); cachedMessageConsumer = null; } if (cachedMessageProducer != null) { cachedMessageProducer.close(); cachedMessageProducer = null; } if (cachedSession != null) { cachedSession.close(); cachedSession = null; } if (cachedConnection != null) { cachedConnection.close(); cachedConnection = null; } }
Source:
<code>private String getTargetWithCheckoutRemoteTrackingDialog() { final String[] dialogResult = new String[1]; PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { public void run() { String[] buttons = new String[] { UIText.BranchOperationUI_CheckoutRemoteTrackingAsLocal, UIText.BranchOperationUI_CheckoutRemoteTrackingCommit, IDialogConstants.CANCEL_LABEL }; MessageDialog questionDialog = new MessageDialog( getShell(), UIText.BranchOperationUI_CheckoutRemoteTrackingTitle, null, UIText.BranchOperationUI_CheckoutRemoteTrackingQuestion, MessageDialog.QUESTION, buttons, 0); int result = questionDialog.open(); if (result == 0) { CreateBranchWizard wizard = new CreateBranchWizard(repository, target); WizardDialog createBranchDialog = new WizardDialog(getShell(), wizard); createBranchDialog.open(); return; } else if (result == 1) { dialogResult[0] = target; return; } else { return; <START> } <END> } }); return dialogResult[0]; }</code><technical_language>Instead of additional levels of indentation, prefer if body of run() a call a new method (e.g. getTargetWithDialogInUI). called method a normal return instead of write array. for other places</technical_language>

Target:
private String getTargetWithCheckoutRemoteTrackingDialog() { final String[] dialogResult = new String[1]; PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { public void run() { dialogResult[0] = getTargetWithCheckoutRemoteTrackingDialogInUI(); } }); return dialogResult[0]; }
Source:
<code>public void shutdown() { this.containerModel.getTasks().forEach((taskName, taskModel) -> getNonSideInputStores(taskName).forEach((storeName, store) -> store.stop()) ); if (sideInputsFlushFuture != null) { sideInputsFlushFuture.cancel(false); } sideInputsFlushExecutor.shutdown(); <START> this.shutDownSideInputRead = true; <END> if (sideInputSystemConsumers != null) { this.sideInputSystemConsumers.stop(); } this.sideInputStorageManagers.values().stream().collect(Collectors.toSet()). forEach(sideInputStorageManager -> sideInputStorageManager.stop()); LOG.info("Shutdown complete"); }</code><technical_language>move this commit processed stop processing prior calling flush. executor perform side input restoration helps gracefully shutdown flush offsets</technical_language>

Target:
public void shutdown() { this.containerModel.getTasks().forEach((taskName, taskModel) -> getNonSideInputStores(taskName).forEach((storeName, store) -> store.stop()) ); if (sideInputsPresent()) { this.shutDownSideInputRead = true; this.sideInputSystemConsumers.stop(); sideInputsFlushFuture.cancel(false); sideInputsFlushExecutor.shutdown(); try { sideInputsFlushExecutor.awaitTermination(SIDE_INPUT_FLUSH_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new SamzaException("Exception while shutting down side inputs", e); } this.getSideInputStorageManagers().forEach(sideInputStorageManager -> sideInputStorageManager.stop()); } LOG.info("Shutdown complete"); }
Source:
<code>public Map<K, ValueHolder<V>> bulkComputeIfAbsent(final Set<? extends K> keys, final Function<Iterable<? extends K>, Iterable<? extends Map.Entry<? extends K, ? extends V>>> mappingFunction) throws StoreAccessException { if(mappingFunction instanceof Ehcache.GetAllFunction) { Map<K, ValueHolder<V>> map = new HashMap<K, ValueHolder<V>>(); for (K key : keys) { <START> ValueHolder<V> value; <END> try { value = getInternal(key); } catch (TimeoutException e) { value = null; } ValueHolder<V> holder = null; if(value != null) { holder = value; } map.put(key, holder); } return map; } else { throw new UnsupportedOperationException("This compute method is not yet capable of handling generic computation functions"); } }</code><technical_language>Code formatting</technical_language>

Target:
public Map<K, ValueHolder<V>> bulkComputeIfAbsent(final Set<? extends K> keys, final Function<Iterable<? extends K>, Iterable<? extends Map.Entry<? extends K, ? extends V>>> mappingFunction) throws StoreAccessException { if(mappingFunction instanceof Ehcache.GetAllFunction) { Map<K, ValueHolder<V>> map = new HashMap<K, ValueHolder<V>>(); for (K key : keys) { ValueHolder<V> value; try { value = getInternal(key); } catch (TimeoutException e) { value = null; } ValueHolder<V> holder = (value != null) ? value : null; map.put(key, holder); } return map; } else { throw new UnsupportedOperationException("This compute method is not yet capable of handling generic computation functions"); } }
Source:
<code>public void fillContextMenu(IMenuManager menu) { ICommonViewerSite site = actionSite.getViewSite(); IStructuredSelection selection = null; if (site instanceof ICommonViewerWorkbenchSite) { ICommonViewerWorkbenchSite wsSite = (ICommonViewerWorkbenchSite) site; selection = (IStructuredSelection) wsSite.getSelectionProvider() .getSelection(); } IContributionItem quick = menu.find("org.eclipse.ui.navigate.showInQuickMenu"); <START> if( quick != null && selection != null && selection.toArray().length == 1 ) { <END> if( selection.getFirstElement() instanceof IServer ) { IServer server = (IServer)selection.getFirstElement(); if( acceptsServer(server) ) { if( menu instanceof MenuManager ) { ((MenuManager)quick).add(showInDockerViewAction); ((MenuManager)quick).add(showInOpenshiftViewAction); } } } } }</code><technical_language>selection.size() == 1</technical_language>

Target:
public void fillContextMenu(IMenuManager menu) { ICommonViewerSite site = actionSite.getViewSite(); IStructuredSelection selection = null; if (site instanceof ICommonViewerWorkbenchSite) { ICommonViewerWorkbenchSite wsSite = (ICommonViewerWorkbenchSite) site; selection = (IStructuredSelection) wsSite.getSelectionProvider() .getSelection(); } IContributionItem quick = menu.find("org.eclipse.ui.navigate.showInQuickMenu"); if( quick != null && selection != null && selection.size() == 1 ) { if( selection.getFirstElement() instanceof IServer ) { IServer server = (IServer)selection.getFirstElement(); if( acceptsServer(server) ) { if( menu instanceof MenuManager ) { ((MenuManager)quick).add(showInDockerViewAction); ((MenuManager)quick).add(showInOpenshiftViewAction); } } } } }
Source:
<code>private boolean shouldUsePreviousAssignment() { if (previousAssignmentIsValid()) { final int previousAssignmentBalanceFactor = <START> computeBalanceFactor(clientStates.values(), statefulTasks, ClientState::prevActiveTasks); <END> return previousAssignmentBalanceFactor <= configs.balanceFactor; } else { return false; } }</code><technical_language>Q: do consider stateful tasks in computeBalanceFactor()</technical_language>

Target:
private boolean shouldUsePreviousAssignment() { if (previousAssignmentIsValid()) { final int previousAssignmentBalanceFactor = computeBalanceFactor(clientStates.values(), statefulTasks); return previousAssignmentBalanceFactor <= configs.balanceFactor; } else { return false; } }
Source:
<code>public void findById() throws Exception { <START> Object operatorID = repository.create(new NewOperator("name", OperatorState.ACTIVE, "description", "domainName", "friendlyName", "emergencyNumber")); <END> Operator got = repository.findById(new ID(operatorID)).get(); Operator want = new Operator(new ID(operatorID), "name", OperatorState.ACTIVE, "description", "domainName", "friendlyName", "emergencyNumber"); assertThat(got, deepEquals(want)); }</code><technical_language>simply id..</technical_language>

Target:
public void findById() throws Exception { Object id = repository.create(new NewOperator("name", OperatorState.ACTIVE, "description", "domainName", "friendlyName", "emergencyNumber")); Operator got = repository.findById(new ID(id)).get(); Operator want = new Operator(new ID(id), "name", OperatorState.ACTIVE, "description", "domainName", "friendlyName", "emergencyNumber"); assertThat(got, deepEquals(want)); }
Source:
<code>public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { Executable declaringExecutable = parameterContext.getParameter().getDeclaringExecutable(); Method testMethod = extensionContext.getTestMethod().orElse(null); return declaringExecutable.equals(testMethod) <START> && ((parameterContext.getIndex() < arguments.length || isAggregate(parameterContext.getParameter()))); <END> }</code><technical_language>Please remove extra pair of parentheses</technical_language>

Target:
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { Executable declaringExecutable = parameterContext.getParameter().getDeclaringExecutable(); Method testMethod = extensionContext.getTestMethod().orElse(null); return declaringExecutable.equals(testMethod) && (parameterContext.getIndex() < arguments.length || isAggregate(parameterContext.getParameter())); }
Source:
<code>protected void update(final Map<String, Object> attributes) { try { final String id = (String) attributes.get(COUCH_ID); <START> final InputStream oldDocStream = couchDbConnector.getAsStream(id); <END> final JsonNode oldDoc = objectMapper.readTree(oldDocStream); final String rev = oldDoc.get("_rev").asText(); attributes.put("_rev", rev); couchDbConnector.update(attributes); logger.debug("Updating id: with attributes: {}", id, attributes); } catch (DocumentNotFoundException e) { couchDbConnector.create(attributes); } catch (IOException e) { logger.error("", e); } }</code><technical_language>is wrong indentation :) is standard in other code pac4j follow this... @leleuj add .editorconfig file in pac4j repository (like I in jax-rs-pac4j dropwizard-pac4j normally)</technical_language>

Target:
protected void update(final Map<String, Object> attributes) { try { final String id = (String) attributes.get(COUCH_ID); final InputStream oldDocStream = couchDbConnector.getAsStream(id); final JsonNode oldDoc = objectMapper.readTree(oldDocStream); final String rev = oldDoc.get("_rev").asText(); attributes.put("_rev", rev); couchDbConnector.update(attributes); logger.debug("Updating id: with attributes: {}", id, attributes); } catch (DocumentNotFoundException e) { couchDbConnector.create(attributes); } catch (IOException e) { logger.error("Unexpected IO CouchDB Exception", e); } }
Source:
<code>public static void cancel(Channel channel, String consumerTag) { try { channel.basicCancel(consumerTag); } catch (AlreadyClosedException e) { if (logger.isTraceEnabled()) { logger.trace(channel + " is already closed", e); } } catch (Exception e) { if (logger.isDebugEnabled()) { <START> logger.debug("Error performing 'basicCancel'", e); <END> } } }</code><technical_language>need a wrapping if - is redundant reason of a constant for a message</technical_language>

Target:
public static void cancel(Channel channel, String consumerTag) { try { channel.basicCancel(consumerTag); } catch (AlreadyClosedException e) { if (LOGGER.isTraceEnabled()) { LOGGER.trace(channel + " is already closed", e); } } catch (Exception e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Error performing 'basicCancel' on " + channel, e); } } }
Source:
<code>private static KeyStore tryLoadKeystore(final Supplier<Provider[]> providers, final String providerName, InputStream is, char[] password, String... types) { for (String type : types) { log.debug("Searching provider for: " + type); Provider provider = findProvider(providers, providerName, KeyStore.class, type); if (provider == null) { log.debug("Provider not found"); <START> return null; <END> } log.debug("Provider found: " + provider.getName()); try { KeyStore keystore = KeyStore.getInstance(type, provider); is.reset(); keystore.load(is, password); return keystore; } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException e) { continue; } } return null; }</code><technical_language>in case if I types= {BCFKS, PKCS12} I dont fips bouncy castle registered. Method BCFKS return null. dont try PKCS12</technical_language>

Target:
private static KeyStore tryLoadKeystore(final Supplier<Provider[]> providers, final String providerName, InputStream is, char[] password, String... types) { for (String type : types) { try { log.debug("Searching provider for: " + type); Provider provider = findProvider(providers, providerName, KeyStore.class, type); if (provider == null) { log.debug("Provider not found"); continue; } log.debug("Provider found: " + provider.getName()); KeyStore keystore = KeyStore.getInstance(type, provider); is.reset(); keystore.load(is, password); return keystore; } catch (Exception e) { log.debug("KeyStore is not of type " + type); continue; } } return null; }
Source:
<code>private Handler addDecorators(Handler handler, Class<?> sqlObjectType, Method method) { List<Class<? extends Annotation>> annotationTypes = Stream.of(method.getAnnotations()) .map(Annotation::annotationType) .filter(type -> type.isAnnotationPresent(SqlMethodDecoratingAnnotation.class)) .collect(toList()); <START> DecoratorOrder order = method.getAnnotation(DecoratorOrder.class); <END> if (order != null) { annotationTypes.sort(createDecoratorComparator(order)); } List<HandlerDecorator> decorators = annotationTypes.stream() .map(type -> type.getAnnotation(SqlMethodDecoratingAnnotation.class)) .map(a -> buildDecorator(a.value())) .collect(toList()); for (HandlerDecorator decorator : decorators) { handler = decorator.decorateHandler(handler, sqlObjectType, method); } return handler; }</code><technical_language>this consider method.getDeclaringClass() potentially superinterfaces? If order, inconvenient do method</technical_language>

Target:
private Handler addDecorators(Handler handler, Class<?> sqlObjectType, Method method) { List<Class<? extends Annotation>> annotationTypes = Stream.of(method.getAnnotations()) .map(Annotation::annotationType) .filter(type -> type.isAnnotationPresent(SqlMethodDecoratingAnnotation.class)) .collect(toList()); Stream.of(method, sqlObjectType) .map(e -> e.getAnnotation(DecoratorOrder.class)) .filter(Objects::nonNull) .findFirst() .ifPresent(order -> { annotationTypes.sort(createDecoratorComparator(order).reversed()); }); List<HandlerDecorator> decorators = annotationTypes.stream() .map(type -> type.getAnnotation(SqlMethodDecoratingAnnotation.class)) .map(a -> buildDecorator(a.value())) .collect(toList()); for (HandlerDecorator decorator : decorators) { handler = decorator.decorateHandler(handler, sqlObjectType, method); } return handler; }
Source:
<code>public boolean unfreeze(ClientConnectionsEntry entry, FreezeReason freezeReason) { synchronized (entry) { if (!entry.isFreezed()) { return false; } if (freezeReason != FreezeReason.RECONNECT || entry.getFreezeReason() == FreezeReason.RECONNECT) { if (!entry.isIniting()) { entry.setIniting(true); entry.resetFirstFail(); <START> slaveConnectionPool.initConnections(entry).onComplete((r, ex) -> { <END> entry.setIniting(false); if (ex == null) { entry.setFreezeReason(null); } }); pubSubConnectionPool.initConnections(entry); return true; } } } return false; }</code><technical_language>please AsyncCountDownLatch here. handlers slaveConnectionPool, pubSubConnectionPool invoke countDown method in latch callback do rest logic</technical_language>

Target:
public boolean unfreeze(ClientConnectionsEntry entry, FreezeReason freezeReason) { synchronized (entry) { if (!entry.isFreezed()) { return false; } if (freezeReason != FreezeReason.RECONNECT || entry.getFreezeReason() == FreezeReason.RECONNECT) { if (!entry.isInitialized()) { entry.setInitialized(true); CountableListener<Void> listener = new CountableListener<Void>() { @Override protected void onSuccess(Void value) { entry.setFreezeReason(null); } }; listener.setCounter(2); BiConsumer<Void, Throwable> initCallBack = (r, ex) -> { if (ex == null) { listener.decCounter(); } }; entry.resetFirstFail(); slaveConnectionPool.initConnections(entry).onComplete(initCallBack); pubSubConnectionPool.initConnections(entry).onComplete(initCallBack); return true; } } } return false; }
Source:
<code>public String getLabel() { <START> return Iterables.getFirst(complexTypes, null).getLabel(); <END> }</code><technical_language>get a NPE if complexTypes is null here</technical_language>

Target:
public String getLabel() { TypeDefinition firstType = Iterables.getFirst(complexTypes, null); return firstType!=null ? firstType.getLabel() : null; }
Source:
<code>public void merge(List<FormStatus> forms) { <START> this.forms.addAll(forms.stream().filter(form -> !this.formsIndex.containsKey(form.getFormDefinition().getFormId())).collect(toList())); <END> refreshIndex(); }</code><technical_language>this.formsIndex formsIndex in refreshIndex</technical_language>

Target:
public void merge(List<FormStatus> forms) { this.forms.addAll(forms.stream().filter(form -> !formsIndex.containsKey(form.getFormDefinition().getFormId())).collect(toList())); rebuildIndex(); }
Source:
<code>protected ResolveMerger(Repository local, boolean inCore) { super(local); <START> SupportedAlgorithm diffAlg = local.getConfig().getEnum( <END> ConfigConstants.CONFIG_DIFF_SECTION, null, ConfigConstants.CONFIG_KEY_ALGORITHM, SupportedAlgorithm.histogram); mergeAlgorithm = new MergeAlgorithm(diffAlg.algorithm); commitNames = new String[] { "BASE", "OURS", "THEIRS" }; oi = getObjectInserter(); this.inCore = inCore; if (inCore) { dircache = DirCache.newInCore(); } }</code><technical_language>honor this variable in DiffFormatter</technical_language>

Target:
protected ResolveMerger(Repository local, boolean inCore) { super(local); SupportedAlgorithm diffAlg = local.getConfig().getEnum( ConfigConstants.CONFIG_DIFF_SECTION, null, ConfigConstants.CONFIG_KEY_ALGORITHM, SupportedAlgorithm.HISTOGRAM); mergeAlgorithm = new MergeAlgorithm(DiffAlgorithm.getAlgorithm(diffAlg)); commitNames = new String[] { "BASE", "OURS", "THEIRS" }; oi = getObjectInserter(); this.inCore = inCore; if (inCore) { dircache = DirCache.newInCore(); } }
Source:
<code>public Spec widgets() { try { return new Spec.Simple( <START> new JdkRequest(UriBuilder.fromUri(this.home).build()) <END> .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML) .header(HttpHeaders.AUTHORIZATION, this.token) .method(Request.GET) .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(XmlResponse.class) .xml() .xpath("/page/stand/widgets/text()") .get(0) ); } catch (IOException ex) { throw new IllegalStateException(ex); } }</code><technical_language>need UriBuilder</technical_language>

Target:
public Spec widgets() { try { return new Spec.Simple( new JdkRequest(this.home) .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML) .header(HttpHeaders.AUTHORIZATION, this.token) .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(XmlResponse.class) .xml() .xpath("/page/stand/widgets/text()") .get(0) ); } catch (IOException ex) { throw new IllegalStateException(ex); } }
Source:
<code>private void setMetacardId(Metacard metacard, String id) { <START> metacard.setAttribute(new AttributeImpl(Metacard.ID, id)); <END> }</code><technical_language>Core.ID</technical_language>

Target:
private void setMetacardId(Metacard metacard, String id) { metacard.setAttribute(new AttributeImpl(Core.ID, id)); }
Source:
<code>public Map<String, Set<DocumentReference>> saveXWikiDocCollection( Collection<XWikiDocument> xdocs) { Set<DocumentReference> savedSuccessfully = new HashSet<DocumentReference>(); Set<DocumentReference> saveFailed = new HashSet<DocumentReference>(); for (XWikiDocument xdoc : xdocs) { if(!xdoc.isNew() || "true".equals(getContext().getRequest().get("createIfNotExists"))) { try { if(getContext().getWiki().getRightService().hasAccessLevel("edit", <START> getContext().getUser(), getWebUtilsService().serializeRef( <END> xdoc.getDocumentReference()), getContext())) { getContext().getWiki().saveDocument(xdoc, "updateAndSaveDocFromRequest", getContext()); savedSuccessfully.add(xdoc.getDocumentReference()); } else { saveFailed.add(xdoc.getDocumentReference()); } } catch(XWikiException xwe) { LOGGER.error("Exception saving document {}.", xdoc, xwe); saveFailed.add(xdoc.getDocumentReference()); } } else { saveFailed.add(xdoc.getDocumentReference()); } } Map<String, Set<DocumentReference>> docs = new HashMap<String, Set<DocumentReference>>(); docs.put("successful", savedSuccessfully); docs.put("failed", saveFailed); return docs; }</code><technical_language>Please move rights checks script service api methods. Components additionally check for rights</technical_language>

Target:
public Map<String, Set<DocumentReference>> saveXWikiDocCollection( Collection<XWikiDocument> xdocs) { Set<DocumentReference> savedSuccessfully = new HashSet<DocumentReference>(); Set<DocumentReference> saveFailed = new HashSet<DocumentReference>(); for (XWikiDocument xdoc : xdocs) { if(notNewOrCreateAllowed(xdoc)) { try { getModelAccessFacade().saveDocument(xdoc, "updateAndSaveDocFromRequest"); savedSuccessfully.add(xdoc.getDocumentReference()); } catch(DocumentSaveException dse) { LOGGER.error("Exception saving document {}.", xdoc, dse); saveFailed.add(xdoc.getDocumentReference()); } } else { saveFailed.add(xdoc.getDocumentReference()); } } Map<String, Set<DocumentReference>> docs = new HashMap<String, Set<DocumentReference>>(); docs.put("successful", savedSuccessfully); docs.put("failed", saveFailed); return docs; }
Source:
<code>MasterRegistry(Configuration conf) throws IOException { this.hedgedReadFanOut = conf.getInt(MASTER_REGISTRY_HEDGED_REQS_FANOUT_KEY, MASTER_REGISTRY_HEDGED_REQS_FANOUT_DEFAULT); int rpcTimeoutMs = (int) Math.min(Integer.MAX_VALUE, <START> conf.getLong(HConstants.HBASE_RPC_TIMEOUT_KEY, HConstants.DEFAULT_HBASE_RPC_TIMEOUT)); <END> rpcClient = RpcClientFactory.createClient(conf, null); rpcControllerFactory = RpcControllerFactory.instantiate(conf); masterAddrs = parseMasterAddrs(conf); ImmutableList.Builder<ClientMetaService.Interface> builder = ImmutableList.builderWithExpectedSize(masterAddrs.size()); User user = User.getCurrent(); for (ServerName masterAddr : masterAddrs) { builder .add(ClientMetaService.newStub(rpcClient.createRpcChannel(masterAddr, user, rpcTimeoutMs))); } masterStubs = builder.build(); }</code><technical_language>Starting wonder, this get flagged in tests. I guess is some test hole token based auth.</technical_language>

Target:
MasterRegistry(Configuration conf) throws IOException { this.hedgedReadFanOut = Math.max(1, conf.getInt(MASTER_REGISTRY_HEDGED_REQS_FANOUT_KEY, MASTER_REGISTRY_HEDGED_REQS_FANOUT_DEFAULT)); int rpcTimeoutMs = (int) Math.min(Integer.MAX_VALUE, conf.getLong(HConstants.HBASE_RPC_TIMEOUT_KEY, HConstants.DEFAULT_HBASE_RPC_TIMEOUT)); rpcClient = RpcClientFactory.createClient(conf, null); rpcControllerFactory = RpcControllerFactory.instantiate(conf); Set<ServerName> masterAddrs = parseMasterAddrs(conf); ImmutableMap.Builder<ServerName, ClientMetaService.Interface> builder = ImmutableMap.builderWithExpectedSize(masterAddrs.size()); User user = User.getCurrent(); for (ServerName masterAddr : masterAddrs) { builder.put(masterAddr, ClientMetaService.newStub(rpcClient.createRpcChannel(masterAddr, user, rpcTimeoutMs))); } masterAddr2Stub = builder.build(); }
Source:
<code>public void testDeactivateNoneActiveDomainFails() { mockDomain(); <START> domain.setStatus(StorageDomainStatus.Maintenance); <END> ValidateTestUtils.runAndAssertValidateFailure(cmd, EngineMessage.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL2); }</code><technical_language>other statues? validate valid deactivation statuses (Active Unknown)? Arrays.asList(StorageDomainStatus.Active, StorageDomainStatus.Unknown).stream().forEach(status -> { domain.setStatus(status); ValidateTestUtils.runAndAssertValidateSuccess(cmd); });</technical_language>

Target:
public void testDeactivateNoneActiveDomainFails() { mockDomain(); EnumSet<StorageDomainStatus> invalidStatuses = EnumSet.allOf(StorageDomainStatus.class); invalidStatuses.remove(StorageDomainStatus.Active); invalidStatuses.stream().forEach(s -> { domain.setStatus(s); ValidateTestUtils.runAndAssertValidateFailure(cmd, EngineMessage.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL2); }); }
Source:
<code>public RuleResult validate(final PasswordData passwordData) { final RuleResult result = new RuleResult(true); for (Rule rule : passwordRules) { final RuleResult rr = rule.validate(passwordData); if (!rr.isValid()) { result.setValid(false); result.getDetails().addAll(rr.getDetails()); } <START> result.getMetadata().putAll(rr.getMetadata().getAll()); <END> } return result; }</code><technical_language>Do want accommodate merging here? I a case present rules produce key, in case implementation overwrite former. Merge semantics preferable. other hand "don't do that."</technical_language>

Target:
public RuleResult validate(final PasswordData passwordData) { final RuleResult result = new RuleResult(true); for (Rule rule : passwordRules) { final RuleResult rr = rule.validate(passwordData); if (!rr.isValid()) { result.setValid(false); result.getDetails().addAll(rr.getDetails()); } result.getMetadata().merge(rr.getMetadata()); } return result; }