auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static Ds3ApiSpec removeInternalRequestsFromSpec(final Ds3ApiSpec spec, final boolean generateInternal) { <START> if (generateInternal) { <END> return spec; } return new Ds3ApiSpec( removeSpectraInternalRequests(spec.getRequests()), spec.getTypes()); }</code><technical_language>add a log statement easier trace if do expect</technical_language>

Target:
public static Ds3ApiSpec removeInternalRequestsFromSpec(final Ds3ApiSpec spec, final boolean generateInternal) { if (generateInternal) { LOG.info("Generating Spectra Internal requests"); return spec; } LOG.info("Removing Spectra Internal requests from Ds3ApiSpec"); return new Ds3ApiSpec( removeSpectraInternalRequests(spec.getRequests()), spec.getTypes()); }
Source:
<code>public String getName() { <START> return "RecycleRefactoring"; <END> }</code><technical_language>this is displayed user "Android recycle" better</technical_language>

Target:
public String getName() { return "AndroidRecycleRefactoring"; }
Source:
<code>public void flushAndReleaseResources() { InfinispanDirectoryProvider directoryProvider = (InfinispanDirectoryProvider) getDirectoryProvider(); int activeDeleteTasks = directoryProvider.pendingDeleteTasks(); boolean wasInterrupted = false; while (activeDeleteTasks > 0) { try { <START> Thread.sleep(POLL_WAIT); <END> log.debugf("Waiting for pending delete tasks, remaining: %s", activeDeleteTasks); activeDeleteTasks = directoryProvider.pendingDeleteTasks(); } catch (InterruptedException e) { wasInterrupted = true; } } if (wasInterrupted) { Thread.currentThread().interrupt(); } log.debugf("Flushing directory provider"); super.flushAndReleaseResources(); }</code><technical_language>happen if a deadlocked delete task? If I read code correctly spinning forever? Is avoid this</technical_language>

Target:
public void flushAndReleaseResources() { InfinispanDirectoryProvider directoryProvider = (InfinispanDirectoryProvider) getDirectoryProvider(); int activeDeleteTasks = directoryProvider.pendingDeleteTasks(); boolean wasInterrupted = false; long endTime = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(POLL_WAIT); while (activeDeleteTasks > 0 && endTime - System.nanoTime() > 0) { try { Thread.sleep(10); log.debugf("Waiting for pending delete tasks, remaining: %s", activeDeleteTasks); activeDeleteTasks = directoryProvider.pendingDeleteTasks(); } catch (InterruptedException e) { wasInterrupted = true; } } if (wasInterrupted) { Thread.currentThread().interrupt(); } log.debugf("Flushing directory provider"); super.flushAndReleaseResources(); }
Source:
<code>public void validateEnums(Host host) { if (host.isSetPowerManagement()) { if (host.getPowerManagement().isSetPmProxies()) { for (PmProxy proxy : host.getPowerManagement().getPmProxies().getPmProxy()) { <START> validateEnum(PmProxyType.class, proxy.getPropietary(), true); <END> } } } }</code><technical_language>iiuc "propietary" is a string enum added is PmProxyType, adding <pm_proxy> validating here</technical_language>

Target:
public void validateEnums(Host host) { if (host.isSetPowerManagement()) { if (host.getPowerManagement().isSetPmProxies()) { for (PmProxy proxy : host.getPowerManagement().getPmProxies().getPmProxy()) { validateEnum(PmProxyType.class, proxy.getType(), true); } } } }
Source:
<code>public void setUp() throws Exception { this.adapter = new DateTimeAdapter(); this.dateTime = new DateTime(2015, 1, 1, 12, 0, DateTimeZone.UTC); <START> this.ValidDateString = "2015-01-01T12:00:00.000Z"; <END> }</code><technical_language>some tests a timezone</technical_language>

Target:
public void setUp() throws Exception { this.adapter = new DateTimeAdapter(); this.dateTime = new DateTime(2015, 1, 1, 12, 0, DateTimeZone.UTC); this.validDateString = "2015-01-01T12:00:00.000Z"; }
Source:
<code>public void sendLayerDeleted(String layerName) { <START> listeners.stream().forEachOrdered(listener->{ <END> listener.layerDeleted(layerName); }); }</code><technical_language>a listeners.forEach(listener -> layerDeleted(layerName)); time more compact, readable, faster (streams slow)</technical_language>

Target:
public void sendLayerDeleted(String layerName) { listeners.forEach(listener->{ listener.layerDeleted(layerName); }); }
Source:
<code>private void setupContent() { mPager = findViewById(R.id.postPager); mPostsPagerAdapter = new PostsPagerAdapter(PostListMainViewModelKt.getPOST_LIST_PAGES(), mSite, this, getSupportFragmentManager()); mPager.setAdapter(mPostsPagerAdapter); TabLayout tabLayout = findViewById(R.id.tabLayout); tabLayout.setupWithViewPager(mPager); <START> mPager.addOnPageChangeListener(new OnPageChangeListener() { <END> @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { mViewModel.onTabChanged(position); } @Override public void onPageScrollStateChanged(int state) { } }); mFab = findViewById(R.id.fab_button); mFab.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { mViewModel.newPost(); } }); }</code><technical_language>this adds a new listener, clear listeners adding new listener? I setupContent is called right now, a difference, hurt defensive a potential change. do think</technical_language>

Target:
private void setupContent() { mPager = findViewById(R.id.postPager); mPostsPagerAdapter = new PostsPagerAdapter(PostListMainViewModelKt.getPOST_LIST_PAGES(), mSite, getSupportFragmentManager()); mPager.setAdapter(mPostsPagerAdapter); TabLayout tabLayout = findViewById(R.id.tabLayout); tabLayout.setupWithViewPager(mPager); mPager.addOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { mViewModel.onTabChanged(position); } @Override public void onPageScrollStateChanged(int state) { } }); mFab = findViewById(R.id.fab_button); mFab.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { mViewModel.newPost(); } }); }
Source:
<code>public void processLeftData(final MistDataEvent input) { try { final WindowData<Tuple2<T, U>> windowData = (WindowData)input.getValue(); final Collection<T> firstInputList = new LinkedList<>(); final Collection<U> secondInputList = new LinkedList<>(); final Collection<Tuple2<T, U>> outputList = new LinkedList<>(); final Iterator<Tuple2<T, U>> inputIterator = windowData.getDataCollection().iterator(); while (inputIterator.hasNext()) { final Tuple2<T, U> tuple = inputIterator.next(); if (tuple.get(0) != null) { firstInputList.add((T)tuple.get(0)); } else { secondInputList.add((U)tuple.get(1)); } } final Iterator<T> firstInputIterator = firstInputList.iterator(); while (firstInputIterator.hasNext()) { final T firstInput = firstInputIterator.next(); final Iterator<U> secondInputIterator = secondInputList.iterator(); while (secondInputIterator.hasNext()) { final U secondInput = secondInputIterator.next(); if (joinBiPredicate.test(firstInput, secondInput)) { outputList.add(new Tuple2<>(firstInput, secondInput)); } } } final long windowStart = windowData.getStart(); final long windowSize = windowData.getEnd() - windowStart + 1; final WindowImpl<Tuple2<T, U>> window = new WindowImpl<>(windowStart, windowSize, outputList); <START> LOG.log(Level.FINE, "{0} joins input data {1} into window {2}", <END> new Object[]{getOperatorIdentifier(), input, window}); input.setValue(window); outputEmitter.emitData(input); } catch (final ClassCastException e) { throw e; } }</code><technical_language>This logging is related this PR, please remove all. If want add loggings, please create another issue</technical_language>

Target:
public void processLeftData(final MistDataEvent input) { try { final WindowData<Tuple2<T, U>> windowData = (WindowData)input.getValue(); final Collection<T> firstInputList = new LinkedList<>(); final Collection<U> secondInputList = new LinkedList<>(); final Collection<Tuple2<T, U>> outputList = new LinkedList<>(); final Iterator<Tuple2<T, U>> inputIterator = windowData.getDataCollection().iterator(); while (inputIterator.hasNext()) { final Tuple2<T, U> tuple = inputIterator.next(); if (tuple.get(0) != null) { firstInputList.add((T)tuple.get(0)); } else { secondInputList.add((U)tuple.get(1)); } } final Iterator<T> firstInputIterator = firstInputList.iterator(); while (firstInputIterator.hasNext()) { final T firstInput = firstInputIterator.next(); final Iterator<U> secondInputIterator = secondInputList.iterator(); while (secondInputIterator.hasNext()) { final U secondInput = secondInputIterator.next(); if (joinBiPredicate.test(firstInput, secondInput)) { outputList.add(new Tuple2<>(firstInput, secondInput)); } } } final long windowStart = windowData.getStart(); final long windowSize = windowData.getEnd() - windowStart + 1; final WindowImpl<Tuple2<T, U>> window = new WindowImpl<>(windowStart, windowSize, outputList); input.setValue(window); outputEmitter.emitData(input); } catch (final ClassCastException e) { throw e; } }
Source:
<code>public void testGetBulkInvalidTable() throws Exception { <START> queryStore.get(UUID.randomUUID().toString(), Arrays.asList("a", "b")); <END> }</code><technical_language>Check for equality of error code</technical_language>

Target:
public void testGetBulkInvalidTable() throws Exception { try { queryStore.getAll(UUID.randomUUID().toString(), Arrays.asList("a", "b")); } catch (QueryStoreException e) { assertEquals(QueryStoreException.ErrorCode.NO_SUCH_TABLE, e.getErrorCode()); throw e; } }
Source:
<code>public CorsConfiguration getCorsConfiguration(HttpServletRequest request) { String path = request.getPathInfo(); if (path.indexOf("/organizations/") > -1) { <START> int orgIdStartIndex = path.indexOf("/organizations/") + "/organizations/".length(); <END> String organizationId = path.substring(orgIdStartIndex, path.indexOf('/', orgIdStartIndex)); GraviteeCorsConfiguration corsConfiguration = corsConfigurationByOrganization.get(organizationId); if (corsConfiguration == null) { corsConfiguration = new GraviteeCorsConfiguration(parameterService, eventManager, organizationId); this.corsConfigurationByOrganization.put(organizationId, corsConfiguration); } return corsConfiguration; } return super.getCorsConfiguration(request); }</code><technical_language>define a const for "/organizations/" also, call time path.indexOf wdyt</technical_language>

Target:
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) { String organizationId = computeOrganizationId(request); if (organizationId != null) { GraviteeCorsConfiguration corsConfiguration = corsConfigurationByOrganization.get(organizationId); if (corsConfiguration == null) { corsConfiguration = new GraviteeCorsConfiguration(parameterService, eventManager, organizationId); this.corsConfigurationByOrganization.put(organizationId, corsConfiguration); } return corsConfiguration; } return super.getCorsConfiguration(request); }
Source:
<code>private static PrivateKey generatePrivateKey(PrivateKeyInfo privateKeyInfo) throws IOException, <START> InvalidKeySpecException, NoSuchAlgorithmException { <END> final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKeyInfo.getEncoded()); return tryGeneratePrivateKey(spec, "RSA", "EC"); }</code><technical_language>remove NoSuchAlgorithmException now</technical_language>

Target:
private static PrivateKey generatePrivateKey(PrivateKeyInfo privateKeyInfo) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException { final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKeyInfo.getEncoded()); final KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePrivate(spec); }
Source:
<code>public StatisticChange(final Statistic statistic, final Player player, final Type type, @Nullable final Long oldValue, @Nullable final Long newValue) { <START> this.statistic = checkNotNull(statistic, "Statistic cannot be null!"); <END> this.player = checkNotNull(player, "Player cannot be null!"); this.type = checkNotNull(type, "Type cannot be null!"); this.oldValue = Optional.fromNullable(oldValue); this.newValue = Optional.fromNullable(newValue); }</code><technical_language>mentioned, this checkNotNull(statistic, "statistic"), this throw a NullPointerException, null</technical_language>

Target:
public StatisticChange(final Statistic statistic, final Player player, final Type type, @Nullable final Long oldValue, @Nullable final Long newValue) { this.statistic = checkNotNull(statistic, "statistic"); this.player = checkNotNull(player, "player"); this.type = checkNotNull(type, "type"); this.oldValue = Optional.fromNullable(oldValue); this.newValue = Optional.fromNullable(newValue); }
Source:
<code>public BenchmarkSuiteConfig setSuite(String suite) { <START> if (suite != null) { this.suite = suite; } <END> return this; }</code><technical_language>This is unnecessary</technical_language>

Target:
public BenchmarkSuiteConfig setSuite(String suite) { this.suite = suite; return this; }
Source:
<code>public synchronized void start() { logger.debug("start Thread"); if (shutdown) { shutdown = false; if (schedduler2 == null || getManagerState() == ManagerStates.stopped) { <START> this.pollingRunnable = new PollingRunnable(); <END> schedduler2 = new Thread(pollingRunnable); schedduler2.start(); } sceneMan.start(); } if (sceneJobExecuter != null) { this.sceneJobExecuter.startExecuter(); } if (sensorJobExecuter != null) { this.sensorJobExecuter.startExecuter(); } }</code><technical_language>simply call scheduler.schedule(new PollingRunnable(), 0, POLLING_FREQUENCY)</technical_language>

Target:
public synchronized void start() { logger.debug("start pollingScheduler"); if (pollingScheduler == null || pollingScheduler.isCancelled()) { pollingScheduler = scheduler.scheduleAtFixedRate(new PollingRunnable(), 0, config.getPollingFrequency(), TimeUnit.MILLISECONDS); sceneMan.start(); } if (sceneJobExecutor != null) { this.sceneJobExecutor.startExecutor(); } if (sensorJobExecutor != null) { this.sensorJobExecutor.startExecutor(); } }
Source:
<code>public void testAddingNewTierWhileUpdating() { ResourcePools existing = new ResourcePoolsImpl(Collections.singletonMap((ResourceType) ResourceType.Core.HEAP, <START> (ResourcePool) new SizedResourcePoolImpl(ResourceType.Core.HEAP, 10L, EntryUnit.ENTRIES, false))); <END> ResourcePools toBeUpdated = new ResourcePoolsImpl(Collections.singletonMap((ResourceType) ResourceType.Core.DISK, (ResourcePool) new SizedResourcePoolImpl(ResourceType.Core.DISK, 10L, MemoryUnit.MB, false))); try { existing.validateAndMerge(toBeUpdated); fail(); } catch (IllegalArgumentException iae) { assertThat(iae.getMessage(), Matchers.is("Pools to be updated cannot contain previously undefined resources pools")); } }</code><technical_language>weird casts... explicit type parameter singletonMap method call</technical_language>

Target:
public void testAddingNewTierWhileUpdating() { ResourcePools existing = new ResourcePoolsImpl(Collections.<ResourceType<?>, ResourcePool>singletonMap( ResourceType.Core.HEAP, new SizedResourcePoolImpl<SizedResourcePool>(ResourceType.Core.HEAP, 10L, EntryUnit.ENTRIES, false))); ResourcePools toBeUpdated = new ResourcePoolsImpl(Collections.<ResourceType<?>, ResourcePool>singletonMap( ResourceType.Core.DISK, new SizedResourcePoolImpl<SizedResourcePool>(ResourceType.Core.DISK, 10L, MemoryUnit.MB, false))); try { existing.validateAndMerge(toBeUpdated); fail(); } catch (IllegalArgumentException iae) { assertThat(iae.getMessage(), Matchers.is("Pools to be updated cannot contain previously undefined resources pools")); } }
Source:
<code>public void closeIndexToCancelPersistorTest() throws StoreException, InterruptedException { state.index.close(); MockScheduledExecutorService mockScheduler = new MockScheduledExecutorService(1, false, 0, 100, TimeUnit.MILLISECONDS); mockScheduler.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); mockScheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); state.initIndex(mockScheduler); Thread.sleep(1); assertEquals("The number of scheduled persistor task should be 1 after initialization", 1, ((ThreadPoolExecutor) state.scheduler).getQueue().size()); state.index.close(); <START> Thread.sleep(150); <END> assertEquals("The number of scheduled persistor task should be 0 after index closed", 0, ((ThreadPoolExecutor) state.scheduler).getQueue().size()); }</code><technical_language>need sleep if persistor.write() call is moved cancel</technical_language>

Target:
public void closeIndexToCancelPersistorTest() throws StoreException, InterruptedException { long SCHEDULER_PERIOD_MS = 10; state.index.close(); ScheduledThreadPoolExecutor scheduler = (ScheduledThreadPoolExecutor) Utils.newScheduler(1, false); ScheduledThreadPoolExecutor mockScheduler = Mockito.spy(scheduler); AtomicReference<ScheduledFuture> persistorTask = new AtomicReference<>(); class MockPersistor implements Runnable { private CountDownLatch invokeCountDown; @Override public void run() { invokeCountDown.countDown(); } } MockPersistor mockPersistor = new MockPersistor(); mockPersistor.invokeCountDown = new CountDownLatch(1); doAnswer(invocation -> { persistorTask.set( mockScheduler.scheduleAtFixedRate(mockPersistor, 0, SCHEDULER_PERIOD_MS, TimeUnit.MILLISECONDS)); return persistorTask.get(); }).when(mockScheduler) .scheduleAtFixedRate(any(PersistentIndex.IndexPersistor.class), anyLong(), anyLong(), any(TimeUnit.SECONDS.getClass())); state.initIndex(mockScheduler); assertTrue("The persistor task wasn't invoked within the expected time", mockPersistor.invokeCountDown.await(2 * SCHEDULER_PERIOD_MS, TimeUnit.MILLISECONDS)); state.index.close(); mockPersistor.invokeCountDown = new CountDownLatch(1); assertTrue("The persistor task should be canceled after index closed", persistorTask.get().isCancelled()); assertFalse("The persistor task should not be invoked again", mockPersistor.invokeCountDown.await(2 * SCHEDULER_PERIOD_MS, TimeUnit.MILLISECONDS)); }
Source:
<code>public PlanWithProperties visitSpatialJoin(SpatialJoinNode node, HashComputationSet parentPreference) { PlanWithProperties left = planAndEnforce(node.getLeft(), new HashComputationSet(), true, new HashComputationSet()); PlanWithProperties right = planAndEnforce(node.getRight(), new HashComputationSet(), true, new HashComputationSet()); <START> checkState(left.getHashSymbols().isEmpty() && right.getHashSymbols().isEmpty()); <END> return new PlanWithProperties( replaceChildren(node, ImmutableList.of(left.getNode(), right.getNode())), ImmutableMap.of()); }</code><technical_language>s/checkState/verify/, add a message in case fails</technical_language>

Target:
public PlanWithProperties visitSpatialJoin(SpatialJoinNode node, HashComputationSet parentPreference) { PlanWithProperties left = planAndEnforce(node.getLeft(), new HashComputationSet(), true, new HashComputationSet()); PlanWithProperties right = planAndEnforce(node.getRight(), new HashComputationSet(), true, new HashComputationSet()); verify(left.getHashSymbols().isEmpty(), "probe side of the spatial join should not include hash symbols"); verify(right.getHashSymbols().isEmpty(), "build side of the spatial join should not include hash symbols"); return new PlanWithProperties( replaceChildren(node, ImmutableList.of(left.getNode(), right.getNode())), ImmutableMap.of()); }
Source:
<code>public void markAsFailed(final ReindexEntry idx, final String cause) throws DotDataException { reindexQueueFactory.markAsFailed(idx, UtilMethods.shortenString(cause, 300)); <START> new Thread( <END> () -> esReadOnlyMonitor.start(idx, cause) ).start(); }</code><technical_language>if create thread, DotConcurrentFactory is friend</technical_language>

Target:
public void markAsFailed(final ReindexEntry idx, final String cause) throws DotDataException { reindexQueueFactory.markAsFailed(idx, UtilMethods.shortenString(cause, 300)); DotConcurrentFactory.getInstance() .getSubmitter() .submit(() -> { final String message = "Reindex failed for :" + idx + " because " + cause; esReadOnlyMonitor.start(message); }); }
Source:
<code>public RoutingDataCache(String clusterName, Map<PropertyType, List<String>> sourceDataTypeMap) { super(clusterName); _sourceDataTypeMap = sourceDataTypeMap; _currentStateCache = new CurrentStateCache(clusterName); <START> _customizedViewCaches = new HashMap<>(); <END> for (String customizedStateType : sourceDataTypeMap.getOrDefault(PropertyType.CUSTOMIZEDVIEW, Collections.emptyList())) { _customizedViewCaches.put(customizedStateType, new CustomizedViewCache(clusterName, customizedStateType)); } _targetExternalViewCache = new TargetExternalViewCache(clusterName); requireFullRefresh(); }</code><technical_language>a fix, I want suggest try lamda. convenient simple here</technical_language>

Target:
public RoutingDataCache(String clusterName, Map<PropertyType, List<String>> sourceDataTypeMap) { super(clusterName); _sourceDataTypeMap = sourceDataTypeMap; _currentStateCache = new CurrentStateCache(clusterName); _customizedViewCaches = new HashMap<>(); sourceDataTypeMap.getOrDefault(PropertyType.CUSTOMIZEDVIEW, Collections.emptyList()) .forEach(customizedStateType -> _customizedViewCaches.put(customizedStateType, new CustomizedViewCache(clusterName, customizedStateType))); _targetExternalViewCache = new TargetExternalViewCache(clusterName); requireFullRefresh(); }
Source:
<code>private QuorumPeer waitForQuorumPeer(MainThread mainThread, int timeout) { long start = Time.currentElapsedTime(); while (true) { QuorumPeer quorumPeer = mainThread.getQuorumPeer(); if (quorumPeer != null) { return quorumPeer; } if (Time.currentElapsedTime() > start + timeout) { LOG.error("Timed out while waiting for QuorumPeer"); break; } try { Thread.sleep(250); } catch (InterruptedException e) { } } <START> throw new NullPointerException(); <END> }</code><technical_language>a exception</technical_language>

Target:
private QuorumPeer waitForQuorumPeer(MainThread mainThread, int timeout) throws TimeoutException { long start = Time.currentElapsedTime(); while (true) { QuorumPeer quorumPeer = mainThread.isAlive() ? mainThread.getQuorumPeer() : null; if (quorumPeer != null) { return quorumPeer; } if (Time.currentElapsedTime() > start + timeout) { LOG.error("Timed out while waiting for QuorumPeer"); throw new TimeoutException(); } try { Thread.sleep(250); } catch (InterruptedException e) { } } }
Source:
<code>public Set<Diff> getDirectMergeDependencies(Diff diff, boolean mergeRightToLeft) { <START> long startTime = System.currentTimeMillis(); <END> final Set<Diff> dependencies = new LinkedHashSet<Diff>(); if (mergeRightToLeft) { if (DifferenceSource.LEFT == diff.getSource()) { dependencies.addAll(diff.getImplies()); dependencies.addAll(diff.getRequiredBy()); } else { dependencies.addAll(diff.getImpliedBy()); dependencies.addAll(diff.getRequires()); } } else { if (DifferenceSource.LEFT == diff.getSource()) { dependencies.addAll(diff.getImpliedBy()); dependencies.addAll(diff.getRequires()); } else { dependencies.addAll(diff.getImplies()); dependencies.addAll(diff.getRequiredBy()); } } dependencies.addAll(diff.getRefinedBy()); if (diff.getEquivalence() != null) { final Diff masterEquivalence = findMasterEquivalence(diff, mergeRightToLeft); if (masterEquivalence != null && masterEquivalence != diff) { dependencies.add(masterEquivalence); } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("getDirectMergeDependencies(Diff, boolean) - " + dependencies.size() + " dependencies found in " + getTimeSpentInMethod(startTime) + LOG_TIME + diff.hashCode()); } return dependencies; }</code><technical_language>start</technical_language>

Target:
public Set<Diff> getDirectMergeDependencies(Diff diff, boolean mergeRightToLeft) { long start = System.currentTimeMillis(); final Set<Diff> dependencies = new LinkedHashSet<Diff>(); if (mergeRightToLeft) { if (DifferenceSource.LEFT == diff.getSource()) { dependencies.addAll(diff.getImplies()); dependencies.addAll(diff.getRequiredBy()); } else { dependencies.addAll(diff.getImpliedBy()); dependencies.addAll(diff.getRequires()); } } else { if (DifferenceSource.LEFT == diff.getSource()) { dependencies.addAll(diff.getImpliedBy()); dependencies.addAll(diff.getRequires()); } else { dependencies.addAll(diff.getImplies()); dependencies.addAll(diff.getRequiredBy()); } } dependencies.addAll(diff.getRefinedBy()); if (diff.getEquivalence() != null) { final Diff masterEquivalence = findMasterEquivalence(diff, mergeRightToLeft); if (masterEquivalence != null && masterEquivalence != diff) { dependencies.add(masterEquivalence); } } if (LOGGER.isDebugEnabled()) { Long duration = new Long(System.currentTimeMillis() - start); String log = String.format( "getDirectMergeDependencies(Diff, boolean) - %d dependencies found in %d ms for diff %d", new Integer(dependencies.size()), duration, new Integer(diff.hashCode())); LOGGER.debug(log); } return dependencies; }
Source:
<code>private Gson buildGsonWithUpdatePersonAdapter() { return new GsonBuilder() <START> .excludeFieldsWithoutExposeAnnotation() <END> .registerTypeAdapter(Person.class, new Person.PersonUpdateSerializer()) .create(); }</code><technical_language>I suppose do need this serializer</technical_language>

Target:
private Gson buildGsonWithUpdatePersonAdapter() { return new GsonBuilder() .registerTypeAdapter(Person.class, new Person.PersonUpdateSerializer()) .create(); }
Source:
<code>public Set<JpaEntry> getEntriesByRecipient(String username) { Validate.notEmpty(username, "Argument 'username' cannot be empty"); final String jpql = "SELECT e FROM JpaEntry e WHERE e.id = ANY (" <START> + "SELECT v FROM JpaEvent v WHERE v.username = :username))"; <END> TypedQuery<JpaEntry> query = entityManager.createQuery(jpql, JpaEntry.class); log.debug("Query getEntriesByRecipient={}", query.toString()); query.setParameter("username", username); List<JpaEntry> rslt = query.getResultList(); return new HashSet<JpaEntry>(rslt); }</code><technical_language>SELECT v.entry v.entry.id</technical_language>

Target:
public Set<JpaEntry> getEntriesByRecipient(String username) { Validate.notEmpty(username, "Argument 'username' cannot be empty"); final String jpql = "SELECT DISTINCT v.entry FROM JpaEvent v " + "WHERE v.username = :username"; TypedQuery<JpaEntry> query = entityManager.createQuery(jpql, JpaEntry.class); log.debug("Query getEntriesByRecipient={}", query.toString()); query.setParameter("username", username); List<JpaEntry> rslt = query.getResultList(); return new HashSet<JpaEntry>(rslt); }
Source:
<code>public void write(@Nonnull final Writer dataWriter) { <START> if (sexGenotypeDataList.size() == 0) { <END> throw new IllegalStateException("The sex genotype data collection is empty"); } boolean extended = true; if (sexGenotypeDataList.stream().filter(dat -> !dat.hasExtendedGenotypingInfo()).count() > 0) { extended = false; } Set<String> commonGenotypes = new HashSet<>(); if (extended) { commonGenotypes = new HashSet<>(sexGenotypeDataList.get(0).getSexGenotypesSet()); for (final SexGenotypeData dat : sexGenotypeDataList) { commonGenotypes = Sets.intersection(commonGenotypes, dat.getSexGenotypesSet()); } if (commonGenotypes.size() == 0) { extended = false; } } final TableColumnCollection columns; if (extended) { final List<String> columnNames = new ArrayList<>(); columnNames.addAll(SexGenotypeTableColumn.MANDATORY_SEX_GENOTYPE_COLUMNS.names()); columnNames.addAll(commonGenotypes); columns = new TableColumnCollection(columnNames); } else { columns = new TableColumnCollection(SexGenotypeTableColumn.MANDATORY_SEX_GENOTYPE_COLUMNS.names()); } try (final SexGenotypeTableWriter writer = new SexGenotypeTableWriter(dataWriter, columns)) { writer.writeAllRecords(sexGenotypeDataList); } catch (final IOException e) { throw new UserException.CouldNotCreateOutputFile("Could not write sex genotype data", e); } }</code><technical_language>change sexGenotypeDataList.isEmpty()</technical_language>

Target:
public void write(@Nonnull final Writer dataWriter) { if (sexGenotypeDataList.isEmpty()) { throw new IllegalStateException("The sex genotype data collection is empty"); } boolean extended = true; if (sexGenotypeDataList.stream().filter(dat -> !dat.hasExtendedGenotypingInfo()).count() > 0) { extended = false; } Set<String> commonGenotypes = new HashSet<>(); if (extended) { commonGenotypes = new HashSet<>(sexGenotypeDataList.get(0).getSexGenotypesSet()); for (final SexGenotypeData dat : sexGenotypeDataList) { commonGenotypes = Sets.intersection(commonGenotypes, dat.getSexGenotypesSet()); } if (commonGenotypes.isEmpty()) { extended = false; } } final TableColumnCollection columns; if (extended) { final List<String> columnNames = new ArrayList<>(); columnNames.addAll(SexGenotypeTableColumn.MANDATORY_SEX_GENOTYPE_COLUMNS.names()); columnNames.addAll(commonGenotypes); columns = new TableColumnCollection(columnNames); } else { columns = new TableColumnCollection(SexGenotypeTableColumn.MANDATORY_SEX_GENOTYPE_COLUMNS.names()); } try (final SexGenotypeTableWriter writer = new SexGenotypeTableWriter(dataWriter, columns)) { writer.writeAllRecords(sexGenotypeDataList); } catch (final IOException e) { throw new UserException.CouldNotCreateOutputFile("Could not write sex genotype data", e); } }
Source:
<code>public static CorruptionHealthReport corruptionHealthReportForHistory( List<CompletePaxosHistoryForNamespaceAndUseCase> history) { Map<NamespaceAndUseCase, CorruptionCheckViolation> namespaceAndUseCaseCorruptionCheckViolationMap = history.stream() .collect(Collectors.toMap( HistoryAnalyzer::extractNamespaceAndUseCase, HistoryAnalyzer::violatedCorruptionChecksForNamespaceAndUseCase)); <START> SetMultimap<CorruptionCheckViolation, NamespaceAndUseCase> entryEntrySetMultimap = KeyedStream.stream( <END> namespaceAndUseCaseCorruptionCheckViolationMap) .mapEntries((k, v) -> Maps.immutableEntry(v, k)) .filterKeys(CorruptionCheckViolation::raiseErrorAlert) .collectToSetMultimap(); return ImmutableCorruptionHealthReport.builder() .statusesToNamespaceAndUseCase(entryEntrySetMultimap) .build(); }</code><technical_language>name this based map does: namespacesExhibitingViolations this</technical_language>

Target:
public static CorruptionHealthReport corruptionHealthReportForHistory( List<CompletePaxosHistoryForNamespaceAndUseCase> history) { Map<NamespaceAndUseCase, CorruptionCheckViolation> namespaceAndUseCaseCorruptionCheckViolationMap = history.stream() .collect(Collectors.toMap( HistoryAnalyzer::extractNamespaceAndUseCase, HistoryAnalyzer::corruptionCheckViolationLevelForNamespaceAndUseCase)); SetMultimap<CorruptionCheckViolation, NamespaceAndUseCase> namespacesExhibitingViolations = KeyedStream.stream( namespaceAndUseCaseCorruptionCheckViolationMap) .mapEntries((k, v) -> Maps.immutableEntry(v, k)) .filterKeys(CorruptionCheckViolation::raiseErrorAlert) .collectToSetMultimap(); return ImmutableCorruptionHealthReport.builder() .violatingStatusesToNamespaceAndUseCase(namespacesExhibitingViolations) .build(); }
Source:
<code>public void update(final InputStream in, final String filePath, final int startLineIncl, final UpdateFileCallback fileCallback, final UpdateRecordCallback recordCallback) { GZIPInputStream gzis = null; InputStreamReader ir = null; BufferedReader br = null; int lineCount = 0; try { gzis = new GZIPInputStream(in); ir = new InputStreamReader(gzis, StandardCharsets.UTF_8); br = new BufferedReader(ir); List<Record> records = parser.parse(br); for (Record record : records) { lineCount++; if (lineCount >= startLineIncl) { <START> updateRecord(record, filePath, startLineIncl, recordCallback); <END> } } } catch (Throwable e) { } finally { try { if (br != null) { br.close(); } if (ir != null) { ir.close(); } if (gzis != null) { gzis.close(); } } catch (IOException e) { throw new RuntimeException(e); } } try { Thread.sleep(lineCount * 5L); while (!isDone()) { Thread.sleep(1000); } } catch (InterruptedException e) { throw new RuntimeException(e); } UpdateResult result = new UpdateResult(filePath, lineCount, UpdateStatus.SUCCEEDED); fileCallback.call(result); logger.info(result.toString()); }</code><technical_language>I thought want pass current line number (lineCount) here, starting line</technical_language>

Target:
public void update(final InputStream in, final String filePath, final int startLineIncl, final UpdateFileCallback fileCallback, final UpdateRecordCallback recordCallback) { GZIPInputStream gzis = null; InputStreamReader ir = null; BufferedReader br = null; int lineCount = 0; try { gzis = new GZIPInputStream(in); ir = new InputStreamReader(gzis, StandardCharsets.UTF_8); br = new BufferedReader(ir); List<Record> records = parser.parse(br); for (Record record : records) { lineCount++; if (lineCount >= startLineIncl) { updateRecord(record, filePath, lineCount, recordCallback); } } } catch (Throwable e) { UpdateResult result = new UpdateResult(filePath, lineCount, UpdateStatus.FAILED); logger.error(result.toString(), e); } finally { try { if (br != null) { br.close(); } if (ir != null) { ir.close(); } if (gzis != null) { gzis.close(); } } catch (IOException e) { throw new RuntimeException(e); } } try { Thread.sleep(lineCount * 5L); while (!isDone()) { Thread.sleep(1000); } } catch (InterruptedException e) { throw new RuntimeException(e); } UpdateResult result = new UpdateResult(filePath, lineCount, UpdateStatus.SUCCEEDED); fileCallback.call(result); logger.info(result.toString()); }
Source:
<code>protected ProjectUploadController createProjectUploadController() { if (projectUploadController == null) { <START> projectUploadController = mock(ProjectUploadController.class); <END> } return projectUploadController; }</code><technical_language>this in test thing, this in setUp(). SharedPreferences call moved there. i code duplication of espresso clicks in test, this. method i suspected anything, clicks "next" in reading tests above</technical_language>

Target:
protected ProjectUploadController createProjectUploadController() { projectUploadController = mock(ProjectUploadController.class); return projectUploadController; }
Source:
<code>public boolean addAcl(OzoneObj obj, OzoneAcl acl) throws IOException { boolean auditSuccess = true; try{ if(isAclEnabled) { checkAcls(obj.getResourceType(), obj.getStoreType(), ACLType.WRITE_ACL, obj.getVolumeName(), obj.getBucketName(), obj.getKeyName()); } switch (obj.getResourceType()) { case VOLUME: return volumeManager.addAcl(obj, acl); case BUCKET: return bucketManager.addAcl(obj, acl); case KEY: return keyManager.addAcl(obj, acl); case PREFIX: return prefixManager.addAcl(obj, acl); default: throw new OMException("Unexpected resource type: " + obj.getResourceType(), INVALID_REQUEST); } } catch(Exception ex) { auditSuccess = false; <START> auditAcl(obj, Arrays.asList(acl), OMAction.ADD_ACL, <END> auditSuccess, ex); throw ex; } finally { if(auditSuccess){ auditAcl(obj, Arrays.asList(acl), OMAction.ADD_ACL, auditSuccess, null); } } }</code><technical_language>@bharatviswa504 I skip this this class this approach of auditSuccess, for code readability/correctness. I discuss @anuengineer this. If is onboard this change change OM, SCM, DN for audit log. a big enough change, do in separate jira. sound good</technical_language>

Target:
public boolean addAcl(OzoneObj obj, OzoneAcl acl) throws IOException { boolean auditSuccess = true; try{ if(isAclEnabled) { checkAcls(obj.getResourceType(), obj.getStoreType(), ACLType.WRITE_ACL, obj.getVolumeName(), obj.getBucketName(), obj.getKeyName()); } switch (obj.getResourceType()) { case VOLUME: return volumeManager.addAcl(obj, acl); case BUCKET: return bucketManager.addAcl(obj, acl); case KEY: return keyManager.addAcl(obj, acl); case PREFIX: return prefixManager.addAcl(obj, acl); default: throw new OMException("Unexpected resource type: " + obj.getResourceType(), INVALID_REQUEST); } } catch(Exception ex) { auditSuccess = false; auditAcl(obj, Arrays.asList(acl), OMAction.ADD_ACL, ex); throw ex; } finally { if(auditSuccess){ auditAcl(obj, Arrays.asList(acl), OMAction.ADD_ACL, null); } } }
Source:
<code>public void testSaveGlobalConfigFiles() { GlobalConfigFiles store = j.getInstance().getExtensionList(GlobalConfigFiles.class).get(GlobalConfigFiles.class); Assert.assertTrue(store.getConfigs().isEmpty()); CustomConfig config = new CustomConfig(CONFIG_ID, "name", "comment", "content"); store.save(config); Assert.assertEquals(1, store.getConfigs().size()); Config savedConfig = store.getConfigs().iterator().next(); Assert.assertEquals("name", savedConfig.name); Assert.assertEquals("comment", savedConfig.comment); Assert.assertEquals("content", savedConfig.content); CustomConfig anotherConfig = new CustomConfig("anotherid", "name", "comment", "content"); store.save(anotherConfig); Assert.assertEquals(2, store.getConfigs().size()); config = new CustomConfig(CONFIG_ID, "new name", "new comment", "new content"); store.save(config); Assert.assertEquals(2, store.getConfigs().size()); savedConfig = store.getById(CONFIG_ID); Assert.assertEquals("new name", savedConfig.name); Assert.assertEquals("new comment", savedConfig.comment); Assert.assertEquals("new content", savedConfig.content); store.remove(savedConfig.id); Assert.assertEquals(1, store.getConfigs().size()); <START> Assert.assertThat(store.getById(anotherConfig.id), Matchers.is((Config) anotherConfig)); <END> Assert.assertNull(store.getById(savedConfig.id)); store.remove(anotherConfig.id); Assert.assertEquals(0, store.getConfigs().size()); }</code><technical_language>java Matchers.<Config>is(anotherConfig))</technical_language>

Target:
public void testSaveGlobalConfigFiles() { GlobalConfigFiles store = j.getInstance().getExtensionList(GlobalConfigFiles.class).get(GlobalConfigFiles.class); Assert.assertTrue(store.getConfigs().isEmpty()); CustomConfig config = new CustomConfig(CONFIG_ID, "name", "comment", "content"); store.save(config); Assert.assertEquals(1, store.getConfigs().size()); Config savedConfig = store.getConfigs().iterator().next(); Assert.assertEquals("name", savedConfig.name); Assert.assertEquals("comment", savedConfig.comment); Assert.assertEquals("content", savedConfig.content); CustomConfig anotherConfig = new CustomConfig("anotherid", "name", "comment", "content"); store.save(anotherConfig); Assert.assertEquals(2, store.getConfigs().size()); config = new CustomConfig(CONFIG_ID, "new name", "new comment", "new content"); store.save(config); Assert.assertEquals(2, store.getConfigs().size()); savedConfig = store.getById(CONFIG_ID); Assert.assertEquals("new name", savedConfig.name); Assert.assertEquals("new comment", savedConfig.comment); Assert.assertEquals("new content", savedConfig.content); store.remove(savedConfig.id); Assert.assertEquals(1, store.getConfigs().size()); Assert.assertThat(store.getById(anotherConfig.id), Matchers.<Config>is(anotherConfig)); Assert.assertNull(store.getById(savedConfig.id)); store.remove(anotherConfig.id); Assert.assertEquals(0, store.getConfigs().size()); }
Source:
<code>protected void ExecuteVdsBrokerCommand() { _result = null; if (getParameters().getStoragePoolId() != null) { <START> if (FeatureSupported.saferGetAllTasksRequest(getVds().getVdsGroupCompatibilityVersion())) { <END> _result = getBroker().getAllTasksInfo(getParameters().getStoragePoolId().toString()); } } if (_result == null) { _result = getBroker().getAllTasksInfo(); } ProceedProxyReturnValue(); setReturnValue(ParseTaskInfoList(_result.TaskInfoList)); }</code><technical_language>do this dc level? i behaviour host in pool - harder debug IMO please add a log able called checking vdsm log atleast</technical_language>

Target:
protected void ExecuteVdsBrokerCommand() { boolean isFilled = false; if (getParameters().getStoragePoolId() != null) { if (FeatureSupported.saferGetAllTasksRequest(getVds().getVdsGroupCompatibilityVersion())) { _result = getBroker().getAllTasksInfo(getParameters().getStoragePoolId().toString()); isFilled = true; } } if (!isFilled) { _result = getBroker().getAllTasksInfo(); } ProceedProxyReturnValue(); setReturnValue(ParseTaskInfoList(_result.TaskInfoList)); }
Source:
<code>public NioNetworking(Context ctx) { this.threadNamePrefix = ctx.threadNamePrefix; this.metricsRegistry = ctx.metricsRegistry; <START> this.metricsRegistryScheduled = new AtomicBoolean(false); <END> this.loggingService = ctx.loggingService; this.inputThreadCount = ctx.inputThreadCount; this.outputThreadCount = ctx.outputThreadCount; this.logger = loggingService.getLogger(NioNetworking.class); this.errorHandler = ctx.errorHandler; this.balancerIntervalSeconds = ctx.balancerIntervalSeconds; this.selectorMode = ctx.selectorMode; this.selectorWorkaroundTest = ctx.selectorWorkaroundTest; this.idleStrategy = ctx.idleStrategy; }</code><technical_language>I move this variable declaration constructor complex</technical_language>

Target:
public NioNetworking(Context ctx) { this.threadNamePrefix = ctx.threadNamePrefix; this.metricsRegistry = ctx.metricsRegistry; this.loggingService = ctx.loggingService; this.inputThreadCount = ctx.inputThreadCount; this.outputThreadCount = ctx.outputThreadCount; this.logger = loggingService.getLogger(NioNetworking.class); this.errorHandler = ctx.errorHandler; this.balancerIntervalSeconds = ctx.balancerIntervalSeconds; this.selectorMode = ctx.selectorMode; this.selectorWorkaroundTest = ctx.selectorWorkaroundTest; this.idleStrategy = ctx.idleStrategy; }
Source:
<code><START> public void testCommon() throws Throwable { <END> doTest("Remove from import"); }</code><technical_language>throws Throwable</technical_language>

Target:
public void testCommon() { doTest(); }
Source:
<code>private void createSharedResources(IInvocationContext context) { List<IBuildInfo> infos = context.getBuildInfos(); if (infos.size() <= 1) { return; } try { <START> File resourcesDir = FileUtil.createTempDir("invocation-resources-dir"); <END> for (IBuildInfo info : infos) { if (info.isTestResourceBuild()) { String name = String.format( "%s_%s_%s", info.getBuildBranch(), info.getBuildId(), info.getBuildFlavor()); File buildDir = FileUtil.createTempDir(name, resourcesDir); for (BuildInfoFileKey key : BuildInfoKey.SHARED_KEY) { File f = info.getFile(key); if (f == null) { continue; } File subDir = new File(buildDir, f.getName()); FileUtil.symlinkFile(f, subDir); } } else { info.setFile(BuildInfoFileKey.SHARED_RESOURCE_DIR, resourcesDir, "v1"); } } } catch (IOException e) { CLog.e("Failed to create the shared resources dir."); CLog.e(e); } }</code><technical_language>this cleaned up</technical_language>

Target:
private void createSharedResources(IInvocationContext context) { List<IBuildInfo> infos = context.getBuildInfos(); if (infos.size() <= 1) { return; } try { File resourcesDir = null; for (IBuildInfo info : infos) { if (info.isTestResourceBuild()) { if (resourcesDir == null) { resourcesDir = FileUtil.createTempDir("invocation-resources-dir"); } String name = String.format( "%s_%s_%s", info.getBuildBranch(), info.getBuildId(), info.getBuildFlavor()); File buildDir = FileUtil.createTempDir(name, resourcesDir); for (BuildInfoFileKey key : BuildInfoKey.SHARED_KEY) { File f = info.getFile(key); if (f == null) { continue; } File subDir = new File(buildDir, f.getName()); FileUtil.symlinkFile(f, subDir); } } } if (resourcesDir == null) { return; } CLog.d("Creating shared resources directory."); for (IBuildInfo info : infos) { if (!info.isTestResourceBuild()) { info.setFile(BuildInfoFileKey.SHARED_RESOURCE_DIR, resourcesDir, "v1"); } } } catch (IOException e) { CLog.e("Failed to create the shared resources dir."); CLog.e(e); } }
Source:
<code>public void testWriteAnnotationDtoToPreparedStatementLongList() throws SQLException{ annotationDto.setValue(Arrays.asList("123", "456", "789")); SQLUtils.writeAnnotationDtoToPreparedStatement(mockPreparedStatement, annotationDto); verify(mockPreparedStatement).setLong(1, annotationDto.getEntityId()); verify(mockPreparedStatement).setString(2, annotationDto.getKey()); verify(mockPreparedStatement).setString(3, annotationDto.getType().name()); verify(mockPreparedStatement).setString(4, annotationDto.getValue().get(0)); verify(mockPreparedStatement).setLong(5, 123L); verify(mockPreparedStatement).setDouble(6, 123); verify(mockPreparedStatement).setNull(7, Types.VARCHAR); verify(mockPreparedStatement).setNull(8, Types.BOOLEAN); <START> verify(mockPreparedStatement).setString(9, "[\"123\",\"456\",\"789\"]"); <END> verify(mockPreparedStatement).setString(10, "[123,456,789]"); verify(mockPreparedStatement).setString(11, null); verify(mockPreparedStatement).setLong(12, 3); }</code><technical_language>3s</technical_language>

Target:
public void testWriteAnnotationDtoToPreparedStatementLongList() throws SQLException{ annotationDto.setValue(Arrays.asList("123", "4560", "789")); SQLUtils.writeAnnotationDtoToPreparedStatement(mockPreparedStatement, annotationDto); verify(mockPreparedStatement).setLong(1, annotationDto.getEntityId()); verify(mockPreparedStatement).setString(2, annotationDto.getKey()); verify(mockPreparedStatement).setString(3, annotationDto.getType().name()); verify(mockPreparedStatement).setString(4, annotationDto.getValue().get(0)); verify(mockPreparedStatement).setLong(5, 123L); verify(mockPreparedStatement).setDouble(6, 123); verify(mockPreparedStatement).setNull(7, Types.VARCHAR); verify(mockPreparedStatement).setNull(8, Types.BOOLEAN); verify(mockPreparedStatement).setString(9, "[\"123\",\"4560\",\"789\"]"); verify(mockPreparedStatement).setString(10, "[123,4560,789]"); verify(mockPreparedStatement).setString(11, null); verify(mockPreparedStatement).setLong(12, 4); }
Source:
<code>private void scanFilesForChanges() { if (watchedFiles.isEmpty() || callback == null) { return; } MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { } ImmutableSet.Builder<File> modifiedFilesBuilder = ImmutableSet.builder(); Map<File, FileMetadata> metadataCache = Maps.newHashMap(metadataCacheRef.get()); for (File file : watchedFiles) { try { FileMetadata meta = new FileMetadata(file, digest); <START> if (!metadataCache.containsKey(file) || !metadataCache.get(file).equals(meta)) { <END> metadataCache.put(file, meta); modifiedFilesBuilder.add(file); } } catch (IOException | SecurityException e) { log.warn( "Error trying to stat or read file %s: %s: %s", file.toString(), e.getClass().getName(), e.getMessage()); metadataCache.remove(file); continue; } } try { Set<File> modifiedFiles = modifiedFilesBuilder.build(); if (!modifiedFiles.isEmpty()) { callback.accept(modifiedFiles); } metadataCacheRef.set(ImmutableMap.copyOf(metadataCache)); } catch (Exception e) { log.warn("Error from user callback: %s: %s", e.getClass().toString(), e.getMessage()); } }</code><technical_language>if (!meta.equals(metadataCache.get(file)) {</technical_language>

Target:
private void scanFilesForChanges() { MessageDigest digest; try { digest = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } ImmutableSet.Builder<File> modifiedFilesBuilder = ImmutableSet.builder(); Map<File, FileMetadata> metadataCache = Maps.newHashMap(metadataCacheRef.get()); for (File file : watchedFiles) { try { FileMetadata meta = new FileMetadata(file, digest); if (!meta.equals(metadataCache.get(file))) { metadataCache.put(file, meta); modifiedFilesBuilder.add(file); } } catch (IOException | SecurityException e) { log.warn( "Error trying to stat or read file %s: %s: %s", file.toString(), e.getClass().getName(), e.getMessage()); metadataCache.remove(file); } } Set<File> modifiedFiles = modifiedFilesBuilder.build(); boolean callbackCalled = false; boolean callbackSucceeded = false; try { if (!modifiedFiles.isEmpty()) { callbackCalled = true; callback.accept(modifiedFiles); callbackSucceeded = true; } metadataCacheRef.set(ImmutableMap.copyOf(metadataCache)); } catch (Exception e) { log.warn("Error from user callback: %s: %s", e.getClass().toString(), e.getMessage()); } if (!modifiedFiles.isEmpty()) { stats.fileChangesDetected.getAndAdd(modifiedFiles.size()); } if (callbackCalled) { stats.callbacksInvoked.getAndIncrement(); if (callbackSucceeded) { stats.callbacksSucceeded.getAndIncrement(); } else { stats.callbacksFailed.getAndIncrement(); } } stats.pollCycles.getAndIncrement(); }