auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Integer index() { try { if (!documents.isEmpty()) { Integer waitSeconds = 0; while (!index.hasStarted() && waitSeconds < 121) { waitSeconds += INDEX_CREATION_DELAY/1000; LOGGER.warn("Index is not ready, has been waiting for seconds", waitSeconds); try { Thread.sleep(INDEX_CREATION_DELAY); } catch (InterruptedException e) { LOGGER.error("interrupted"); } } <START> if (waitSeconds == 121) { <END> LOGGER.error("Stop waiting on index creation. Opting out"); System.exit(1); } index.addDocuments(ImmutableList.copyOf(documents)); final Integer count = documents.size(); LOGGER.info("Indexed documents", count); documents.clear(); return count; } } catch (IndexDoesNotExistException e) { LOGGER.error("Index does not exist: {}", e.getMessage()); System.exit(1); } catch (IOException e) { LOGGER.error("Failed connecting to searchify: {}", e.getMessage()); } catch(IndexOutOfBoundsException e) { LOGGER.error("Searchify client error: {}", e.getMessage()); } catch (UnexpectedCodeException e) { LOGGER.error("Unexpected: {}", e.getMessage()); } return 0; }</code><technical_language>=</technical_language>

Target:
public Integer index() { try { if (!documents.isEmpty()) { index.addDocuments(ImmutableList.copyOf(documents)); final Integer count = documents.size(); LOGGER.info("Indexed documents", count); documents.clear(); return count; } } catch (IndexDoesNotExistException e) { LOGGER.error("Index does not exist: {}", e.getMessage()); System.exit(1); } catch (IOException e) { LOGGER.error("Failed connecting to searchify: {}", e.getMessage()); } catch(IndexOutOfBoundsException e) { LOGGER.error("Searchify client error: {}", e.getMessage()); } catch (UnexpectedCodeException e) { LOGGER.error("Unexpected: {}", e.getMessage()); } return 0; }
Source:
<code>private Mono<Object> authenticate(ServiceMessage message) { return Mono.defer( () -> { if (!methodInfo.isAuth()) { return Mono.empty(); } Object credentials = message.credentials(); <START> if (credentials == null) { <END> throw new UnauthorizedException("Credentials not found"); } if (authenticator == null) { throw new UnauthorizedException("Authenticator not found"); } return authenticator.authenticate(credentials); }) .defaultIfEmpty(NO_PRINCIPAL); }</code><technical_language>redundant check, IMHO check it, call authenticatorImpl a decision</technical_language>

Target:
private Mono<Object> authenticate(ServiceMessage message) { return Mono.defer( () -> { if (!methodInfo.isAuth()) { return Mono.empty(); } if (authenticator == null) { throw new UnauthorizedException("Authenticator not found"); } return authenticator.authenticate(message).onErrorMap(this::toUnauthorizedException); }) .defaultIfEmpty(NO_PRINCIPAL); }
Source:
<code>protected void addVmPayload() { VmPayload payload = getParameters().getVmPayload(); if (payload != null) { VmDeviceUtils.addManagedDevice(new VmDeviceId(Guid.NewGuid(), getParameters().getVmId()), VmDeviceType.DISK, payload.getType(), payload.getSpecParams(), true, true, <START> ""); <END> } }</code><technical_language>please remove alias setting (should encapsulated in addManagedDevice</technical_language>

Target:
protected void addVmPayload() { VmPayload payload = getParameters().getVmPayload(); if (payload != null) { VmDeviceUtils.addManagedDevice(new VmDeviceId(Guid.NewGuid(), getParameters().getVmId()), VmDeviceType.DISK, payload.getType(), payload.getSpecParams(), true, true); } }
Source:
<code>public void testCollectionIsNotArray() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class A {\n"); buf.append(" public void foo() {\n"); buf.append(" java.util.List list = new ArrayList();\n"); buf.append(" list.add(null);\n"); buf.append(" for (int i = 0; i < list.size(); i++) {\n"); buf.append(" System.out.println(list.get(i));\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("A.java", buf.toString(), false, null); List<IJavaCompletionProposal> proposals= fetchConvertingProposal(buf, cu); assertNotNull(fConvertLoopProposal); String preview1= getPreviewContent(fConvertLoopProposal); buf= new <START> StringBuffer(); <END> buf.append("package test1;\n"); buf.append("public class A {\n"); buf.append(" public void foo() {\n"); buf.append(" java.util.List list = new ArrayList();\n"); buf.append(" list.add(null);\n"); buf.append(" for (Object element : list) {\n"); buf.append(" System.out.println(element);\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); String expected= buf.toString(); assertEqualString(preview1, expected); assertCorrectLabels(proposals); assertCorrectLabels(proposals); }</code><technical_language>Is a reason for stringbuffer instead of stringbuilder</technical_language>

Target:
public void testCollectionIsNotArray() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuilder buf= new StringBuilder(); buf.append("package test1;\n"); buf.append("public class A {\n"); buf.append(" public void foo() {\n"); buf.append(" java.util.List list = new ArrayList();\n"); buf.append(" list.add(null);\n"); buf.append(" for (int i = 0; i < list.size(); i++) {\n"); buf.append(" System.out.println(list.get(i));\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("A.java", buf.toString(), false, null); List<IJavaCompletionProposal> proposals= fetchConvertingProposal(buf, cu); assertNotNull(fConvertLoopProposal); String preview1= getPreviewContent(fConvertLoopProposal); buf= new StringBuilder(); buf.append("package test1;\n"); buf.append("public class A {\n"); buf.append(" public void foo() {\n"); buf.append(" java.util.List list = new ArrayList();\n"); buf.append(" list.add(null);\n"); buf.append(" for (Object element : list) {\n"); buf.append(" System.out.println(element);\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); String expected= buf.toString(); assertEqualString(preview1, expected); assertCorrectLabels(proposals); assertCorrectLabels(proposals); }
Source:
<code>void addResource(int id, String type, String name) { ResName resName = new ResName(packageName, type, name); int resIdPackageIdentifier = ResourceIds.getPackageIdentifier(id); if (getPackageIdentifier() == 0) { this.packageIdentifier = resIdPackageIdentifier; } else if (getPackageIdentifier() != resIdPackageIdentifier) { throw new IllegalArgumentException("Attempted to add resId " + resIdPackageIdentifier + " to PackageResourceIndex with packageIdentifier " + getPackageIdentifier()); } <START> ResName existingEntry = resourceTable.put(id, resName); <END> if (existingEntry != null && !existingEntry.equals(resName)) { throw new IllegalArgumentException("ResId " + Integer.toHexString(id) + " mapped to both " + resName + " and " + existingEntry); } }</code><technical_language>Method synchronized probably</technical_language>

Target:
synchronized void addResource(int id, String type, String name) { if (ResourceIds.isFrameworkResource(id)) { androidResourceIdGenerator.record(id, type, name); } ResName resName = new ResName(packageName, type, name); int resIdPackageIdentifier = ResourceIds.getPackageIdentifier(id); if (getPackageIdentifier() == 0) { this.packageIdentifier = resIdPackageIdentifier; } else if (getPackageIdentifier() != resIdPackageIdentifier) { throw new IllegalArgumentException("Attempted to add resId " + resIdPackageIdentifier + " to PackageResourceIndex with packageIdentifier " + getPackageIdentifier()); } ResName existingEntry = resourceTable.put(id, resName); if (existingEntry != null && !existingEntry.equals(resName)) { throw new IllegalArgumentException("ResId " + Integer.toHexString(id) + " mapped to both " + resName + " and " + existingEntry); } }
Source:
<code>private void queueWork(int maximumMessageCount, Duration maxWaitTime, FluxSink<ServiceBusReceivedMessageContext> emitter) { <START> if (messageProcessor.get() != null && messageProcessor.get().isDisposed()) { <END> logger.error("[{}]: Can not receive messaged because client is closed.", asyncClient.getEntityPath()); return; } if (messageProcessor.get() == null) { EmitterProcessor<ServiceBusReceivedMessageContext> processor = asyncClient.receive(DEFAULT_RECEIVE_OPTIONS) .subscribeWith(EmitterProcessor.create(false)); if (!messageProcessor.compareAndSet(null, processor)) { processor.dispose(); } logger.info("[{}]: Started ContinuesMessageSubscriber message subscriber for entity.", asyncClient.getEntityPath()); } Disposable newSubscription = messageProcessor.get() .take(maximumMessageCount) .timeout(maxWaitTime) .doOnNext(messageContext -> { emitter.next(messageContext); }) .doOnError(throwable -> { emitter.error(throwable); }) .doOnComplete(emitter::complete) .subscribe(); Disposable oldSubscription = messageProcessorSubscription.getAndSet(newSubscription); if (oldSubscription != null) { oldSubscription.dispose(); } }</code><technical_language>This thread safe, in time check for null, else set it. if is null, create it, possibly overwrite existing EmitterProcessor set in this time</technical_language>

Target:
private void queueWork(int maximumMessageCount, Duration maxWaitTime, FluxSink<ServiceBusReceivedMessageContext> emitter) { synchronized (lock) { final long id = idGenerator.getAndIncrement(); EmitterProcessor<ServiceBusReceivedMessageContext> emitterProcessor = messageProcessor.get(); final SynchronousReceiveWork work = new SynchronousReceiveWork(id, maximumMessageCount, maxWaitTime, emitter); final SynchronousMessageSubscriber syncSubscriber = new SynchronousMessageSubscriber(work); logger.info("[{}]: Started synchronous message subscriber.", id); if (emitterProcessor == null) { emitterProcessor = this.asyncClient.receive(DEFAULT_RECEIVE_OPTIONS) .subscribeWith(EmitterProcessor.create(asyncClient.getReceiverOptions().getPrefetchCount(), false)); messageProcessor.set(emitterProcessor); } emitterProcessor.subscribe(syncSubscriber); } }
Source:
<code>private void initSubjectsGrid() { final String subjectItemsJson; try { subjectItemsJson = FileUtil.loadTextFileFromResources(getContext(), R.raw.subjects); final Type type = new TypeToken<List<SubjectModel>>() { }.getType(); final List<SubjectModel> allSubjects = new Gson().fromJson(subjectItemsJson, type); adapter = new SubjectsAdapter(getContext(), allSubjects); binding.glSubjects.setAdapter(adapter); binding.glSubjects.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final SubjectModel subjectModel = adapter.getItem(position); <START> final Intent data = new Intent().putExtra("SUBJECT_FILTER", subjectModel.filter); <END> analyticsRegistry.trackSubjectClicked(subjectModel.filter); getActivity().setResult(Activity.RESULT_OK, data); getActivity().finish(); } }); } catch (IOException e) { e.printStackTrace(); } }</code><technical_language>SUBJECT_FILTER put extra keys in class constants</technical_language>

Target:
private void initSubjectsGrid() { final String subjectItemsJson; try { subjectItemsJson = FileUtil.loadTextFileFromResources(getContext(), R.raw.subjects); final Type type = new TypeToken<List<SubjectModel>>() { }.getType(); final List<SubjectModel> allSubjects = new Gson().fromJson(subjectItemsJson, type); adapter = new SubjectsAdapter(getContext(), allSubjects); binding.glSubjects.setAdapter(adapter); binding.glSubjects.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final SubjectModel subjectModel = adapter.getItem(position); final Intent data = new Intent().putExtra(Router.EXTRA_SUBJECT_FILTER, subjectModel.filter); analyticsRegistry.trackSubjectClicked(subjectModel.filter); getActivity().setResult(Activity.RESULT_OK, data); getActivity().finish(); } }); } catch (IOException e) { e.printStackTrace(); } }
Source:
<code>private InstanceTypeDescription getInstanceTypeInfo() { if (LOG.isDebugEnabled()) { LOG.debug("Connecting compiler to JobManager to dertermine instance information."); } Map<InstanceType, InstanceTypeDescription> instances = null; JobManagerConnector jmc = new JobManagerConnector(this.jobManagerAddress); Thread connectorThread = new Thread(jmc, "Compiler - JobManager connector."); connectorThread.setDaemon(true); connectorThread.start(); try { jmc.waitForCompletion(); instances = jmc.instances; if (instances == null) { throw new NullPointerException("Returned instance map is <null>"); } } catch (Throwable t) { <START> throw new CompilerException("Cannot connect to the JobManager to determine the available machines. " <END> + "Check if the JobManager is running (using the web interface or log files). Reason: " + t.getMessage(), t); } return getType(instances); }</code><technical_language>"available machines" -> "available TaskManagers"</technical_language>

Target:
private InstanceTypeDescription getInstanceTypeInfo() { if (LOG.isDebugEnabled()) { LOG.debug("Connecting compiler to JobManager to dertermine instance information."); } Map<InstanceType, InstanceTypeDescription> instances = null; JobManagerConnector jmc = new JobManagerConnector(this.jobManagerAddress); Thread connectorThread = new Thread(jmc, "Compiler - JobManager connector."); connectorThread.setDaemon(true); connectorThread.start(); try { jmc.waitForCompletion(); instances = jmc.instances; if (instances == null) { throw new NullPointerException("Returned instance map is <null>"); } } catch (IOException e) { throw new CompilerException(e.getMessage()); } catch (Throwable t) { throw new CompilerException("Cannot connect to the JobManager to determine the available TaskManagers. " + "Check if the JobManager is running (using the web interface or log files). Reason: " + t.getMessage(), t); } return getType(instances); }
Source:
<code>public CompletableFuture<? extends Iterable<Row>> apply(BatchIterator<Row> batchIterator) { BatchIterator<ShardedRequests<ShardUpsertRequest, ShardUpsertRequest.Item>> reqBatchIterator = BatchIterators.partition(batchIterator, bulkSize, () -> new ShardedRequests<>(requestFactory), grouper, bulkShardCreationLimiter.or(heapThresholdChecker)); Predicate<ShardedRequests<ShardUpsertRequest, ShardUpsertRequest.Item>> shouldPause = this::shouldPauseOnPartitionCreation; <START> shouldPause.or(heapThresholdChecker); <END> if (batchIterator.involvesIO()) { shouldPause = shouldPause.or(this::shouldPauseOnTargetNodeJobsCounter); } BatchIteratorBackpressureExecutor<ShardedRequests<ShardUpsertRequest, ShardUpsertRequest.Item>, UpsertResults> executor = new BatchIteratorBackpressureExecutor<>( scheduler, this.executor, reqBatchIterator, this::execute, resultCollector.combiner(), resultCollector.supplier().get(), shouldPause, BACKOFF_POLICY ); return executor.consumeIteratorAndExecute() .thenApply(upsertResults -> resultCollector.finisher().apply(upsertResults)); }</code><technical_language>This is currently a no-op result is assigned anything</technical_language>

Target:
public CompletableFuture<? extends Iterable<Row>> apply(BatchIterator<Row> batchIterator) { var reqBatchIterator = BatchIterators.partition( batchIterator, bulkSize, () -> new ShardedRequests<>(requestFactory), grouper, bulkShardCreationLimiter.or(isUsedBytesOverThreshold) ); Predicate<ShardedRequests<ShardUpsertRequest, ShardUpsertRequest.Item>> shouldPause = this::shouldPauseOnPartitionCreation; if (batchIterator.involvesIO()) { shouldPause = shouldPause.or(this::shouldPauseOnTargetNodeJobsCounter); } BatchIteratorBackpressureExecutor<ShardedRequests<ShardUpsertRequest, ShardUpsertRequest.Item>, UpsertResults> executor = new BatchIteratorBackpressureExecutor<>( scheduler, this.executor, reqBatchIterator, this::execute, resultCollector.combiner(), resultCollector.supplier().get(), shouldPause, BACKOFF_POLICY ); return executor.consumeIteratorAndExecute() .thenApply(upsertResults -> resultCollector.finisher().apply(upsertResults)); }
Source:
<code>private static String getTitleValue(Object responseTitle) { if (!(responseTitle instanceof Map)) { return null; } final Map<String, String> map; try { map = (Map<String, String>) responseTitle; return map.get(""); } catch (ClassCastException ignored) { <START> return null; <END> } }</code><technical_language>add some warning message here, in case of ClassCastException</technical_language>

Target:
private String getTitleValue(Object responseTitle) { if (!(responseTitle instanceof Map)) { return null; } final Map<String, String> map; try { map = (Map<String, String>) responseTitle; return map.get(""); } catch (ClassCastException error) { logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error); return null; } }
Source:
<code><START> public String getUsername() { <END> return username; }</code><technical_language>aforementioned "never return null" rule good for string getters here</technical_language>

Target:
public String getUsername() { return StringUtils.notNullStr(username); }
Source:
<code>private final boolean isDateInvalid(Elements elements) { boolean result = false; <START> if (!elements.isEmpty()) { <END> Element dcTermsDateElement = elements.get(0); try { new SimpleDateFormat(MrrtReportTemplateConstants.DATE_FORMAT).parse(dcTermsDateElement.attr("content")); } catch (ParseException ex) { result = true; } } return result; }</code><technical_language>@ivange94 turn this a positive check/guard clause. java if (elements.isEmpty()) { return false; } this removes level of nesting easier read, reader see's immediately if elements is empty return</technical_language>

Target:
private final boolean isDateInvalid(Elements elements) { boolean result = false; if (elements.isEmpty()) { return result; } Element dcTermsDateElement = elements.get(0); try { new SimpleDateFormat(MrrtReportTemplateConstants.DATE_FORMAT).parse(dcTermsDateElement.attr("content")); } catch (ParseException ex) { result = true; } return result; }
Source:
<code>public void addDeadWatcher(int watcherBit) { while (maxInProcessingDeadWatchers > 0 && !stopped && totalDeadWatchers.get() >= maxInProcessingDeadWatchers) { try { RATE_LOGGER.rateLimitLog("Waiting for dead watchers cleaning"); synchronized(produserAndConsumerLock) { produserAndConsumerLock.wait(100); } } catch (InterruptedException e) { LOG.info("Got interrupted while waiting for dead watches " + "queue size"); break; } } <START> synchronized (this) { <END> if (deadWatchers.add(watcherBit)) { totalDeadWatchers.incrementAndGet(); if (deadWatchers.size() >= watcherCleanThreshold) { synchronized (cleanEvent) { cleanEvent.notifyAll(); } } } } }</code><technical_language>indent correct</technical_language>

Target:
public void addDeadWatcher(int watcherBit) { while (maxInProcessingDeadWatchers > 0 && !stopped && totalDeadWatchers.get() >= maxInProcessingDeadWatchers) { try { RATE_LOGGER.rateLimitLog("Waiting for dead watchers cleaning"); synchronized(processingCompletedEvent) { processingCompletedEvent.wait(100); } } catch (InterruptedException e) { LOG.info("Got interrupted while waiting for dead watches " + "queue size"); break; } } synchronized (this) { if (deadWatchers.add(watcherBit)) { totalDeadWatchers.incrementAndGet(); if (deadWatchers.size() >= watcherCleanThreshold) { synchronized (cleanEvent) { cleanEvent.notifyAll(); } } } } }
Source:
<code>public static void setUpClass() throws Exception { server = HttpServer.create(new InetSocketAddress(0), 0); server.createContext("/", exchange -> { byte[] content = "Hello World!".getBytes(); exchange.sendResponseHeaders(200, content.length); try (OutputStream responseBody = exchange.getResponseBody()) { responseBody.write(content); responseBody.flush(); } }); server.start(); Map<Integer, Integer> portMapping = new HashMap<>(); <START> portMapping.put(server.getAddress().getPort(), 80); <END> Testcontainers.exposeHostPorts(portMapping); }</code><technical_language>Please do change test, is valid</technical_language>

Target:
public static void setUpClass() throws Exception { server = HttpServer.create(new InetSocketAddress(0), 0); server.createContext("/", exchange -> { byte[] content = "Hello World!".getBytes(); exchange.sendResponseHeaders(200, content.length); try (OutputStream responseBody = exchange.getResponseBody()) { responseBody.write(content); responseBody.flush(); } }); server.start(); Testcontainers.exposeHostPorts(server.getAddress().getPort()); Testcontainers.exposeHostPorts(ImmutableMap.of(server.getAddress().getPort(), 80)); Testcontainers.exposeHostPorts(ImmutableMap.of(server.getAddress().getPort(), 81)); }
Source:
<code>public List<Dataverse> findLinkingDataverses(Long datasetId) { List<Dataverse> retList = new ArrayList<>(); <START> Query query = em.createQuery("select object(o) from DatasetLinkingDataverse as o where o.dataset.id =:datasetId order by o.id"); <END> query.setParameter("datasetId", datasetId); for (Object o : query.getResultList()) { DatasetLinkingDataverse converted = (DatasetLinkingDataverse) o; retList.add(converted.getLinkingDataverse()); } return retList; }</code><technical_language>reason this added a named query</technical_language>

Target:
public List<Dataverse> findLinkingDataverses(Long datasetId) { List<Dataverse> retList = new ArrayList<>(); TypedQuery<DatasetLinkingDataverse> typedQuery = em.createNamedQuery("DatasetLinkingDataverse.findByDatasetId", DatasetLinkingDataverse.class) .setParameter("datasetId", datasetId); for (DatasetLinkingDataverse datasetLinkingDataverse : typedQuery.getResultList()) { retList.add(datasetLinkingDataverse.getLinkingDataverse()); } return retList; }
Source:
<code>public void addConfigNode() { DataNode zookeeperZnode = nodes.get(procZookeeper); <START> if (zookeeperZnode!=null) { END> zookeeperZnode.addChild(configChildZookeeper); } else { LOG.error("There's no /zookeeper znode - this should never happen."); } nodes.put(configZookeeper, configDataNode); try { setACL(configZookeeper, ZooDefs.Ids.READ_ACL_UNSAFE, -1); } catch (KeeperException.NoNodeException e) { LOG.error("Fail to set ACL on - this should never happen: {}", configZookeeper, e); throw new RuntimeException(e.getMessage()); } }</code><technical_language>nit: spaces !=</technical_language>

Target:
public void addConfigNode() { DataNode zookeeperZnode = nodes.get(procZookeeper); if (zookeeperZnode != null) { zookeeperZnode.addChild(configChildZookeeper); } else { assert false : "There's no /zookeeper znode - this should never happen."; } nodes.put(configZookeeper, configDataNode); try { setACL(configZookeeper, ZooDefs.Ids.READ_ACL_UNSAFE, -1); } catch (KeeperException.NoNodeException e) { assert false : "There's no " + configZookeeper + " znode - this should never happen."; } }
Source:
<code>public CommandRequirement(List<Command> setupCommands) { <START> this.setupCommands = setupCommands; <END> }</code><technical_language>require empty</technical_language>

Target:
public CommandRequirement(List<Command> setupCommands) { this.setupCommands = requireNonNull(setupCommands, "setupCommands is null"); }
Source:
<code>@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { <START> IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName); <END> cfg.setIncludeEventTypes(EventType.EVTS_ALL); return cfg; }</code><technical_language>suggest simplifying this block (and for similar cases below): return super.getConfiguration(igniteInstanceName) .setIncludeEventTypes(EventType.EVTS_ALL);</technical_language>

Target:
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { return super.getConfiguration(igniteInstanceName).setIncludeEventTypes(EventType.EVTS_ALL); }
Source:
<code>public void visitMemberAccess(MemberAccessTree tree) { tree.object().accept(this); <START> Set<String> selfObjects = ImmutableSet.of("$this", "self", "static"); <END> String strObject = SourceBuilder.build(tree.object()).trim(); classMemberUsageState = new ClassMemberUsageState(); classMemberUsageState.isStatic = tree.isStatic(); classMemberUsageState.isSelfMember = selfObjects.contains(strObject.toLowerCase()); classMemberUsageState.isField = insideCallee.isEmpty(); classMemberUsageState.isConst = classMemberUsageState.isField && tree.isStatic(); tree.member().accept(this); }</code><technical_language>@vilchik-elena This defined a constant</technical_language>

Target:
public void visitMemberAccess(MemberAccessTree tree) { tree.object().accept(this); final ImmutableSet<String> selfObjects = ImmutableSet.of("$this", "self", "static"); String strObject = SourceBuilder.build(tree.object()).trim(); classMemberUsageState = new ClassMemberUsageState(); classMemberUsageState.isStatic = tree.isStatic(); classMemberUsageState.isSelfMember = selfObjects.contains(strObject.toLowerCase()); classMemberUsageState.isField = insideCallee.isEmpty(); classMemberUsageState.isConst = classMemberUsageState.isField && tree.isStatic(); tree.member().accept(this); }
Source:
<code>protected void downloadFileFromRemote(URL remoteURL, File localFile) throws IOException{ <START> LOGGER.info("Downloaded file to local file {}", remoteURL, localFile); <END> long timeS = System.currentTimeMillis(); File tempFile = File.createTempFile(FileDownloadUtils.getFilePrefix(localFile), "."+ FileDownloadUtils.getFileExtension(localFile)); FileOutputStream out = new FileOutputStream(tempFile); InputStream in = remoteURL.openStream(); byte[] buf = new byte[4 * 1024]; int bytesRead; while ((bytesRead = in.read(buf)) != -1) { out.write(buf, 0, bytesRead); } in.close(); out.close(); FileDownloadUtils.copy(tempFile,localFile); tempFile.delete(); long size = localFile.length(); double disp = size / 1024.0; String unit = " kB"; if ( disp > 1024 ) { unit = " MB"; disp = disp / 1024.0; } long timeE = System.currentTimeMillis(); LOGGER.info("Downloaded in sec. to {}", String.format("%.1f",disp) + unit, (timeE - timeS)/1000, localFile); }</code><technical_language>this "Downloading"? downloaded this point</technical_language>

Target:
protected void downloadFileFromRemote(URL remoteURL, File localFile) throws IOException{ LOGGER.info("Downloading file to local file {}", remoteURL, localFile); long timeS = System.currentTimeMillis(); File tempFile = File.createTempFile(FileDownloadUtils.getFilePrefix(localFile), "."+ FileDownloadUtils.getFileExtension(localFile)); FileOutputStream out = new FileOutputStream(tempFile); InputStream in = remoteURL.openStream(); byte[] buf = new byte[4 * 1024]; int bytesRead; while ((bytesRead = in.read(buf)) != -1) { out.write(buf, 0, bytesRead); } in.close(); out.close(); FileDownloadUtils.copy(tempFile,localFile); tempFile.delete(); long size = localFile.length(); double disp = size / 1024.0; String unit = " kB"; if ( disp > 1024 ) { unit = " MB"; disp = disp / 1024.0; } long timeE = System.currentTimeMillis(); LOGGER.info("Downloaded in sec. to {}", String.format("%.1f",disp) + unit, (timeE - timeS)/1000, localFile); }
Source:
<code><START> public static void main(String[] args) { <END> CommandLine cmdLine = new CommandLine(); OptionSet options = cmdLine.parser().parse(args); Config orgConfig = cmdLine.loadConfig(options); Config config = Util.rewriteConfig(orgConfig); LocalApplicationRunner runner = new LocalApplicationRunner(config); WikipediaApplication app = new WikipediaApplication(); runner.run(app); runner.waitForFinish(); }</code><technical_language>StreamApplication app = new WikipediaApplication();</technical_language>

Target:
public static void main(String[] args) { CommandLine cmdLine = new CommandLine(); OptionSet options = cmdLine.parser().parse(args); Config config = cmdLine.loadConfig(options); LocalApplicationRunner runner = new LocalApplicationRunner(config); WikipediaApplication app = new WikipediaApplication(); runner.run(app); runner.waitForFinish(); }
Source:
<code><START> public SignAlgorithm getSignRequestAlgorithm() { <END> if (getSAMLProtocol().getSignRequest() != null && getSAMLProtocol().getSignRequest().getAlgorithm() != null) { return SignAlgorithm.fromValue(getSAMLProtocol().getSignRequest().getAlgorithm().value()); } return SignAlgorithm.SHA1; }</code><technical_language>Rename getSignatureDigestAlgorithm</technical_language>

Target:
public SignatureDigestAlgorithm getSignRequestAlgorithm() { if (getSAMLProtocol().getSignRequest() != null && getSAMLProtocol().getSignRequest().getAlgorithm() != null) { return SignatureDigestAlgorithm.fromValue(getSAMLProtocol().getSignRequest().getAlgorithm().value()); } return SignatureDigestAlgorithm.RSA_SHA1; }
Source:
<code>private void iterateOverHigherLevelMetadata(LegacyDocStructHelperInterface enricher, Map<String, Map<String, LegacyMetadataHelper>> higherLevelMetadata) { <START> HIGHER: for (Entry<String, Map<String, LegacyMetadataHelper>> availableHigherMetadata : higherLevelMetadata <END> .entrySet()) { String enrichable = availableHigherMetadata.getKey(); if (!isAddable(enricher, enrichable)) { continue HIGHER; } for (Entry<String, LegacyMetadataHelper> higherElement : availableHigherMetadata.getValue().entrySet()) { List<LegacyMetadataHelper> amNotNull = enricher.getAllMetadata(); if (Objects.isNull(amNotNull)) { amNotNull = Collections.emptyList(); } for (LegacyMetadataHelper existentMetadata : amNotNull) { if (existentMetadata.getMetadataType().getName().equals(enrichable) && existentMetadata.getValue().equals(higherElement.getKey())) { continue HIGHER; } } enricher.addMetadata(higherElement.getValue()); } } }</code><technical_language>Please introduce labels, I removed in anoher pull request sonarcloud complains (and sonarcloud)</technical_language>

Target:
private void iterateOverHigherLevelMetadata(LegacyDocStructHelperInterface enricher, Map<String, Map<String, LegacyMetadataHelper>> higherLevelMetadata) { for (Entry<String, Map<String, LegacyMetadataHelper>> availableHigherMetadata : higherLevelMetadata .entrySet()) { String enrichable = availableHigherMetadata.getKey(); if (!isAddable(enricher, enrichable)) { continue; } for (Entry<String, LegacyMetadataHelper> higherElement : availableHigherMetadata.getValue().entrySet()) { List<LegacyMetadataHelper> amNotNull = enricher.getAllMetadata(); if (Objects.isNull(amNotNull)) { amNotNull = Collections.emptyList(); } boolean breakMiddle = false; for (LegacyMetadataHelper existentMetadata : amNotNull) { if (existentMetadata.getMetadataType().getName().equals(enrichable) && existentMetadata.getValue().equals(higherElement.getKey())) { breakMiddle = true; break; } } if (breakMiddle) { break; } else { enricher.addMetadata(higherElement.getValue()); } } } }
Source:
<code>public static String url(Server server, String path) { <START> return "http://localhost:" + server.activePort().localAddress().getPort() + path; <END> }</code><technical_language>nit: server.activeLocalPort()? <LINK_0></technical_language>

Target:
public static String url(Server server, String path) { return "http://localhost:" + server.activeLocalPort() + path; }
Source:
<code>public void action() { filesToOpen.clear(); final AppendDatabaseDialog dialog = new AppendDatabaseDialog(); Optional<Boolean> response = dialog.showAndWait(); if (OptionalUtil.isPresentAndTrue(response)) { FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() .withDefaultExtension(StandardFileType.BIBTEX_DB) .withInitialDirectory(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)) .build(); List<Path> chosen = dialogService.showFileOpenDialogAndGetMultipleFiles(fileDialogConfiguration); if (chosen.isEmpty()) { return; } filesToOpen.addAll(chosen); if (filesToOpen.isEmpty()) { return; } for (Path file : filesToOpen) { BackgroundTask.wrap(() -> openIt(file, dialog.importEntries(), dialog.importStrings(), dialog.importGroups(), dialog.importSelectorWords())) <START> .onSuccess(fileName -> { dialogService.notify(Localization.lang("Imported from library") + " '" + fileName + "'");}) <END> .onFailure(exception -> { LOGGER.warn("Could not open database", exception); dialogService.showErrorDialogAndWait(Localization.lang("Open library"), exception);}) .executeWith(Globals.TASK_EXECUTOR);; } } }</code><technical_language>singleLineLambdas need curly braces</technical_language>

Target:
public void action() { filesToOpen.clear(); final AppendDatabaseDialog dialog = new AppendDatabaseDialog(); Optional<Boolean> response = dialog.showAndWait(); if (OptionalUtil.isPresentAndTrue(response)) { FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() .withDefaultExtension(StandardFileType.BIBTEX_DB) .withInitialDirectory(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)) .build(); List<Path> chosen = dialogService.showFileOpenDialogAndGetMultipleFiles(fileDialogConfiguration); if (chosen.isEmpty()) { return; } filesToOpen.addAll(chosen); if (filesToOpen.isEmpty()) { return; } for (Path file : filesToOpen) { BackgroundTask.wrap(() -> openIt(file, dialog.importEntries(), dialog.importStrings(), dialog.importGroups(), dialog.importSelectorWords())) .onSuccess(fileName -> dialogService.notify(Localization.lang("Imported from library") + " '" + fileName + "'")) .onFailure(exception -> { LOGGER.warn("Could not open database", exception); dialogService.showErrorDialogAndWait(Localization.lang("Open library"), exception);}) .executeWith(Globals.TASK_EXECUTOR);; } } }
Source:
<code>public synchronized void addMutation(TableId table, Mutation m) throws MutationsRejectedException { if (closed) throw new IllegalStateException("Closed"); if (m.size() == 0) throw new IllegalArgumentException("Can not add empty mutations"); checkForFailures(); waitRTE(() -> (totalMemUsed > MAX_MEM_PERCENTAGE * maxMem || flushing)); if (closed) throw new IllegalStateException("Closed"); checkForFailures(); if (startTime == 0) { startTime = System.currentTimeMillis(); List<GarbageCollectorMXBean> gcmBeans = ManagementFactory.getGarbageCollectorMXBeans(); for (GarbageCollectorMXBean garbageCollectorMXBean : gcmBeans) { initialGCTimes += garbageCollectorMXBean.getCollectionTime(); } CompilationMXBean compMxBean = ManagementFactory.getCompilationMXBean(); if (compMxBean.isCompilationTimeMonitoringSupported()) { initialCompileTimes = compMxBean.getTotalCompilationTime(); } initialSystemLoad = ManagementFactory.getOperatingSystemMXBean().getSystemLoadAverage(); } m = new Mutation(m); totalMemUsed += m.estimatedMemoryUsed(); mutations.addMutation(table, m); totalAdded++; if (mutations.getMemoryUsed() >= maxMem / MAX_MEMORY_DIVISOR) { if (!somethingFailed) { startProcessing(); consecutiveFailedProcessCalls.set(0); } else <START> consecutiveFailedProcessCalls.getAndIncrement(); <END> if (consecutiveFailedProcessCalls.get() > 5000) log.error( "TabletServerBatchWriter::startProcessing is not occurring in over 5000 attempts in addMutation."); checkForFailures(); } }</code><technical_language>merge this conditional for >= 5000 ? if failed hit conditional anyway</technical_language>

Target:
public synchronized void addMutation(TableId table, Mutation m) throws MutationsRejectedException { if (closed) throw new IllegalStateException("Closed"); if (m.size() == 0) throw new IllegalArgumentException("Can not add empty mutations"); checkForFailures(); waitRTE(() -> (totalMemUsed > maxMem || flushing) && !somethingFailed); if (closed) throw new IllegalStateException("Closed"); checkForFailures(); if (startTime == 0) { startTime = System.currentTimeMillis(); List<GarbageCollectorMXBean> gcmBeans = ManagementFactory.getGarbageCollectorMXBeans(); for (GarbageCollectorMXBean garbageCollectorMXBean : gcmBeans) { initialGCTimes += garbageCollectorMXBean.getCollectionTime(); } CompilationMXBean compMxBean = ManagementFactory.getCompilationMXBean(); if (compMxBean.isCompilationTimeMonitoringSupported()) { initialCompileTimes = compMxBean.getTotalCompilationTime(); } initialSystemLoad = ManagementFactory.getOperatingSystemMXBean().getSystemLoadAverage(); } m = new Mutation(m); totalMemUsed += m.estimatedMemoryUsed(); mutations.addMutation(table, m); totalAdded++; if (mutations.getMemoryUsed() >= maxMem / MAX_MEMORY_DIVISOR) { startProcessing(); if (!somethingFailed) consecutiveFailedProcessCalls.set(0); if (consecutiveFailedProcessCalls.get() > 5000) log.error( "TabletServerBatchWriter::startProcessing is not occurring in over 5000 attempts in addMutation."); else if (somethingFailed) consecutiveFailedProcessCalls.getAndIncrement(); checkForFailures(); } }
Source:
<code>public UserProfileServiceHandler() { userProfileRepository = new UserProfileRepository(UserProfile.class, UserProfileEntity.class); try { GenericObjectPool.Config poolConfig = new GenericObjectPool.Config(); poolConfig.maxActive = 100; poolConfig.minIdle = 5; poolConfig.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK; poolConfig.testOnBorrow = true; poolConfig.testWhileIdle = true; poolConfig.numTestsPerEvictionRun = 10; poolConfig.maxWait = 3000; iasClientPool = new ThriftClientPool<>( tProtocol -> new IamAdminServices.Client(tProtocol), poolConfig, ServerSettings.getProfileServiceServerHost(), Integer.parseInt(ServerSettings.getProfileServiceServerPort())); <START> }catch (ApplicationSettingsException e) { <END> logger.error("Error occured while reading airavata-server properties..", e); } }</code><technical_language>space }</technical_language>

Target:
public UserProfileServiceHandler() throws Exception { userProfileRepository = new UserProfileRepository(UserProfile.class, UserProfileEntity.class); try { GenericObjectPool.Config poolConfig = new GenericObjectPool.Config(); poolConfig.maxActive = 100; poolConfig.minIdle = 5; poolConfig.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK; poolConfig.testOnBorrow = true; poolConfig.testWhileIdle = true; poolConfig.numTestsPerEvictionRun = 10; poolConfig.maxWait = 3000; iasClientPool = new ThriftClientPool<>( tProtocol -> new IamAdminServices.Client(tProtocol), poolConfig, ServerSettings.getProfileServiceServerHost(), Integer.parseInt(ServerSettings.getProfileServiceServerPort())); } catch (ApplicationSettingsException e) { logger.error("Error occured while reading airavata-server properties..", e); throw new Exception(e); } }
Source:
<code>@BeforeClass public static void beforeClass() throws Exception { service = AppiumDriverLocalService.buildDefaultService(); service.start(); if (service == null || !service.isRunning()) { <START> throw new RuntimeException("An appium server node is not started!"); <END> } File appDir = new File("src/test/java/io/appium/java_client"); File app = new File(appDir, "ApiDemos-debug.apk"); DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator"); capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, AutomationName.ANDROID_UIAUTOMATOR2); driver = new AndroidDriver<>(service.getUrl(), capabilities); }</code><technical_language>@saikrishna321 throw AppiumServerHasNotBeenStartedLocallyException</technical_language>

Target:
@BeforeClass public static void beforeClass() throws Exception { service = AppiumDriverLocalService.buildDefaultService(); service.start(); if (service == null || !service.isRunning()) { throw new AppiumServerHasNotBeenStartedLocallyException ("An appium server node is not started!"); } File appDir = new File("src/test/java/io/appium/java_client"); File app = new File(appDir, "ApiDemos-debug.apk"); DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator"); capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, AutomationName.ANDROID_UIAUTOMATOR2); driver = new AndroidDriver<>(service.getUrl(), capabilities); }
Source:
<code><START> public static TrustManagerFactory createTrustManagerFactory( <END> Path trustStorePath, SslConfiguration.StoreType trustStoreType) { KeyStore keyStore; switch (trustStoreType) { case JKS: case PKCS12: keyStore = KeyStores.loadKeyStore(trustStoreType.name(), trustStorePath, Optional.<String>absent()); break; case PEM: keyStore = KeyStores.createTrustStoreFromCertificates(trustStorePath); break; case PUPPET: Path puppetCertsDir = trustStorePath.resolve("certs"); if (!puppetCertsDir.toFile().isDirectory()) { throw new IllegalStateException( String.format("Puppet certs directory did not exist at path \"%s\"", puppetCertsDir)); } keyStore = KeyStores.createTrustStoreFromCertificates(puppetCertsDir); break; default: throw new IllegalStateException("Unrecognized trust store type: " + trustStoreType); } try { TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); return trustManagerFactory; } catch (GeneralSecurityException e) { throw Throwables.propagate(e); } }</code><technical_language>trustStorePath parameter is non-trivial (can file directory, depending type), this need docs, unfortunately</technical_language>

Target:
private static TrustManagerFactory createTrustManagerFactory( Path trustStorePath, SslConfiguration.StoreType trustStoreType) { KeyStore keyStore; switch (trustStoreType) { case JKS: case PKCS12: keyStore = KeyStores.loadKeyStore(trustStoreType.name(), trustStorePath, Optional.<String>absent()); break; case PEM: keyStore = KeyStores.createTrustStoreFromCertificates(trustStorePath); break; case PUPPET: Path puppetCertsDir = trustStorePath.resolve("certs"); if (!puppetCertsDir.toFile().isDirectory()) { throw new IllegalStateException( String.format("Puppet certs directory did not exist at path \"%s\"", puppetCertsDir)); } keyStore = KeyStores.createTrustStoreFromCertificates(puppetCertsDir); break; default: throw new IllegalStateException("Unrecognized trust store type: " + trustStoreType); } try { TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); return trustManagerFactory; } catch (GeneralSecurityException e) { throw Throwables.propagate(e); } }
Source:
<code>void start() throws StoreException { File mountPath = new File(disk.getMountPath()); if (mountPath.exists()) { ScheduledExecutorService storeStartupScheduler = Utils .newScheduler(Math.min(stores.size(), config.storeNumStoreStartupThreads), "store-startup-" + disk, false); try { Map<PartitionId, Future<Void>> futures = new HashMap<>(); for (final Map.Entry<PartitionId, BlobStore> partitionAndStore : stores.entrySet()) { Future<Void> future = storeStartupScheduler.submit(new Callable<Void>() { @Override public Void call() throws Exception { partitionAndStore.getValue().start(); return null; } }); futures.put(partitionAndStore.getKey(), future); } int numFailed = 0; for (Map.Entry<PartitionId, Future<Void>> partitionAndFuture : futures.entrySet()) { try { partitionAndFuture.getValue().get(); } catch (ExecutionException e) { numFailed++; logger.error("Exception while starting store for partition " + partitionAndFuture.getKey(), e.getCause()); <START> } catch (InterruptedException e) { <END> numFailed++; logger.error("Store startup for partition " + partitionAndFuture.getKey() + " was interrupted", e); } } if (numFailed > 0) { throw new StoreException( "Could not start " + numFailed + " out of " + stores.size() + " stores on the disk " + disk, StoreErrorCodes.Initialization_Error); } } finally { storeStartupScheduler.shutdown(); } } else { throw new StoreException("Mount path does not exist: " + mountPath + " ; cannot start stores on this disk", StoreErrorCodes.Initialization_Error); } }</code><technical_language>for simplicity, I catch Exception (or do catch (ExecutionException | InterruptedException e)) do logger.error("Exception while starting store", e). I modifying error message exception printed</technical_language>

Target:
void start() throws InterruptedException { Timer.Context context = metrics.diskStartTime.time(); try { File mountPath = new File(disk.getMountPath()); if (mountPath.exists()) { List<Thread> startupThreads = new ArrayList<>(); final AtomicInteger numFailures = new AtomicInteger(0); for (final Map.Entry<PartitionId, BlobStore> partitionAndStore : stores.entrySet()) { Thread thread = Utils.newThread("store-startup-" + partitionAndStore.getKey(), new Runnable() { @Override public void run() { try { partitionAndStore.getValue().start(); } catch (Exception e) { numFailures.incrementAndGet(); metrics.totalStoreStartFailures.inc(); logger.error("Exception while starting store for the partition" + partitionAndStore.getKey(), e); } } }, false); thread.start(); startupThreads.add(thread); } for (Thread startupThread : startupThreads) { startupThread.join(); } if (numFailures.get() > 0) { logger.error( "Could not start " + numFailures.get() + " out of " + stores.size() + " stores on the disk " + disk); } } else { metrics.diskMountPathFailures.inc(); metrics.totalStoreStartFailures.inc(stores.size()); logger.error("Mount path does not exist: " + mountPath + " ; cannot start stores on this disk"); } } finally { context.stop(); } }
Source:
<code>private boolean clusterHasNonInitializingServers() { for (VDS vds : getVdsDAO().getAllForVdsGroup(getVdsGroupId())) { if (vds.getStatus() != VDSStatus.Installing && vds.getStatus() != VDSStatus.InstallingOS && vds.getStatus() != VDSStatus.PendingApproval && vds.getStatus() != VDSStatus.Initializing) <START> return true; <END> } return false; }</code><technical_language>this returns true if vds in cluster in "initialization" state (which states check - depends declare initialization - be: deploy process, provision process, host installed up, installation failed.. - ways declare initialization state states installing things, pendingApproval (don't understand installFailed..)) anyway, logic allow try prevent if of hosts in cluster is in "initialization". for example, if host in InstallFailed good go. is meant</technical_language>

Target:
private boolean clusterHasNonInitializingServers() { for (VDS vds : getVdsDAO().getAllForVdsGroup(getVdsGroupId())) { if (vds.getStatus() != VDSStatus.Installing && vds.getStatus() != VDSStatus.InstallingOS && vds.getStatus() != VDSStatus.PendingApproval && vds.getStatus() != VDSStatus.Initializing && vds.getStatus() != VDSStatus.InstallFailed) return true; } return false; }
Source:
<code>public void setUp() throws Exception { Map<String, Integer> samplesPosition = new HashMap<>(); samplesPosition.put("sample1", 123); VARIANT_SOURCE_ENTITY.setSamplesPosition(samplesPosition); Map<String, Object> metadata = new HashMap<>(); metadata.put("header", "myHeader"); VARIANT_SOURCE_ENTITY.setMetadata(metadata); List<VariantSourceEntity> variantSourceEntities = Collections.singletonList(VARIANT_SOURCE_ENTITY); given(variantSourceEntityRepository.findByStudyIdIn(eq(Collections.singletonList("studyId")), any())) .willReturn(variantSourceEntities); given(variantSourceEntityRepository.countByStudyIdIn(eq(Collections.singletonList("studyId")))) <START> .willReturn(1L); <END> }</code><technical_language>Replacing 1L variantSourceEntities.size() ensure if collection size changes, mocked data sense</technical_language>

Target:
public void setUp() throws Exception { VariantSourceEntity variantSourceEntity = new VariantSourceEntity("fileId", "fileName", "studyId", "studyName", VariantStudy.StudyType.CASE, VariantSource.Aggregation.NONE, null, null, null); Map<String, Integer> samplesPosition = new HashMap<>(); samplesPosition.put("sample1", 123); variantSourceEntity.setSamplesPosition(samplesPosition); Map<String, Object> metadata = new HashMap<>(); metadata.put("header", "myHeader"); variantSourceEntity.setMetadata(metadata); List<VariantSourceEntity> variantSourceEntities = Collections.singletonList(variantSourceEntity); given(variantSourceEntityRepository.findByStudyIdIn(eq(Collections.singletonList("studyId")), any())) .willReturn(variantSourceEntities); given(variantSourceEntityRepository.countByStudyIdIn(eq(Collections.singletonList("studyId")))) .willReturn(Long.valueOf(variantSourceEntities.size())); }