auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testInit() throws Exception { final List<DefinitionSetService> definitionSetServices = new LinkedList<>(); final DefinitionSetService definitionSetService1 = mock(DefinitionSetService.class); final DefinitionSetService definitionSetService2 = mock(DefinitionSetService.class); definitionSetServices.add(definitionSetService1); definitionSetServices.add(definitionSetService2); when(definitionSetServiceInstances.iterator()).thenReturn(definitionSetServices.iterator()); doAnswer(invocation -> { final Consumer consumer = invocation.getArgumentAt(0, Consumer.class); Iterator var2 = definitionSetServiceInstances.iterator(); while (var2.hasNext()) { Object t = var2.next(); consumer.accept(t); } return null; }).when(definitionSetServiceInstances).forEach(any(Consumer.class)); tested.init(); assertEquals(tested.definitionSetServices.size(), definitionSetServices.size()); tested.definitionSetServices.containsAll(definitionSetServices); }

Target:
public void testInit() { final List<DefinitionSetService> definitionSetServices = new LinkedList<>(); final DefinitionSetService definitionSetService1 = mock(DefinitionSetService.class); final DefinitionSetService definitionSetService2 = mock(DefinitionSetService.class); definitionSetServices.add(definitionSetService1); definitionSetServices.add(definitionSetService2); when(definitionSetServiceInstances.iterator()).thenReturn(definitionSetServices.iterator()); doAnswer(invocation -> { final Consumer consumer = invocation.getArgumentAt(0, Consumer.class); Iterator var2 = definitionSetServiceInstances.iterator(); while (var2.hasNext()) { Object t = var2.next(); consumer.accept(t); } return null; }).when(definitionSetServiceInstances).forEach(any(Consumer.class)); tested.init(); assertEquals(tested.definitionSetServices.size(), definitionSetServices.size()); tested.definitionSetServices.containsAll(definitionSetServices); }
Source:
public void validateItemType(Item item, String bindingConfig) throws BindingConfigParseException { if (!(item instanceof SwitchItem || item instanceof StringItem)) { throw new BindingConfigParseException("item '" + item.getName() + "' is of type '" + item.getClass().getSimpleName() + "', only Switch- and StringItems are allowed - please check your *.items configuration"); } }

Target:
public void validateItemType(Item item, String bindingConfig) throws BindingConfigParseException { if (!(item instanceof SwitchItem || item instanceof StringItem)) { throw new BindingConfigParseException("item '" + item.getName() + "' is of type '" + item.getClass().getSimpleName() + "', only Switch-, Dimmer- and StringItems are allowed - please check your *.items configuration"); } }
Source:
public void execute() throws MetaClassNotFoundException, FeatureNotFoundException { final EObject currentTarget = this.getContext().getCurrentTarget(); Object value = RuntimeLoggerManager.INSTANCE.decorate(interpreter).evaluate(currentTarget, this.let, ToolPackage.eINSTANCE.getLet_ValueExpression()); String variableName = Optional.ofNullable(this.let.getVariableName()).orElse(""); if (!variableName.isEmpty()) { if ("self".equals(variableName) && value instanceof EObject) { context.setNextPushEObject((EObject) value); } else { ICommandTask childTask = new InterpretedExpressionVariableTask(context, extPackage, InterpretedExpressionVariableTask.KIND_SET, variableName, value, interpreter); childTask.execute(); } } }

Target:
public void execute() throws MetaClassNotFoundException, FeatureNotFoundException { final EObject currentTarget = this.getContext().getCurrentTarget(); Object value = RuntimeLoggerManager.INSTANCE.decorate(interpreter).evaluate(currentTarget, this.let, ToolPackage.eINSTANCE.getLet_ValueExpression()); String variableName = Optional.ofNullable(this.let.getVariableName()).orElse(""); if (!variableName.isEmpty()) { if ("self".equals(variableName) && value instanceof EObject) { context.setNextPushEObject((EObject) value); for (ICommandTask childTask : this.getChildrenTasks()) { childTask.execute(); } } else { ICommandTask setVariableChildTask = new InterpretedExpressionVariableTask(context, extPackage, InterpretedExpressionVariableTask.KIND_SET, variableName, value, interpreter); this.getChildrenTasks().add(setVariableChildTask); this.let.getSubModelOperations().stream().map(childModelOperation -> { return new ExecuteToolOperationTask(extPackage, currentTarget, context.getRepresentation(), childModelOperation, uiCallback); }).forEach(this.getChildrenTasks()::add); ICommandTask unsetVariableChildTask = new InterpretedExpressionVariableTask(context, extPackage, InterpretedExpressionVariableTask.KIND_UNSET, variableName, value, interpreter); this.getChildrenTasks().add(unsetVariableChildTask); for (ICommandTask childTask : this.getChildrenTasks()) { childTask.execute(); } } } }
Source:
protected AdsFandomObject loadPage(String pageName, String pageType) { String pageUrl; String queryString = Configuration.getQS(); Boolean isF2 = queryString.matches(".*f2(?=\\=|&|$|\\n).*"); PageObjectLogging.log("queryString", queryString, true); PageObjectLogging.log("isF2", isF2.toString(), true); if(isF2) { pageUrl = urlBuilder.getF2Url(pageName, pageType); } else { switch (pageType) { case PAGE_TYPE_HUB: pageUrl = urlBuilder.getUrlForFandomHub(pageName); break; case PAGE_TYPE_ARTICLE: default: pageUrl = urlBuilder.getUrlForFandomPage(pageName); break; } } return new AdsFandomObject(driver, pageUrl); }

Target:
protected AdsFandomObject loadPage(String pageName, String pageType) { String pageUrl; Boolean isF2 = isF2(); if(isF2) { pageUrl = urlBuilder.getF2Url(pageName, pageType); } else { switch (pageType) { case PAGE_TYPE_HUB: pageUrl = urlBuilder.getUrlForFandomHub(pageName); break; case PAGE_TYPE_ARTICLE: default: pageUrl = urlBuilder.getUrlForFandomPage(pageName); break; } } return new AdsFandomObject(driver, pageUrl); }
Source:
public void testCreate3desSubKey() throws Exception { byte[] input1 = CodePointIterator.ofString("FFFFFFFFFFFFFF").hexDecode().drain(); byte[] output1 = create3desSubKey(input1, 0); assertEquals("FEFEFEFEFEFEFEFE".toLowerCase(Locale.ENGLISH), ByteIterator.ofBytes(output1).hexEncode().drainToString()); byte[] input2 = CodePointIterator.ofString("d7c920cf2564cec39c570490f7ea").hexDecode().drain(); byte[] output2 = create3desSubKey(input2, 0); assertEquals("D6E54919F22A929D".toLowerCase(Locale.ENGLISH), ByteIterator.ofBytes(output2).hexEncode().drainToString()); byte[] input3 = CodePointIterator.ofString("d7c920cf2564cec39c570490f7ea").hexDecode().drain(); byte[] output3 = create3desSubKey(input3, 7); assertEquals("C2CE15E04986DFD5".toLowerCase(Locale.ENGLISH), ByteIterator.ofBytes(output3).hexEncode().drainToString()); }

Target:
public void testCreate3desSubKey() throws Exception { byte[] input1 = CodePointIterator.ofString("FFFFFFFFFFFFFF").hexDecode().drain(); byte[] output1 = create3desSubKey(input1, 0); assertEquals("FEFEFEFEFEFEFEFE".toLowerCase(Locale.ROOT), ByteIterator.ofBytes(output1).hexEncode().drainToString()); byte[] input2 = CodePointIterator.ofString("d7c920cf2564cec39c570490f7ea").hexDecode().drain(); byte[] output2 = create3desSubKey(input2, 0); assertEquals("D6E54919F22A929D".toLowerCase(Locale.ROOT), ByteIterator.ofBytes(output2).hexEncode().drainToString()); byte[] input3 = CodePointIterator.ofString("d7c920cf2564cec39c570490f7ea").hexDecode().drain(); byte[] output3 = create3desSubKey(input3, 7); assertEquals("C2CE15E04986DFD5".toLowerCase(Locale.ROOT), ByteIterator.ofBytes(output3).hexEncode().drainToString()); }
Source:
public Map<Long, Double> uniquenessDistribution(long histogramSize) { Map<Long, Double> out = new TreeMap<>(); LongStream.rangeClosed(1, histogramSize).forEach(l -> out.put(l, 0D)); int size = minhash.size(); for (HyperLogLog hll : minhash.values()) { long bucket = Math.min(hll.cardinality(), histogramSize); out.merge(bucket, (double) 1 / size, Double::sum); } return out; }

Target:
public Long2DoubleMap uniquenessDistribution(long histogramSize) { Long2DoubleMap out = new Long2DoubleOpenHashMap(); PrimitiveIterator.OfLong iterator = LongStream.rangeClosed(1, histogramSize).iterator(); while (iterator.hasNext()) { out.put(iterator.nextLong(), 0D); } int size = minhash.size(); for (HyperLogLog hll : minhash.values()) { long bucket = Math.min(hll.cardinality(), histogramSize); out.merge(bucket, (double) 1 / size, Double::sum); } return out; }
Source:
protected void runInContext() { try { s_logger.debug("HostOutOfBandManagementStatsCollector is running..."); List<OutOfBandManagementVO> outOfBandManagementHosts = outOfBandManagementDao.findAllByManagementServer(ManagementServerNode.getManagementServerId()); if (outOfBandManagementHosts == null) { return; } for (OutOfBandManagement outOfBandManagementHost : outOfBandManagementHosts) { Host host = _hostDao.findById(outOfBandManagementHost.getHostId()); if (host == null) { continue; } if (outOfBandManagementService.isOutOfBandManagementEnabled(host)) { outOfBandManagementService.submitBackgroundPowerSyncTask(host); } else { if (outOfBandManagementHost.getPowerState() != OutOfBandManagement.PowerState.Disabled) { if (outOfBandManagementService.transitionPowerStateToDisabled(Collections.singletonList(host))) { s_logger.debug("Out-of-band management was disabled in zone/cluster/host, disabled power state for host id:" + host.getId()); } } } } } catch (Throwable t) { s_logger.error("Error trying to retrieve host out-of-band management stats", t); } }

Target:
protected void runInContext() { try { s_logger.debug("HostOutOfBandManagementStatsCollector is running..."); List<OutOfBandManagementVO> outOfBandManagementHosts = outOfBandManagementDao.findAllByManagementServer(ManagementServerNode.getManagementServerId()); if (outOfBandManagementHosts == null) { return; } for (OutOfBandManagement outOfBandManagementHost : outOfBandManagementHosts) { Host host = _hostDao.findById(outOfBandManagementHost.getHostId()); if (host == null) { continue; } if (outOfBandManagementService.isOutOfBandManagementEnabled(host)) { outOfBandManagementService.submitBackgroundPowerSyncTask(host); } else if (outOfBandManagementHost.getPowerState() != OutOfBandManagement.PowerState.Disabled) { if (outOfBandManagementService.transitionPowerStateToDisabled(Collections.singletonList(host))) { if (s_logger.isDebugEnabled()) { s_logger.debug("Out-of-band management was disabled in zone/cluster/host, disabled power state for host id:" + host.getId()); } } } } } catch (Throwable t) { s_logger.error("Error trying to retrieve host out-of-band management stats", t); } }
Source:
protected void showLocationFilter() { final Collection<String> locations; if (getCollector() instanceof TargetPlatformClassContributionCollector) { locations = TargetPlatformClassContributionCollector.getInstance().getLocations(); } else if (getCollector() instanceof TargetPlatformIconContributionCollector) { locations = TargetPlatformIconContributionCollector.getInstance().getLocations(); } else { return; } final HashSet<String> parentLocations = new HashSet<String>(); for (String location : locations) { if (location.endsWith(".jar")) { int index = location.lastIndexOf(File.separator); if (index >= 0) { location = location.substring(0, index); parentLocations.add(location); } } else { parentLocations.add(location); } } final ArrayList<String> sorted = new ArrayList<String>(parentLocations); Collections.sort(sorted); TitleAreaFilterDialog dlg = new TitleAreaFilterDialog(getShell(), new ColumnLabelProvider()) { @Override protected Control createContents(Composite parent) { Control ret = super.createContents(parent); getViewer().setInput(sorted); setMessage("Select the location to filter on."); setTitle("Location Filter"); getShell().setText("Location Filter"); setTitleImage(new Image(getShell().getDisplay(), getClass().getResourceAsStream("/icons/full/wizban/location_wiz.png"))); return ret; } }; if (dlg.open() == Dialog.OK) { setFilterLocations((List<String>) dlg.asList()); refreshSearch(); } updateUiState(); }

Target:
protected void showLocationFilter() { final Collection<String> locations; if (getCollector() instanceof TargetPlatformClassContributionCollector) { locations = TargetPlatformClassContributionCollector.getInstance().getLocations(); } else if (getCollector() instanceof TargetPlatformIconContributionCollector) { locations = TargetPlatformIconContributionCollector.getInstance().getLocations(); } else { return; } final HashSet<String> parentLocations = new HashSet<String>(); for (String location : locations) { if (location.endsWith(".jar")) { int index = location.lastIndexOf(File.separator); if (index >= 0) { location = location.substring(0, index); parentLocations.add(location); } } else { parentLocations.add(location); } } final ArrayList<String> sorted = new ArrayList<String>(parentLocations); Collections.sort(sorted); TitleAreaFilterDialog dlg = new TitleAreaFilterDialog(getShell(), new ColumnLabelProvider()) { @Override protected Control createContents(Composite parent) { Control ret = super.createContents(parent); getViewer().setInput(sorted); setMessage("Select the location to filter on."); setTitle("Location Filter"); getShell().setText("Location Filter"); setTitleImage(imageCache.create("/icons/full/wizban/location_wiz.png")); return ret; } }; if (dlg.open() == Dialog.OK) { setFilterLocations((List<String>) dlg.asList()); refreshSearch(); } updateUiState(); }
Source:
private void applyChanges(LibraryDilution target, LibraryDilution source) { target.setConcentration(source.getConcentration()); if (!autoGenerateIdBarcodes) target.setIdentificationBarcode(source.getIdentificationBarcode()); }

Target:
private void applyChanges(LibraryDilution target, LibraryDilution source) { target.setConcentration(source.getConcentration()); target.setTargetedSequencing(source.getTargetedSequencing()); target.setIdentificationBarcode(source.getIdentificationBarcode()); }
Source:
public void setUp() throws Exception { VARIANT.setIds(Collections.singleton("1_1000_A_C")); VARIANT.addSourceEntry(new VariantSourceEntry("FILE_ID", "STUDY_ID")); List<VariantEntity> variantEntities = Collections.singletonList(VARIANT); Region region = new Region("1", 500, 2000); given(variantEntityRepository.findByRegionsAndComplexFilters(eq(Collections.singletonList(region)), any(), any(), any())) .willReturn(variantEntities); given(variantEntityRepository.countByRegionsAndComplexFilters(eq(Collections.singletonList(region)), any())) .willReturn(new Long(variantEntities.size())); }

Target:
public void setUp() throws Exception { variant = new VariantEntity("1", 1000, 1005, "A", "C"); variant.setIds(Collections.singleton("1_1000_A_C")); variant.addSourceEntry(new VariantSourceEntry("FILE_ID", "STUDY_ID")); List<VariantEntity> variantEntities = Collections.singletonList(variant); Region region = new Region("1", 500, 2000); given(variantEntityRepository.findByRegionsAndComplexFilters(eq(Collections.singletonList(region)), any(), any(), any())) .willReturn(variantEntities); given(variantEntityRepository.countByRegionsAndComplexFilters(eq(Collections.singletonList(region)), any())) .willReturn(Long.valueOf(variantEntities.size())); }
Source:
private boolean isAnalyze(DispoAnnotationData annotation) { String type = annotation.getResolutionType(); boolean toReturn = false; if (type.equals("Modify_Code") || type.equals("Modify_Test") || type.equals("Modify_Reqt")) { toReturn = true; } return toReturn; }

Target:
private boolean isAnalyze(DispoAnnotationData annotation) { String type = annotation.getResolutionType(); boolean toReturn = false; if (type.equals(ANALYZE_CODE) || type.equals(ANALYZE_TEST) || type.equals(ANALYZE_REQT)) { toReturn = true; } return toReturn; }
Source:
public String calculatePartition(final EventType eventType, final JSONObject event, final List<String> partitions) throws InvalidPartitionKeyFieldsException { final List<String> partitionKeyFields = eventType.getPartitionKeyFields(); if (partitionKeyFields.isEmpty()) { throw new RuntimeException("Applying " + this.getClass().getSimpleName() + " although event type " + "has no partition key fields configured."); } try { final JsonPathAccess traversableJsonEvent = new JsonPathAccess(event); final ArrayList<String> fieldValues = new ArrayList<>(); final int hashValue = partitionKeyFields.stream() .map(pkf -> EventCategory.DATA.equals(eventType.getCategory()) ? DATA_PATH_PREFIX + pkf : pkf) .map(Try.wrap(okf -> { final String fieldValue = traversableJsonEvent.get(okf).toString(); fieldValues.add(fieldValue); return stringHash.hashCode(fieldValue); })) .map(Try::getOrThrow) .mapToInt(hc -> hc) .sum(); int partitionIndex = abs(hashValue) % partitions.size(); partitionIndex = hashPartitioningCrutch.adjustPartitionIndex(partitionIndex, partitions.size()); final List<String> sortedPartitions = partitions.stream().sorted().collect(Collectors.toList()); final String partition = sortedPartitions.get(partitionIndex); LOG.info("[HASH_BUG] hash - values:{} -> hash:{} -> index:{} -> partition:{}; " + "partitions of '{}' [PNUM:{}]: {}", fieldValues, hashValue, partitionIndex, partition, eventType.getName(), partitions.size(), partitions.stream().collect(Collectors.joining(","))); return partition; } catch (NakadiRuntimeException e) { final Exception original = e.getException(); if (original instanceof InvalidPartitionKeyFieldsException) { throw (InvalidPartitionKeyFieldsException) original; } else { throw e; } } }

Target:
public String calculatePartition(final EventType eventType, final JSONObject event, final List<String> partitions) throws InvalidPartitionKeyFieldsException { final List<String> partitionKeyFields = eventType.getPartitionKeyFields(); if (partitionKeyFields.isEmpty()) { throw new RuntimeException("Applying " + this.getClass().getSimpleName() + " although event type " + "has no partition key fields configured."); } try { final JsonPathAccess traversableJsonEvent = new JsonPathAccess(event); final int hashValue = partitionKeyFields.stream() .map(pkf -> EventCategory.DATA.equals(eventType.getCategory()) ? DATA_PATH_PREFIX + pkf : pkf) .map(Try.wrap(okf -> { final String fieldValue = traversableJsonEvent.get(okf).toString(); return stringHash.hashCode(fieldValue); })) .map(Try::getOrThrow) .mapToInt(hc -> hc) .sum(); int partitionIndex = abs(hashValue) % partitions.size(); partitionIndex = hashPartitioningCrutch.adjustPartitionIndex(partitionIndex, partitions.size()); final List<String> sortedPartitions = partitions.stream().sorted().collect(Collectors.toList()); return sortedPartitions.get(partitionIndex); } catch (NakadiRuntimeException e) { final Exception original = e.getException(); if (original instanceof InvalidPartitionKeyFieldsException) { throw (InvalidPartitionKeyFieldsException) original; } else { throw e; } } }
Source:
public void shouldInvokePartitionerWhenSet() { final int[] expectedKeys = new int[]{0, 1}; final StreamPartitioner<Integer, String> streamPartitionerMock = EasyMock.mock(StreamPartitioner.class); expect(streamPartitionerMock.partition(anyString(), eq(0), eq("X0"), anyInt())).andReturn(1).times(1); expect(streamPartitionerMock.partition(anyString(), eq(1), eq("X1"), anyInt())).andReturn(1).times(1); replay(streamPartitionerMock); final Repartitioned<Integer, String> repartitioned = Repartitioned .streamPartitioner(streamPartitionerMock) .withName("repartition"); final KStream<Integer, String> repartitionedStream = builder.<Integer, String>stream(inputTopic) .repartition(repartitioned); final MockProcessorSupplier<Integer, String> supplier = new MockProcessorSupplier<>(); repartitionedStream.process(supplier); try (final TopologyTestDriver driver = new TopologyTestDriver(builder.build(), props)) { final TestInputTopic<Integer, String> testInputTopic = driver.createInputTopic( inputTopic, new IntegerSerializer(), new StringSerializer() ); for (int i = 0; i < 2; i++) { testInputTopic.pipeInput(expectedKeys[i], "X" + expectedKeys[i], i + 10); } final MockProcessor<Integer, String> proc = supplier.theCapturedProcessor(); proc.checkAndClearProcessResult( new KeyValueTimestamp<>(0, "X0", 10), new KeyValueTimestamp<>(1, "X1", 11) ); } verify(streamPartitionerMock); }

Target:
public void shouldInvokePartitionerWhenSet() { final int[] expectedKeys = new int[]{0, 1}; final StreamPartitioner<Integer, String> streamPartitionerMock = EasyMock.mock(StreamPartitioner.class); expect(streamPartitionerMock.partition(anyString(), eq(0), eq("X0"), anyInt())).andReturn(1).times(1); expect(streamPartitionerMock.partition(anyString(), eq(1), eq("X1"), anyInt())).andReturn(1).times(1); replay(streamPartitionerMock); final String repartitionOperationName = "test"; final Repartitioned<Integer, String> repartitioned = Repartitioned .streamPartitioner(streamPartitionerMock) .withName(repartitionOperationName); builder.<Integer, String>stream(inputTopic) .repartition(repartitioned); try (final TopologyTestDriver driver = new TopologyTestDriver(builder.build(), props)) { final TestInputTopic<Integer, String> testInputTopic = driver.createInputTopic(inputTopic, new IntegerSerializer(), new StringSerializer()); final String topicName = repartitionOutputTopic(props, repartitionOperationName); final TestOutputTopic<Integer, String> testOutputTopic = driver.createOutputTopic( topicName, new IntegerDeserializer(), new StringDeserializer() ); for (int i = 0; i < 2; i++) { testInputTopic.pipeInput(expectedKeys[i], "X" + expectedKeys[i], i + 10); } assertThat(testOutputTopic.readRecord(), equalTo(new TestRecord<>(0, "X0", Instant.ofEpochMilli(10)))); assertThat(testOutputTopic.readRecord(), equalTo(new TestRecord<>(1, "X1", Instant.ofEpochMilli(11)))); assertTrue(testOutputTopic.readRecordsToList().isEmpty()); } verify(streamPartitionerMock); }
Source:
private void startWorkersHandling() throws InterruptedException { final CountDownLatch workerViewInitialized = new CountDownLatch(1); DruidNodeDiscovery druidNodeDiscovery = druidNodeDiscoveryProvider.getForNodeType(NodeType.MIDDLE_MANAGER); druidNodeDiscovery.registerListener( new DruidNodeDiscovery.Listener() { @Override public void nodesAdded(Collection<DiscoveryDruidNode> nodes) { nodes.forEach(node -> addWorker(toWorker(node))); } @Override public void nodesRemoved(Collection<DiscoveryDruidNode> nodes) { nodes.forEach(node -> removeWorker(toWorker(node))); } @Override public void nodeViewInitialized() { workerViewInitialized.countDown(); } } ); DruidNodeDiscovery druidNodeDiscoveryIndexer = druidNodeDiscoveryProvider.getForNodeType(NodeType.INDEXER); druidNodeDiscoveryIndexer.registerListener( new DruidNodeDiscovery.Listener() { @Override public void nodesAdded(Collection<DiscoveryDruidNode> nodes) { nodes.forEach(node -> addWorker(toWorker(node))); } @Override public void nodesRemoved(Collection<DiscoveryDruidNode> nodes) { nodes.forEach(node -> removeWorker(toWorker(node))); } @Override public void nodeViewInitialized() { workerViewInitialized.countDown(); } } ); long workerDiscoveryStartTime = System.currentTimeMillis(); while (!workerViewInitialized.await(30, TimeUnit.SECONDS)) { if (System.currentTimeMillis() - workerDiscoveryStartTime > TimeUnit.MINUTES.toMillis(5)) { throw new ISE("WTF! Couldn't discover workers."); } else { log.info("Waiting for worker discovery..."); } } log.info("[%s] Workers are discovered.", workers.size()); for (WorkerHolder worker : workers.values()) { log.info("Waiting for worker[%s] to sync state...", worker.getWorker().getHost()); worker.waitForInitialization(); } log.info("Workers have sync'd state successfully."); }

Target:
private void startWorkersHandling() throws InterruptedException { final CountDownLatch workerViewInitialized = new CountDownLatch(1); DruidNodeDiscovery druidNodeDiscovery = druidNodeDiscoveryProvider.getForService( WorkerNodeService.DISCOVERY_SERVICE_KEY ); druidNodeDiscovery.registerListener( new DruidNodeDiscovery.Listener() { @Override public void nodesAdded(Collection<DiscoveryDruidNode> nodes) { nodes.forEach(node -> addWorker(toWorker(node))); } @Override public void nodesRemoved(Collection<DiscoveryDruidNode> nodes) { nodes.forEach(node -> removeWorker(toWorker(node))); } @Override public void nodeViewInitialized() { workerViewInitialized.countDown(); } } ); long workerDiscoveryStartTime = System.currentTimeMillis(); while (!workerViewInitialized.await(30, TimeUnit.SECONDS)) { if (System.currentTimeMillis() - workerDiscoveryStartTime > TimeUnit.MINUTES.toMillis(5)) { throw new ISE("WTF! Couldn't discover workers."); } else { log.info("Waiting for worker discovery..."); } } log.info("[%s] Workers are discovered.", workers.size()); for (WorkerHolder worker : workers.values()) { log.info("Waiting for worker[%s] to sync state...", worker.getWorker().getHost()); worker.waitForInitialization(); } log.info("Workers have sync'd state successfully."); }
Source:
void addThreadMetrics(List<MetricFamilySamples> sampleFamilies) { List<MetricFamilySamples.Sample> threads = new ArrayList<MetricFamilySamples.Sample>(); threads.add( new MetricFamilySamples.Sample( "jvm_threads", Arrays.asList("type"), Arrays.asList("daemon"), threadBean.getDaemonThreadCount())); threads.add( new MetricFamilySamples.Sample( "jvm_threads", Arrays.asList("type"), Arrays.asList("nondaemon"), threadBean.getThreadCount() - threadBean.getDaemonThreadCount())); sampleFamilies.add( new MetricFamilySamples( "jvm_threads", Type.GAUGE, "Thread count of a JVM", threads)); List<MetricFamilySamples.Sample> peakThreads = new ArrayList<MetricFamilySamples.Sample>(); peakThreads.add( new MetricFamilySamples.Sample( "jvm_threads_peak", Arrays.asList("type"), Arrays.asList("peak"), threadBean.getPeakThreadCount())); sampleFamilies.add( new MetricFamilySamples( "jvm_threads_peak", Type.GAUGE, "Peak thread count of a JVM", peakThreads)); List<MetricFamilySamples.Sample> startedThreads = new ArrayList<MetricFamilySamples.Sample>(); startedThreads.add( new MetricFamilySamples.Sample( "jvm_threads_started", Arrays.asList("type"), Arrays.asList("started"), threadBean.getTotalStartedThreadCount())); sampleFamilies.add( new MetricFamilySamples( "jvm_threads", Type.GAUGE, "Started thread count of a JVM", startedThreads)); }

Target:
void addThreadMetrics(List<MetricFamilySamples> sampleFamilies) { sampleFamilies.add( new MetricFamilySamples( "jvm_threads_current", Type.GAUGE, "Current thread count of a JVM", Collections.singletonList( new MetricFamilySamples.Sample( "jvm_threads_current", EMPTY_LABEL, EMPTY_LABEL, threadBean.getThreadCount())))); sampleFamilies.add( new MetricFamilySamples( "jvm_threads_daemon", Type.GAUGE, "Daemon thread count of a JVM", Collections.singletonList( new MetricFamilySamples.Sample( "jvm_threads_daemon", EMPTY_LABEL, EMPTY_LABEL, threadBean.getDaemonThreadCount())))); sampleFamilies.add( new MetricFamilySamples( "jvm_peak_threads", Type.GAUGE, "Peak thread count of a JVM", Collections.singletonList( new MetricFamilySamples.Sample( "jvm_threads_peak", EMPTY_LABEL, EMPTY_LABEL, threadBean.getPeakThreadCount())))); sampleFamilies.add( new MetricFamilySamples( "jvm_threads_started_total", Type.COUNTER, "Started thread count of a JVM", Collections.singletonList( new MetricFamilySamples.Sample( "jvm_threads_started_total", EMPTY_LABEL, EMPTY_LABEL, threadBean.getTotalStartedThreadCount())))); }
Source:
private static Method findMatchingMethod(Class<?> receiver, String method, Object[] args) { Method candidate = null; for (Method m : receiver.getDeclaredMethods()) { if (m.getName().equals(method) && (matches(m.getParameterTypes(), args, isVargsMethod(m, args)))) { if (candidate == null || isMoreSpecific(m, m.getParameterTypes(), isVargsMethod(m, args), candidate, candidate.getParameterTypes(), isVargsMethod(candidate, args))) { candidate = m; } } } return candidate; }

Target:
private static Method findMatchingMethod(Class<?> receiver, String method, Object[] args) { Method candidate = null; for (Method m : receiver.getDeclaredMethods()) { boolean isVarArgs = isVarArgsMethod(m, args); if (m.getName().equals(method) && (matches(m.getParameterTypes(), args, isVarArgs))) { if (candidate == null || isMoreSpecific(m, m.getParameterTypes(), isVarArgs, candidate, candidate.getParameterTypes(), isVarArgsMethod(candidate, args))) { candidate = m; } } } return candidate; }
Source:
private static HiveConf createHiveConf(@Nullable String hiveConfDir, @Nullable String hadoopConfDir) { Configuration hadoopConf = null; if (isNullOrWhitespaceOnly(hadoopConfDir)) { for (String possibleHadoopConfPath : HadoopUtils.possibleHadoopConfPaths(new org.apache.flink.configuration.Configuration())) { hadoopConf = getHadoopConfiguration(possibleHadoopConfPath); if (hadoopConf != null) { break; } } } else { hadoopConf = getHadoopConfiguration(hadoopConfDir); } HiveConf hiveConf = new HiveConf(hadoopConf == null ? new Configuration() : hadoopConf, HiveConf.class); LOG.info("Setting hive conf dir as {}", hiveConfDir); if (hiveConfDir != null) { Path hiveSite = new Path(hiveConfDir, "hive-site.xml"); if (!hiveSite.toUri().isAbsolute()) { hiveSite = new Path("file", null, hiveSite.toString()); } hiveConf.addResource(hiveSite); } return hiveConf; }

Target:
private static HiveConf createHiveConf(@Nullable String hiveConfDir, @Nullable String hadoopConfDir) { Configuration hadoopConf = null; if (isNullOrWhitespaceOnly(hadoopConfDir)) { for (String possibleHadoopConfPath : HadoopUtils.possibleHadoopConfPaths(new org.apache.flink.configuration.Configuration())) { hadoopConf = getHadoopConfiguration(possibleHadoopConfPath); if (hadoopConf != null) { break; } } } else { hadoopConf = getHadoopConfiguration(hadoopConfDir); } if (hadoopConf == null) { hadoopConf = new Configuration(); } HiveConf hiveConf = new HiveConf(hadoopConf, HiveConf.class); LOG.info("Setting hive conf dir as {}", hiveConfDir); if (hiveConfDir != null) { Path hiveSite = new Path(hiveConfDir, "hive-site.xml"); if (!hiveSite.toUri().isAbsolute()) { hiveSite = new Path(new File(hiveSite.toString()).toURI()); } try (InputStream inputStream = hiveSite.getFileSystem(hadoopConf).open(hiveSite)) { hiveConf.addResource(inputStream, hiveSite.toString()); isEmbeddedMetastore(hiveConf); } catch (IOException e) { throw new CatalogException("Failed to load hive-site.xml from specified path:" + hiveSite, e); } } return hiveConf; }
Source:
public ITmfTimestamp getInitialRangeOffset() { final long DEFAULT_INITIAL_OFFSET_VALUE = (1L * 100 * 1000 * 1000); return createTimestamp(DEFAULT_INITIAL_OFFSET_VALUE); }

Target:
public ITmfTimestamp getInitialRangeOffset() { final long DEFAULT_INITIAL_OFFSET_VALUE = (1L * 100 * 1000 * 1000); return new TmfNanoTimestamp(DEFAULT_INITIAL_OFFSET_VALUE); }
Source:
public static String getKafkaGroupId(DatastreamTask task, GroupIdConstructor groupIdConstructor, CommonConnectorMetrics consumerMetrics, Logger logger) { try { String result = groupIdConstructor.getTaskGroupId(task, Optional.of(logger)); return result; } catch (Exception e) { consumerMetrics.updateErrorRate(1, "Can't find group ID", e); throw e; } }

Target:
public static String getKafkaGroupId(DatastreamTask task, GroupIdConstructor groupIdConstructor, CommonConnectorMetrics consumerMetrics, Logger logger) { try { return groupIdConstructor.getTaskGroupId(task, Optional.of(logger)); } catch (Exception e) { consumerMetrics.updateErrorRate(1, "Can't find group ID", e); throw e; } }
Source:
public boolean processRow(ExportRow rd) throws RestartBlockException { if (!m_primed) checkOnFirstRow(); String pval = (rd.partitionValue == null) ? String.valueOf(rd.partitionId) : rd.partitionValue.toString(); ProducerRecord<String, Object> krec; if (m_encodeType == EncodeType.AVRO) { GenericRecord avroRecord = (GenericRecord) m_decoder.decode(rd.generation, rd.tableName, rd.types, rd.names, null, rd.values); krec = new ProducerRecord<>(m_topic, pval, avroRecord); } else { String decoded = (String) m_decoder.decode(rd.generation, rd.tableName, rd.types, rd.names, null, rd.values); krec = new ProducerRecord<>(m_topic, pval, decoded); } try { m_futures.add(m_producer.send(krec, new Callback() { @Override public void onCompletion(RecordMetadata metadata, Exception e) { if (e != null){ LOG.warn("Failed to send data. Verify if the kafka server matches bootstrap.servers %s", e, m_decoderProducerConfig.getProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG)); m_failure.compareAndSet(false, true); } } })); } catch (KafkaException e) { LOG.warn("Unable to send %s", e, krec); throw new RestartBlockException("Unable to send message", e, true); } catch (IllegalStateException e) { LOG.warn("Unable to send %s", e, krec); if (m_producer != null) try { m_producer.close(); } catch (Exception ignoreIt) m_primed = false; throw new RestartBlockException("Unable to send message", e, true); } return true; }

Target:
public boolean processRow(ExportRow rd) throws RestartBlockException { if (!m_primed) checkOnFirstRow(); String pval = (rd.partitionValue == null) ? String.valueOf(rd.partitionId) : rd.partitionValue.toString(); ProducerRecord<String, Object> krec; if (m_encodeFormat == EncodeFormat.AVRO) { AvroDecoder decoder = m_tableAvroDecoderMap.computeIfAbsent(rd.tableName, k -> new AvroDecoder.Builder().build()); GenericRecord avroRecord = decoder.decode(rd.generation, rd.tableName, rd.types, rd.names, null, rd.values); krec = new ProducerRecord<>(m_topic, pval, avroRecord); } else { String decoded = m_csvDecoder.decode(rd.generation, rd.tableName, rd.types, rd.names, null, rd.values); krec = new ProducerRecord<>(m_topic, pval, decoded); } try { m_futures.add(m_producer.send(krec, new Callback() { @Override public void onCompletion(RecordMetadata metadata, Exception e) { if (e != null){ LOG.warn("Failed to send data. Verify if the kafka server matches bootstrap.servers %s", e, m_decoderProducerConfig.getProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG)); m_failure.compareAndSet(false, true); } } })); } catch (KafkaException e) { LOG.warn("Unable to send %s", e, krec); throw new RestartBlockException("Unable to send message", e, true); } catch (IllegalStateException e) { LOG.warn("Unable to send %s", e, krec); if (m_producer != null) try { m_producer.close(); } catch (Exception ignoreIt) m_primed = false; throw new RestartBlockException("Unable to send message", e, true); } return true; }
Source:
public void onClearFieldAnchorClick(final ClickEvent e) { presenter.setValue(""); }

Target:
public void onClearFieldAnchorClick(final ClickEvent e) { presenter.setValue(""); typedValueSelector.select(); }
Source:
public void test() { ServiceAmbassador ambassador = new ServiceAmbassador(); long result = ambassador.doRemoteFunction(10); assert result == 100 || result == -1; }

Target:
public void test() { long result = new ServiceAmbassador().doRemoteFunction(10); assert result == 100 || result == -1; }
Source:
public static List<String> getStringsFromJSONArray(JSONArray jsonStringArray) throws JSONException { List<String> stringArray = Lists.newArrayList(); for (int stringIndex = 0; stringIndex < jsonStringArray.length(); stringIndex++) { stringArray.add(jsonStringArray.getString(stringIndex)); } return stringArray; }

Target:
public static List<String> getStringsFromJSONArray(JSONArray jsonStringArray) throws JSONException { List<String> stringArray = Lists.newArrayListWithCapacity(jsonStringArray.length()); for (int stringIndex = 0; stringIndex < jsonStringArray.length(); stringIndex++) { stringArray.add(jsonStringArray.getString(stringIndex)); } return stringArray; }
Source:
void loadINodeSectionInParallel(ExecutorService service, ArrayList<FileSummary.Section> sections, String compressionCodec, StartupProgress prog, Step currentStep) throws IOException { LOG.info("Loading the INode section in parallel with sub-sections", sections.size()); CountDownLatch latch = new CountDownLatch(sections.size()); AtomicInteger totalLoaded = new AtomicInteger(0); final CopyOnWriteArrayList<IOException> exceptions = new CopyOnWriteArrayList<>(); for (int i=0; i < sections.size(); i++) { FileSummary.Section s = sections.get(i); InputStream ins = parent.getInputStreamForSection(s, compressionCodec); if (i == 0) { loadINodeSectionHeader(ins, prog, currentStep); } service.submit(new Runnable() { public void run() { try { totalLoaded.addAndGet(loadINodesInSection(ins, null)); prog.setCount(Phase.LOADING_FSIMAGE, currentStep, totalLoaded.get()); } catch (Exception e) { LOG.error("An exception occurred loading INodes in parallel", e); exceptions.add(new IOException(e)); } finally { latch.countDown(); try { ins.close(); } catch (IOException ioe) { LOG.warn("Failed to close the input stream, ignoring", ioe); } } } }); } try { latch.await(); } catch (InterruptedException e) { LOG.info("Interrupted waiting for countdown latch"); } if (exceptions.size() != 0) { LOG.error("{} exceptions occurred loading INodes", exceptions.size()); throw exceptions.get(0); } LOG.info("Completed loading all INode sections. Loaded inodes.", totalLoaded.get()); }

Target:
void loadINodeSectionInParallel(ExecutorService service, ArrayList<FileSummary.Section> sections, String compressionCodec, StartupProgress prog, Step currentStep) throws IOException { LOG.info("Loading the INode section in parallel with sub-sections", sections.size()); long expectedInodes = 0; CountDownLatch latch = new CountDownLatch(sections.size()); AtomicInteger totalLoaded = new AtomicInteger(0); final CopyOnWriteArrayList<IOException> exceptions = new CopyOnWriteArrayList<>(); for (int i=0; i < sections.size(); i++) { FileSummary.Section s = sections.get(i); InputStream ins = parent.getInputStreamForSection(s, compressionCodec); if (i == 0) { expectedInodes = loadINodeSectionHeader(ins, prog, currentStep); } service.submit(() -> { try { totalLoaded.addAndGet(loadINodesInSection(ins, null)); prog.setCount(Phase.LOADING_FSIMAGE, currentStep, totalLoaded.get()); } catch (Exception e) { LOG.error("An exception occurred loading INodes in parallel", e); exceptions.add(new IOException(e)); } finally { latch.countDown(); try { ins.close(); } catch (IOException ioe) { LOG.warn("Failed to close the input stream, ignoring", ioe); } } }); } try { latch.await(); } catch (InterruptedException e) { LOG.info("Interrupted waiting for countdown latch"); } if (exceptions.size() != 0) { LOG.error("{} exceptions occurred loading INodes", exceptions.size()); throw exceptions.get(0); } if (totalLoaded.get() != expectedInodes) { throw new IOException("Expected to load "+expectedInodes+" in " + "parallel, but loaded "+totalLoaded.get()+". The image may " + "be corrupt."); } LOG.info("Completed loading all INode sections. Loaded inodes.", totalLoaded.get()); }
Source:
private boolean checkForOverwrite() { List<TmfTraceElement> traces = fTmfTraceFolder.getTraces(); TracePackageElement[] traceElements = (TracePackageElement[]) getElementViewer().getInput(); for (TracePackageElement packageElement : traceElements) { TracePackageTraceElement traceElement = (TracePackageTraceElement) packageElement; if (!AbstractTracePackageOperation.isFilesChecked(traceElement)) { continue; } for (TmfTraceElement t : traces) { String traceName = traceElement.getText(); if (t.getName().equals(traceName)) { final MessageDialog dialog = new MessageDialog(getContainer() .getShell(), null, null, MessageFormat.format(Messages.ImportTracePackageWizardPage_AlreadyExists, traceName), MessageDialog.QUESTION, new String[] { IDialogConstants.NO_LABEL, IDialogConstants.YES_TO_ALL_LABEL, IDialogConstants.YES_LABEL, }, 2) { @Override protected int getShellStyle() { return super.getShellStyle() | SWT.SHEET; } }; int code = dialog.open(); final String[] response = new String[] { IDialogConstants.NO_LABEL, IDialogConstants.YES_TO_ALL_LABEL, IDialogConstants.YES_LABEL }; if (response[code].equals(IDialogConstants.YES_TO_ALL_LABEL)) { return true; } else if (response[code].equals(IDialogConstants.NO_LABEL)) { return false; } } } } return true; }

Target:
private boolean checkForOverwrite() { TracePackageElement[] traceElements = (TracePackageElement[]) getElementViewer().getInput(); List<TracePackageTraceElement> noImportTraces = new ArrayList<TracePackageTraceElement>(); boolean noToAll = false; for (TracePackageElement packageElement : traceElements) { TracePackageTraceElement traceElement = (TracePackageTraceElement) packageElement; if (!AbstractTracePackageOperation.isFilesChecked(traceElement)) { continue; } if (noToAll) { noImportTraces.add(traceElement); continue; } String traceName = traceElement.getText(); if (traceExists(traceName)) { int returnCode = promptForOverwrite(traceName); final String[] response = new String[] { IDialogConstants.NO_TO_ALL_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.YES_TO_ALL_LABEL, IDialogConstants.YES_LABEL }; if (response[returnCode].equals(IDialogConstants.YES_TO_ALL_LABEL)) { break; } else if (response[returnCode].equals(IDialogConstants.NO_TO_ALL_LABEL)) { noToAll = true; noImportTraces.add(traceElement); } else if (response[returnCode].equals(IDialogConstants.NO_LABEL)) { noImportTraces.add(traceElement); } } } for (TracePackageTraceElement t : noImportTraces) { for (TracePackageElement e : t.getChildren()) { if (e instanceof TracePackageFilesElement) { ((TracePackageFilesElement) e).setChecked(false); } } } return true; }
Source:
public List<MemberCandidate> getCompleteCandidates(PerunSession sess, Vo vo, Group group, List<String> attrNames, String searchString, List<ExtSource> extSources) throws InternalErrorException { List<RichUser> richUsers = getRichUsersForMemberCandidates(sess, vo, attrNames, searchString); List<Candidate> candidates = findCandidates(sess, group, searchString, extSources, false); return createMemberCandidates(sess, richUsers, vo, group, candidates, attrNames); }

Target:
public List<MemberCandidate> getCompleteCandidates(PerunSession sess, Vo vo, Group group, List<String> attrNames, String searchString, List<ExtSource> extSources) throws InternalErrorException { List<RichUser> richUsers = getRichUsersForMemberCandidates(sess, vo, attrNames, searchString); List<Candidate> candidates = findCandidates(sess, group, searchString, extSources, false); if (vo == null) { vo = getPerunBl().getGroupsManagerBl().getVo(sess, group); } return createMemberCandidates(sess, richUsers, vo, group, candidates, attrNames); }
Source:
private void initEditMessageAction() { NativeMap<ActionInfo> actions = changeInfo.revision(revision).actions(); if (actions != null && actions.containsKey("message")) { editMessage.setVisible(true); editMessageAction = new EditMessageAction(changeInfo.legacy_id(), revision, changeInfo.revision(revision).commit().message(), style, editMessage, reply); keysAction.add(new KeyCommand(0, 'e', Util.C.keyEditMessage()) { @Override public void onKeyPress(KeyPressEvent event) { editMessageAction.onEdit(); } }); } else { editMessage.setVisible(false); } }

Target:
private void initEditMessageAction() { NativeMap<ActionInfo> actions = changeInfo.revision(revision).actions(); if (actions != null && actions.containsKey("message")) { editMessage.setVisible(true); editMessageAction = new EditMessageAction( changeInfo.legacy_id(), revision, changeInfo.revision(revision).commit().message(), style, editMessage, reply); keysAction.add(new KeyCommand(0, 'e', Util.C.keyEditMessage()) { @Override public void onKeyPress(KeyPressEvent event) { editMessageAction.onEdit(); } }); } }
Source:
private void completeInner() { if (WIP_FOR_UNSUBSCRIBE_UPDATER.decrementAndGet(this) == 0) { unsubscribe(); } if (groups.isEmpty() && (terminated == 1 || child.isUnsubscribed())) { if (COMPLETION_EMITTED_UPDATER.compareAndSet(this, 0, 1)) { if (child.isUnsubscribed()) { unsubscribe(); } else if (!errorEmitted) { child.onCompleted(); } } } }

Target:
private void completeInner() { if (WIP_FOR_UNSUBSCRIBE_UPDATER.decrementAndGet(this) == 0) { unsubscribe(); } else if (groups.isEmpty() && terminated == TERMINATED_WITH_COMPLETED) { if (COMPLETION_EMITTED_UPDATER.compareAndSet(this, 0, 1)) { child.onCompleted(); } } }
Source:
public void onWireReceive(final WireEnvelope wireEnvelope) { requireNonNull(wireEnvelope, message.wireEnvelopeNonNull()); logger.debug(message.wireEnvelopeReceived(), wireEnvelope); if (isCacheExpired()) { refreshCachedRecords(); } if (nonNull(this.lastRecords)) { this.wireSupport.emit(this.lastRecords); } else { this.wireSupport.emit(new ArrayList<WireRecord>()); } }

Target:
public void onWireReceive(final WireEnvelope wireEnvelope) { requireNonNull(wireEnvelope, message.wireEnvelopeNonNull()); logger.debug(message.wireEnvelopeReceived(), wireEnvelope); if (isCacheExpired()) { refreshCachedRecords(); } List<WireRecord> result; if (nonNull(this.lastRecords)) { result = Collections.unmodifiableList(this.lastRecords); } else { result = Collections.unmodifiableList(new ArrayList<WireRecord>()); } this.wireSupport.emit(result); }
Source:
private void onFragmentLoaded() { if (searchAdapter == null) { searchAdapter = new SearchlistAdapter(getActivity(), itemAccess); setListAdapter(searchAdapter); } searchAdapter.notifyDataSetChanged(); setListShown(true); String query = getArguments().getString(ARG_QUERY); setEmptyText(getString(R.string.no_results_for_query) + " \"" + query + "\""); }

Target:
private void onFragmentLoaded() { if (searchAdapter == null) { searchAdapter = new SearchlistAdapter(getActivity(), itemAccess); setListAdapter(searchAdapter); } searchAdapter.notifyDataSetChanged(); setListShown(true); String query = getArguments().getString(ARG_QUERY); setEmptyText(getString(R.string.no_results_for_query, query)); }
Source:
private void search() { logger.debug("start search"); try { runQuery( getExtensionByName((String)this.actionArgs.get("authz-name")) ); } catch (Exception ex) { throw new RuntimeException(ex); } logger.info("search action completed"); }

Target:
private void search() { logger.debug("start search"); try { runQuery( getExtensionManager().getExtensionByName((String) this.actionArgs.get("authz-name")) ); } catch (Exception ex) { throw new RuntimeException(ex); } logger.info("search action completed"); }
Source:
public void testGetAppointmentByIDAndExpectIsOk() throws Exception { List<String> applicants = new ArrayList<>(); applicants.add("testApplicantId"); List<String> users = new ArrayList<>(); users.add("testUserId"); Appointment appointment = new Appointment(users, applicants, 1401866602 + TOMORROW); String appointmentJson = jsonUtil.toJson(appointment); mockMvc.perform( get("/appointments/0/") ) .andExpect(content().string(appointmentJson)) .andExpect(status().isOk()); }

Target:
public void testGetAppointmentByIDAndExpectIsOk() throws Exception { List<String> applicants2 = new ArrayList<>(); applicants2.add("My test Appointment"); List<String> users2 = new ArrayList<>(); users2.add("testUserId"); Appointment appointment2 = new Appointment(users2, applicants2, 555); String appointmentJson2 = jsonUtil.toJson(appointment2); MvcResult TestAppointmentID = mockMvc.perform( post("/appointments") .contentType(MediaType.APPLICATION_JSON) .content(appointmentJson2) ) .andExpect(content().contentType("application/json")) .andExpect(status().isAccepted()) .andReturn(); String AppointmentID = TestAppointmentID.getResponse().getContentAsString(); mockMvc.perform( get("/appointments/" + AppointmentID) .contentType(MediaType.APPLICATION_JSON) ) .andExpect(content().contentType("application/json;charset=UTF-8")) .andExpect(content().string(appointmentJson2)) .andExpect(status().isOk()); }
Source:
public void shouldNotHitCacheLoaderWhenWarm() throws Throwable { recursiveFileRemove(indexDir); Cache<Object, Object> cache = cacheManagers.get(0).getCache(); Directory directory = DirectoryBuilder.newDirectoryInstance(cache, cache, cache, INDEX_NAME).create(); assertTrue(LuceneUtils.readTerms("main", directory).contains("500")); assertEquals(TERMS_NUMBER + 1, LuceneUtils.numDocs(directory)); LuceneUtils.collect(directory, TERMS_NUMBER); }

Target:
public void shouldNotHitCacheLoaderWhenWarm() throws Throwable { Cache<Object, Object> cache = cacheManagers.get(0).getCache(); Directory directory = DirectoryBuilder.newDirectoryInstance(cache, cache, cache, INDEX_NAME).create(); assertTrue(LuceneUtils.readTerms("main", directory).contains("500")); assertEquals(TERMS_NUMBER + 1, LuceneUtils.numDocs(directory)); LuceneUtils.collect(directory, TERMS_NUMBER); assertNoCacheLoaderInteractions(); }