auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void validateIdentifiers(final EObject element) { new ElkGraphSwitch<Object>() { @Override public Object caseElkNode(final ElkNode node) { validateIdentifier(node); node.getLabels().stream().forEach(l -> generateIdentifiers(l)); node.getPorts().stream().forEach(p -> generateIdentifiers(p)); node.getContainedEdges().stream().forEach(e -> generateIdentifiers(e)); node.getChildren().stream().forEach(c -> generateIdentifiers(c)); return null; } @Override public Object caseElkPort(final ElkPort port) { validateIdentifier(port); port.getLabels().stream().forEach(l -> generateIdentifiers(l)); return null; } @Override public Object caseElkLabel(final ElkLabel label) { validateIdentifier(label); label.getLabels().stream().forEach(l -> generateIdentifiers(l)); return null; } @Override public Object caseElkEdge(final ElkEdge edge) { validateIdentifier(edge); edge.getLabels().stream().forEach(l -> generateIdentifiers(l)); edge.getSections().stream().forEach(s -> generateIdentifiers(s)); return null; } @Override public Object caseElkEdgeSection(final ElkEdgeSection section) { validateIdentifier(section); return null; } }.doSwitch(element); }

Target:
private void validateIdentifiers(final EObject element) { new ElkGraphSwitch<Object>() { @Override public Object caseElkNode(final ElkNode node) { validateIdentifier(node); node.getLabels().stream().forEach(l -> validateIdentifier(l)); node.getPorts().stream().forEach(p -> validateIdentifier(p)); node.getContainedEdges().stream().forEach(e -> validateIdentifier(e)); node.getChildren().stream().forEach(c -> validateIdentifier(c)); return null; } @Override public Object caseElkPort(final ElkPort port) { validateIdentifier(port); port.getLabels().stream().forEach(l -> validateIdentifier(l)); return null; } @Override public Object caseElkLabel(final ElkLabel label) { validateIdentifier(label); label.getLabels().stream().forEach(l -> validateIdentifier(l)); return null; } @Override public Object caseElkEdge(final ElkEdge edge) { validateIdentifier(edge); edge.getLabels().stream().forEach(l -> validateIdentifier(l)); edge.getSections().stream().forEach(s -> validateIdentifier(s)); return null; } @Override public Object caseElkEdgeSection(final ElkEdgeSection section) { validateIdentifier(section); return null; } }.doSwitch(element); }
Source:
public void setDetails(String key, Object value) { this.details.put(key, value); }

Target:
public void setDetails(String key, Object value) { if (details == null) { this.details = newHashMap(); } this.details.put(key, value); }
Source:
public ImmutableBoundedValue<Integer> fireDelay() { return ImmutableDataCachingUtil.getValue(ImmutableSpongeBoundedValue.class, Keys.FIRE_DAMAGE_DELAY, this.fireDelay, this.fireDelay, intComparator(), 0); }

Target:
public ImmutableBoundedValue<Integer> fireDelay() { return new ImmutableSpongeBoundedValue<Integer>(Keys.FIRE_DAMAGE_DELAY, this.fireDelay, 20, intComparator(), 0, Integer.MAX_VALUE); }
Source:
private boolean requestForbidden(HttpServletRequest request) { if (!xsrfProtectionEnabled) { return false; } HttpSession session = request.getSession(false); String csrfTokenInHeader = request.getHeader("X-CSRF-Token"); if (session == null) { return csrfTokenInHeader != null; } else { String csrfTokenInSession = (String) session.getAttribute(VaadinService.getCsrfTokenAttributeName()); return csrfTokenInSession == null || !csrfTokenInSession.equals(csrfTokenInHeader); } }

Target:
private boolean requestForbidden(HttpServletRequest request) { if (!xsrfProtectionEnabled) { return false; } HttpSession session = request.getSession(false); if (session == null) { return false; } String csrfTokenInSession = (String) session.getAttribute(VaadinService.getCsrfTokenAttributeName()); return csrfTokenInSession == null || !csrfTokenInSession.equals(request.getHeader("X-CSRF-Token")); }
Source:
public List<String> getConfigList(String xpathString) { SAXReader reader = new SAXReader(); List<String> returnValue = new ArrayList<>(); try { Document doc = reader.read(getConfigFile()); DefaultXPath xpath = new DefaultXPath(xpathString); @SuppressWarnings("unchecked") List<DefaultElement> list = xpath.selectNodes(doc); for (final DefaultElement element : list) { returnValue.add(element.getText()); } } catch (DocumentException e) { LOGGER.log(Level.WARNING, String.format("Could not open config file '%s': '%s'", getConfigFile(), e.getMessage())); } return returnValue; }

Target:
public List<String> getConfigList(String xpathString) { SAXReader reader = new SAXReader(); List<String> returnValue = new ArrayList<>(); try { Document doc = reader.read(getConfigFile()); DefaultXPath xpath = new DefaultXPath(xpathString); @SuppressWarnings("unchecked") List<DefaultElement> list = xpath.selectNodes(doc); for (final DefaultElement element : list) { returnValue.add(element.getText()); } } catch (DocumentException e) { LOGGER.log(Level.WARNING, String.format("Could not read '%s' as an xml document: '%s'", getConfigFile(), e.getMessage())); } catch (ClassCastException e) { LOGGER.log(Level.WARNING, String.format("Error reading configuration file %s: '%s' does not return a list of elements", getConfigFile(), xpathString)); } return returnValue; }
Source:
DeleteOperation(ClusterMap clusterMap, RouterConfig routerConfig, NonBlockingRouterMetrics routerMetrics, ResponseHandler responsehandler, BlobId blobId, String serviceId, Callback<Void> callback, Time time, FutureResult<Void> futureResult) { this.submissionTimeMs = time.milliseconds(); this.routerConfig = routerConfig; this.routerMetrics = routerMetrics; this.responseHandler = responsehandler; this.blobId = blobId; this.serviceId = serviceId; this.futureResult = futureResult; this.callback = callback; this.time = time; this.deletionTimeMs = time.milliseconds(); this.deleteRequestInfos = new HashMap<Integer, DeleteRequestInfo>(); byte blobDcId = blobId.getDatacenterId(); String preferredDcName = clusterMap.findDatacenterName(blobDcId); this.operationTracker = new SimpleOperationTracker(routerConfig.routerDatacenterName, blobId.getPartition(), true, preferredDcName, routerConfig.routerDeleteSuccessTarget, routerConfig.routerDeleteRequestParallelism, false); }

Target:
DeleteOperation(ClusterMap clusterMap, RouterConfig routerConfig, NonBlockingRouterMetrics routerMetrics, ResponseHandler responsehandler, BlobId blobId, String serviceId, Callback<Void> callback, Time time, FutureResult<Void> futureResult) { this.submissionTimeMs = time.milliseconds(); this.routerConfig = routerConfig; this.routerMetrics = routerMetrics; this.responseHandler = responsehandler; this.blobId = blobId; this.serviceId = serviceId; this.futureResult = futureResult; this.callback = callback; this.time = time; this.deletionTimeMs = time.milliseconds(); this.deleteRequestInfos = new HashMap<Integer, DeleteRequestInfo>(); byte blobDcId = blobId.getDatacenterId(); String originatingDcName = clusterMap.getDatacenterName(blobDcId); this.operationTracker = new SimpleOperationTracker(routerConfig.routerDatacenterName, blobId.getPartition(), true, originatingDcName, true, Integer.MAX_VALUE, routerConfig.routerDeleteSuccessTarget, routerConfig.routerDeleteRequestParallelism, false); }
Source:
public Set<LockRefreshToken> refreshLockRefreshTokens(Iterable<LockRefreshToken> tokens) { List<HeldLocksToken> fakeTokens = Lists.newArrayList(); LockDescriptor fakeLockDesc = StringLockDescriptor.of("refreshLockRefreshTokens"); SortedLockCollection<LockDescriptor> fakeLockSet = LockCollections.of(ImmutableSortedMap.of(fakeLockDesc, LockMode.READ)); for (LockRefreshToken token : tokens) { fakeTokens.add(new HeldLocksToken( token.getTokenId(), LockClient.ANONYMOUS, 0L, 0L, fakeLockSet, maxAllowedLockTimeout, 0L, "fakeThread-refreshLockRefreshTokens")); } return ImmutableSet.copyOf(Iterables.transform(refreshTokens(fakeTokens), HeldLocksTokens.getRefreshTokenFun())); }

Target:
public Set<LockRefreshToken> refreshLockRefreshTokens(Iterable<LockRefreshToken> tokens) { List<HeldLocksToken> fakeTokens = Lists.newArrayList(); LockDescriptor fakeLockDesc = StringLockDescriptor.of("refreshLockRefreshTokens"); SortedLockCollection<LockDescriptor> fakeLockSet = LockCollections.of(ImmutableSortedMap.of(fakeLockDesc, LockMode.READ)); for (LockRefreshToken token : tokens) { fakeTokens.add(new HeldLocksToken( token.getTokenId(), LockClient.ANONYMOUS, 0L, 0L, fakeLockSet, maxAllowedLockTimeout, 0L, "UnknownThread-refreshLockRefreshTokens")); } return ImmutableSet.copyOf(Iterables.transform(refreshTokens(fakeTokens), HeldLocksTokens.getRefreshTokenFun())); }
Source:
public void setScrollView(@Nullable ObservableWebView webView) { this.webView = webView; if (this.webView != null) { this.webView.clearAllListeners(); this.webView.addOnScrollChangeListener(this); this.webView.addOnDownMotionEventListener(this); this.webView.addOnUpOrCancelMotionEventListener(this); } }

Target:
public void setScrollView(@Nullable ObservableWebView webView) { if (this.webView != null) { this.webView.clearAllListeners(); } this.webView = webView; if (this.webView != null) { this.webView.addOnScrollChangeListener(this); this.webView.addOnDownMotionEventListener(this); this.webView.addOnUpOrCancelMotionEventListener(this); } }
Source:
public InterpreterResult interpret(String input, InterpreterContext context) { String[] tokens = splitTokens(input); String keyword = tokens[0]; InterpreterResult result; Protocol.Command command = Protocol.Command.valueOf(keyword); if (COMMANDS.containsKey(command)) { result = COMMANDS.get(command).execute(tokens); } else { result = new InterpreterResult(ERROR, "keyword not found"); } return result; }

Target:
public InterpreterResult interpret(String input, InterpreterContext context) { String[] tokens = splitTokens(input); String keyword = tokens[0].toUpperCase(); InterpreterResult result; Protocol.Command command = Protocol.Command.valueOf(keyword); if (COMMANDS.containsKey(command)) { result = COMMANDS.get(command).execute(tokens); } else { result = new InterpreterResult(ERROR, "Keyword " + tokens + " is not supported"); } return result; }
Source:
public void fromStream(ObjectInput inputStream) throws CacheLoaderException { Object objectFromStream; try { objectFromStream = getMarshaller().objectFromObjectStream(inputStream); } catch (IOException e) { throw log.unableToUnmarshall(e); } catch (ClassNotFoundException e) { throw log.unableToUnmarshall(e); } catch (InterruptedException e) { throw log.unableToUnmarshall(e); } if (objectFromStream instanceof InternalCacheEntry) { InternalCacheEntry ice = (InternalCacheEntry) objectFromStream; this.store(ice); } else if (objectFromStream instanceof Set) { Set<InternalCacheEntry> internalCacheEntries = (Set<InternalCacheEntry>) objectFromStream; for (InternalCacheEntry ice : internalCacheEntries) { this.store(ice); } } }

Target:
public void fromStream(ObjectInput inputStream) throws CacheLoaderException { Object objectFromStream; try { objectFromStream = getMarshaller().objectFromObjectStream(inputStream); } catch (IOException e) { Thread.currentThread().interrupt(); throw log.unableToUnmarshall(e); } catch (ClassNotFoundException e) { throw log.unableToUnmarshall(e); } catch (InterruptedException e) { throw log.unableToUnmarshall(e); } if (objectFromStream instanceof InternalCacheEntry) { InternalCacheEntry ice = (InternalCacheEntry) objectFromStream; this.store(ice); } else if (objectFromStream instanceof Set) { Set<InternalCacheEntry> internalCacheEntries = (Set<InternalCacheEntry>) objectFromStream; for (InternalCacheEntry ice : internalCacheEntries) { this.store(ice); } } }
Source:
public synchronized EditTokenStorage getEditTokenStorage() { if (editTokenStorage == null) { editTokenStorage = new EditTokenStorage(this); } return editTokenStorage; }

Target:
public EditTokenStorage getEditTokenStorage() { return editTokenStorage; }
Source:
public SoundEffectPlayer(final String soundPath) { super(); path = soundPath; if (State.isSoundEffectsEnabled()) { initializeAudio(path); } this.setVolume(DEFAULT_VOLUMELEVEL); }

Target:
public SoundEffectPlayer(final String soundPath) { super(); path = soundPath; if (State.isSoundEffectsEnabled()) { initializeAudio(path); } this.setVolume(State.getSoundEffectVolume()); }
Source:
private NBTTagCompound loadSpawnData( int dim, int chunkX, int chunkZ ) { if( !Thread.holdsLock( SpawnData.class ) ) { throw new IllegalStateException( "Invalid Request" ); } NBTTagCompound data = null; File file = new File( this.spawnDirectory, dim + "_" + ( chunkX >> 4 ) + '_' + ( chunkZ >> 4 ) + ".dat" ); if( file.isFile() ) { FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream( file ); data = CompressedStreamTools.readCompressed( fileInputStream ); } catch( Throwable e ) { data = new NBTTagCompound(); AELog.error( e ); } finally { if( fileInputStream != null ) { try { fileInputStream.close(); } catch( IOException e ) { AELog.error( e ); } } } } else { data = new NBTTagCompound(); } return data; }

Target:
private NBTTagCompound loadSpawnData( int dim, int chunkX, int chunkZ ) { if( !Thread.holdsLock( SpawnData.class ) ) { throw new IllegalStateException( "Invalid Request" ); } NBTTagCompound data = null; final String fileName = this.encoder.encode( dim, chunkX, chunkZ ); final File file = new File( this.spawnDirectory, fileName ); if( file.isFile() ) { FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream( file ); data = CompressedStreamTools.readCompressed( fileInputStream ); } catch( Throwable e ) { data = new NBTTagCompound(); AELog.error( e ); } finally { if( fileInputStream != null ) { try { fileInputStream.close(); } catch( IOException e ) { AELog.error( e ); } } } } else { data = new NBTTagCompound(); } return data; }
Source:
public Boolean call() throws IdentityProvisioningException { boolean success = false; String tenantDomainName = this.tenantDomainName; try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomainName); ProvisionedIdentifier provisionedIdentifier = null; provisionedIdentifier = connector.provision(provisioningEntity); if (provisioningEntity.getOperation() == ProvisioningOperation.DELETE) { deleteProvisionedEntityIdentifier(idPName, connectorType, provisioningEntity, tenantDomainName); } else if (provisioningEntity.getOperation() == ProvisioningOperation.POST) { if (provisionedIdentifier == null || provisionedIdentifier.getIdentifier() == null) { provisionedIdentifier = new ProvisionedIdentifier(); provisionedIdentifier.setIdentifier(UUID.randomUUID().toString()); } provisioningEntity.setIdentifier(provisionedIdentifier); storeProvisionedEntityIdentifier(idPName, connectorType, provisioningEntity, tenantDomainName); } success = true; } catch (Exception e) { String errMsg = " Provisioning for Entity " + provisioningEntity.getEntityName() + " For operation = " + provisioningEntity.getOperation(); throw new IdentityProvisioningException(errMsg, e); } finally { PrivilegedCarbonContext.endTenantFlow(); if (tenantDomainName != null) { PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( tenantDomainName); } } return success; }

Target:
public Boolean call() throws IdentityProvisioningException { boolean success = false; String tenantDomainName = this.tenantDomainName; try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomainName); ProvisionedIdentifier provisionedIdentifier = null; provisionedIdentifier = connector.provision(provisioningEntity); if (provisioningEntity.getOperation() == ProvisioningOperation.DELETE) { deleteProvisionedEntityIdentifier(idPName, connectorType, provisioningEntity, tenantDomainName); } else if (provisioningEntity.getOperation() == ProvisioningOperation.POST) { if (provisionedIdentifier == null || provisionedIdentifier.getIdentifier() == null) { provisionedIdentifier = new ProvisionedIdentifier(); provisionedIdentifier.setIdentifier(UUID.randomUUID().toString()); } provisioningEntity.setIdentifier(provisionedIdentifier); storeProvisionedEntityIdentifier(idPName, connectorType, provisioningEntity, tenantDomainName); } success = true; } catch (IdentityApplicationManagementException e) { String errMsg = " Provisioning for Entity " + provisioningEntity.getEntityName() + " For operation = " + provisioningEntity.getOperation(); throw new IdentityProvisioningException(errMsg, e); } finally { PrivilegedCarbonContext.endTenantFlow(); if (tenantDomainName != null) { PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( tenantDomainName); } } return success; }
Source:
public int read(int offset, int[] positions, int positionCount) throws IOException { checkState(!valuesInUse, "BlockLease hasn't been closed yet"); if (!rowGroupOpen) { openRowGroup(); } allNulls = false; if (outputRequired) { ensureValuesCapacity(positionCount, nullsAllowed && presentStream != null); } if (filter != null) { ensureOutputPositionsCapacity(positionCount); } else { outputPositions = positions; } systemMemoryContext.setBytes(getRetainedSizeInBytes()); if (readOffset < offset) { skip(offset - readOffset); } int streamPosition = 0; if (dataStream == null && presentStream != null) { streamPosition = readAllNulls(positions, positionCount); } else if (filter == null) { streamPosition = readNoFilter(positions, positionCount); } else { streamPosition = readWithFilter(positions, positionCount); } readOffset = offset + streamPosition; return outputPositionCount; }

Target:
public int read(int offset, int[] positions, int positionCount) throws IOException { checkState(!valuesInUse, "BlockLease hasn't been closed yet"); if (!rowGroupOpen) { openRowGroup(); } allNulls = false; if (outputRequired) { ensureValuesCapacity(positionCount, nullsAllowed && presentStream != null); } if (filter != null) { outputPositions = ensureCapacity(outputPositions, positionCount); } else { outputPositions = positions; } systemMemoryContext.setBytes(getRetainedSizeInBytes()); if (readOffset < offset) { skip(offset - readOffset); } int streamPosition; if (dataStream == null && presentStream != null) { streamPosition = readAllNulls(positions, positionCount); } else if (filter == null) { streamPosition = readNoFilter(positions, positionCount); } else { streamPosition = readWithFilter(positions, positionCount); } readOffset = offset + streamPosition; return outputPositionCount; }
Source:
public String[] getColumnFamilies() { return columnFamilies; }

Target:
public String[] getColumnFamilies() { return Arrays.copyOf(columnFamilies, columnFamilies.length); }
Source:
private void proceedGuaranteedMemoryCheck() { for (VmInternalData vmInternalData : _runningVms.values()) { VM savedVm = _vmDict.get(vmInternalData.getVmDynamic().getId()); VmStatistics vmStatistics = vmInternalData.getVmStatistics(); if (vmStatistics.getCurrentMemory() != null && savedVm.getMinAllocatedMem() > vmStatistics.getCurrentMemory()) { AuditLogableBase auditLogable = new AuditLogableBase(); auditLogable.addCustomValue("VmName", savedVm.getName()); auditLogable.addCustomValue("VdsName", this._vds.getName()); auditLogable.addCustomValue("MemGuaranteed", String.valueOf(savedVm.getMinAllocatedMem())); auditLogable.addCustomValue("MemActual", vmStatistics.getCurrentMemory().toString()); auditLog(auditLogable, AuditLogType.VM_MEMORY_UNDER_GUARANTEED_VALUE); } } }

Target:
private void proceedGuaranteedMemoryCheck() { for (VmInternalData vmInternalData : _runningVms.values()) { VM savedVm = _vmDict.get(vmInternalData.getVmDynamic().getId()); VmStatistics vmStatistics = vmInternalData.getVmStatistics(); if (vmStatistics.getCurrentMemory() != null && vmStatistics.getCurrentMemory() > 0 && savedVm.getMinAllocatedMem() > vmStatistics.getCurrentMemory() / TO_MEGA_BYTES) { AuditLogableBase auditLogable = new AuditLogableBase(); auditLogable.addCustomValue("VmName", savedVm.getName()); auditLogable.addCustomValue("VdsName", this._vds.getName()); auditLogable.addCustomValue("MemGuaranteed", String.valueOf(savedVm.getMinAllocatedMem())); auditLogable.addCustomValue("MemActual", vmStatistics.getCurrentMemory().toString()); auditLog(auditLogable, AuditLogType.VM_MEMORY_UNDER_GUARANTEED_VALUE); } } }
Source:
private void establishHistoryLimit() { int historyLimit= SearchPreferencePage.getHistoryLimit(); QueryManager searchManager= getSearchManager(); if (historyLimit >= searchManager.getSize()) { return; } int numberQueriesNotShown= 0; SearchViewManager searchViewManager= getSearchViewManager(); ISearchQuery[] queries= searchManager.getQueries(); for (ISearchQuery querie : queries) { ISearchQuery query= querie; if (!searchViewManager.isShown(query)) { if (++numberQueriesNotShown >= historyLimit) { removeQuery(query); } } } }

Target:
private void establishHistoryLimit() { int historyLimit= SearchPreferencePage.getHistoryLimit(); QueryManager searchManager= getSearchManager(); if (historyLimit >= searchManager.getSize()) { return; } int numberQueriesNotShown= 0; SearchViewManager searchViewManager= getSearchViewManager(); ISearchQuery[] queries= searchManager.getQueries(); for (ISearchQuery query : queries) { if (!searchViewManager.isShown(query)) { if (++numberQueriesNotShown >= historyLimit) { removeQuery(query); } } } }
Source:
getTabletServers(@QueryParam("s") @Pattern(regexp = HOSTNAME_PORT_REGEX) String server) { Map<String,Object> model = getModel(); model.put("title", "Tablet Server Status"); if (!server.isBlank()) { model.put("template", "server.ftl"); model.put("js", "server.js"); model.put("server", server); return model; } model.put("template", "tservers.ftl"); model.put("js", "tservers.js"); return model; }

Target:
getTabletServers(@QueryParam("s") @Pattern(regexp = HOSTNAME_PORT_REGEX) String server) { Map<String,Object> model = getModel(); model.put("title", "Tablet Server Status"); if (server != null && !server.isBlank()) { model.put("template", "server.ftl"); model.put("js", "server.js"); model.put("server", server); return model; } model.put("template", "tservers.ftl"); model.put("js", "tservers.js"); return model; }
Source:
public void setCanonicalizationMethod(String cMethod) { if (Arrays.stream(VALID_CANONICALIZATION_METHODS.split("\\s*,\\s*")).noneMatch(cMethod.toUpperCase()::equals)) { throw new SlimFixtureException(false, "Invalid canonicalization method: " + cMethod.toUpperCase() + ". Valid options: " + Arrays.toString(VALID_CANONICALIZATION_METHODS.split("\\s*,\\s*"))); } signatureCanonicalizationMethod = getStringValueFromField(CanonicalizationMethod.class, cMethod.toUpperCase()); }

Target:
public void setCanonicalizationMethod(String cMethod) { if (Arrays.stream(VALID_CANONICALIZATION_METHODS.split("\\s*,\\s*")).noneMatch(cMethod.toUpperCase()::equals)) { throw new SlimFixtureException(false, "Invalid canonicalization method: " + cMethod.toUpperCase() + ". Valid options: " + VALID_CANONICALIZATION_METHODS); } signatureCanonicalizationMethod = getStringValueFromField(CanonicalizationMethod.class, cMethod.toUpperCase()); }
Source:
private BriefcaseAnalytics() { config = new GoogleAnalyticsConfig(); checkTrackingConsentState(); this.googleAnalytics = new GoogleAnalytics(config, GOOGLE_TRACKING_ID); }

Target:
private BriefcaseAnalytics() { }
Source:
public void afterCompletion(int status) { if (status == 3) { StreamWorkManager.this.schedule(this.work, this.scheduling, false); } else { if (status != 4) { throw new IllegalArgumentException("Unsupported transaction status " + status); } } }

Target:
public void afterCompletion(int status) { if (status == Status.STATUS_COMMITTED) { StreamWorkManager.this.schedule(this.work, this.scheduling, false); } else { if (status != Status.STATUS_ROLLEDBACK) { throw new IllegalArgumentException("Unsupported transaction status " + status); } } }
Source:
public void checkImmutability() throws Exception { final Collection<Class<?>> result = classpath.allTypes(); final Class<? extends Annotation> expected = Immutable.class; final Set<String> skip = this.skip(); for (final Class<?> clazz : result) { if (skip.contains(clazz.getName())) { continue; } MatcherAssert.assertThat( String.format( "Class %s should have annotation %s", clazz.getName(), expected.getSimpleName() ), clazz.isAnnotationPresent(expected), Matchers.is(true) ); } }

Target:
public void checkImmutability() throws Exception { MatcherAssert.assertThat( Iterables.filter( this.classpath.allTypes(), new Predicate<Class<?>>() { @Override public boolean apply(final Class<?> input) { return !skip().contains(input.getName()); } } ), Matchers.everyItem( new CustomTypeSafeMatcher<Class<?>>("annotated type") { @Override protected boolean matchesSafely(final Class<?> item) { return item.isAnnotationPresent(Immutable.class); } } ) ); }
Source:
public RuleMatch[] match(AnalyzedSentence sentence) throws IOException { List<RuleMatch> matches = new ArrayList<>(); Set<String> ignoredWords = ignoredWordsCache.getUnchecked(language); for (AnalyzedTokenReadings token : sentence.getTokensWithoutWhitespace()) { if (token.isSentenceStart() || token.isSentenceEnd() || token.isNonWord()) continue; String word = token.getToken(); if (ignoredWords.contains(word)) { continue; } List<String> candidates = filterCandidates(getSpellerMatches(word, defaultDictSpeller)); List<String> userCandidates = getSpellerMatches(word, userDictSpeller); RuleMatch match = null; if (candidates.size() + userCandidates.size() == 0) { match = new RuleMatch(this, sentence, token.getStartPos(), token.getEndPos(), "Misspelling or unknown word!"); } else if (!(candidates.size() > 0 && candidates.get(0).equals(word) || userCandidates.size() > 0 && userCandidates.get(0).equals(word))) { match = new RuleMatch(this, sentence, token.getStartPos(), token.getEndPos(), "Misspelling!"); addSuggestionsToRuleMatch(token.getToken(), userCandidates, candidates, orderer, match); } if (match != null) { matches.add(match); } } return matches.toArray(new RuleMatch[0]); }

Target:
public RuleMatch[] match(AnalyzedSentence sentence) throws IOException { List<RuleMatch> matches = new ArrayList<>(); Set<String> ignoredWords = ignoredWordsCache.getUnchecked(language); for (AnalyzedTokenReadings token : sentence.getTokensWithoutWhitespace()) { if (token.isSentenceStart() || token.isImmunized() || token.isIgnoredBySpeller() || token.isNonWord()) continue; String word = token.getToken(); if (ignoredWords.contains(word)) { continue; } List<String> candidates = filterCandidates(getSpellerMatches(word, defaultDictSpeller)); List<String> userCandidates = getSpellerMatches(word, userDictSpeller); RuleMatch match = null; if (candidates.size() + userCandidates.size() == 0) { match = new RuleMatch(this, sentence, token.getStartPos(), token.getEndPos(), "Misspelling or unknown word!"); } else if (!(candidates.size() > 0 && candidates.get(0).equals(word) || userCandidates.size() > 0 && userCandidates.get(0).equals(word))) { match = new RuleMatch(this, sentence, token.getStartPos(), token.getEndPos(), "Misspelling!"); addSuggestionsToRuleMatch(token.getToken(), userCandidates, candidates, orderer, match); } if (match != null) { matches.add(match); } } return matches.toArray(new RuleMatch[0]); }
Source:
public void goToDiffPageFromHistoryPage() { historySubmit.click(); waitForTextToBePresentInElementByElement(diffHeader, "Changes"); }

Target:
public DiffPagePageObject goToDiffPageFromHistoryPage() { historySubmit.click(); waitForTextToBePresentInElementByElement(diffHeader, "Changes"); return new DiffPagePageObject(driver); }
Source:
public static void main(final String[] args) throws Exception { final LoadGeneratorCommandLineConfig config = new LoadGeneratorCommandLineConfig(); JCommander jCommander = new JCommander(config, args); if (config.displayUsage) { jCommander.usage(); } else { injector = Guice.createInjector( Stage.PRODUCTION, new ConfigurationModule(new ConfigurationFactory(ImmutableMap.<String, String>of())), new LifeCycleModule(), new ThriftCodecModule(), new ThriftClientModule(), new Module() { @Override public void configure(Binder binder) { thriftClientBinder(binder).bindThriftClient(AsyncClientWorker.LoadTest.class); thriftClientBinder(binder).bindThriftClient(SyncClientWorker.LoadTest.class); binder.bind(LoadGeneratorCommandLineConfig.class).toInstance(config); binder.bind(LoadGenerator.class).in(Singleton.class); if (!config.asyncMode) { binder.bind(AbstractClientWorker.class).to(SyncClientWorker.class); } else { binder.bind(AbstractClientWorker.class).to(AsyncClientWorker.class); } TypeLiteral<NiftyClientChannel.Factory<? extends NiftyClientChannel>> channelFactoryType = new TypeLiteral<NiftyClientChannel.Factory<? extends NiftyClientChannel>>() {}; if (config.transport == TransportType.FRAMED) { binder.bind(channelFactoryType) .to(FramedClientChannel.Factory.class); } else if (config.transport == TransportType.UNFRAMED) { binder.bind(channelFactoryType) .to(UnframedClientChannel.Factory.class); } else { throw new IllegalStateException("Unknown transport"); } } } ); injector.getInstance(LifeCycleManager.class).start(); } }

Target:
public static void main(final String[] args) throws Exception { final LoadGeneratorCommandLineConfig config = new LoadGeneratorCommandLineConfig(); JCommander jCommander = new JCommander(config, args); if (config.displayUsage) { jCommander.usage(); } else { injector = Guice.createInjector( Stage.PRODUCTION, new ConfigurationModule(new ConfigurationFactory(ImmutableMap.<String, String>of())), new LifeCycleModule(), new ThriftCodecModule(), new ThriftClientModule(), new Module() { @Override public void configure(Binder binder) { thriftClientBinder(binder).bindThriftClient(AsyncClientWorker.LoadTest.class); thriftClientBinder(binder).bindThriftClient(SyncClientWorker.LoadTest.class); binder.bind(LoadGeneratorCommandLineConfig.class).toInstance(config); binder.bind(LoadGenerator.class).in(Singleton.class); if (!config.asyncMode) { binder.bind(AbstractClientWorker.class).to(SyncClientWorker.class); } else { binder.bind(AbstractClientWorker.class).to(AsyncClientWorker.class); } TypeLiteral<NiftyClientChannel.Factory<? extends NiftyClientChannel>> channelFactoryType = new TypeLiteral<NiftyClientChannel.Factory<? extends NiftyClientChannel>>() {}; switch (config.transport) { case FRAMED: binder.bind(channelFactoryType) .to(FramedClientChannel.Factory.class); break; case UNFRAMED: binder.bind(channelFactoryType) .to(UnframedClientChannel.Factory.class); break; default: throw new IllegalStateException("Unknown transport"); } } } ); injector.getInstance(LifeCycleManager.class).start(); } }
Source:
public void testNativePlugin() throws Exception { BuildTarget pluginTarget = BuildTargetFactory.newInstance(" workspace.runBuckCommand("build", pluginTarget.toString()).assertSuccess(); BuildTarget binTarget = BuildTargetFactory.newInstance(" workspace.runBuckCommand("build", binTarget.toString()).assertSuccess(); Path ocamlNativePluginDir = workspace.getDestPath().resolve("buck-out").resolve("gen").resolve("ce9b6f2e").resolve("ocaml_native_plugin"); Path pluginCmxsFile = ocamlNativePluginDir.resolve("plugin#default").resolve("libplugin.cmxs"); Path testerExecutableFile = ocamlNativePluginDir.resolve("tester").resolve("tester"); String out = workspace .runCommand(testerExecutableFile.toString(), pluginCmxsFile.toString()) .getStdout() .get(); assertEquals("it works!\n", out); }

Target:
public void testNativePlugin() throws Exception { BuildTarget pluginTarget = BuildTargetFactory.newInstance(" workspace.runBuckCommand("build", pluginTarget.toString()).assertSuccess(); BuildTarget binTarget = BuildTargetFactory.newInstance(" workspace.runBuckCommand("build", binTarget.toString()).assertSuccess(); Path ocamlNativePluginDir = workspace.getPath( BuildTargetPaths.getGenPath( workspace.getProjectFileSystem(), pluginTarget, "%s" )).getParent(); Path pluginCmxsFile = ocamlNativePluginDir.resolve("plugin#default").resolve("libplugin.cmxs"); Path testerExecutableFile = ocamlNativePluginDir.resolve("tester").resolve("tester"); String out = workspace .runCommand(testerExecutableFile.toString(), pluginCmxsFile.toString()) .getStdout() .get(); assertEquals("it works!\n", out); }
Source:
protected <T> T handleError(Class<T> clz, Exception e, boolean notFoundAs404) { if ((e instanceof EntityNotFoundException) && (notFoundAs404)) { throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).build()); } else if ((e instanceof BackendFailureException) && (!StringUtils.isEmpty(e.getMessage()))) { log.error(localize(Messages.BACKEND_FAILED_TEMPLATE), e.getMessage()); BackendFailureException e2 = (BackendFailureException) e; throw new WebFaultException(null, e.getMessage(), e2.getHttpStatus() != null ? e2.getHttpStatus() : Response.Status.BAD_REQUEST); } else if (e instanceof WebFaultException) { WebFaultException e2 = (WebFaultException) e; log.error(localize(Messages.BACKEND_FAILED_TEMPLATE), e2.getMessage()); log.debug("Exception", e2); throw e2; } else { log.error(localize(Messages.BACKEND_FAILED_TEMPLATE), e.getMessage()); log.debug("Exception", e); throw new WebFaultException(e, detail(e), Response.Status.INTERNAL_SERVER_ERROR); } }

Target:
protected <T> T handleError(Class<T> clz, Exception e, boolean notFoundAs404) { if ((e instanceof EntityNotFoundException) && (notFoundAs404)) { throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).build()); } else if ((e instanceof BackendFailureException) && (!StringUtils.isEmpty(e.getMessage()))) { log.error(localize(Messages.BACKEND_FAILED_TEMPLATE), e.getMessage()); BackendFailureException e2 = (BackendFailureException) e; throw new WebFaultException(null, e.getMessage(), e2.getHttpStatus() != null ? e2.getHttpStatus() : Response.Status.BAD_REQUEST); } else if (e instanceof WebFaultException) { WebFaultException e2 = (WebFaultException) e; log.error(localize(Messages.BACKEND_FAILED_TEMPLATE), e2.getMessage()); log.error("Exception", e2); throw e2; } else { log.error(localize(Messages.BACKEND_FAILED_TEMPLATE), e.getMessage()); log.error("Exception", e); throw new WebFaultException(e, detail(e), Response.Status.INTERNAL_SERVER_ERROR); } }
Source:
void handlePrefsDialog(final ClientPrefsOpenedEvent event) { final PreferencesCategory category = new PreferencesCategory("Channel Who", "Provides " + "support for sendinw WHO requests to channels at regular intervals"); category.addSetting(new PreferencesSetting(PreferencesType.DURATION, new NumericalValidator(0, Integer.MAX_VALUE), domain, "whointerval", "Who Interval", "The interval WHO requests will be sent to channels", event.getModel().getConfigManager(), event.getModel().getIdentity())); }

Target:
void handlePrefsDialog(final ClientPrefsOpenedEvent event) { final PreferencesCategory category = new PreferencesCategory("Channel Who", "Provides " + "support for sending WHO requests to channels at regular intervals"); category.addSetting(new PreferencesSetting(PreferencesType.DURATION, new NumericalValidator(0, Integer.MAX_VALUE), domain, "whointerval", "Who Interval", "The interval WHO requests will be sent to channels", event.getModel().getConfigManager(), event.getModel().getIdentity())); }
Source:
private static void showNotification(int newEpisodes, Feed feed, Context context, NotificationManagerCompat notificationManager) { Resources res = context.getResources(); String text = res.getQuantityString( R.plurals.new_episode_notification_message, newEpisodes, newEpisodes, feed.getTitle() ); String title = res.getQuantityString(R.plurals.new_episode_notification_title, newEpisodes); Intent intent = new Intent(); intent.setComponent(new ComponentName(context, "de.danoeh.antennapod.activity.MainActivity")); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); intent.putExtra("fragment_feed_id", feed.getId()); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); Notification notification = new NotificationCompat.Builder( context, NotificationUtils.CHANNEL_ID_EPISODE_NOTIFICATIONS ) .setSmallIcon(R.drawable.ic_notification) .setContentTitle(title) .setContentText(text) .setContentIntent(pendingIntent) .setGroup(GROUP_KEY) .setAutoCancel(true) .build(); notificationManager.notify(NotificationUtils.CHANNEL_ID_EPISODE_NOTIFICATIONS, feed.hashCode(), notification); }

Target:
private static void showNotification(int newEpisodes, Feed feed, Context context, NotificationManagerCompat notificationManager) { Resources res = context.getResources(); String text = res.getQuantityString( R.plurals.new_episode_notification_message, newEpisodes, newEpisodes, feed.getTitle() ); String title = res.getQuantityString(R.plurals.new_episode_notification_title, newEpisodes); Intent intent = new Intent(); intent.setComponent(new ComponentName(context, "de.danoeh.antennapod.activity.MainActivity")); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); intent.putExtra("fragment_feed_id", feed.getId()); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); Notification notification = new NotificationCompat.Builder( context, NotificationUtils.CHANNEL_ID_EPISODE_NOTIFICATIONS) .setSmallIcon(R.drawable.ic_notification) .setContentTitle(title) .setContentText(text) .setContentIntent(pendingIntent) .setGroup(GROUP_KEY) .setAutoCancel(true) .setCategory(res.getString(R.string.notification_group_news)) .build(); notificationManager.notify(NotificationUtils.CHANNEL_ID_EPISODE_NOTIFICATIONS, feed.hashCode(), notification); }
Source:
public void consume(String message) { logger.info("[MQ] receive message: {}: {}.", this.queue(), message); if (Strings.isNullOrEmpty(message)) { logger.error("[MQ] message is empty"); return; } try { String loginName = message; Date date = new Date(); if (date.before(activityStartTime) || date.after(activityEndTime)) { logger.info("[MQ] NewYearActivity_Coupon, new year activity not in the activity time range"); return; } String key = MessageFormat.format(KEY, loginName); if (redisWrapperClient.exists(key)) { logger.info(MessageFormat.format("{0}:已经领取了新年更有钱优惠券", loginName)); return; } List<Long> coupons = Arrays.asList(481L, 481L, 481L, 482L, 482L, 482L, 482L, 482L); coupons.stream().forEach(couponId -> { logger.info(MessageFormat.format("[NewYearActivity_Coupon] loginName:{0},couponId:{1} send message begin", loginName, couponId)); mqWrapperClient.sendMessage(MessageQueue.CouponAssigning, loginName + ":" + couponId); logger.info(MessageFormat.format("[NewYearActivity_Coupon] loginName:{0},couponId:{1} send message end", loginName, couponId)); }); redisWrapperClient.setex(key, lifeSecond,"SUCCESS"); } catch (Exception e) { logger.error("[MQ] 程序內部异常: {}: {}.{}", this.queue(), message, e.getMessage()); } }

Target:
public void consume(String message) { logger.info("[MQ] receive message: {}: {}.", this.queue(), message); if (Strings.isNullOrEmpty(message)) { logger.error("[MQ] message is empty"); return; } try { String loginName = message; Date date = new Date(); if (date.before(activityStartTime) || date.after(activityEndTime)) { logger.info("[MQ] NewYearActivity_Coupon, new year activity not in the activity time range"); return; } String key = MessageFormat.format(KEY, loginName); if (redisWrapperClient.exists(key)) { logger.info(MessageFormat.format("{0}:已经领取了新年更有钱优惠券", loginName)); return; } List<Long> coupons = Arrays.asList(481L, 481L, 481L, 482L, 482L, 482L, 482L, 482L); coupons.stream().forEach(couponId -> { try { logger.info(MessageFormat.format("[NewYearActivity_Coupon] loginName:{0},couponId:{1} send message begin", loginName, couponId)); mqWrapperClient.sendMessage(MessageQueue.CouponAssigning, loginName + ":" + couponId); logger.info(MessageFormat.format("[NewYearActivity_Coupon] loginName:{0},couponId:{1} send message end", loginName, couponId)); }catch (Exception e){ logger.error(MessageFormat.format("[NewYearActivity_Coupon] loginName:{0},couponId:{1} send message fail", loginName, couponId)); smsWrapperClient.sendFatalNotify(new SmsFatalNotifyDto(MessageFormat.format("【新年更有钱活动】用户:{0}, 优惠券:{1}, 发送优惠券失败, 业务处理异常", loginName, couponId))); } }); redisWrapperClient.setex(key, lifeSecond,"SUCCESS"); } catch (Exception e) { logger.error("[MQ] 程序內部异常: {}: {}.{}", this.queue(), message, e.getMessage()); } }
Source:
public <T> T get(Class<T> type, String key) throws IOException { final DocumentMapping mapping = admin.mappings().getMapping(type); final GetResponse response = admin.client() .prepareGet(admin.name(), mapping.typeAsString(), key) .setRouting(mapping.typeAsString()) .setFetchSource(true) .get(); if (response.isExists()) { return mapper.readValue(response.getSourceAsBytes(), type); } else { return null; } }

Target:
public <T> T get(Class<T> type, String key) throws IOException { final DocumentMapping mapping = admin.mappings().getMapping(type); final GetResponse response = admin.client() .prepareGet(admin.name(), mapping.typeAsString(), key) .setRouting(mapping.typeAsString()) .setFetchSource(true) .get(); if (response.isExists()) { final BytesReference bytesRef = response.getSourceAsBytesRef(); return mapper.readValue(bytesRef.array(), bytesRef.arrayOffset(), bytesRef.length(), type); } else { return null; } }
Source:
public Object clone() { final RetryOptions cloned = (RetryOptions) getRetryOptions().clone(); return new FixedRetryPolicy(cloned); }

Target:
public RetryPolicy clone() { final RetryOptions cloned = getRetryOptions().clone(); return new FixedRetryPolicy(cloned); }
Source:
public void init() { URI uri = spacesAPI.resolveFileSystemURI(SpacesAPI.Scheme.DEFAULT, SpacesAPI.DASHBUILDER_SPACE, "navigation"); HashMap<String, Object> env = new HashMap<String, Object>() {{ put("init", Boolean.TRUE); put("internal", Boolean.TRUE); }}; fileSystem = ioService.getOrNewFileSystem(uri, env); root = fileSystem.getRootDirectories().iterator().next(); }

Target:
public void init() { root = fileSystem.getRootDirectories().iterator().next(); }
Source:
public void populateSparkWebUrl(InterpreterContext ctx) { if (sparkUrl == null) { sparkUrl = getSparkUIUrl(); Map<String, String> infos = new java.util.HashMap<>(); if (sparkUrl != null) { infos.put("url", sparkUrl); logger.info("Sending metainfos to Zeppelin server: {}", infos.toString()); if (ctx != null && ctx.getClient() != null) { getZeppelinContext().setEventClient(ctx.getClient()); ctx.getClient().onMetaInfosReceived(infos); } } } }

Target:
public void populateSparkWebUrl(InterpreterContext ctx) { if (sparkUrl == null) { sparkUrl = getSparkUIUrl(); Map<String, String> infos = new java.util.HashMap<>(); if (sparkUrl != null) { infos.put("url", sparkUrl); if (ctx != null && ctx.getClient() != null) { logger.info("Sending metainfos to Zeppelin server: {}", infos.toString()); getZeppelinContext().setEventClient(ctx.getClient()); ctx.getClient().onMetaInfosReceived(infos); } } } }
Source:
public void testDefaultScriptExtension() throws Exception { ScriptMetadata metadata = ScriptMetadataParser.parse("test", " assertEquals("test", metadata.name()); metadata = ScriptMetadataParser.parse("test.", " "); assertEquals("test.", metadata.name()); }

Target:
public void testDefaultScriptExtension() throws Exception { ScriptMetadata metadata = ScriptMetadataParser.parse("test", " assertEquals("test", metadata.name()); }
Source:
private String listToSemicolonSeparatedString(List<String> cookieStrings) { StringBuilder builder = new StringBuilder(); int index = 1; for (String cookieString : cookieStrings) { builder.append(cookieString); if (index != cookieStrings.size()) { builder.append("; "); } } return builder.toString(); }

Target:
private String listToSemicolonSeparatedString(List<String> cookieStrings) { StringBuilder builder = new StringBuilder(); int index = 0; for (String cookieString : cookieStrings) { builder.append(cookieString); if (++index != cookieStrings.size()) { builder.append("; "); } } return builder.toString(); }
Source:
public String getMessage() { String baseMessage = super.getMessage(); if (this.errorCodeValue == null) { return super.getMessage(); } else { baseMessage = String.format(Locale.US, "%s %s: {%s}", baseMessage, "ErrorCodeValue", errorCodeValue); } if (this.target == null) { return baseMessage; } else { baseMessage = String.format(Locale.US, "%s %s: {%s}", baseMessage, "target", target); } return baseMessage; }

Target:
public String getMessage() { StringBuilder baseMessage = new StringBuilder().append(super.getMessage()).append(" ").append(ERROR_CODE) .append(": {").append(errorCodeValue).append("}"); if (this.target == null) { return baseMessage.toString(); } else { return baseMessage.append(", ").append(TARGET).append(": {").append(target).append("}").toString(); } }
Source:
@Override public TraceContextOrSamplingFlags extract(C carrier) { if (carrier == null) throw new NullPointerException("carrier == null"); TraceContext.Builder result = TraceContext.newBuilder(); String sampled = getter.get(carrier, propagation.sampledKey); Boolean sampledV = sampled != null ? sampled.equals("1") || sampled.equalsIgnoreCase("true") : null; boolean debug = "1".equals(getter.get(carrier, propagation.debugKey)); if (!result.parseTraceId(getter, carrier, propagation.traceIdKey)) { return TraceContextOrSamplingFlags.create( debug ? SamplingFlags.DEBUG : SamplingFlags.Builder.build(sampledV) ); } if (result.parseSpanId(getter, carrier, propagation.spanIdKey) && result.parseParentId(getter, carrier, propagation.parentSpanIdKey)) { return TraceContextOrSamplingFlags.create(result.sampled(sampledV).debug(debug).build()); } return TraceContextOrSamplingFlags.EMPTY; }

Target:
@Override public TraceContextOrSamplingFlags extract(C carrier) { if (carrier == null) throw new NullPointerException("carrier == null"); String sampled = getter.get(carrier, propagation.sampledKey); Boolean sampledV = sampled != null ? sampled.equals("1") || sampled.equalsIgnoreCase("true") : null; boolean debug = "1".equals(getter.get(carrier, propagation.debugKey)); String traceIdString = getter.get(carrier, propagation.traceIdKey); if (traceIdString == null) { return TraceContextOrSamplingFlags.create( debug ? SamplingFlags.DEBUG : SamplingFlags.Builder.build(sampledV) ); } TraceContext.Builder result = TraceContext.newBuilder(); if (result.parseTraceId(traceIdString, propagation.traceIdKey) && result.parseSpanId(getter, carrier, propagation.spanIdKey) && result.parseParentId(getter, carrier, propagation.parentSpanIdKey)) { return TraceContextOrSamplingFlags.create(result.sampled(sampledV).debug(debug).build()); } return TraceContextOrSamplingFlags.EMPTY; }
Source:
void sendAddSuccessCallbacks() { PendingAddOp pendingAddOp; while ((pendingAddOp = pendingAddOps.peek()) != null && blockAddCompletions.get() == 0) { if (!pendingAddOp.completed) { if (LOG.isDebugEnabled()) { LOG.debug("pending add not completed: {}", pendingAddOp); } return; } if (pendingAddOp.entryId != 0 && pendingAddOp.entryId != pendingAddsSequenceHead) { if (LOG.isDebugEnabled()) { LOG.debug("Head of the queue entryId: is not the expected value: {}", pendingAddOp.entryId, pendingAddsSequenceHead); } return; } pendingAddOps.remove(); explicitLacFlushPolicy.updatePiggyBackedLac(lastAddConfirmed); if (writeFlags.contains(WriteFlag.DEFERRED_SYNC)) { this.lastAddConfirmed = lastAddSyncedManager.calculateCurrentLastAddSynced(); } else { this.lastAddConfirmed = Math.max(lastAddConfirmed, pendingAddOp.entryId); } pendingAddsSequenceHead = pendingAddOp.entryId + 1; pendingAddOp.submitCallback(BKException.Code.OK); } }

Target:
void sendAddSuccessCallbacks() { PendingAddOp pendingAddOp; while ((pendingAddOp = pendingAddOps.peek()) != null && blockAddCompletions.get() == 0) { if (!pendingAddOp.completed) { if (LOG.isDebugEnabled()) { LOG.debug("pending add not completed: {}", pendingAddOp); } return; } if (pendingAddOp.entryId != 0 && pendingAddOp.entryId != pendingAddsSequenceHead + 1) { if (LOG.isDebugEnabled()) { LOG.debug("Head of the queue entryId: is not the expected value: {}", pendingAddOp.entryId, pendingAddsSequenceHead + 1); } return; } pendingAddOps.remove(); explicitLacFlushPolicy.updatePiggyBackedLac(lastAddConfirmed); pendingAddsSequenceHead = pendingAddOp.entryId; if (!writeFlags.contains(WriteFlag.DEFERRED_SYNC)) { this.lastAddConfirmed = pendingAddsSequenceHead; } pendingAddOp.submitCallback(BKException.Code.OK); } }