auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testNoShrink_SameNullable() throws SQLException { executeSql("create table SOMETABLE (PID bigint not null, TEXTCOL varchar(255), newcol bigint)"); ModifyColumnTask task = new ModifyColumnTask(); task.setTableName("SOMETABLE"); task.setColumnName("TEXTCOL"); task.setColumnType(AddColumnTask.ColumnTypeEnum.STRING); task.setNullable(true); task.setColumnLength(200); getMigrator().setNoColumnShrink(true); getMigrator().addTask(task); getMigrator().migrate(); assertEquals("varchar(255)", JdbcUtils.getColumnType(getConnectionProperties(), "SOMETABLE", "TEXTCOL")); getMigrator().migrate(); getMigrator().migrate(); }

Target:
public void testNoShrink_SameNullable() throws SQLException { executeSql("create table SOMETABLE (PID bigint not null, TEXTCOL varchar(255), newcol bigint)"); ModifyColumnTask task = new ModifyColumnTask(); task.setTableName("SOMETABLE"); task.setColumnName("TEXTCOL"); task.setColumnType(AddColumnTask.ColumnTypeEnum.STRING); task.setNullable(true); task.setColumnLength(200); getMigrator().setNoColumnShrink(true); getMigrator().addTask(task); getMigrator().migrate(); assertEquals(0, task.getExecutedStatements().size()); assertEquals(new JdbcUtils.ColumnType(BaseTableColumnTypeTask.ColumnTypeEnum.STRING, 255), JdbcUtils.getColumnType(getConnectionProperties(), "SOMETABLE", "TEXTCOL")); getMigrator().migrate(); getMigrator().migrate(); }
Source:
public boolean tryAdd(final EventData eventData) { if (eventData == null) { throw new IllegalArgumentException("eventData cannot be null"); } final int size; try { size = getSize(eventData, events.isEmpty()); } catch (java.nio.BufferOverflowException exception) { throw new AmqpException(false, ErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, String.format(Locale.US, "Size of the payload exceeded maximum message size: %s kb", maxMessageSize / 1024), contextProvider.getErrorContext()); } synchronized (lock) { if (this.currentSize + size > this.maxMessageSize) { return false; } this.currentSize += size; } this.events.add(eventData); return true; }

Target:
public boolean tryAdd(final EventData eventData) { if (eventData == null) { logger.logAndThrow(new IllegalArgumentException("eventData cannot be null")); return false; } final int size; try { size = getSize(eventData, events.isEmpty()); } catch (java.nio.BufferOverflowException exception) { logger.logAndThrow(new AmqpException(false, ErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, String.format(Locale.US, "Size of the payload exceeded maximum message size: %s kb", maxMessageSize / 1024), contextProvider.getErrorContext())); return false; } synchronized (lock) { if (this.sizeInBytes + size > this.maxMessageSize) { return false; } this.sizeInBytes += size; } this.events.add(eventData); return true; }
Source:
@Override public T next() { if (closed) throw new IllegalStateException("closed"); checkForComodification(); if (size() == 0) throw new NoSuchElementException(); if (nextElementIndex >= size()) throw new NoSuchElementException(); return entries.get(nextElementIndex++); }

Target:
@Override public T next() { if (closed) throw new IllegalStateException("closed"); checkForComodification(); if (nextElementIndex >= size()) throw new NoSuchElementException(); return entries.get(nextElementIndex++); }
Source:
public long getBytesToUpload() { return ioStatisticsStore.getCounterReference(getStatName(BYTES_TO_UPLOAD)).get(); }

Target:
public long getBytesToUpload() { return ioStatisticsStore.counters().get(getStatName(BYTES_TO_UPLOAD)); }
Source:
getDescriptor() { return org.apache.druid.data.input.protobuf.ProtoTestEventWrapper.INTERNAL_STATIC_PROTOTEST_PROTOTESTEVENT_DESCRIPTOR; }

Target:
getDescriptor() { return org.apache.druid.data.input.protobuf.ProtoTestEventWrapper.internal_static_prototest_ProtoTestEvent_descriptor; }
Source:
private boolean popMessageFromQueue(MessageConsumer messageConsumer) throws AxisFault { try { messageConsumer.receive(); return messageConsumer.ack(); } catch (SynapseException e) { handleException(log, "MessageConsumer failed to receive or acknowledge the message :" , e); return false; } }

Target:
private boolean popMessageFromQueue(MessageConsumer messageConsumer) throws AxisFault { try { if (messageConsumer.receive() != null) { return messageConsumer.ack(); } } catch (SynapseException e) { handleException(log, "MessageConsumer failed to receive or acknowledge the message :" , e); } return false; }
Source:
private ResultsWrapper<ContentDTO> getEventsBookedByUser(final HttpServletRequest request, final List<String> tags, final RegisteredUserDTO currentUser) throws SegueDatabaseException, ContentManagerException { List<ContentDTO> filteredResults = Lists.newArrayList(); Map<String, BookingStatus> userBookingMap = this.bookingManager.getAllEventStatesForUser(currentUser.getId()); for (String eventId : userBookingMap.keySet()) { if (BookingStatus.CANCELLED.equals(userBookingMap.get(eventId))) { continue; } final IsaacEventPageDTO eventDTOById = this.getEventDTOById(request, eventId); if (tags != null) { Set<String> tagsList = Sets.newHashSet(tags); tagsList.retainAll(eventDTOById.getTags()); if (tagsList.size() == 0) { continue; } } filteredResults.add(eventDTOById); } return new ResultsWrapper<>(filteredResults, (long) filteredResults.size()); }

Target:
private ResultsWrapper<ContentDTO> getEventsBookedByUser(final HttpServletRequest request, final List<String> tags, final RegisteredUserDTO currentUser) throws SegueDatabaseException, ContentManagerException { List<ContentDTO> filteredResults = Lists.newArrayList(); Map<String, BookingStatus> userBookingMap = this.bookingManager.getAllEventStatesForUser(currentUser.getId()); for (String eventId : userBookingMap.keySet()) { if (BookingStatus.CANCELLED.equals(userBookingMap.get(eventId))) { continue; } final IsaacEventPageDTO eventDTOById = this.getAugmentedEventDTOById(request, eventId); if (tags != null) { Set<String> tagsList = Sets.newHashSet(tags); tagsList.retainAll(eventDTOById.getTags()); if (tagsList.size() == 0) { continue; } } filteredResults.add(eventDTOById); } return new ResultsWrapper<>(filteredResults, (long) filteredResults.size()); }
Source:
static public RpmVersion getOvirtHostOsVersion(VDS vds) { try { return new RpmVersion(vds.getHostOs(), "RHEV Hypervisor -", true); } catch (RuntimeException e) { log.error("Failed to parse version of Host '{}','{}' and Host OS '{}' with error {}", vds.getId(), vds.getName(), vds.getHostOs(), ExceptionUtils.getMessage(e)); } return null; }

Target:
static public RpmVersion getOvirtHostOsVersion(VDS vds) { try { return new RpmVersion(vds.getHostOs(), "RHEV Hypervisor -", true); } catch (RuntimeException e) { log.error("Failed to parse version of Host '{}','{}' and Host OS '{}': {}", vds.getId(), vds.getName(), vds.getHostOs(), ExceptionUtils.getMessage(e)); log.debug("Exception", e); } return null; }
Source:
public boolean checkYearlyRetirements() { if (getCampaignOptions().getUseAtB() && (Math.toIntExact(ChronoUnit.YEARS.between(getRetirementDefectionTracker() .getLastRetirementRoll(), getLocalDate())) == 1)) { Object[] options = { "Show Retirement Dialog", "Not Now" }; return JOptionPane.YES_OPTION == JOptionPane .showOptionDialog( null, "It has been a year since the last retirement/defection roll, and it is time to do another.", "Retirement/Defection roll required", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]); } return false; }

Target:
public boolean checkYearlyRetirements() { if (getCampaignOptions().getUseAtB() && (ChronoUnit.YEARS.between(getRetirementDefectionTracker() .getLastRetirementRoll(), getLocalDate()) == 1L)) { Object[] options = { "Show Retirement Dialog", "Not Now" }; return JOptionPane.YES_OPTION == JOptionPane .showOptionDialog( null, "It has been a year since the last retirement/defection roll, and it is time to do another.", "Retirement/Defection roll required", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]); } return false; }
Source:
public Operator createOperator(DriverContext driverContext) { checkState(!closed, "Factory is already closed"); OperatorContext operatorContext = driverContext.addOperatorContext(operatorId, planNodeId, NestedLoopJoinOperator.class.getSimpleName()); return new NestedLoopJoinOperator(operatorContext, nestedLoopJoinPagesSupplier, probeTypes, pageFilterSupplier.map(s -> s.get())); }

Target:
public Operator createOperator(DriverContext driverContext) { checkState(!closed, "Factory is already closed"); OperatorContext operatorContext = driverContext.addOperatorContext(operatorId, planNodeId, NestedLoopJoinOperator.class.getSimpleName()); return new NestedLoopJoinOperator(operatorContext, nestedLoopJoinPagesSupplier, probeTypes, processor.get(), new MergingPageOutput(types, minOutputPageSize.toBytes(), minOutputPageRowCount)); }
Source:
public CardDetails(uk.gov.pay.api.model.CardDetails cardDetails) { this.last_digits_card_number = cardDetails.getLastDigitsCardNumber(); this.first_digits_card_number = cardDetails.getFirstDigitsCardNumber(); this.cardholder_name = cardDetails.getCardHolderName(); this.expiry_date = cardDetails.getExpiryDate(); this.card_brand = cardDetails.getCardBrand(); this.billing_address = cardDetails.getBillingAddress().isPresent() ? new Address( cardDetails.getBillingAddress().get()) : null; }

Target:
public CardDetails(uk.gov.pay.api.model.CardDetails cardDetails) { this.last_digits_card_number = cardDetails.getLastDigitsCardNumber(); this.first_digits_card_number = cardDetails.getFirstDigitsCardNumber(); this.cardholder_name = cardDetails.getCardHolderName(); this.expiry_date = cardDetails.getExpiryDate(); this.card_brand = cardDetails.getCardBrand(); this.billing_address = cardDetails.getBillingAddress().map(Address::new).orElse(null); }
Source:
public Iterator<Page> getPages() { return new Iterator<Page>() { private int pageCounter; @Override public boolean hasNext() { return pageCounter < channels[0].size(); } @Override public Page next() { Block[] blocks = Stream.of(channels) .map(channel -> channel.get(pageCounter)) .toArray(Block[]::new); pageCounter++; return new Page(blocks); } }; }

Target:
public Iterator<Page> getPages() { return new AbstractIterator<Page>() { private int pageCounter; @Override protected Page computeNext() { if (pageCounter == channels[0].size()) { return endOfData(); } Block[] blocks = Stream.of(channels) .map(channel -> channel.get(pageCounter)) .toArray(Block[]::new); pageCounter++; return new Page(blocks); } }; }
Source:
public void checkAttributeSemantics(PerunSessionImpl sess, Group group, Attribute attribute) throws InternalErrorException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException { try { Attribute foundAttribute = sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, group, GroupsManager.GROUP_STRUCTURE_SYNCHRO_INTERVAL_ATTRNAME); if(foundAttribute.getValue() != null) { throw new WrongReferenceAttributeValueException(attribute, foundAttribute, group, null, group, null, "Attribute " + attribute.getName() + " cannot be set because attribute " + GroupsManager.GROUP_STRUCTURE_SYNCHRO_INTERVAL_ATTRNAME + " is already set."); } } catch (AttributeNotExistsException exc) { throw new ConsistencyErrorException("Attribute " + GroupsManager.GROUP_STRUCTURE_SYNCHRO_INTERVAL_ATTRNAME + " is supposed to exist", exc); } }

Target:
public void checkAttributeSemantics(PerunSessionImpl sess, Group group, Attribute attribute) throws InternalErrorException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException { if (attribute.getValue() == null) return; try { Attribute foundAttribute = sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, group, GroupsManager.GROUP_STRUCTURE_SYNCHRO_INTERVAL_ATTRNAME); if(foundAttribute.getValue() != null) { throw new WrongReferenceAttributeValueException(attribute, foundAttribute, group, null, group, null, "Attribute " + attribute.getName() + " cannot be set because attribute " + GroupsManager.GROUP_STRUCTURE_SYNCHRO_INTERVAL_ATTRNAME + " is already set."); } } catch (AttributeNotExistsException exc) { throw new ConsistencyErrorException("Attribute " + GroupsManager.GROUP_STRUCTURE_SYNCHRO_INTERVAL_ATTRNAME + " is supposed to exist", exc); } }
Source:
public Counter getCounter() { return numLateRecordsDropped; }

Target:
protected Counter getCounter() { return numLateRecordsDropped; }
Source:
private int getDefultHashPartitionCount() { String url = config.getTestGateway(); String username = Optional.ofNullable(config.getTestUsernameOverride()).orElse("verifier-test"); String password = Optional.ofNullable(config.getTestPasswordOverride()).orElse(null); int defaultHashPartitionCount = 0; int numOfActiveNodes = 0; try { ResultSet result = executeQuery(url, username, password, "select count(*) as NUM_OF_WORKERS from system.runtime.nodes where coordinator=false"); while (result.next()) { numOfActiveNodes = result.getInt("NUM_OF_WORKERS"); } result.close(); result = executeQuery(url, username, password, "show session"); while (result.next()) { if ((result.getString("Name")).equals("hash_partition_count")) { defaultHashPartitionCount = Integer.parseInt(result.getString("Value")); break; } } result.close(); } catch (SQLException e) { e.printStackTrace(); } return Math.min(defaultHashPartitionCount, numOfActiveNodes); }

Target:
private int getDefultHashPartitionCount() { String url = config.getTestGateway(); String username = Optional.ofNullable(config.getTestUsernameOverride()).orElse(DEFAULT_USER_NAME); String password = Optional.ofNullable(config.getTestPasswordOverride()).orElse(null); int defaultHashPartitionCount = 0; int numOfActiveNodes = 0; try (ResultSet result = executeQuery(url, username, password, "select count(*) as NUM_OF_WORKERS from system.runtime.nodes where coordinator=false")) { while (result.next()) { numOfActiveNodes = result.getInt("NUM_OF_WORKERS"); } } catch (SQLException e) { e.printStackTrace(); } try (ResultSet result = executeQuery(url, username, password, "show session")) { while (result.next()) { if ((result.getString("Name")).equals(HASH_PARTITION_COUNT)) { defaultHashPartitionCount = Integer.parseInt(result.getString("Value")); break; } } } catch (SQLException e) { e.printStackTrace(); } return Math.min(defaultHashPartitionCount, numOfActiveNodes); }
Source:
public String call() { StringBuilder result = new StringBuilder(); final File rootPath = new File(this.rootPathName); final File[] files = rootPath.listFiles(); if (files != null) { for (File file : files) { if (file.isFile()) { try { result.append(Util.getDigestOf(new FileInputStream(file))) .append(" ") .append(file.getName()).append('\n'); } catch (IOException e) { } } } } return result.toString(); }

Target:
public String call() { StringBuilder result = new StringBuilder(); final File rootPath = new File(this.rootPathName); for (File file : FileUtils.listFiles(rootPath, null, false)) { if (file.isFile()) { try { result.append(Util.getDigestOf(new FileInputStream(file))) .append(" ") .append(file.getName()).append('\n'); } catch (IOException e) { } } } return result.toString(); }
Source:
private void reweightTrainingData(Iterable<? extends AbstractInstance> sortedData, DateTime mostRecentInstance) { for (AbstractInstance instance : sortedData) { double decayConstant = (instance.getClassification().equals(POSITIVE_CLASSIFICATION)) ? decayConstantOfPositive : decayConstantOfNegative; DateTime timeOfInstance = dateTimeExtractor.extractDateTime(instance); double hoursBack = Hours.hoursBetween(mostRecentInstance, timeOfInstance).getHours(); double newWeight = Math.exp(-1.0 * hoursBack / decayConstant); instance.setWeight(newWeight); } }

Target:
private List<AbstractInstance> reweightTrainingData(Iterable<? extends AbstractInstance> sortedData, DateTime mostRecentInstance) { ArrayList<AbstractInstance> trainingDataList = Lists.newArrayList(); for (AbstractInstance instance : sortedData) { double decayConstant = (instance.getClassification().equals(POSITIVE_CLASSIFICATION)) ? decayConstantOfPositive : decayConstantOfNegative; DateTime timeOfInstance = dateTimeExtractor.extractDateTime(instance); double hoursBack = Hours.hoursBetween(mostRecentInstance, timeOfInstance).getHours(); double newWeight = Math.exp(-1.0 * hoursBack / decayConstant); trainingDataList.add(instance.reweight(newWeight)); } return trainingDataList; }
Source:
public void getIccSlotsStatus(Message result) { IRadio radioProxy = getRadioProxy(result); riljLog("getIccSlotsStatus"); if (radioProxy != null) { riljLog("getIccSlotsStatus: radioProxy != null"); android.hardware.radio.V1_2.IRadio radioProxy12 = android.hardware.radio.V1_2.IRadio.castFrom(radioProxy); if (radioProxy12 == null) { riljLog("getIccSlotsStatus: radioProxy12 == null"); if (result != null) { riljLog("getIccSlotsStatus: result != null"); AsyncResult.forMessage(result, null, CommandException.fromRilErrno(REQUEST_NOT_SUPPORTED)); result.sendToTarget(); } } else { RILRequest rr = obtainRequest(RIL_REQUEST_GET_SLOT_STATUS, result, mRILDefaultWorkSource); if (RILJ_LOGD) { riljLog(rr.serialString() + "> " + requestToString(rr.mRequest)); } try { radioProxy12.getSimSlotsStatus(rr.mSerial); } catch (RemoteException | RuntimeException e) { handleRadioProxyExceptionForRR(rr, "getIccSlotStatus", e); } } } }

Target:
public void getIccSlotsStatus(Message result) { IRadio radioProxy = getRadioProxy(result); if (radioProxy != null) { android.hardware.radio.V1_2.IRadio radioProxy12 = android.hardware.radio.V1_2.IRadio.castFrom(radioProxy); if (radioProxy12 == null) { if (result != null) { AsyncResult.forMessage(result, null, CommandException.fromRilErrno(REQUEST_NOT_SUPPORTED)); result.sendToTarget(); } } else { RILRequest rr = obtainRequest(RIL_REQUEST_GET_SLOT_STATUS, result, mRILDefaultWorkSource); if (RILJ_LOGD) { riljLog(rr.serialString() + "> " + requestToString(rr.mRequest)); } try { radioProxy12.getSimSlotsStatus(rr.mSerial); } catch (RemoteException | RuntimeException e) { handleRadioProxyExceptionForRR(rr, "getIccSlotStatus", e); } } } }
Source:
public void getAnswer_whenPromptHasAnswer_returnsAnswer() { AudioWidget widget = createWidget(promptWithAnswer(new StringData(destinationPath))); assertThat(widget.getAnswer().getDisplayText(), equalTo(destinationPath)); }

Target:
public void getAnswer_whenPromptHasAnswer_returnsAnswer() { AudioWidget widget = createWidget(promptWithAnswer(new StringData(FILE_PATH))); assertThat(widget.getAnswer().getDisplayText(), equalTo(FILE_PATH)); }
Source:
private void updateMemoryBalloonDevice() { VDSGroup cluster = getSelectedCluster(); Integer osType = getOSType().getSelectedItem(); if (cluster == null || osType == null) { return; } boolean isBalloonEnabled = AsyncDataProvider.isBalloonEnabled(osType, cluster.getcompatibility_version()); getMemoryBalloonDeviceEnabled().setEntity(isBalloonEnabled); }

Target:
private void updateMemoryBalloonDevice() { VDSGroup cluster = getSelectedCluster(); Integer osType = getOSType().getSelectedItem(); if (cluster == null || osType == null) { return; } boolean isBalloonEnabled = AsyncDataProvider.isBalloonEnabled(osType, cluster.getcompatibility_version()); getMemoryBalloonDeviceEnabled().setIsChangable(isBalloonEnabled); getMemoryBalloonDeviceEnabled().setEntity(isBalloonEnabled); if (!isBalloonEnabled) { getBehavior().deactivateInstanceTypeManager(); getMemoryBalloonDeviceEnabled().setEntity(isBalloonEnabled); getBehavior().activateInstanceTypeManager(); } }
Source:
public void testGetLogicalTypeNameDate() { Schema logicalDateSchema = AvroUtils._logicalDate(); assertEquals("date", LogicalTypeUtils.getLogicalTypeName(logicalDateSchema)); }

Target:
public void testGetLogicalTypeNameDate() { Schema logicalDateSchema = AvroUtils._logicalDate(); assertEquals(LogicalTypeUtils.DATE, LogicalTypeUtils.getLogicalTypeName(logicalDateSchema)); }
Source:
public void toString_() { final StringBuilder sb = new StringBuilder("RealmList<").append(listType.getValueTypeName()).append(">@["); final String separator = ","; for (int i = 0; i < NON_NULL_TEST_SIZE; i++) { final Object value = generateValue(listType, i); if (value instanceof byte[]) { sb.append("byte[").append(((byte[]) value).length).append("]"); } else { sb.append(value); } sb.append(separator); if (typeIsNullable) { sb.append("null").append(separator); } } sb.setLength(sb.length() - separator.length()); sb.append("]"); assertEquals(sb.toString(), list.toString()); }

Target:
public void toString_() { final StringBuilder sb = new StringBuilder("RealmList<").append(listType.getValueTypeName()).append(">@["); final String separator = ","; for (int i = 0; i < NON_NULL_TEST_SIZE; i++) { final Object value = generateValue(listType, i); if (value instanceof byte[]) { sb.append("byte[").append(((byte[]) value).length).append("]"); } else { sb.append(value); } sb.append(separator); if (isTypeNullable) { sb.append("null").append(separator); } } sb.setLength(sb.length() - separator.length()); sb.append("]"); assertEquals(sb.toString(), list.toString()); }
Source:
public void onBlockPhysics(final BlockPhysicsEvent event) { final Block block = event.getBlock(); try (MCTiming timing = TimingPhysicsWaterManipulationCheck.startTiming()) { if (!WaterManipulation.canPhysicsChange(block)) { event.setCancelled(true); return; } } try (MCTiming timing = TimingPhysicsEarthPassiveCheck.startTiming()) { if (!EarthPassive.canPhysicsChange(block)) { event.setCancelled(true); return; } } try (MCTiming timing = TimingPhysicsIlluminationTorchCheck.startTiming()) { if (Illumination.isIlluminationTorch(block) || Illumination.isIlluminationTorch(block.getRelative(BlockFace.UP))) { System.out.println("Ran Timing Physics Check"); event.setCancelled(true); return; } } try (MCTiming timing = TimingPhysicsEarthAbilityCheck.startTiming()) { if (EarthAbility.getPreventPhysicsBlocks().contains(block)) { event.setCancelled(true); return; } } try (MCTiming timing = TimingPhysicsAirTempBlockBelowFallingBlockCheck.startTiming()) { if ((block.getType() == Material.SAND || block.getType() == Material.RED_SAND || block.getType() == Material.GRAVEL || block.getType() == Material.ANVIL || block.getType() == Material.DRAGON_EGG) && ElementalAbility.isAir(block.getRelative(BlockFace.DOWN).getType()) && TempBlock.isTempBlock(block.getRelative(BlockFace.DOWN))) { event.setCancelled(true); } } }

Target:
public void onBlockPhysics(final BlockPhysicsEvent event) { final Block block = event.getBlock(); try (MCTiming timing = TimingPhysicsWaterManipulationCheck.startTiming()) { if (!WaterManipulation.canPhysicsChange(block)) { event.setCancelled(true); return; } } try (MCTiming timing = TimingPhysicsEarthPassiveCheck.startTiming()) { if (!EarthPassive.canPhysicsChange(block)) { event.setCancelled(true); return; } } try (MCTiming timing = TimingPhysicsIlluminationTorchCheck.startTiming()) { if (Illumination.isIlluminationTorch(block) || Illumination.isIlluminationTorch(block.getRelative(BlockFace.UP))) { event.setCancelled(true); return; } } try (MCTiming timing = TimingPhysicsEarthAbilityCheck.startTiming()) { if (EarthAbility.getPreventPhysicsBlocks().contains(block)) { event.setCancelled(true); return; } } try (MCTiming timing = TimingPhysicsAirTempBlockBelowFallingBlockCheck.startTiming()) { if ((block.getType() == Material.SAND || block.getType() == Material.RED_SAND || block.getType() == Material.GRAVEL || block.getType() == Material.ANVIL || block.getType() == Material.DRAGON_EGG) && ElementalAbility.isAir(block.getRelative(BlockFace.DOWN).getType()) && TempBlock.isTempBlock(block.getRelative(BlockFace.DOWN))) { event.setCancelled(true); } } }
Source:
public FullRevision getPlatformToolsRevision() { File platformTools = new File(mSdkLocation, SdkConstants.FD_PLATFORM_TOOLS); if (!platformTools.isDirectory()) { return null; } Reader reader = null; try { reader = new FileReader(new File(platformTools, SdkConstants.FN_SOURCE_PROP)); Properties props = new Properties(); props.load(reader); String value = props.getProperty(PkgProps.PKG_REVISION); FullRevision toolsRevision = null; try { toolsRevision = FullRevision.parseRevision(value); } catch (NumberFormatException ignore) { } return toolsRevision; } catch (FileNotFoundException ignore) { } catch (IOException ignore) { } finally { Closeables.closeQuietly(reader); } return null; }

Target:
public FullRevision getPlatformToolsRevision() { File platformTools = new File(mSdkLocation, SdkConstants.FD_PLATFORM_TOOLS); if (!platformTools.isDirectory()) { return null; } Reader reader = null; try { reader = new FileReader(new File(platformTools, SdkConstants.FN_SOURCE_PROP)); Properties props = new Properties(); props.load(reader); String value = props.getProperty(PkgProps.PKG_REVISION); return FullRevision.parseRevision(value); } catch (FileNotFoundException ignore) { } catch (IOException ignore) { } catch (NumberFormatException ignore) { } finally { Closeables.closeQuietly(reader); } return null; }
Source:
public Synonym anonymize(Object from, int size, boolean shortlived) { if (size < 2) { throw new UnsupportedOperationException("Can not produce country codes of one character."); } String country = null; while (country == null || country.length() < 1) { Locale l = AVAILABLE_LOCALES[r.nextInt(AVAILABLE_LOCALES.length)]; try { if (size > 2) { country = l.getISO3Country(); if(country.length()==0) { continue; } country = padRight(country, size); } else if (size == 2) { country = l.getCountry(); } } catch (MissingResourceException e) { } } return new StringSynonym( getType(), from.toString(), country, shortlived ); }

Target:
public Synonym anonymize(Object from, int size, boolean shortlived) { if (size < 2) { throw new UnsupportedOperationException("Can not produce country codes of one character."); } String country = null; while (country == null || country.length() < 1) { Locale l = AVAILABLE_LOCALES[r.nextInt(AVAILABLE_LOCALES.length)]; try { if (size > 2) { country = l.getISO3Country(); if(StringUtils.isEmpty(country)) { continue; } country = padRight(country, size); } else if (size == 2) { country = l.getCountry(); } } catch (MissingResourceException e) { } } return new StringSynonym( getType(), from.toString(), country, shortlived ); }
Source:
public void shouldFetchAllPatientEncounterIncludingVoidedPatientEncountersIfIncludeAllParamIsSetToTrue() throws Exception { String encounterUuuid = "c59b3942-4fdd-11e5-8c3c-410f8777c163"; String patientUuid = "da7f524f-27ce-4bb2-86d6-6d1d05312bd5"; Patient patient = Context.getPatientService().getPatientByUuid(patientUuid); Encounter enc = Context.getEncounterService().getEncounterByUuid(encounterUuuid); Context.getEncounterService().voidEncounter(enc, "bcbcb"); Context.getEncounterService().saveEncounter(enc); List<Encounter> encs = Context.getEncounterService().getEncountersByPatient(patient.getGivenName()); Assert.assertEquals(1, encs.size()); MockHttpServletRequest req = request(RequestMethod.GET, getURI()); req.addParameter("patient", patientUuid); req.addParameter("includeAll", "true"); SimpleObject result = deserialize(handle(req)); List<Object> encounters = result.get("results"); Assert.assertEquals(2, encounters.size()); }

Target:
public void shouldFetchAllPatientEncounterIncludingVoidedPatientEncountersIfIncludeAllParamIsSetToTrue() throws Exception { Patient patient = Context.getPatientService().getPatientByUuid(RestTestConstants1_9.PATIENT_WITH_ENCOUNTER_UUID); Encounter enc = Context.getEncounterService().getEncounterByUuid(RestTestConstants1_9.ENCOUNTER_UUID); Context.getEncounterService().voidEncounter(enc, "some reason"); Context.getEncounterService().saveEncounter(enc); List<Encounter> encs = Context.getEncounterService().getEncountersByPatient(patient); Assert.assertEquals(1, encs.size()); MockHttpServletRequest req = request(RequestMethod.GET, getURI()); req.addParameter("patient", RestTestConstants1_9.PATIENT_WITH_ENCOUNTER_UUID); req.addParameter("includeAll", "true"); SimpleObject result = deserialize(handle(req)); List<Object> encounters = result.get("results"); Assert.assertEquals(2, encounters.size()); }
Source:
private void validate() { ArgChecker.isTrue(settlementDateOffset.getDays() >= 0, "The settlement date offset must be non-negative"); ArgChecker.isTrue(notional.getAmount() > 0, "Notionanl must be strictly positve"); }

Target:
private void validate() { ArgChecker.isTrue(settlementDateOffset.getDays() >= 0, "The settlement date offset must be non-negative"); ArgChecker.isTrue(notional.getAmount() > 0, "Notional must be strictly positive"); }
Source:
public void disconnect() throws IOException { }

Target:
public void disconnect() throws IOException { channel.disconnect().syncUninterruptibly(); workerGroup.shutdownGracefully(); }
Source:
private static Stream<String> makeQueries(List<String> inputs, QueryMode queryMode, int queryCount) { queryCount = queryCount > 0 ? queryCount : inputs.size(); switch (queryMode) { case LIST: return inputs.stream().limit(queryCount); case SAMPLE: Random r = new Random(inputs.hashCode()); return r.ints(queryCount, 0, inputs.size()).boxed().map(inputs::get); default: throw new IllegalArgumentException(String.format("Unsupported queryMode '%s", queryMode)); } }

Target:
private static Stream<String> makeQueries(List<String> inputs, QueryMode queryMode, int queryCount) { queryCount = queryCount > 0 ? queryCount : inputs.size(); switch (queryMode) { case FULL: return inputs.stream().limit(queryCount); case RESAMPLE: Random r = new Random(0); return r.ints(queryCount, 0, inputs.size()).boxed().map(inputs::get); default: throw new IllegalArgumentException(String.format("Unsupported queryMode '%s", queryMode)); } }
Source:
public void start(final Environment env) { startThread(new CommandRunnable() { @Override public void run() throws Exception { parseCommandLine(); if ((newParent != null && !newParent.canCreateChildProject()) || (newParent == null && !currentUser.getCapabilityByProject(null) .canCreateProject())) { String msg = String.format( "fatal: %s does not have \"Create Project\" capability.", currentUser.getUserName()); throw new UnloggedFailure(BaseCommand.STATUS_NOT_ADMIN, msg); } validateParameters(); try { nameKey = new Project.NameKey(projectName); String head = permissionsOnly ? GitRepositoryManager.REF_CONFIG : branch; final Repository repo = repoManager.createRepository(nameKey); try { rq.replicateNewProject(nameKey, head); RefUpdate u = repo.updateRef(Constants.HEAD); u.disableRefLog(); u.link(head); createProjectConfig(); if (!permissionsOnly && createEmptyCommit) { createEmptyCommit(repo, nameKey, branch); } } finally { repo.close(); } } catch (IllegalStateException err) { try { Repository repo = repoManager.openRepository(nameKey); try { if (repo.getObjectDatabase().exists()) { throw new UnloggedFailure(1, "fatal: project \"" + projectName + "\" exists"); } } finally { repo.close(); } } catch (RepositoryNotFoundException doesNotExist) { throw new Failure(1, "fatal: Cannot create " + projectName, err); } } catch (RepositoryNotFoundException badName) { throw new UnloggedFailure(1, "fatal: " + badName.getMessage()); } catch (Exception err) { throw new Failure(1, "fatal: Cannot create " + projectName, err); } } }); }

Target:
public void start(final Environment env) { startThread(new CommandRunnable() { @Override public void run() throws Exception { parseCommandLine(); if ((newParent != null && !newParent.canCreateChildProject()) || (newParent == null && !currentUser.getCapabilities() .canCreateProject())) { final String msg = String.format( "fatal: %s does not have \"Create Project\" capability.", currentUser.getUserName()); throw new UnloggedFailure(BaseCommand.STATUS_NOT_ADMIN, msg); } validateParameters(); try { nameKey = new Project.NameKey(projectName); String head = permissionsOnly ? GitRepositoryManager.REF_CONFIG : branch; final Repository repo = repoManager.createRepository(nameKey); try { rq.replicateNewProject(nameKey, head); RefUpdate u = repo.updateRef(Constants.HEAD); u.disableRefLog(); u.link(head); createProjectConfig(); if (!permissionsOnly && createEmptyCommit) { createEmptyCommit(repo, nameKey, branch); } } finally { repo.close(); } } catch (IllegalStateException err) { handleRepositoryExistsException(nameKey); } catch (RepositoryCaseMismatchException err) { handleRepositoryExistsException(err.getNameOfExistingProject()); } catch (RepositoryNotFoundException badName) { throw new UnloggedFailure(1, "fatal: " + badName.getMessage()); } catch (Exception err) { throw new Failure(1, "fatal: Cannot create " + projectName, err); } } }); }
Source:
private void cleanup() { try { log.info("Start cleanup"); DateTime latestTimeToKeep = DateTime.getNow().addDays( Config.<Integer>getValue(ConfigValues.CommandEntityAgingThreshold) * -1); commandCoordinatorUtil.removeAllCommandsBeforeDate(latestTimeToKeep); log.info("Finished cleanup"); } catch (Throwable t) { log.error("Exception in performing command entity cleanup: {}", ExceptionUtils.getRootCauseMessage(t)); log.debug("Exception", t); } }

Target:
private void cleanup() { try { log.debug("Start cleanup"); DateTime latestTimeToKeep = DateTime.getNow().addDays( Config.<Integer>getValue(ConfigValues.CommandEntityAgingThreshold) * -1); commandCoordinatorUtil.removeAllCommandsBeforeDate(latestTimeToKeep); log.debug("Finished cleanup"); } catch (Throwable t) { log.error("Exception in performing command entity cleanup: {}", ExceptionUtils.getRootCauseMessage(t)); log.debug("Exception", t); } }
Source:
private TNiftyFuture(final NiftyClientConnector<T> clientChannelConnector, final Duration receiveTimeout, final Duration sendTimeout, final ChannelFuture channelFuture) { channelFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { try { if (future.isSuccess()) { Channel nettyChannel = future.getChannel(); T channel = clientChannelConnector.newThriftClientChannel(nettyChannel, timer); channel.setReceiveTimeout(receiveTimeout); channel.setSendTimeout(sendTimeout); set(channel); } else if (future.isCancelled()) { if (!cancel(true)) { setException(new TTransportException("Unable to cancel client channel connection")); } } else { throw future.getCause(); } } catch (Throwable t) { setException(new TTransportException("Failed to connect client channel", future.getCause())); } } }); }

Target:
private TNiftyFuture(final NiftyClientConnector<T> clientChannelConnector, final Duration receiveTimeout, final Duration sendTimeout, final ChannelFuture channelFuture) { channelFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { try { if (future.isSuccess()) { Channel nettyChannel = future.getChannel(); T channel = clientChannelConnector.newThriftClientChannel(nettyChannel, timer); channel.setReceiveTimeout(receiveTimeout); channel.setSendTimeout(sendTimeout); set(channel); } else if (future.isCancelled()) { if (!cancel(true)) { setException(new TTransportException("Unable to cancel client channel connection")); } } else { throw future.getCause(); } } catch (Throwable t) { setException(new TTransportException("Failed to connect client channel", t)); } } }); }
Source:
private static MetaData loadMetaData() throws IOException { InputStream stream = RsdlManager.class.getResourceAsStream(METADATA_FILE_NAME); if (stream == null) { throw new IOException("Can't find metadata resource \"" + METADATA_FILE_NAME + "\""); } MetaData metaData; try { Constructor constructor = new CustomClassLoaderConstructor(Thread.currentThread().getContextClassLoader()); metaData = (MetaData) new Yaml(constructor).load(stream); if (metaData == null) { throw new IOException("Can't load metadata file \"" + METADATA_FILE_NAME + "\""); } } finally { stream.close(); } assignDefaults(metaData); for (Action action : metaData.getActions()) { String name = action.getName(); name = name.replaceAll("^/?", ""); action.setName(name); } return metaData; }

Target:
private static MetaData loadMetaData() throws IOException { try (InputStream in = RsdlManager.class.getResourceAsStream(METADATA_FILE_NAME)) { if (in == null) { throw new IOException("Can't find metadata from resource \"" + METADATA_FILE_NAME + "\""); } return loadMetaData(in); } }
Source:
public List<String> extractData(ResultSet rs) throws SQLException, DataAccessException { List<String> columnNames = new LinkedList<>(); ResultSetMetaData metadata = rs.getMetaData(); for (int col = 1; col <= metadata.getColumnCount(); col++) { columnNames.add(metadata.getColumnName(col)); } return columnNames; }

Target:
public List<String> extractData(ResultSet rs) throws SQLException, DataAccessException { ResultSetMetaData metadata = rs.getMetaData(); int columnCount = metadata.getColumnCount(); List<String> columnNames = new ArrayList<>(columnCount); for (int col = 1; col <= columnCount; col++) { columnNames.add(metadata.getColumnName(col)); } return columnNames; }
Source:
public void onError(final InterstitialAd interstitialAd, final ErrorInfo errorInfo) { Log.e(TAG, "Verizon Ads SDK interstitial error: " + errorInfo); }

Target:
public void onError(final InterstitialAd interstitialAd, final ErrorInfo errorInfo) { Log.e(TAG, "Verizon Ads SDK interstitial error: " + errorInfo); ThreadUtils.postOnUiThread(new Runnable() { @Override public void run() { MediationInterstitialAdapter adapter = interstitialAdapterWeakRef.get(); if ((adapter != null) && (interstitialListener != null)) { interstitialListener.onAdOpened(adapter); interstitialListener.onAdClosed(adapter); } } }); }
Source:
public final int parseArguments(final Parameters params) throws CmdLineException { String token = params.getParameter(0); String projectName = token; while (projectName.endsWith("/")) { projectName = projectName.substring(0, projectName.length() - 1); } while (projectName.startsWith("/")) { projectName = projectName.substring(1); token=projectName; } if (projectName.endsWith(".git")) { projectName = projectName.substring(0, projectName.length() - 4); while (projectName.endsWith("/")) { projectName = projectName.substring(0, projectName.length() - 1); } } final ProjectControl control; try { Project.NameKey nameKey = new Project.NameKey(projectName); control = projectControlFactory.validateFor(nameKey, ProjectControl.OWNER | ProjectControl.VISIBLE); } catch (NoSuchProjectException e) { throw new CmdLineException(owner, "'" + token + "': is not a Gerrit project"); } setter.addValue(control); return 1; }

Target:
public final int parseArguments(final Parameters params) throws CmdLineException { String projectName = params.getParameter(0); while (projectName.endsWith("/")) { projectName = projectName.substring(0, projectName.length() - 1); } while (projectName.startsWith("/")) { projectName = projectName.substring(1); } String projectNameWithoutSuffix = projectName; if (projectName.endsWith(Constants.DOT_GIT_EXT)) { projectNameWithoutSuffix = projectName.substring(0, projectName.length() - 4); while (projectNameWithoutSuffix.endsWith("/")) { projectNameWithoutSuffix = projectName.substring(0, projectName.length() - 1); } } final ProjectControl control; try { Project.NameKey nameKey = new Project.NameKey(projectNameWithoutSuffix); control = projectControlFactory.validateFor(nameKey, ProjectControl.OWNER | ProjectControl.VISIBLE); } catch (NoSuchProjectException e) { throw new CmdLineException(owner, "'" + projectName + "': is not a Gerrit project"); } setter.addValue(control); return 1; }
Source:
private AbstractPanel getStatusPanel() { NotesTableModel notesTableModel = new NotesTableModel(); notesTable.setModel(notesTableModel); ExtensionHistory extHist = org.parosproxy.paros.control.Control.getSingleton().getExtensionLoader() .getExtension(ExtensionHistory.class); if (extHist != null) { int LastHistoryId = extHist.getLastHistoryId(); int i = 0; while (i++ < LastHistoryId) { HistoryReference hr = extHist.getHistoryReference(i); if (hr != null) { if (hr.hasNote()) { eventConsumerImpl.addRowToNotesTable(i); } } } } notesTable.setColumnSelectionAllowed(false); notesTable.setCellSelectionEnabled(false); notesTable.setRowSelectionAllowed(true); notesTable.setAutoCreateRowSorter(true); notesTable.setColumnControlVisible(true); notesTable .getSelectionModel() .addListSelectionListener(new NotesTableSelectionHandler(notesTable, extHist)); exportButton = new TableExportButton<>(notesTable); JPanel buttonContainer = new JPanel(); buttonContainer.setLayout(new BoxLayout(buttonContainer, BoxLayout.X_AXIS)); buttonContainer.add(reload); buttonContainer.add(exportButton); JPanel pContainer = new JPanel(); pContainer.setLayout(new BoxLayout(pContainer, BoxLayout.Y_AXIS)); pContainer.add(buttonContainer); pContainer.add(new JScrollPane(notesTable)); if (statusPanel != null) { statusPanel.removeAll(); statusPanel.add(pContainer); } else { statusPanel = new AbstractPanel(); statusPanel.setLayout(new CardLayout()); statusPanel.setName(Constant.messages.getString(PREFIX + ".panel.title")); statusPanel.setIcon(ICON); statusPanel.add(pContainer); } return statusPanel; }

Target:
private AbstractPanel getStatusPanel() { if (statusPanel == null) { statusPanel = new AbstractPanel(); statusPanel.setLayout(new BorderLayout()); statusPanel.setName(Constant.messages.getString(PREFIX + ".panel.title")); statusPanel.setIcon(ICON); statusPanel.add(getToolBar(), BorderLayout.NORTH); statusPanel.add(new JScrollPane(getNotesTable()), BorderLayout.CENTER); } return statusPanel; }
Source:
protected void executeCommand() { VDS vds = vdsDao.get(getVdsId()); HostUpgradeManagerResult hostUpgradeManagerResult; try { hostUpgradeManagerResult = availableUpdatesFinder.isUpdateAvailable(vds); if (hostUpgradeManagerResult.isUpdatesAvailable()) { String message = hostUpgradeManagerResult.getAvailablePackages() == null ? "found updates." : String.format("found updates for packages %s", StringUtils.join(hostUpgradeManagerResult.getAvailablePackages(), ", ")); addCustomValue("Message", message); vds.getDynamicData().setUpdateAvailable(hostUpgradeManagerResult.isUpdatesAvailable()); vdsDynamicDao.updateUpdateAvailable(vds.getId(), hostUpgradeManagerResult.isUpdatesAvailable()); } else { addCustomValue("Message", "no updates found."); } getReturnValue().setActionReturnValue(hostUpgradeManagerResult); setSucceeded(true); setCommandStatus(CommandStatus.SUCCEEDED); } catch (Exception e) { log.error("Failed to check if updates are available for host '{}'", vds.getName()); setSucceeded(false); setCommandStatus(CommandStatus.FAILED); } }

Target:
protected void executeCommand() { HostUpgradeManagerResult hostUpgradeManagerResult = resourceManager.getVdsManager(getVdsId()).checkForUpdates(vdsDao.get(getVdsId())); getReturnValue().setActionReturnValue(hostUpgradeManagerResult); setSucceeded(hostUpgradeManagerResult != null); setCommandStatus(hostUpgradeManagerResult != null ? CommandStatus.SUCCEEDED : CommandStatus.FAILED); }
Source:
public static int indexOfChangeId(String message, String delimiter) { String[] lines = message.split(delimiter); int indexOfChangeIdLine = 0; boolean inFooter = false; for (int i = lines.length - 1; i >= 0; --i) { if (!inFooter && isEmptyLine(lines[i])) continue; inFooter = true; if (changeIdPattern.matcher(lines[i].trim()).matches()) { indexOfChangeIdLine = i; break; } else if (isEmptyLine(lines[i]) || i == 0) return -1; } int indexOfChangeIdLineinString = 0; for (int i = 0; i < indexOfChangeIdLine; ++i) indexOfChangeIdLineinString += lines[i].length() + delimiter.length(); return indexOfChangeIdLineinString; }

Target:
public static int indexOfChangeId(String message, String delimiter) { String[] lines = message.split(delimiter); int indexOfChangeIdLine = 0; boolean inFooter = false; for (int i = lines.length - 1; i >= 0; --i) { if (!inFooter && isEmptyLine(lines[i])) continue; inFooter = true; if (changeIdPattern.matcher(lines[i].trim()).matches()) { indexOfChangeIdLine = i; break; } else if (isEmptyLine(lines[i]) || i == 0) return -1; } int indexOfChangeIdLineinString = 0; for (int i = 0; i < indexOfChangeIdLine; ++i) indexOfChangeIdLineinString += lines[i].length() + delimiter.length(); return indexOfChangeIdLineinString + lines[indexOfChangeIdLine].indexOf(CHANGE_ID); }
Source:
public Double getAggregate(AverageAccumulator<Double> result) { return (result.value)/result.count; }

Target:
public Double getAggregate(AverageAccumulator<Double> result) { return (result.count == 0) ? null : ((double)result.value)/result.count; }
Source:
public InputStream getObject(String bucketName, String objectName, ServerSideEncryption sse) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException, InvalidArgumentException { if ((sse.getType() == ServerSideEncryption.Type.SSE_S3) || (sse.getType() == ServerSideEncryption.Type.SSE_KMS)) { throw new InvalidArgumentException("Encryption type is not supported for this operation."); } else if ((sse.getType() == ServerSideEncryption.Type.SSE_C) && (!this.baseUrl.isHttps())) { throw new InvalidArgumentException("SSE_C provided keys must be made over a secure connection."); } else { Map<String, String> headers = new HashMap<>(); sse.marshal(headers); HttpResponse response = executeGet(bucketName, objectName, headers, null); return response.body().byteStream(); } }

Target:
public InputStream getObject(String bucketName, String objectName, ServerSideEncryption sse) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException, InvalidArgumentException { if ((sse.getType() == ServerSideEncryption.Type.SSE_S3) || (sse.getType() == ServerSideEncryption.Type.SSE_KMS)) { throw new InvalidArgumentException("GetObject doesn't support encryption type " + sse.getType()); } else if ((sse.getType() == ServerSideEncryption.Type.SSE_C) && (!this.baseUrl.isHttps())) { throw new InvalidArgumentException("SSE_C provided keys must be made over a secure connection."); } Map<String, String> headers = new HashMap<>(); sse.marshal(headers); HttpResponse response = executeGet(bucketName, objectName, headers, null); return response.body().byteStream(); }
Source:
public void standbyShouldNotPerformRestoreAtStartup() throws InterruptedException, ExecutionException { final int numMessages = 10; final int key = 1; final Semaphore semaphore = new Semaphore(0); final StreamsBuilder builder = new StreamsBuilder(); builder .table(INPUT_TOPIC_NAME, Consumed.with(Serdes.Integer(), Serdes.Integer()), Materialized.<Integer, Integer, KeyValueStore<Bytes, byte[]>>as(TABLE_NAME) .withCachingDisabled()) .toStream() .peek((k, v) -> semaphore.release()); final KafkaStreams client1 = createClient(builder, streamsConfiguration()); final KafkaStreams client2 = createClient(builder, streamsConfiguration()); final List<KafkaStreams> clients = Arrays.asList(client1, client2); final AtomicLong restoreStartOffset = new AtomicLong(-1); clients.forEach(client -> { client.setGlobalStateRestoreListener(createTrackingRestoreListener(restoreStartOffset)); client.start(); }); waitForClientsToEnterRunningState(clients, 60, TimeUnit.SECONDS); produceValueRange(key, 0, 10); assertThat("all messages in the first batch were processed in a timely manner", semaphore.tryAcquire(numMessages, 60, TimeUnit.SECONDS)); assertThat("no restore has occurred", restoreStartOffset.get(), is(equalTo(-1L))); }

Target:
public void standbyShouldNotPerformRestoreAtStartup() throws Exception { final int numMessages = 10; final int key = 1; final Semaphore semaphore = new Semaphore(0); final StreamsBuilder builder = new StreamsBuilder(); builder .table(INPUT_TOPIC_NAME, Consumed.with(Serdes.Integer(), Serdes.Integer()), Materialized.<Integer, Integer, KeyValueStore<Bytes, byte[]>>as(TABLE_NAME) .withCachingDisabled()) .toStream() .peek((k, v) -> semaphore.release()); final KafkaStreams kafkaStreams1 = createKafkaStreams(builder, streamsConfiguration()); final KafkaStreams kafkaStreams2 = createKafkaStreams(builder, streamsConfiguration()); final List<KafkaStreams> kafkaStreamsList = Arrays.asList(kafkaStreams1, kafkaStreams2); produceValueRange(key, 0, 10); final AtomicLong restoreStartOffset = new AtomicLong(-1); kafkaStreamsList.forEach(kafkaStreams -> { kafkaStreams.setGlobalStateRestoreListener(createTrackingRestoreListener(restoreStartOffset, new AtomicLong())); kafkaStreams.start(); }); waitForKafkaStreamssToEnterRunningState(kafkaStreamsList, 60, TimeUnit.SECONDS); assertThat(semaphore.tryAcquire(numMessages, 60, TimeUnit.SECONDS), is(equalTo(true))); assertThat(restoreStartOffset.get(), is(equalTo(-1L))); }