auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void processCaches(Document doc, Element parent, Jsr107Configuration configuration) { Map<String, String> cacheMap = configuration.getTemplates(); <START> if (!cacheMap.isEmpty()) { <END> cacheMap.forEach((k, v) -> { Element cacheElement = doc.createElement(JSR_NAMESPACE_PREFIX + COLON + CACHE_ELEMENT_NAME); cacheElement.setAttribute(CACHE_NAME_ATTRIBUTE, k); cacheElement.setAttribute(TEMPLATE_NAME_ATTRIBUTE, v); parent.appendChild(cacheElement); }); } }</code><technical_language>need check for empty</technical_language>

Target:
private void processCaches(Document doc, Element parent, Jsr107Configuration configuration) { Map<String, String> cacheMap = configuration.getTemplates(); cacheMap.forEach((k, v) -> { Element cacheElement = doc.createElement(JSR_NAMESPACE_PREFIX + COLON + CACHE_ELEMENT_NAME); cacheElement.setAttribute(CACHE_NAME_ATTRIBUTE, k); cacheElement.setAttribute(TEMPLATE_NAME_ATTRIBUTE, v); parent.appendChild(cacheElement); }); }
Source:
<code>public void testCloneValues() { PhysicsObject originPhysicsObject = world.getPhysicsObject(sprite); <START> Sprite cloneSprite = new Sprite("Clone"); <END> PhysicsLook cloneLook = new PhysicsLook(cloneSprite, world); PhysicsObject clonePhysicsObject = world.getPhysicsObject(cloneSprite); physicsLook.setXInUserInterfaceDimensionUnit(10); physicsLook.setBrightnessInUserInterfaceDimensionUnit(32); originPhysicsObject.setMass(20); physicsLook.copyTo(cloneLook); assertEquals(physicsLook.getXInUserInterfaceDimensionUnit(), cloneLook.getXInUserInterfaceDimensionUnit()); assertEquals(physicsLook.getBrightnessInUserInterfaceDimensionUnit(), cloneLook.getBrightnessInUserInterfaceDimensionUnit()); assertEquals(originPhysicsObject.getMass(), clonePhysicsObject.getMass()); }</code><technical_language>Please mock :D</technical_language>

Target:
public void testCloneValues() { Sprite cloneSprite = mock(Sprite.class); PhysicsObject clonePhysicsObject = mock(PhysicsObject.class); when(physicsWorldSpy.getPhysicsObject(cloneSprite)).thenReturn(clonePhysicsObject); PhysicsLook cloneLook = new PhysicsLook(cloneSprite, physicsWorldSpy); PhysicsWorld.activeArea = new Vector2(0.0f, 0.0f); when(clonePhysicsObject.getMassCenter()).thenReturn(new Vector2(0.0f, 0.0f)); when(clonePhysicsObject.getCircumference()).thenReturn(0.0f); physicsLook.setBrightnessInUserInterfaceDimensionUnit(32); physicsLook.copyTo(cloneLook); assertEquals(physicsLook.getBrightnessInUserInterfaceDimensionUnit(), cloneLook.getBrightnessInUserInterfaceDimensionUnit()); verify(physicsObject, times(1)).copyTo(clonePhysicsObject); }
Source:
<code>default <R> Option<R> collect(PartialFunction<? super T, ? extends R> partialFunction){ Objects.requireNonNull(partialFunction, "partialFunction is null"); final Option<T> valueInDomain = filter(partialFunction::isDefinedAt); <START> return valueInDomain.isEmpty() ? none(): some(partialFunction.apply(valueInDomain.get())); <END> }</code><technical_language>Please return filter(partialFunction::isDefinedAt).map(partialFunction::apply);. try omit if-branches if possible</technical_language>

Target:
default <R> Option<R> collect(PartialFunction<? super T, ? extends R> partialFunction) { Objects.requireNonNull(partialFunction, "partialFunction is null"); return filter(partialFunction::isDefinedAt).map(partialFunction::apply); }
Source:
<code>public TestStreamingClient startWithAutocommit(final Consumer<List<StreamBatch>> batchesListener) throws InterruptedException { this.batchesListener = batchesListener; final TestStreamingClient client = startInternal(true); final Thread autocommitThread = new Thread(() -> { int oldIdx = 0; while (client.isRunning()) { while (oldIdx < client.getBatches().size()) { final StreamBatch batch = client.getBatches().get(oldIdx); if (batch.getEvents() != null && !batch.getEvents().isEmpty()) { try { final SubscriptionCursor cursor = batch.getCursor(); final int responseCode = NakadiTestUtils.commitCursors( client.subscriptionId, Collections.singletonList(batch.getCursor()), client.getSessionId()); <START> System.out.println("Committing " + responseCode + ": " + cursor); <END> } catch (JsonProcessingException e) { throw new RuntimeException(e); } } oldIdx += 1; } try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); } } }); autocommitThread.setDaemon(true); autocommitThread.start(); return client; }</code><technical_language>slf4j logger defined</technical_language>

Target:
public TestStreamingClient startWithAutocommit(final Consumer<List<StreamBatch>> batchesListener) throws InterruptedException { this.batchesListener = batchesListener; final TestStreamingClient client = startInternal(true); final Thread autocommitThread = new Thread(() -> { int oldIdx = 0; while (client.isRunning()) { while (oldIdx < client.getBatches().size()) { final StreamBatch batch = client.getBatches().get(oldIdx); if (batch.getEvents() != null && !batch.getEvents().isEmpty()) { try { final SubscriptionCursor cursor = batch.getCursor(); final int responseCode = NakadiTestUtils.commitCursors( client.subscriptionId, Collections.singletonList(batch.getCursor()), client.getSessionId()); LOG.info("Committing " + responseCode + ": " + cursor); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } oldIdx += 1; } try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); } } }); autocommitThread.setDaemon(true); autocommitThread.start(); return client; }
Source:
<code>public static VirtualColumns create(List<VirtualColumn> virtualColumns) { if (virtualColumns == null || virtualColumns.isEmpty()) { return EMPTY; } Map<String, VirtualColumn> withDotSupport = Maps.newHashMap(); Map<String, VirtualColumn> withoutDotSupport = Maps.newHashMap(); for (VirtualColumn vc : virtualColumns) { <START> if (vc.getOutputName() == null || vc.getOutputName().isEmpty()) { <END> throw new IAE("Empty or null virtualColumn name"); } if (vc.getOutputName().equals(Column.TIME_COLUMN_NAME)) { throw new IAE("virtualColumn name[%s] not allowed", vc.getOutputName()); } if (withDotSupport.containsKey(vc.getOutputName()) || withoutDotSupport.containsKey(vc.getOutputName())) { throw new IAE("Duplicate virtualColumn name[%s]", vc.getOutputName()); } if (vc.usesDotNotation()) { withDotSupport.put(vc.getOutputName(), vc); } else { withoutDotSupport.put(vc.getOutputName(), vc); } } return new VirtualColumns(ImmutableList.copyOf(virtualColumns), withDotSupport, withoutDotSupport); }</code><technical_language>Strings.isNullOrEmpty</technical_language>

Target:
public static VirtualColumns create(List<VirtualColumn> virtualColumns) { if (virtualColumns == null || virtualColumns.isEmpty()) { return EMPTY; } Map<String, VirtualColumn> withDotSupport = Maps.newHashMap(); Map<String, VirtualColumn> withoutDotSupport = Maps.newHashMap(); for (VirtualColumn vc : virtualColumns) { if (Strings.isNullOrEmpty(vc.getOutputName())) { throw new IAE("Empty or null virtualColumn name"); } if (vc.getOutputName().equals(Column.TIME_COLUMN_NAME)) { throw new IAE("virtualColumn name[%s] not allowed", vc.getOutputName()); } if (withDotSupport.containsKey(vc.getOutputName()) || withoutDotSupport.containsKey(vc.getOutputName())) { throw new IAE("Duplicate virtualColumn name[%s]", vc.getOutputName()); } if (vc.usesDotNotation()) { withDotSupport.put(vc.getOutputName(), vc); } else { withoutDotSupport.put(vc.getOutputName(), vc); } } return new VirtualColumns(ImmutableList.copyOf(virtualColumns), withDotSupport, withoutDotSupport); }
Source:
<code>protected void ExecuteIrsBrokerCommand() { uuidReturn = getIrsProxy().deleteImage(getParameters().getStorageDomainId().toString(), getParameters().getStoragePoolId().toString(), getParameters().getImageGroupId().toString(), <START> (Boolean.valueOf(getParameters().getPostZeros())).toString(), <END> (Boolean.valueOf(getParameters().getForceDelete())).toString().toLowerCase()); ProceedProxyReturnValue(); Guid taskID = new Guid(uuidReturn.mUuid); getVDSReturnValue().setCreationInfo( new AsyncTaskCreationInfo(taskID, AsyncTaskType.deleteImage, getParameters().getStoragePoolId())); }</code><technical_language>Instead of Boolean.valueOf(boolean).toString(), String.valueOf(boolean)</technical_language>

Target:
protected void ExecuteIrsBrokerCommand() { uuidReturn = getIrsProxy().deleteImage(getParameters().getStorageDomainId().toString(), getParameters().getStoragePoolId().toString(), getParameters().getImageGroupId().toString(), String.valueOf(getParameters().getPostZeros()), String.valueOf(getParameters().getForceDelete()).toLowerCase()); ProceedProxyReturnValue(); Guid taskID = new Guid(uuidReturn.mUuid); getVDSReturnValue().setCreationInfo( new AsyncTaskCreationInfo(taskID, AsyncTaskType.deleteImage, getParameters().getStoragePoolId())); }
Source:
<code><START> private boolean tryLoadProperty(WebContext webContext, BaseEntity<?> entity, Property property) { <END> String propertyName = property.getName(); Value parameterValue = webContext.get(propertyName); if (parameterValue.isNull()) { return false; } try { property.parseValues(entity, Values.of(parameterValue.get(List.class, Collections.singletonList(parameterValue.get())))); ensureTenantMatch(entity, property); } catch (HandledException exception) { UserContext.setFieldError(propertyName, parameterValue); UserContext.setErrorMessage(propertyName, exception.getMessage()); return true; } return false; }</code><technical_language>invert true = success false = failure</technical_language>

Target:
private boolean tryLoadProperty(WebContext webContext, BaseEntity<?> entity, Property property) { String propertyName = property.getName(); Value parameterValue = webContext.get(propertyName); if (parameterValue.isNull()) { return true; } try { property.parseValues(entity, Values.of(parameterValue.get(List.class, Collections.singletonList(parameterValue.get())))); ensureTenantMatch(entity, property); } catch (HandledException exception) { UserContext.setFieldError(propertyName, parameterValue); UserContext.setErrorMessage(propertyName, exception.getMessage()); return false; } return true; }
Source:
<code>public void canRetrieveAsJson() throws Exception { final Pull pull = repo().pulls().create("Test Pull", "blah", "aaa"); final JsonObject json = pull.json(); MatcherAssert.assertThat( json.getString("number"), Matchers.equalTo("1") ); MatcherAssert.assertThat( json.getString("head"), <START> Matchers.equalTo("blah") <END> ); MatcherAssert.assertThat( json.getString("base"), Matchers.equalTo("aaa") ); }</code><technical_language>a good idea. introducing un-obvious coupling here. I remember blah means blah 8 lines above. If in future I want change here, I find place above, in order this test valid. a variable instead. for other methods constants</technical_language>

Target:
public void canRetrieveAsJson() throws Exception { final String head = "blah"; final String base = "aaa"; final Pull pull = repo().pulls().create("Test Pull Json", head, base); final JsonObject json = pull.json(); MatcherAssert.assertThat( json.getString("number"), Matchers.equalTo("1") ); MatcherAssert.assertThat( json.getString("head"), Matchers.equalTo(head) ); MatcherAssert.assertThat( json.getString("base"), Matchers.equalTo(base) ); }
Source:
<code>public List<Map<String, Object>> getPluginsForApplication(String appName) { try { List<Map<String, Object>> returnValues = new ArrayList<>(); for (ApplicationPlugin plugin : applicationPlugins) { if (plugin.matchesAssocationName(appName)) { returnValues.add(plugin.toJSON()); } } return returnValues; <START> } catch (Exception e) { <END> LOGGER.error("Could not get plugins for application", e); throw new ApplicationServiceBeanException("Could not get plugins for application"); } }</code><technical_language>exceptions is this try/catch catch</technical_language>

Target:
public List<Map<String, Object>> getPluginsForApplication(String appName) { try { List<Map<String, Object>> returnValues = new ArrayList<>(); for (ApplicationPlugin plugin : applicationPlugins) { if (plugin.matchesAssocationName(appName)) { returnValues.add(plugin.toJSON()); } } return returnValues; } catch (VirtualMachineError e) { throw e; } catch (Throwable e) { LOGGER.info("Could not retrieve plugins for application", e); throw new ApplicationServiceBeanException("Could not get plugins for application"); } }
Source:
<code>private void dispatch() { if (isDbInBadState()) { return; } CommCareApp currentApp = CommCareApplication._().getCurrentApp(); if (currentApp == null) { if (CommCareApplication._().usableAppsPresent()) { CommCareApplication._().initFirstUsableAppRecord(); dispatch(); return; } else { Intent i = new Intent(getApplicationContext(), CommCareSetupActivity.class); this.startActivityForResult(i, INIT_APP); } } else { if (CommCareApplication._().isConsumerApp() && !alreadyCheckedForAppFilesChange) { checkForChangedCCZ(); <START> return; <END> } ApplicationRecord currentRecord = currentApp.getAppRecord(); try { if (currentApp.getAppResourceState() == CommCareApplication.STATE_CORRUPTED) { handleDamagedApp(); } else if (!currentRecord.isUsable()) { boolean unseated = handleUnusableApp(currentRecord); if (unseated) { dispatch(); } } else if (!CommCareApplication._().getSession().isActive()) { launchLoginScreen(); } else if (this.getIntent().hasExtra(SESSION_REQUEST)) { handleExternalLaunch(); } else if (this.getIntent().hasExtra(AndroidShortcuts.EXTRA_KEY_SHORTCUT) && !shortcutExtraWasConsumed) { handleShortcutLaunch(); } else { launchHomeScreen(); } } catch (SessionUnavailableException sue) { launchLoginScreen(); } } }</code><technical_language>return is needed creates a lint warning</technical_language>

Target:
private void dispatch() { if (isDbInBadState()) { return; } CommCareApp currentApp = CommCareApplication._().getCurrentApp(); if (currentApp == null) { if (CommCareApplication._().usableAppsPresent()) { CommCareApplication._().initFirstUsableAppRecord(); dispatch(); } else { Intent i = new Intent(getApplicationContext(), CommCareSetupActivity.class); this.startActivityForResult(i, INIT_APP); } } else { if (CommCareApplication._().isConsumerApp() && !alreadyCheckedForAppFilesChange) { checkForChangedCCZ(); return; } ApplicationRecord currentRecord = currentApp.getAppRecord(); try { if (currentApp.getAppResourceState() == CommCareApplication.STATE_CORRUPTED) { handleDamagedApp(); } else if (!currentRecord.isUsable()) { boolean unseated = handleUnusableApp(currentRecord); if (unseated) { dispatch(); } } else if (!CommCareApplication._().getSession().isActive()) { launchLoginScreen(); } else if (this.getIntent().hasExtra(SESSION_REQUEST)) { handleExternalLaunch(); } else if (this.getIntent().hasExtra(AndroidShortcuts.EXTRA_KEY_SHORTCUT) && !shortcutExtraWasConsumed) { handleShortcutLaunch(); } else { launchHomeScreen(); } } catch (SessionUnavailableException sue) { launchLoginScreen(); } } }
Source:
<code>public Response toResponse(GitException exception) { if (exception instanceof GitRefNotFoundException) return Response.status(Response.Status.NOT_FOUND) .entity(DtoFactory.getInstance().toJson(exception.getServiceError())) .type(MediaType.APPLICATION_JSON).build(); else if (exception instanceof GitInvalidRefNameException) <START> return Response.status(Response.Status.UNAUTHORIZED) <END> .entity(DtoFactory.getInstance().toJson(exception.getServiceError())) .type(MediaType.APPLICATION_JSON).build(); else if (exception instanceof GitRefAlreadyExistsException) return Response.status(Response.Status.BAD_REQUEST) .entity(DtoFactory.getInstance().toJson(exception.getServiceError())) .type(MediaType.APPLICATION_JSON).build(); else if (exception instanceof GitConflictException) { ConflictExceptionError conflictExceptionError = DtoFactory.getInstance() .createDto(ConflictExceptionError.class) .withMessage(exception.getServiceError().getMessage()) .withConflictingPaths(((GitConflictException) exception).getConflictPaths()); return Response.status(Response.Status.CONFLICT) .entity(DtoFactory.getInstance().toJson(conflictExceptionError)) .type(MediaType.APPLICATION_JSON).build(); } else if (exception instanceof GitException) return Response.serverError().entity(DtoFactory.getInstance().toJson(exception.getServiceError())) .type(MediaType.APPLICATION_JSON).build(); else return Response.serverError().entity(DtoFactory.getInstance().toJson(exception.getServiceError())) .type(MediaType.APPLICATION_JSON).build(); }</code><technical_language>UNAUTHORIZED</technical_language>

Target:
public Response toResponse(GitException exception) { if (exception instanceof GitRefNotFoundException) return Response.status(Response.Status.NOT_FOUND) .entity(DtoFactory.getInstance().toJson(exception.getServiceError())) .type(MediaType.APPLICATION_JSON).build(); else if (exception instanceof GitInvalidRefNameException) return Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity(DtoFactory.getInstance().toJson(exception.getServiceError())) .type(MediaType.APPLICATION_JSON).build(); else if (exception instanceof GitRefAlreadyExistsException) return Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity(DtoFactory.getInstance().toJson(exception.getServiceError())) .type(MediaType.APPLICATION_JSON).build(); else if (exception instanceof GitConflictException) { ConflictExceptionError conflictExceptionError = newDto(ConflictExceptionError.class).withMessage(exception.getServiceError().getMessage()) .withConflictingPaths(((GitConflictException) exception).getConflictPaths()); return Response.status(Response.Status.CONFLICT) .entity(DtoFactory.getInstance().toJson(conflictExceptionError)) .type(MediaType.APPLICATION_JSON).build(); } return Response.serverError() .entity(DtoFactory.getInstance() .toJson(exception.getServiceError())) .type(MediaType.APPLICATION_JSON).build(); }
Source:
<code>public Iterable<Node> treeIterable(TreeTraversal traversal) { <START> return () -> treeIterator(traversal); <END> }</code><technical_language>Wow</technical_language>

Target:
private Iterable<Node> treeIterable(TreeTraversal traversal) { return () -> treeIterator(traversal); }
Source:
<code>public void execute() { if (shouldRetry()) { LOG.warn("Retry #" + numFailures + ": Going to sleep for " + retryInterval + " milliseconds."); sleep(retryInterval); <START> retryInterval <<= 1; <END> } }</code><technical_language>Whoa a while bitshift code - fancy C stuff here</technical_language>

Target:
public boolean execute() { if (succeeded || numFailures == 0 || numFailures > maxRetries) { return false; } LOG.warn("Retry #" + numFailures + ": Going to sleep for " + retryInterval + " milliseconds."); sleep(retryInterval); retryInterval *= multiplier; return true; }
Source:
<code>void reset() { m_syncedSinceLastEdit = false; if (m_segmentHeaderBuf != null) { m_segmentHeaderBuf.discard(); m_segmentHeaderBuf = null; } if (m_entryHeaderBuf != null) { m_entryHeaderBuf.discard(); m_entryHeaderBuf = null; } m_crc.reset(); <START> m_crc.reset(); <END> }</code><technical_language>Duplicated line (probably global replace)</technical_language>

Target:
void reset() { m_syncedSinceLastEdit = false; if (m_segmentHeaderBuf != null) { m_segmentHeaderBuf.discard(); m_segmentHeaderBuf = null; } if (m_entryHeaderBuf != null) { m_entryHeaderBuf.discard(); m_entryHeaderBuf = null; } }
Source:
<code><START> public void testDmPingResponse() throws IllegalAccessException, InterruptedException { <END> MsgEcho ping = new MsgEcho( "PING:TEST" ); AgentMessageProcessor processor = (AgentMessageProcessor) this.agent.getMessagingClient().getMessageProcessor(); processor.processMessage( ping ); List<Message> messages = this.client.messagesForTheDm; Assert.assertEquals( 1, messages.size()); Message message = messages.get(0); Assert.assertTrue( message instanceof MsgEcho ); MsgEcho echo = (MsgEcho) message; Assert.assertEquals( "PONG:TEST", echo.getContent()); Assert.assertEquals( ping.getUuid(), echo.getUuid()); }</code><technical_language>No, this method throw interrupted exceptions</technical_language>

Target:
public void testDmPingResponse() throws IllegalAccessException { MsgEcho ping = new MsgEcho( "PING:TEST" ); AgentMessageProcessor processor = (AgentMessageProcessor) this.agent.getMessagingClient().getMessageProcessor(); processor.processMessage( ping ); List<Message> messages = this.client.messagesForTheDm; Assert.assertEquals( 1, messages.size()); Message message = messages.get(0); Assert.assertTrue( message instanceof MsgEcho ); MsgEcho echo = (MsgEcho) message; Assert.assertEquals( "PONG:TEST", echo.getContent()); Assert.assertEquals( ping.getUuid(), echo.getUuid()); }
Source:
<code>public PatternBasedHeaderMatcher(Collection<String> patterns) { <START> this(patterns, false); <END> }</code><technical_language>is PR code, I share concern: for (String pattern : this.patterns) { if (PatternMatchUtils.simpleMatch(pattern.toLowerCase(), header)) { pattern.toLowerCase() done initialization, header</technical_language>

Target:
public PatternBasedHeaderMatcher(Collection<String> patterns) { Assert.notNull(patterns, "Patterns must no be null"); Assert.notEmpty(patterns, "At least one pattern must be specified"); for (String pattern : patterns) { this.patterns.add(pattern.toLowerCase()); } }
Source:
<code><START> public String getDirectoryUrl() { <END> return directoryAsyncClient.getDirectoryUrl(); }</code><technical_language>This return a URL</technical_language>

Target:
public URL getDirectoryUrl() { return directoryAsyncClient.getDirectoryUrl(); }
Source:
<code>private void saveAndSetHeaders(final Message message, final PendingReply pendingReply, String messageTag) { String savedReplyTo = message.getMessageProperties().getReplyTo(); pendingReply.setSavedReplyTo(savedReplyTo); if (StringUtils.hasLength(savedReplyTo) && logger.isDebugEnabled()) { logger.debug("Replacing replyTo header:" + savedReplyTo <START> + " in favor of template's configured reply-queue:" <END> + RabbitTemplate.this.replyAddress); } message.getMessageProperties().setReplyTo(RabbitTemplate.this.replyAddress); String savedCorrelation = null; if (this.correlationKey == null) { String correlationId = message.getMessageProperties().getCorrelationId(); if (correlationId != null) { savedCorrelation = correlationId; } } else { savedCorrelation = (String) message.getMessageProperties() .getHeaders().get(RabbitTemplate.this.correlationKey); } pendingReply.setSavedCorrelation(savedCorrelation); if (this.correlationKey == null) { message.getMessageProperties().setCorrelationId(messageTag); } else { message.getMessageProperties().setHeader(this.correlationKey, messageTag); } }</code><technical_language>Whitespaces colons</technical_language>

Target:
private void saveAndSetHeaders(final Message message, final PendingReply pendingReply, String messageTag) { String savedReplyTo = message.getMessageProperties().getReplyTo(); pendingReply.setSavedReplyTo(savedReplyTo); if (StringUtils.hasLength(savedReplyTo) && logger.isDebugEnabled()) { logger.debug("Replacing replyTo header: " + savedReplyTo + " in favor of template's configured reply-queue:" + RabbitTemplate.this.replyAddress); } message.getMessageProperties().setReplyTo(this.replyAddress); String savedCorrelation = null; if (this.correlationKey == null) { String correlationId = message.getMessageProperties().getCorrelationId(); if (correlationId != null) { savedCorrelation = correlationId; } } else { savedCorrelation = (String) message.getMessageProperties() .getHeaders().get(this.correlationKey); } pendingReply.setSavedCorrelation(savedCorrelation); if (this.correlationKey == null) { message.getMessageProperties().setCorrelationId(messageTag); } else { message.getMessageProperties().setHeader(this.correlationKey, messageTag); } }
Source:
<code>private boolean isValid(Repository repo, Block block) { boolean isValid = true; if (!block.isGenesis()) { <START> <END> String trieHash = toHexString(block.getTxTrieRoot()); String trieListHash = toHexString(calcTxTrie(block.getTransactionsList())); if (!trieHash.equals(trieListHash)) { logger.warn("Block's given Trie Hash doesn't match: != {}", trieHash, trieListHash); return false; } List<Transaction> txs = block.getTransactionsList(); if (!txs.isEmpty()) { Map<ByteArrayWrapper, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { byte[] txSender = tx.getSender(); if (txSender == null) { logger.warn("Invalid transaction: sender in tx with rlp={} is null." + "Not valid until EIP-86", ByteUtil.toHexString(tx.getEncoded())); return false; } ByteArrayWrapper key = new ByteArrayWrapper(txSender); BigInteger expectedNonce = curNonce.get(key); if (expectedNonce == null) { expectedNonce = repo.getNonce(txSender); } curNonce.put(key, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce != expected nonce (parent nonce: {}): {}", txNonce, expectedNonce, repo.getNonce(txSender), tx); return false; } } } } return isValid; }</code><technical_language>sense leave this check if heavy? leave default add a flag skip check soon is needed</technical_language>

Target:
private boolean isValid(Repository repo, Block block) { boolean isValid = true; if (!block.isGenesis()) { isValid = isValid(block.getHeader()); String trieHash = toHexString(block.getTxTrieRoot()); String trieListHash = toHexString(calcTxTrie(block.getTransactionsList())); if (!trieHash.equals(trieListHash)) { logger.warn("Block's given Trie Hash doesn't match: != {}", trieHash, trieListHash); return false; } List<Transaction> txs = block.getTransactionsList(); if (!txs.isEmpty()) { Map<ByteArrayWrapper, BigInteger> curNonce = new HashMap<>(); for (Transaction tx : txs) { byte[] txSender = tx.getSender(); if (txSender == null) { logger.warn("Invalid transaction: sender in tx with rlp={} is null." + "Not valid until EIP-86", ByteUtil.toHexString(tx.getEncoded())); return false; } ByteArrayWrapper key = new ByteArrayWrapper(txSender); BigInteger expectedNonce = curNonce.get(key); if (expectedNonce == null) { expectedNonce = repo.getNonce(txSender); } curNonce.put(key, expectedNonce.add(ONE)); BigInteger txNonce = new BigInteger(1, tx.getNonce()); if (!expectedNonce.equals(txNonce)) { logger.warn("Invalid transaction: Tx nonce != expected nonce (parent nonce: {}): {}", txNonce, expectedNonce, repo.getNonce(txSender), tx); return false; } } } } return isValid; }
Source:
<code>public synchronized AsyncJobStatus cancelJob(String jobId) { if (jobId == null || jobId.isEmpty()) { throw new IllegalArgumentException("jobId is null or empty"); } <START> AsyncJobStatus status = this.jobCurator.lockAndLoad(jobId); <END> if (status != null) { if (status.getState().isTerminal()) { throw new IllegalStateException("job is already in a terminal state: " + status); } if (status.getState() != JobState.RUNNING) { this.setJobState(status, JobState.CANCELED); } else { log.warn("Attempting to cancel job that's already running: {}", status); if (status.getMaxAttempts() > 1) { log.warn("Setting max attempts to: 1"); status.setMaxAttempts(1); } } status = this.jobCurator.merge(status); } return status; }</code><technical_language>Do need a lock? optimistic "update where" & react appropriately if update fails update rows</technical_language>

Target:
public synchronized AsyncJobStatus cancelJob(String jobId) { if (jobId == null || jobId.isEmpty()) { throw new IllegalArgumentException("jobId is null or empty"); } AsyncJobStatus status = this.jobCurator.get(jobId); if (status != null) { if (status.getState().isTerminal()) { throw new IllegalStateException("job is already in a terminal state: " + status); } if (status.getState() != JobState.RUNNING) { this.setJobState(status, JobState.CANCELED); } else { log.warn("Attempting to cancel job that's already running: {}", status); if (status.getMaxAttempts() > 1) { log.warn("Setting max attempts to: 1"); status.setMaxAttempts(1); } } status = this.jobCurator.merge(status); } return status; }
Source:
<code>private Pool createBonusPool(Pool masterPool, List<Pool> existingPools) { Map<String, String> attributes = PoolHelper.getFlattenedAttributes(masterPool.getProduct()); String virtQuantity = getVirtQuantity(attributes.get("virt_limit"), masterPool.getQuantity()); log.info("Checking if bonus pools need to be created for pool: {}", masterPool); if (attributes.containsKey("virt_limit") && virtQuantity != null) { <START> if (!hasBonusPool(existingPools)) { <END> boolean hostLimited = attributes.containsKey("host_limited") && attributes.get("host_limited").equals("true"); HashMap<String, String> virtAttributes = new HashMap<String, String>(); virtAttributes.put("virt_only", "true"); virtAttributes.put("pool_derived", "true"); virtAttributes.put("physical_only", "false"); if (hostLimited || config.getBoolean(ConfigProperties.STANDALONE)) { virtAttributes.put("unmapped_guests_only", "true"); } virtAttributes.put("virt_limit", "0"); Product sku = masterPool.getDerivedProduct() != null ? masterPool.getDerivedProduct() : masterPool.getProduct(); Pool bonusPool = PoolHelper.clonePool(masterPool, sku, virtQuantity, virtAttributes, "derived", prodCurator, null); log.info("Creating new derived pool: {}", bonusPool); return bonusPool; } else { Pool bonus = getBonusPool(existingPools); long virtLong = -1L; try { virtLong = Long.parseLong(virtQuantity); } catch (NumberFormatException pe) { } if (virtLong != bonus.getQuantity()) { bonus.setQuantity(virtLong); poolManager.setPoolQuantity(bonus, virtLong); return bonus; } } } return null; }</code><technical_language>is : java Pool bonusPool = getBonusPool(existingPools); if(bonusPool == null) { //create bonus pool } else { //update pool if needed } this we: - iterate pools - get clean hasBonusPool method</technical_language>

Target:
private Pool createBonusPool(Pool masterPool, List<Pool> existingPools) { Map<String, String> attributes = masterPool.getProductAttributes(); String virtQuantity = getVirtQuantity( attributes.get(Product.Attributes.VIRT_LIMIT), masterPool.getQuantity() ); log.info("Checking if bonus pools need to be created for pool: {}", masterPool); if (attributes.containsKey(Product.Attributes.VIRT_LIMIT) && !hasBonusPool(existingPools) && virtQuantity != null) { boolean hostLimited = "true".equals(attributes.get(Product.Attributes.HOST_LIMITED)); HashMap<String, String> virtAttributes = new HashMap<String, String>(); virtAttributes.put(Pool.Attributes.VIRT_ONLY, "true"); virtAttributes.put(Pool.Attributes.DERIVED_POOL, "true"); virtAttributes.put(Pool.Attributes.PHYSICAL_ONLY, "false"); if (hostLimited || config.getBoolean(ConfigProperties.STANDALONE)) { virtAttributes.put(Pool.Attributes.UNMAPPED_GUESTS_ONLY, "true"); } virtAttributes.put(Product.Attributes.VIRT_LIMIT, "0"); Product sku = masterPool.getDerivedProduct() != null ? masterPool.getDerivedProduct() : masterPool.getProduct(); Pool bonusPool = PoolHelper.clonePool(masterPool, sku, virtQuantity, virtAttributes, "derived", ownerProductCurator, null, productCurator); log.info("Creating new derived pool: {}", bonusPool); return bonusPool; } return null; }
Source:
<code>protected void executeVmCommand() { if (shouldAddLease(getVm())) { if <START> (FeatureSupported.isVmLeasesSupported(getVm().getCompatibilityVersion())) <END> { if (!addVmLease(getVm().getLeaseStorageDomainId(), getVm().getId())) { getVm().setLeaseStorageDomainId(null); } } else { getVm().setLeaseStorageDomainId(null); auditLogDirector.log(this, AuditLogType.CANNOT_IMPORT_VM_WITH_LEASE_COMPAT_VERSION); } } super.executeVmCommand(); }</code><technical_language>effective compatibility version is correct well, 'getEffectiveCompatibilityVersion', I</technical_language>

Target:
protected void executeVmCommand() { if (shouldAddLease(getVm())) { if (FeatureSupported.isVmLeasesSupported(getEffectiveCompatibilityVersion())) { if (!addVmLease(getVm().getLeaseStorageDomainId(), getVm().getId())) { getVm().setLeaseStorageDomainId(null); } } else { getVm().setLeaseStorageDomainId(null); auditLogDirector.log(this, AuditLogType.CANNOT_IMPORT_VM_WITH_LEASE_COMPAT_VERSION); } } super.executeVmCommand(); }
Source:
<code>public ProjectStatusWsResponse.ProjectStatus format() { if (!optionalMeasureData.isPresent()) { return newResponseWithoutQualityGateDetails(); } JsonParser parser = new JsonParser(); JsonObject json = parser.parse(optionalMeasureData.get()).getAsJsonObject(); ProjectStatusWsResponse.Status qualityGateStatus = measureLevelToQualityGateStatus(json.get("level").getAsString()); projectStatusBuilder.setStatus(qualityGateStatus); JsonElement ignoredConditions = json.get("ignoredConditions"); if (ignoredConditions != null) { projectStatusBuilder.setIgnoredConditions(ignoredConditions.getAsBoolean()); } else { projectStatusBuilder.setIgnoredConditions(false); } formatConditions(json.getAsJsonArray("conditions")); <START> formatPeriods(); <END> return projectStatusBuilder.build(); }</code><technical_language>extract in method formatIgnoredConditions</technical_language>

Target:
public ProjectStatusWsResponse.ProjectStatus format() { if (!optionalMeasureData.isPresent()) { return newResponseWithoutQualityGateDetails(); } JsonParser parser = new JsonParser(); JsonObject json = parser.parse(optionalMeasureData.get()).getAsJsonObject(); ProjectStatusWsResponse.Status qualityGateStatus = measureLevelToQualityGateStatus(json.get("level").getAsString()); projectStatusBuilder.setStatus(qualityGateStatus); formatIgnoredConditions(json); formatConditions(json.getAsJsonArray("conditions")); formatPeriods(); return projectStatusBuilder.build(); }
Source:
<code>protected File findPom(String side, String version, File json) throws IOException { File pom = cache("versions", version, side + ".pom"); HashStore cache = new HashStore(this.cache).load(cache("versions", version, side + ".pom.input")); if ("client".equals(side)) { cache.add(json); } if (!cache.isSame() || !pom.exists()) { POMBuilder builder = new POMBuilder(GROUP, side, version); if ("client".equals(side)) { VersionJson meta = Utils.loadJson(json, VersionJson.class); for (VersionJson.Library lib : meta.libraries) { if (lib.downloads.classifiers != null) { if (lib.downloads.classifiers.containsKey("test")) { builder.dependencies().add(lib.name, "test").withClassifier("test"); } if (lib.natives != null && lib.natives.containsKey(CURRENT_OS) && !lib.getArtifact().getName().contains("java-objc-bridge")) { builder.dependencies().add(lib.name, "runtime").withClassifier(lib.natives.get(CURRENT_OS)); } } else { <START> builder.dependencies().add(lib.name, "compile"); <END> } } } else { builder.dependencies().add(GROUP + ":" + side + ":" + version, "compile").withClassifier("extra"); } builder.dependencies().add(GROUP + ":" + side + ":" + version, "compile").withClassifier("data"); builder.dependencies().add("com.google.code.findbugs:jsr305:3.0.1", "compile"); String ret = builder.tryBuild(); if (ret == null) { return null; } FileUtils.writeByteArrayToFile(pom, ret.getBytes()); cache.save(); Utils.updateHash(pom); } return pom; }</code><technical_language>This correct, want main artifact classified one..</technical_language>

Target:
protected File findPom(String side, String version, File json) throws IOException { File pom = cache("versions", version, side + ".pom"); HashStore cache = new HashStore(this.cache).load(cache("versions", version, side + ".pom.input")); if ("client".equals(side)) { cache.add(json); } if (!cache.isSame() || !pom.exists()) { POMBuilder builder = new POMBuilder(GROUP, side, version); if ("client".equals(side)) { VersionJson meta = Utils.loadJson(json, VersionJson.class); for (VersionJson.Library lib : meta.libraries) { builder.dependencies().add(lib.name, "compile"); if (lib.downloads.classifiers != null) { if (lib.downloads.classifiers.containsKey("test")) { builder.dependencies().add(lib.name, "test").withClassifier("test"); } if (lib.natives != null && lib.natives.containsKey(CURRENT_OS) && !lib.getArtifact().getName().contains("java-objc-bridge")) { builder.dependencies().add(lib.name, "runtime").withClassifier(lib.natives.get(CURRENT_OS)); } } } } else { builder.dependencies().add(GROUP + ":" + side + ":" + version, "compile").withClassifier("extra"); } builder.dependencies().add(GROUP + ":" + side + ":" + version, "compile").withClassifier("data"); builder.dependencies().add("com.google.code.findbugs:jsr305:3.0.1", "compile"); String ret = builder.tryBuild(); if (ret == null) { return null; } FileUtils.writeByteArrayToFile(pom, ret.getBytes()); cache.save(); Utils.updateHash(pom); } return pom; }
Source:
<code>static <T> T build( StructureBuilder<AnyValue,T> builder, MapValue map ) { if ( map.size() == 0 ) { <START> throw new InvalidTemporalArgumentException( "At least one temporal unit must be specified." ); <END> } return build( builder, map.entrySet() ); }</code><technical_language>message get (just out of curiosity)</technical_language>

Target:
static <T> T build( StructureBuilder<AnyValue,T> builder, MapValue map ) { if ( map.size() == 0 ) { throw new InvalidValuesArgumentException( "At least one temporal unit must be specified." ); } return build( builder, map.entrySet() ); }
Source:
<code>public String evaluate( String referer ) { <START> ExternalSearch es_inst = ExternalSearch.getInstance(); <END> return es_inst.refererClassify( referer ); }</code><technical_language>Please Change externalSearch</technical_language>

Target:
public String evaluate( String referer ) { ExternalSearch externalSearch = ExternalSearch.getInstance(); return externalSearch.refererClassify( referer ); }
Source:
<code>public boolean hasMethod(String method) { Object obj = properties.get(method); <START> if(obj != null) { <END> return (obj instanceof MethodHandle); } else { return false; } }</code><technical_language>if space ( (...)</technical_language>

Target:
public boolean hasMethod(String method) { Object obj = properties.get(method); if (obj != null) { return (obj instanceof MethodHandle); } return false; }
Source:
<code>public void logIn(HttpServletRequest request, HttpServletResponse response, Member member) { try { Authentication authentication = authenticationService.authenticate(request, response, member); <START> authenticationSuccessHandler.onAuthenticationSuccess(request, response, authentication, false); <END> } catch (IOException e) { authenticationService.logout(request, response); throw new InternalException(e); } }</code><technical_language>is false coming is false? Consider moving a variable name easier understand code</technical_language>

Target:
public void logIn(HttpServletRequest request, HttpServletResponse response, Member member) { try { Authentication authentication = authenticationService.authenticate(request, response, member); final boolean redirectOnSuccess = false; authenticationSuccessHandler.onAuthenticationSuccess(request, response, authentication, redirectOnSuccess); } catch (IOException e) { authenticationService.logout(request, response); throw new InternalException(e); } }
Source:
<code>public boolean isEnabled() { return <START> getActiveTextEditor() != null; <END> }</code><technical_language>return 'true'</technical_language>

Target:
public boolean isEnabled() { return true; }
Source:
<code>private Optional<Stage> getStageFromRequestParam(Request request, HttpOperationResult operationResult) { String pipelineName = request.params("pipeline_name"); String pipelineCounter = request.params("pipeline_counter"); String stageName = request.params("stage_name"); String stageCounter = request.params("stage_counter"); Stage stage = stageService.findStageWithIdentifier(pipelineName, Integer.parseInt(pipelineCounter), stageName, stageCounter, currentUsername().getUsername().toString(), operationResult); if (!operationResult.isSuccess()) { return Optional.empty(); } if (stage == null || stage instanceof NullStage) { <START> String message = String.format("Stage '%s' not found", stageName); <END> operationResult.notFound("Not Found", message, HealthStateType.general(HealthStateScope.GLOBAL)); return Optional.empty(); } return Optional.ofNullable(stage); }</code><technical_language>I this message change, get a NullStage for a wrong stage counter</technical_language>

Target:
private Optional<Stage> getStageFromRequestParam(Request request, HttpOperationResult operationResult) { String pipelineName = request.params("pipeline_name"); String pipelineCounter = request.params("pipeline_counter"); String stageName = request.params("stage_name"); String stageCounter = request.params("stage_counter"); Stage stage = stageService.findStageWithIdentifier(pipelineName, Integer.parseInt(pipelineCounter), stageName, stageCounter, currentUsername().getUsername().toString(), operationResult); if (!operationResult.isSuccess()) { return Optional.empty(); } if (stage == null || stage instanceof NullStage) { String message = String.format("Stage '%s' with counter '%s' not found. Please make sure specified stage or stage run with specified counter exists.", stageName, stageCounter); operationResult.notFound("Not Found", message, HealthStateType.general(HealthStateScope.GLOBAL)); return Optional.empty(); } return Optional.ofNullable(stage); }
Source:
<code>public boolean canReadCommit(RevWalk rw, RevCommit commit) { NameKey projName = state.getProject().getNameKey(); try { Repository repo = repoManager.openRepository(projName); try { for (Entry<String, Ref> entry : repo.getAllRefs().entrySet()) { String refName = entry.getKey(); <START> if (refName.startsWith("refs/changes") || refName.startsWith("refs/cache-automerge")) { <END> continue; } RevCommit tip; try { tip = rw.parseCommit(entry.getValue().getObjectId()); } catch (IncorrectObjectTypeException e) { continue; } if (rw.isMergedInto(commit, tip) && controlForRef(entry.getKey()).canPerform(Permission.READ)) { return true; } } } finally { repo.close(); } } catch (IOException e) { String msg = String.format( "Cannot verify permissions to commit object %s in repository %s", commit.name(), projName.get()); log.error(msg, e); } return controlForRef("refs/*").canPerform(Permission.READ); }</code><technical_language>1. "refs/notes/" excluded 2. more sense check opposite: if (!refName.startsWith("refs/heads/") && !refName.startsWith("refs/tags/")) { continue; } I guess is more in Gerrit introduce a new "refs/xyz" namespace require change add this exception Git introduce a new namespace for branches tags. Alternatively, instead of getAllRefs() filtering out is necessary, getRefs(Constants.R_HEADS) getRefs(Constants.R_TAGS) fetch (sub)set of references interested into</technical_language>

Target:
public boolean canReadCommit(RevWalk rw, RevCommit commit) { NameKey projName = state.getProject().getNameKey(); try { Repository repo = repoManager.openRepository(projName); try { for (Entry<String, Ref> entry : repo.getAllRefs().entrySet()) { String refName = entry.getKey(); if (!refName.startsWith("refs/heads") && !refName.startsWith("refs/tags")) { continue; } RevCommit tip; try { tip = rw.parseCommit(entry.getValue().getObjectId()); } catch (IncorrectObjectTypeException e) { continue; } if (rw.isMergedInto(commit, tip) && controlForRef(entry.getKey()).canPerform(Permission.READ)) { return true; } } } finally { repo.close(); } } catch (IOException e) { String msg = String.format( "Cannot verify permissions to commit object %s in repository %s", commit.name(), projName.get()); log.error(msg, e); } return controlForRef("refs/*").canPerform(Permission.READ); }
Source:
<code>private void createIndexToolTables(Connection connection) throws Exception { ConnectionQueryServices queryServices = connection.unwrap(PhoenixConnection.class).getQueryServices(); Admin admin = queryServices.getAdmin(); <START> if (!admin.tableExists(TableName.valueOf(OUTPUT_TABLE_NAME))) { <END> HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf(OUTPUT_TABLE_NAME)); tableDescriptor.setValue("DISABLE_TABLE_SOR", "true"); tableDescriptor.setValue(HColumnDescriptor.TTL, String.valueOf(MetaDataProtocol.DEFAULT_LOG_TTL)); HColumnDescriptor columnDescriptor = new HColumnDescriptor(OUTPUT_TABLE_COLUMN_FAMILY); tableDescriptor.addFamily(columnDescriptor); admin.createTable(tableDescriptor); } if (!admin.tableExists(TableName.valueOf(RESULT_TABLE_NAME))) { HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf(RESULT_TABLE_NAME)); tableDescriptor.setValue("DISABLE_TABLE_SOR", "true"); tableDescriptor.setValue(HColumnDescriptor.TTL, String.valueOf(MetaDataProtocol.DEFAULT_LOG_TTL)); HColumnDescriptor columnDescriptor = new HColumnDescriptor(RESULT_TABLE_COLUMN_FAMILY); tableDescriptor.addFamily(columnDescriptor); admin.createTable(tableDescriptor); } }</code><technical_language>this work a cluster namespaces enabled</technical_language>

Target:
private void createIndexToolTables(Connection connection) throws Exception { ConnectionQueryServices queryServices = connection.unwrap(PhoenixConnection.class).getQueryServices(); Admin admin = queryServices.getAdmin(); if (!admin.tableExists(TableName.valueOf(OUTPUT_TABLE_NAME))) { HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf(OUTPUT_TABLE_NAME)); tableDescriptor.setValue(HColumnDescriptor.TTL, String.valueOf(MetaDataProtocol.DEFAULT_LOG_TTL)); HColumnDescriptor columnDescriptor = new HColumnDescriptor(OUTPUT_TABLE_COLUMN_FAMILY); tableDescriptor.addFamily(columnDescriptor); admin.createTable(tableDescriptor); } if (!admin.tableExists(TableName.valueOf(RESULT_TABLE_NAME))) { HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf(RESULT_TABLE_NAME)); tableDescriptor.setValue(HColumnDescriptor.TTL, String.valueOf(MetaDataProtocol.DEFAULT_LOG_TTL)); HColumnDescriptor columnDescriptor = new HColumnDescriptor(RESULT_TABLE_COLUMN_FAMILY); tableDescriptor.addFamily(columnDescriptor); admin.createTable(tableDescriptor); } }
Source:
<code>private void possiblyResetOffsetsOrWait( Map<TopicPartition, Long> outOfRangePartitions, KafkaConsumer<byte[], byte[]> consumer, TaskToolbox taskToolbox ) throws InterruptedException, IOException { final Map<TopicPartition, Long> resetPartitions = Maps.newHashMap(); boolean doReset = false; if (tuningConfig.isResetOffsetAutomatically()) { for (Map.Entry<TopicPartition, Long> outOfRangePartition : outOfRangePartitions.entrySet()) { final TopicPartition topicPartition = outOfRangePartition.getKey(); final long nextOffset = outOfRangePartition.getValue(); <START> consumer.seekToBeginning(Lists.newArrayList(topicPartition)); <END> final long leastAvailableOffset = consumer.position(topicPartition); consumer.seek(topicPartition, nextOffset); if (leastAvailableOffset > nextOffset) { doReset = true; resetPartitions.put(topicPartition, nextOffset); } } } if (doReset) { sendResetRequestAndWait(resetPartitions, taskToolbox); } else { log.warn("Retrying in %dms", POLL_RETRY_MS); pollRetryLock.lockInterruptibly(); try { long nanos = TimeUnit.MILLISECONDS.toNanos(POLL_RETRY_MS); while (nanos > 0L && !pauseRequested && !stopRequested) { nanos = isAwaitingRetry.awaitNanos(nanos); } } finally { pollRetryLock.unlock(); } } }</code><technical_language>Collections.singletonList()</technical_language>

Target:
private void possiblyResetOffsetsOrWait( Map<TopicPartition, Long> outOfRangePartitions, KafkaConsumer<byte[], byte[]> consumer, TaskToolbox taskToolbox ) throws InterruptedException, IOException { final Map<TopicPartition, Long> resetPartitions = Maps.newHashMap(); boolean doReset = false; if (tuningConfig.isResetOffsetAutomatically()) { for (Map.Entry<TopicPartition, Long> outOfRangePartition : outOfRangePartitions.entrySet()) { final TopicPartition topicPartition = outOfRangePartition.getKey(); final long nextOffset = outOfRangePartition.getValue(); consumer.seekToBeginning(Collections.singletonList(topicPartition)); final long leastAvailableOffset = consumer.position(topicPartition); consumer.seek(topicPartition, nextOffset); if (leastAvailableOffset > nextOffset) { doReset = true; resetPartitions.put(topicPartition, nextOffset); } } } if (doReset) { sendResetRequestAndWait(resetPartitions, taskToolbox); } else { log.warn("Retrying in %dms", POLL_RETRY_MS); pollRetryLock.lockInterruptibly(); try { long nanos = TimeUnit.MILLISECONDS.toNanos(POLL_RETRY_MS); while (nanos > 0L && !pauseRequested && !stopRequested) { nanos = isAwaitingRetry.awaitNanos(nanos); } } finally { pollRetryLock.unlock(); } } }