auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private DatasetTrainer<IgniteModel<IS, O>, L> getTrainer() { if (submodelInput2AggregatingInputConverter == null && submodelsTrainers.isEmpty()) throw new IllegalStateException("There should be at least one way for submodels " + "input to be propageted to aggregator."); if (submodelOutput2VectorConverter == null || vector2SubmodelInputConverter == null) throw new IllegalStateException("There should be a specified way to convert vectors to submodels " + "input and submodels output to vector"); if (aggregatingInputMerger == null) throw new IllegalStateException("Binary operator used to convert outputs of submodels is not specified"); List<DatasetTrainer<IgniteModel<IS, IA>, L>> subs = new ArrayList<>(); if (submodelInput2AggregatingInputConverter != null) { DatasetTrainer<IgniteModel<IS, IS>, L> id = DatasetTrainer.identityTrainer(); DatasetTrainer<IgniteModel<IS, IA>, L> mappedId = CompositionUtils.unsafeCoerce( AdaptableDatasetTrainer.of(id).afterTrainedModel(submodelInput2AggregatingInputConverter)); subs.add(mappedId); } subs.addAll(submodelsTrainers); TrainersParallelComposition<IS, IA, L> composition = new TrainersParallelComposition<>(subs); IgniteBiFunction<List<IgniteModel<IS, IA>>, Vector, Vector> featureMapper = getFeatureExtractorForAggregator( submodelOutput2VectorConverter, vector2SubmodelInputConverter); return AdaptableDatasetTrainer .of(composition) .afterTrainedModel(lst -> lst.stream().reduce(aggregatingInputMerger).get()) .andThen(aggregatorTrainer, model -> new DatasetMapping<L, L>() { @Override public Vector mapFeatures(Vector v) { List<IgniteModel<IS, IA>> models = ((ModelsParallelComposition<IS, IA>)model.innerModel()).submodels(); return featureMapper.apply(models, v); } @Override public L mapLabels(L lbl) { return lbl; } }).unsafeSimplyTyped(); }

Target:
private DatasetTrainer<IgniteModel<IS, O>, L> getTrainer() { checkConsistency(); List<DatasetTrainer<IgniteModel<IS, IA>, L>> subs = new ArrayList<>(); if (submodelInput2AggregatingInputConverter != null) { DatasetTrainer<IgniteModel<IS, IS>, L> id = DatasetTrainer.identityTrainer(); DatasetTrainer<IgniteModel<IS, IA>, L> mappedId = CompositionUtils.unsafeCoerce( AdaptableDatasetTrainer.of(id).afterTrainedModel(submodelInput2AggregatingInputConverter)); subs.add(mappedId); } subs.addAll(submodelsTrainers); TrainersParallelComposition<IS, IA, L> composition = new TrainersParallelComposition<>(subs); IgniteBiFunction<List<IgniteModel<IS, IA>>, Vector, Vector> featureMapper = getFeatureExtractorForAggregator( submodelOutput2VectorConverter, vector2SubmodelInputConverter); return AdaptableDatasetTrainer .of(composition) .afterTrainedModel(lst -> lst.stream().reduce(aggregatingInputMerger).get()) .andThen(aggregatorTrainer, model -> new DatasetMapping<L, L>() { @Override public Vector mapFeatures(Vector v) { List<IgniteModel<IS, IA>> models = ((ModelsParallelComposition<IS, IA>)model.innerModel()).submodels(); return featureMapper.apply(models, v); } @Override public L mapLabels(L lbl) { return lbl; } }).unsafeSimplyTyped(); }
Source:
public void proxy(HttpServletRequest req, HttpServletResponse resp, HttpProxyRequestOptions options) throws IOException { if (options == null) { options = new HttpProxyRequestOptions(); } boolean includeRequestPayload = isIncludeRequestPayload(req); String url = rewriteUrl(req, options); HttpRequest httpReq = BEANS.get(DefaultHttpTransportManager.class).getHttpRequestFactory().buildRequest(req.getMethod(), new GenericUrl(url), null); httpReq = prepareRequest(httpReq); writeRequestHeaders(req, httpReq); writeCustomRequestHeaders(httpReq, options.getCustomRequestHeaders()); if (includeRequestPayload) { if (!req.getParameterMap().isEmpty()) { writeRequestParameters(req, httpReq); } else { writeRequestPayload(req, httpReq); } } HttpResponse httpResp = httpReq.execute(); writeResponseHeaders(resp, httpResp); writeResponseStatus(resp, httpResp); writeResponsePayload(resp, httpResp); LOG.debug("Forwarded request to {}", req.getMethod(), url); }

Target:
public void proxy(HttpServletRequest req, HttpServletResponse resp, HttpProxyRequestOptions options) throws IOException { if (options == null) { options = new HttpProxyRequestOptions(); } String url = rewriteUrl(req, options); HttpRequest httpReq = BEANS.get(DefaultHttpTransportManager.class).getHttpRequestFactory().buildRequest(req.getMethod(), new GenericUrl(url), null); httpReq = prepareRequest(httpReq); writeRequestHeaders(req, httpReq); writeCustomRequestHeaders(httpReq, options.getCustomRequestHeaders()); if (shouldIncludeRequestPayload(req)) { if (!req.getParameterMap().isEmpty()) { writeRequestParameters(req, httpReq); } else { writeRequestPayload(req, httpReq); } } HttpResponse httpResp = httpReq.execute(); writeResponseHeaders(resp, httpResp); writeResponseStatus(resp, httpResp); writeResponsePayload(resp, httpResp); LOG.debug("Forwarded request to {}", req.getMethod(), url); }
Source:
protected AdditionsAndRetractions parseN3ToChange( List<String> requiredAdds, List<String> optionalAdds, List<String> requiredDels, List<String> optionalDels, VitroRequest vreq, EditConfigurationVTwo editConfig) throws Exception{ List<Model> adds = parseN3ToRDF(requiredAdds, REQUIRED); adds.addAll( parseN3ToRDF(optionalAdds, OPTIONAL)); List<Model> retracts = new ArrayList<Model>(); if( requiredDels != null && optionalDels != null ){ String lingCxt=null; try { if (editConfig != null && editConfig.getLiteralsInScope().get("label").get(0).getLanguage() != "") { lingCxt = editConfig.getLiteralsInScope().get("label").get(0).getLanguage(); } else { lingCxt = vreq.getLocale().getLanguage(); if (!vreq.getLocale().getCountry().isEmpty()) { lingCxt += "-" + vreq.getLocale().getCountry(); } } } catch (Exception e) { } retracts.addAll( parseN3ToRDF(requiredDels, REQUIRED, lingCxt) ); retracts.addAll( parseN3ToRDF(optionalDels, OPTIONAL, lingCxt) ); } return new AdditionsAndRetractions(adds,retracts); }

Target:
protected AdditionsAndRetractions parseN3ToChange( List<String> requiredAdds, List<String> optionalAdds, List<String> requiredDels, List<String> optionalDels, VitroRequest vreq, EditConfigurationVTwo editConfig) throws Exception{ List<Model> adds = parseN3ToRDF(requiredAdds, REQUIRED); adds.addAll( parseN3ToRDF(optionalAdds, OPTIONAL)); List<Model> retracts = new ArrayList<Model>(); if( requiredDels != null && optionalDels != null ){ String lingCxt=null; try { Boolean getLabelLanguage = false; if (!StringUtils.isBlank(editConfig.formUrl) && editConfig.formUrl.contains("RDFSLabelGenerator")) { getLabelLanguage = true; } if (editConfig != null && !StringUtils.isBlank(editConfig.getLiteralsInScope().get("label").get(0).getLanguage()) && getLabelLanguage) { lingCxt = editConfig.getLiteralsInScope().get("label").get(0).getLanguage(); } else { lingCxt = vreq.getLocale().getLanguage(); if (!vreq.getLocale().getCountry().isEmpty()) { lingCxt += "-" + vreq.getLocale().getCountry(); } } } catch (Exception e) { } retracts.addAll( parseN3ToRDF(requiredDels, REQUIRED, lingCxt) ); retracts.addAll( parseN3ToRDF(optionalDels, OPTIONAL, lingCxt) ); } return new AdditionsAndRetractions(adds,retracts); }
Source:
private static EventFiringWebDriver getChromeInstance() { String chromeBinaryPath = ""; String osName = System.getProperty("os.name").toUpperCase(); if (osName.contains("WINDOWS")) { chromeBinaryPath = "/chromedriver_win32/chromedriver.exe"; }else if (osName.contains("MAC")) { chromeBinaryPath = "/chromedriver_mac32/chromedriver"; }else if (osName.contains("LINUX")) { chromeBinaryPath ="/chromedriver_linux32/chromedriver"; File chromedriver = new File(ClassLoader.getSystemResource("ChromeDriver" + chromeBinaryPath ) .getPath()); chromedriver.setExecutable(true); } System.setProperty("webdriver.chrome.driver", new File(ClassLoader.getSystemResource("ChromeDriver" + chromeBinaryPath ).getPath()).getAbsolutePath()); if ("CHROMEMOBILE".equals(browserName)) { chromeOptions.addArguments( "--user-agent=" + userAgentRegistry.getUserAgent("iPhone") ); } if ("CHROMEMOBILEMERCURY".equals(browserName)) { chromeOptions.addArguments( "--user-agent=" + userAgentRegistry.getUserAgent("iPhone+Mercury") ); } caps.setCapability(ChromeOptions.CAPABILITY, chromeOptions); setBrowserLogging(Level.SEVERE); return new EventFiringWebDriver(new ChromeDriver(caps)); }

Target:
private static EventFiringWebDriver getChromeInstance() { String chromeBinaryPath = ""; String osName = System.getProperty("os.name").toUpperCase(); if (osName.contains("WINDOWS")) { chromeBinaryPath = "/chromedriver_win32/chromedriver.exe"; }else if (osName.contains("MAC")) { chromeBinaryPath = "/chromedriver_mac32/chromedriver"; }else if (osName.contains("LINUX")) { chromeBinaryPath ="/chromedriver_linux64/chromedriver"; File chromedriver = new File(ClassLoader.getSystemResource("ChromeDriver" + chromeBinaryPath ) .getPath()); chromedriver.setExecutable(true); } System.setProperty("webdriver.chrome.driver", new File(ClassLoader.getSystemResource("ChromeDriver" + chromeBinaryPath ).getPath()).getPath()); if ("CHROMEMOBILE".equals(browserName)) { chromeOptions.addArguments( "--user-agent=" + userAgentRegistry.getUserAgent("iPhone") ); } if ("CHROMEMOBILEMERCURY".equals(browserName)) { chromeOptions.addArguments( "--user-agent=" + userAgentRegistry.getUserAgent("iPhone+Mercury") ); } caps.setCapability(ChromeOptions.CAPABILITY, chromeOptions); setBrowserLogging(Level.SEVERE); return new EventFiringWebDriver(new ChromeDriver(caps)); }
Source:
public void testValidatePipeFailAsNotTheSame() throws Exception { session.put("key", "2:22:22"); pipe.setHashSessionKey("key"); pipe.configure(); PipeRunResult res = doPipe(pipe, "password", session); assertEquals(null, res.getPipeForward()); }

Target:
public void testValidatePipeFailAsNotTheSame() throws Exception { String hashed = PasswordHash.createHash("password"); session.put("key", hashed+"2132"); pipe.setHashSessionKey("key"); pipe.configure(); pipe.registerForward(new PipeForward("failure", "random/path")); PipeRunResult res = doPipe(pipe, "password", session); assertEquals("failure", res.getPipeForward().getName()); }
Source:
public MergeRequestFilterWIP getWip() { return wip; }

Target:
public Boolean getWip() { return wip; }
Source:
public void setQueryDatum(ExternalDataInstance queryResultInstance) { SessionDatum datum = getNeededDatum(); if (datum instanceof RemoteQueryDatum) { StackFrameStep step = new StackFrameStep(SessionFrame.STATE_QUERY_REQUEST, datum.getDataId(), datum.getValue()); frame.pushStep(step); if (queryResultInstance != null) { instances.put(datum.getDataId(), queryResultInstance); } syncState(); } else { throw new RuntimeException("Trying to set query successful when one isn't needed."); } }

Target:
public void setQueryDatum(ExternalDataInstance queryResultInstance) { SessionDatum datum = getNeededDatum(); if (datum instanceof RemoteQueryDatum) { StackFrameStep step = new StackFrameStep(SessionFrame.STATE_QUERY_REQUEST, datum.getDataId(), datum.getValue(), queryResultInstance); frame.pushStep(step); syncState(); } else { throw new RuntimeException("Trying to set query successful when one isn't needed."); } }
Source:
String getTraceId(HttpServletRequest req) { final String stringValue = getStringParameter(req, "id", null); return TRACE_ID_PATTERN.matcher(stringValue).matches() ? stringValue : null; }

Target:
String getTraceId(HttpServletRequest req) { final String stringValue = getStringParameter(req, "id", null); if (stringValue == null) { return null; } return TRACE_ID_PATTERN.matcher(stringValue).matches() ? stringValue : null; }
Source:
private void checkValidationParameterValue(IElementParameter param) { if (param.isShow(getElementParameters()) && param.getFieldType().equals(EParameterFieldType.TEXT) && param instanceof IGenericElementParameter) { String paramValue = String.valueOf(param.getValue()); if (!ContextParameterUtils.isContainContextParam(paramValue)) { org.talend.daikon.properties.property.Property property = ((IGenericElementParameter) param).getProperty(); if (property != null && GenericTypeUtils.isIntegerType(property)) { boolean isDigits = org.apache.commons.lang.math.NumberUtils.isDigits(paramValue); if (!isDigits) { String errorMessage = Messages.getString("Node.parameter.value.validation.integer", param.getDisplayName()); Problems.add(ProblemStatus.ERROR, this, errorMessage); } } } } }

Target:
private void checkValidationParameterValue(IElementParameter param) { if (param instanceof IGenericElementParameter && param.getFieldType().equals(EParameterFieldType.TEXT) && param.isShow(getElementParameters())) { String paramValue = String.valueOf(param.getValue()); if (!ContextParameterUtils.isContainContextParam(paramValue)) { org.talend.daikon.properties.property.Property property = ((IGenericElementParameter) param).getProperty(); if (property != null && GenericTypeUtils.isIntegerType(property)) { boolean isDigits = org.apache.commons.lang.math.NumberUtils.isDigits(paramValue); if (!isDigits) { String errorMessage = Messages.getString("Node.parameter.value.validation.integer", param.getDisplayName()); Problems.add(ProblemStatus.ERROR, this, errorMessage); } } } } }
Source:
public void shouldReturnRefundTransactionWhenThereAreChargeAndRefundTransactions() throws Exception { RefundTransactionEntity refundTransaction = new RefundTransactionEntity(); String refundReference = "someRefundReference"; refundTransaction.setRefundExternalId(refundReference); paymentRequestEntity.addTransaction(refundTransaction); List<RefundTransactionEntity> refundTransactions = paymentRequestEntity.getRefundTransactions(); assertThat(refundTransactions.size(), is(1)); assertThat(refundTransactions.get(0).getRefundExternalId(), is(refundReference)); }

Target:
public void shouldReturnRefundTransactionWhenThereAreChargeAndRefundTransactions() throws Exception { RefundTransactionEntity refundTransaction = new RefundTransactionEntity(); String refundExternalId = "someRefundExternalId"; refundTransaction.setRefundExternalId(refundExternalId); paymentRequestEntity.addTransaction(refundTransaction); List<RefundTransactionEntity> refundTransactions = paymentRequestEntity.getRefundTransactions(); assertThat(refundTransactions.size(), is(1)); assertThat(refundTransactions.get(0).getRefundExternalId(), is(refundExternalId)); }
Source:
public void setObservationLevel(final String observationLevel) { final Integer datasetTypeId = DatasetTypeEnum.getIdByName(observationLevel); if(datasetTypeId > 0) { this.observationLevel = Integer.toString(datasetTypeId); } else { this.observationLevel = observationLevel; } }

Target:
public void setObservationLevel(final String observationLevel) { this.observationLevel = observationLevel; }
Source:
public void expungeMessages(List<? extends Message> messages) throws MessagingException { if (messages.isEmpty()) { return; } checkOpen(); String[] uids = new String[messages.size()]; for (int i = 0, count = messages.size(); i < count; i++) { uids[i] = messages.get(i).getUid(); } try { executeSimpleCommand(String.format("UID EXPUNGE %s", combine(uids, ','))); return; } catch (IOException ioe) { throw ioExceptionHandler(connection, ioe); } }

Target:
public void expungeMessages(List<? extends Message> messages) throws MessagingException { if (messages.isEmpty()) { return; } checkOpen(); String[] uids = MessageUtils.getUidsFromMessages(messages); try { executeSimpleCommand(String.format("UID EXPUNGE %s", combine(uids, ','))); } catch (IOException ioe) { throw ioExceptionHandler(connection, ioe); } }
Source:
boolean fillChunks() { PutChunk chunkToFill; if (chunkFillComplete || operationCompleted) { return true; } do { if (channelReadBuffer == null) { try { channelReadBuffer = chunkFillerChannel.getNextChunk(0); } catch (InterruptedException e) { throw new IllegalStateException( "Received InterruptedException from a call that is expected to be non-blocking."); } } if (channelReadBuffer != null) { chunkToFill = getChunkToFill(); if (chunkToFill == null) { break; } bytesFilledSoFar += chunkToFill.fillFrom(channelReadBuffer); if (chunkToFill.isFull() || bytesFilledSoFar == blobSize) { chunkToFill.onFillComplete(); } if (!channelReadBuffer.hasRemaining()) { channelReadBuffer = null; chunkFillerChannel.resolveOldestChunk(null); } } else { break; } } while (bytesFilledSoFar < blobSize); if (bytesFilledSoFar == blobSize) { chunkFillComplete = true; } return chunkFillComplete; }

Target:
void fillChunks() throws InterruptedException { PutChunk chunkToFill; if (!chunkFillingCompleted && !operationCompleted) { do { if (channelReadBuffer == null) { channelReadBuffer = chunkFillerChannel.getNextChunk(0); } if (channelReadBuffer != null) { chunkToFill = getChunkToFill(); if (chunkToFill == null) { break; } bytesFilledSoFar += chunkToFill.fillFrom(channelReadBuffer); if (!channelReadBuffer.hasRemaining()) { chunkFillerChannel.resolveOldestChunk(null); channelReadBuffer = null; } } else { break; } } while (bytesFilledSoFar < blobSize); if (bytesFilledSoFar == blobSize) { chunkFillingCompleted = true; } } }
Source:
public long writeTo(WritableByteChannel channel) throws IOException { long written = 0; try { if (sentBytes < sizeInBytes()) { prepareBuffer(); if (bufferToSend.hasRemaining()) { written = channel.write(bufferToSend); } if (!bufferToSend.hasRemaining() && blob != null) { int n = 0, currentWritten = -1; while (bufferIndex < nioBuffersFromBlob.length && currentWritten != 0) { ByteBuffer byteBuffer = nioBuffersFromBlob[bufferIndex]; currentWritten = channel.write(byteBuffer); n += currentWritten; if (!byteBuffer.hasRemaining()) { bufferIndex++; } } blob.skipBytes(n); written += n; okayToWriteCrc = !blob.isReadable(); } if (okayToWriteCrc && crcBuf.hasRemaining()) { if (blob != null) { blob.release(); blob = null; } written += channel.write(crcBuf); } sentBytes += written; } } catch (Exception e) { if (blob != null) { blob.release(); blob = null; } } return written; }

Target:
public long writeTo(WritableByteChannel channel) throws IOException { long written = 0; try { if (sentBytes < sizeInBytes()) { if (bufferToSend == null) { prepareBuffer(); } if (bufferToSend.hasRemaining()) { written = channel.write(bufferToSend); } if (!bufferToSend.hasRemaining() && blob != null) { int totalWrittenBytesForBlob = 0, currentWritten = -1; while (bufferIndex < nioBuffersFromBlob.length && currentWritten != 0) { ByteBuffer byteBuffer = nioBuffersFromBlob[bufferIndex]; currentWritten = channel.write(byteBuffer); totalWrittenBytesForBlob += currentWritten; if (!byteBuffer.hasRemaining()) { bufferIndex++; } } blob.skipBytes(totalWrittenBytesForBlob); written += totalWrittenBytesForBlob; okayToWriteCrc = !blob.isReadable(); } if (okayToWriteCrc && crcBuf.hasRemaining()) { if (blob != null) { blob.release(); blob = null; } written += channel.write(crcBuf); } sentBytes += written; } } catch (Exception e) { if (blob != null) { blob.release(); blob = null; } } return written; }
Source:
public void setHeader(final SAMFileHeader header) { this.mHeader = header; if (null == header) { if (null != mReferenceIndex && !mReferenceIndex.equals(NO_ALIGNMENT_REFERENCE_INDEX)) { mReferenceIndex = null; } if (null != mMateReferenceIndex && !mMateReferenceIndex.equals(NO_ALIGNMENT_REFERENCE_INDEX)) { mMateReferenceIndex = null; } } else { setReferenceName(mReferenceName); setMateReferenceName(mMateReferenceName); } }

Target:
public void setHeader(final SAMFileHeader header) { this.mHeader = header; if (null == header) { mReferenceIndex = null; mMateReferenceIndex = null; } else { setReferenceName(mReferenceName); setMateReferenceName(mMateReferenceName); } }
Source:
public Sprite slice(int x, int y, int width, int height) { if(withinImage(x, y) && withinImage(x + width - 1, y + height - 1)) { BufferedImage bi = ImageStore.createTranslucentImage(width, height); bi.createGraphics().drawImage(image, 0, 0, width, height, x, y, x + width, y + height, null); return new StaticImageSprite(bi); } return new EmptySprite(); }

Target:
public Sprite slice(int x, int y, int width, int height) { if(withinImage(x, y) && withinImage(x + width - 1, y + height - 1)) { BufferedImage newImage = ImageStore.createTranslucentImage(width, height); newImage.createGraphics().drawImage(this.image, 0, 0, width, height, x, y, x + width, y + height, null); return new StaticImageSprite(newImage); } return new EmptySprite(); }
Source:
private PooledWriter(final Writer<A> writer, final BlockingQueue<A> queue, final int writeThreshold) { if (writeThreshold <= 0) throw new IllegalArgumentException("writeThreshold must be >= 1"); if (writeThreshold > queue.remainingCapacity()) throw new IllegalArgumentException("writeThreshold can't be larger then queue capacity."); this.writer = writer; this.queue = queue; this.writeThreshold = writeThreshold; }

Target:
private PooledWriter(final Writer<A> writer, final BlockingQueue<A> queue, final int writeThreshold) { if (writeThreshold <= 0) throw new IllegalArgumentException("writeThreshold must be >= 1: " + writeThreshold); if (writeThreshold > queue.remainingCapacity()) throw new IllegalArgumentException("writeThreshold (" + writeThreshold + ") can't be larger then queue capacity (" + queue.remainingCapacity() + ")."); this.writer = writer; this.queue = queue; this.writeThreshold = writeThreshold; }
Source:
public Set<Pair<WorkerInfo, ArrayList<String>>> selectExecutors(StressBenchConfig config, List<WorkerInfo> jobWorkerInfoList, SelectExecutorsContext context) throws Exception { Set<Pair<WorkerInfo, ArrayList<String>>> result = Sets.newHashSet(); for (WorkerInfo worker : jobWorkerInfoList) { ArrayList<String> args = new ArrayList<>(2); args.add(BaseParameters.ID_FLAG); args.add(worker.getAddress().getHost() + "-" + worker.getId()); result.add(new Pair<>(worker, args)); LOG.info("selectExecutors() args={}", args); } return result; }

Target:
public Set<Pair<WorkerInfo, ArrayList<String>>> selectExecutors(StressBenchConfig config, List<WorkerInfo> jobWorkerInfoList, SelectExecutorsContext context) throws Exception { Set<Pair<WorkerInfo, ArrayList<String>>> result = Sets.newHashSet(); List<WorkerInfo> workerList = Lists.newArrayList(jobWorkerInfoList); workerList.sort(Comparator.comparingInt(w -> w.getAddress().hashCode())); int clusterLimit = config.getClusterLimit(); if (clusterLimit <= 0) { clusterLimit = workerList.size(); } workerList = workerList.subList(0, clusterLimit); for (WorkerInfo worker : workerList) { ArrayList<String> args = new ArrayList<>(2); args.add(BaseParameters.ID_FLAG); args.add(worker.getAddress().getHost() + "-" + worker.getId()); result.add(new Pair<>(worker, args)); } return result; }
Source:
public Value getValue(Session session) { Value value = expr.getValue(session); if (value == ValueNull.INSTANCE) { return ValueNull.INSTANCE; } int valueType = value.getValueType(); if (valueType >= Value.TINYINT && valueType <= Value.BIGINT) { return value; } String name = value.getString(); ArrayList<Table> tables = session.getDatabase().getAllTablesAndViews(true); ArrayList<Table> tempTables = session.getLocalTempTables(); tables.addAll(tempTables); for (Table table : tables) { if (table.isHidden()) { continue; } if (table.getName().equals(name)) { return ValueInteger.get(table.getId()); } ArrayList<Index> indexes = table.getIndexes(); if (indexes != null) { for (Index index : indexes) { if (index.getCreateSQL() == null) { continue; } if (index.getName().equals(name)) { return ValueInteger.get(index.getId()); } } } } throw DbException.get(ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1, name); }

Target:
public Value getValue(Session session) { Value value = expr.getValue(session); if (value == ValueNull.INSTANCE) { return ValueNull.INSTANCE; } int valueType = value.getValueType(); if (valueType >= Value.TINYINT && valueType <= Value.INTEGER) { return value.convertToInt(null); } if (valueType == Value.BIGINT) { return ValueInteger.get((int) value.getLong()); } String name = value.getString(); ArrayList<Table> tables = session.getDatabase().getAllTablesAndViews(true); ArrayList<Table> tempTables = session.getLocalTempTables(); tables.addAll(tempTables); for (Table table : tables) { if (table.isHidden()) { continue; } if (table.getName().equals(name)) { return ValueInteger.get(table.getId()); } ArrayList<Index> indexes = table.getIndexes(); if (indexes != null) { for (Index index : indexes) { if (index.getCreateSQL() == null) { continue; } if (index.getName().equals(name)) { return ValueInteger.get(index.getId()); } } } } throw DbException.get(ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1, name); }
Source:
public static Properties getIntegrationProperties(BeanFactory beanFactory) { Properties properties = new Properties(IntegrationProperties.defaults()); if (beanFactory != null) { Properties userProperties = getBeanOfType(beanFactory, INTEGRATION_PROPERTIES_BEAN_NAME, Properties.class); if (userProperties != null) { properties.putAll(userProperties); } } return properties; }

Target:
public static Properties getIntegrationProperties(BeanFactory beanFactory) { Properties properties = new Properties(); properties.putAll(IntegrationProperties.defaults()); if (beanFactory != null) { Properties userProperties = getBeanOfType(beanFactory, INTEGRATION_GLOBAL_PROPERTIES_BEAN_NAME, Properties.class); if (userProperties != null) { properties.putAll(userProperties); } } return properties; }
Source:
public int syncFromChangesMerging(Collection<Change> changes, boolean verifyResult) { if (changes.isEmpty()) { return 0; } Set<String> entityIds = newHashSetWithExpectedSize(changes.size()); List<Statement> insertStatements = new ArrayList<>(); ClassifiedStatements classifiedStatements = new ClassifiedStatements(uris); Set<String> valueSet = new HashSet<>(); Set<String> refSet = new HashSet<>(); int modified = 0; for (final Change change : changes) { if (change.getStatements() == null) { continue; } entityIds.add(change.entityId()); insertStatements.addAll(change.getStatements()); classifiedStatements.classify(change.getStatements(), change.entityId()); valueSet.addAll(change.getValueCleanupList()); refSet.addAll(change.getRefCleanupList()); if (insertStatements.size() > maxStatementsPerBatch || classifiedStatements.getDataSize() > maxPostDataSize) { log.info("Too much data with bytes - sending batch out, last ID {}", classifiedStatements.getDataSize(), change.entityId()); modified += sendMergingUpdateBatch(uris.entity(), uris.statement(), entityIds, insertStatements, classifiedStatements, refSet, valueSet, verifyResult); entityIds.clear(); insertStatements.clear(); classifiedStatements.clear(); valueSet.clear(); refSet.clear(); } } if (!entityIds.isEmpty()) { modified += sendMergingUpdateBatch(uris.entity(), uris.statement(), entityIds, insertStatements, classifiedStatements, refSet, valueSet, verifyResult); } return modified; }

Target:
public int syncFromChangesMerging(Collection<Change> changes, boolean verifyResult) { if (changes.isEmpty()) { return 0; } Set<String> entityIds = newHashSetWithExpectedSize(changes.size()); List<Statement> insertStatements = new ArrayList<>(); ClassifiedStatements classifiedStatements = new ClassifiedStatements(uris); Set<String> valueSet = new HashSet<>(); Set<String> refSet = new HashSet<>(); int modified = 0; for (final Change change : changes) { if (change.getStatements() == null) { continue; } entityIds.add(change.entityId()); insertStatements.addAll(change.getStatements()); classifiedStatements.classify(change.getStatements(), change.entityId()); valueSet.addAll(change.getValueCleanupList()); refSet.addAll(change.getRefCleanupList()); if (insertStatements.size() > maxStatementsPerBatch || classifiedStatements.getDataSize() > maxPostDataSize) { log.info("Too much data with bytes - sending batch out, last ID {}", classifiedStatements.getDataSize(), change.entityId()); modified += sendMergingUpdateBatch(uris.entity(), uris.statement(), entityIds, insertStatements, refSet, valueSet, verifyResult); entityIds.clear(); insertStatements.clear(); classifiedStatements.clear(); valueSet.clear(); refSet.clear(); } } if (!entityIds.isEmpty()) { modified += sendMergingUpdateBatch(uris.entity(), uris.statement(), entityIds, insertStatements, refSet, valueSet, verifyResult); } return modified; }
Source:
public static void output(@AggregationState TDigestAndPercentileState state, BlockBuilder out) { TDigest digest = state.getDigest(); List<Double> percentiles = state.getPercentiles(); if (percentiles == null || digest == null) { out.appendNull(); return; } checkState(percentiles.get(0) != -1.0, "Percentile is missing"); checkCondition(0 <= percentiles.get(0), INVALID_FUNCTION_ARGUMENT, "Percentile must be non-negative"); DOUBLE.writeDouble(out, digest.getQuantile(percentiles.get(0))); out.closeEntry(); }

Target:
public static void output(@AggregationState TDigestAndPercentileState state, BlockBuilder out) { TDigest digest = state.getDigest(); List<Double> percentiles = state.getPercentiles(); if (percentiles == null || digest == null) { out.appendNull(); return; } checkCondition(0 <= percentiles.get(0) && percentiles.get(0) <= 1, INVALID_FUNCTION_ARGUMENT, "Percentile must be between 0 and 1"); DOUBLE.writeDouble(out, digest.getQuantile(percentiles.get(0))); out.closeEntry(); }
Source:
public Range<String> toRange() { if (this.range == null) { synchronized (this) { if (range != null) { this.range = new Range<String>(this.getMinInclusive(), this.getMaxExclusive(), true, false); } } } return this.range; }

Target:
public Range<String> toRange() { if (this.range == null) { synchronized (this) { if (range == null) { this.range = new Range<String>(this.getMinInclusive(), this.getMaxExclusive(), true, false); } } } return this.range; }
Source:
protected final List<?> createValues() { switch (withNulls) { case ALL: return NULL_VALUES; case PARTIAL: return IntStream.range(0, ROWS).mapToObj(i -> i % 2 == 0 ? createValue() : null).collect(toList()); default: return IntStream.range(0, ROWS).mapToObj(i -> createValue()).collect(toList()); } }

Target:
protected List<?> createValues() { switch (withNulls) { case ALL: return NULL_VALUES; case PARTIAL: return IntStream.range(0, ROWS).mapToObj(i -> i % 2 == 0 ? createValue() : null).collect(toList()); default: return IntStream.range(0, ROWS).mapToObj(i -> createValue()).collect(toList()); } }
Source:
public RemoteFramework fork(List<String> vmArgs, Map<String, String> systemProperties, Map<String, Object> frameworkProperties, List<String> beforeFrameworkClasspath, List<String> afterFrameworkClasspath) { port = Integer.parseInt(System.getProperty(EXAM_FORKED_INVOKER_PORT, String.valueOf(getFreePort().getPort()))); LOG.debug("using RMI registry at port {}", port); String rmiName = "ExamRemoteFramework-" + UUID.randomUUID().toString(); try { String address = InetAddress.getLoopbackAddress().getHostAddress(); System.setProperty("java.rmi.server.hostname", address); registry = LocateRegistry.createRegistry(port); Map<String, String> systemPropsNew = new HashMap<>(systemProperties); systemPropsNew.put("java.rmi.server.hostname", address); systemPropsNew.put(RemoteFramework.RMI_PORT_KEY, Integer.toString(port)); systemPropsNew.put(RemoteFramework.RMI_NAME_KEY, rmiName); String[] vmOptions = buildSystemProperties(vmArgs, systemPropsNew); String[] args = buildFrameworkProperties(frameworkProperties); javaRunner = new DefaultJavaRunner(false); javaRunner.exec(vmOptions, buildClasspath(beforeFrameworkClasspath, afterFrameworkClasspath), RemoteFrameworkImpl.class.getName(), args, getJavaHome(), null); return findRemoteFramework(address, port, rmiName); } catch (RemoteException | ExecutionException | URISyntaxException exc) { throw new TestContainerException(exc); } }

Target:
public RemoteFramework fork(List<String> vmArgs, Map<String, String> systemProperties, Map<String, Object> frameworkProperties, List<String> beforeFrameworkClasspath, List<String> afterFrameworkClasspath) { port = getPort(); LOG.debug("using RMI registry at port {}", port); String rmiName = "ExamRemoteFramework-" + UUID.randomUUID().toString(); try { String address = InetAddress.getLoopbackAddress().getHostAddress(); System.setProperty("java.rmi.server.hostname", address); registry = LocateRegistry.createRegistry(port); Map<String, String> systemPropsNew = new HashMap<>(systemProperties); systemPropsNew.put("java.rmi.server.hostname", address); systemPropsNew.put(RemoteFramework.RMI_PORT_KEY, Integer.toString(port)); systemPropsNew.put(RemoteFramework.RMI_NAME_KEY, rmiName); String[] vmOptions = buildSystemProperties(vmArgs, systemPropsNew); String[] args = buildFrameworkProperties(frameworkProperties); javaRunner = new DefaultJavaRunner(false); javaRunner.exec(vmOptions, buildClasspath(beforeFrameworkClasspath, afterFrameworkClasspath), RemoteFrameworkImpl.class.getName(), args, getJavaHome(), null); return findRemoteFramework(address, port, rmiName); } catch (RemoteException | ExecutionException | URISyntaxException exc) { throw new TestContainerException(exc); } }
Source:
private void checkIndexValue(MockId id) throws StoreException { IndexValue value = state.getExpectedValue(id, false); IndexValue valueFromStore = state.index.findKey(id); assertEquals("Unexpected size in IndexValue", value.getSize(), valueFromStore.getSize()); assertEquals("Unexpected expiresAtMs in IndexValue", value.getExpiresAtMs(), valueFromStore.getExpiresAtMs()); assertEquals("Unexpected op time in IndexValue " + value + ", actual " + valueFromStore, value.getOperationTimeInMs(), valueFromStore.getOperationTimeInMs()); assertEquals("Unexpected service ID in IndexValue", value.getServiceId(), valueFromStore.getServiceId()); assertEquals("Unexpected container ID in IndexValue", value.getContainerId(), valueFromStore.getContainerId()); assertEquals("Unexpected flags in IndexValue", value.getFlags(), valueFromStore.getFlags()); }

Target:
private void checkIndexValue(MockId id) throws StoreException { IndexValue value = state.getExpectedValue(id, false); IndexValue valueFromStore = state.index.findKey(id); assertEquals("Unexpected size in IndexValue", value.getSize(), valueFromStore.getSize()); assertEquals("Unexpected expiresAtMs in IndexValue", value.getExpiresAtMs(), valueFromStore.getExpiresAtMs()); assertEquals("Unexpected op time in IndexValue ", value.getOperationTimeInMs(), valueFromStore.getOperationTimeInMs()); assertEquals("Unexpected account ID in IndexValue", value.getAccountId(), valueFromStore.getAccountId()); assertEquals("Unexpected container ID in IndexValue", value.getContainerId(), valueFromStore.getContainerId()); assertEquals("Unexpected flags in IndexValue", value.getFlags(), valueFromStore.getFlags()); }
Source:
public void testCheckNotClosed() { AbstractServiceConnectionManager<Object> connectionManager = new TestServiceConnectionManager(); connectionManager.checkNotClosed(); connectionManager.connect(new Object()); connectionManager.checkNotClosed(); connectionManager.disconnect(); connectionManager.checkNotClosed(); connectionManager.close(); try { connectionManager.checkNotClosed(); } catch (IllegalStateException expected) { } }

Target:
public void testCheckNotClosed() { AbstractServiceConnectionManager<Object> connectionManager = new TestServiceConnectionManager(); connectionManager.checkNotClosed(); connectionManager.connect(new Object()); connectionManager.checkNotClosed(); connectionManager.disconnect(); connectionManager.checkNotClosed(); connectionManager.close(); try { connectionManager.checkNotClosed(); fail("checkNotClosed() did not fail for a closed connection manager"); } catch (IllegalStateException expected) { } }
Source:
public TimelockServiceStatus getTimelockServiceStatus() { Map<String, Meter> meters = AtlasDbMetrics.getMetricRegistry().getMeters(); if (!meters.containsKey("timelock.success") && !meters.containsKey("timelock.fail")) { log.error("Timelock client metrics is not properly set"); throw new IllegalStateException(); } boolean isHealthy = meters.get("timelock.success").getFiveMinuteRate() >= meters.get("timelock.fail").getFiveMinuteRate(); if (isHealthy) { return TimelockServiceStatus.HEALTHY; } else { return TimelockServiceStatus.UNHEALTHY; } }

Target:
public TimelockServiceStatus getTimelockServiceStatus() { return timelockHealthCheck.getStatus(); }
Source:
public synchronized boolean setReplicaSealedState(ReplicaId replicaId, boolean isSealed) { if (!(replicaId instanceof AmbryReplica)) { throw new IllegalArgumentException( "HelixParticipant only works with the AmbryReplica implementation of ReplicaId"); } HelixAdmin helixAdmin = manager.getClusterManagmentTool(); InstanceConfig instanceConfig = helixAdmin.getInstanceConfig(clusterName, instanceName); if (instanceConfig == null) { throw new IllegalStateException( "No instance config found for cluster: \"" + clusterName + "\", instance: \"" + instanceName + "\""); } List<String> sealedReplicas = ClusterMapUtils.getSealedReplicas(instanceConfig); if (sealedReplicas == null) { sealedReplicas = new ArrayList<>(); } String partitionId = replicaId.getPartitionId().toPathString(); if (!isSealed && sealedReplicas.contains(partitionId)) { sealedReplicas.remove(partitionId); } else if (isSealed && !sealedReplicas.contains(partitionId)) { sealedReplicas.add(partitionId); } else { return true; } instanceConfig.getRecord().setListField(ClusterMapUtils.SEALED_STR, sealedReplicas); return helixAdmin.setInstanceConfig(clusterName, instanceName, instanceConfig); }

Target:
public synchronized boolean setReplicaSealedState(ReplicaId replicaId, boolean isSealed) { if (!(replicaId instanceof AmbryReplica)) { throw new IllegalArgumentException( "HelixParticipant only works with the AmbryReplica implementation of ReplicaId"); } List<String> sealedReplicas = getSealedReplicas(); if (sealedReplicas == null) { sealedReplicas = new ArrayList<>(); } String partitionId = replicaId.getPartitionId().toPathString(); boolean success = true; if (!isSealed && sealedReplicas.contains(partitionId)) { sealedReplicas.remove(partitionId); success = setSealedReplicas(sealedReplicas); } else if (isSealed && !sealedReplicas.contains(partitionId)) { sealedReplicas.add(partitionId); success = setSealedReplicas(sealedReplicas); } return success; }
Source:
public CtfIterator getIterator(final CtfTmfContext context) { CtfIterator retVal = fMap.get(context); if (retVal == null) { fAccessLock.lock(); try { if (fRandomAccess.size() < MAX_SIZE) { retVal = fTrace.createIterator(); addElement(context, retVal); } else { retVal = replaceRandomElement(context); } if (context.getLocation() != null) { final CtfLocationInfo location = (CtfLocationInfo) context.getLocation().getLocationInfo(); retVal.seek(location); } } finally { fAccessLock.unlock(); } } return retVal; }

Target:
public CtfIterator getIterator(final CtfTmfContext context) { CtfIterator iter = fMap.get(context); if (iter == null) { fAccessLock.lock(); try { if (fRandomAccess.size() < MAX_SIZE) { iter = fTrace.createIterator(); addElement(context, iter); } else { iter = replaceRandomElement(context); } if (context.getLocation() != null) { final CtfLocationInfo location = (CtfLocationInfo) context.getLocation().getLocationInfo(); iter.seek(location); } } finally { fAccessLock.unlock(); } } return iter; }
Source:
private Iterator<BatchOfCellsToSweep> getBatchesToSweep(Iterator<List<CandidateCellForSweeping>> candidates, SweepBatchConfig batchConfig, SweepableCellFilter sweepableCellFilter, ExaminedCellLimit limit) { Iterator<List<CandidateCellForSweeping>> validCandidates = Iterators.filter(candidates, list -> list != null && !list.isEmpty()); Iterator<BatchOfCellsToSweep> cellsToSweep = Iterators.transform( validCandidates, sweepableCellFilter::getCellsToSweep); return new CellsToSweepPartitioningIterator(cellsToSweep, batchConfig.deleteBatchSize(), limit); }

Target:
private Iterator<BatchOfCellsToSweep> getBatchesToSweep(Iterator<List<CandidateCellForSweeping>> candidates, SweepBatchConfig batchConfig, SweepableCellFilter sweepableCellFilter, ExaminedCellLimit limit) { Iterator<BatchOfCellsToSweep> cellsToSweep = Iterators.transform( Iterators.filter(candidates, list -> !list.isEmpty()), sweepableCellFilter::getCellsToSweep); return new CellsToSweepPartitioningIterator(cellsToSweep, batchConfig.deleteBatchSize(), limit); }
Source:
public ServiceCall<Collection> createCollection(CreateCollectionOptions createCollectionOptions) { String[] pathSegments = {"v4/collections"}; RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getServiceUrl(), pathSegments)); builder.query("version", versionDate); Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("watson_vision_combined", "v4", "createCollection"); for (Entry<String, String> header : sdkHeaders.entrySet()) { builder.header(header.getKey(), header.getValue()); } builder.header("Accept", "application/json"); final JsonObject contentJson = new JsonObject(); if (createCollectionOptions != null) { if (createCollectionOptions.name() != null) { contentJson.addProperty("name", createCollectionOptions.name()); } if (createCollectionOptions.description() != null) { contentJson.addProperty("description", createCollectionOptions.description()); } } builder.bodyJson(contentJson); ResponseConverter<Collection> responseConverter = ResponseConverterUtils.getValue( new com.google.gson.reflect.TypeToken<Collection>() {}.getType()); return createServiceCall(builder.build(), responseConverter); }

Target:
public ServiceCall<Collection> createCollection(CreateCollectionOptions createCollectionOptions) { com.ibm.cloud.sdk.core.util.Validator.notNull( createCollectionOptions, "createCollectionOptions cannot be null"); String[] pathSegments = {"v4/collections"}; RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getServiceUrl(), pathSegments)); builder.query("version", versionDate); Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("watson_vision_combined", "v4", "createCollection"); for (Entry<String, String> header : sdkHeaders.entrySet()) { builder.header(header.getKey(), header.getValue()); } builder.header("Accept", "application/json"); final JsonObject contentJson = new JsonObject(); if (createCollectionOptions != null) { if (createCollectionOptions.name() != null) { contentJson.addProperty("name", createCollectionOptions.name()); } if (createCollectionOptions.description() != null) { contentJson.addProperty("description", createCollectionOptions.description()); } } builder.bodyJson(contentJson); ResponseConverter<Collection> responseConverter = ResponseConverterUtils.getValue( new com.google.gson.reflect.TypeToken<Collection>() {}.getType()); return createServiceCall(builder.build(), responseConverter); }
Source:
protected Map<String, String> readContext(final String property) throws JMSException { final String json = readProperty(property); IDoEntity context = m_contextDataObjectMapper.get().readValue(json, IDoEntity.class); if (context == null) { return Collections.emptyMap(); } return context.allNodes().entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> assertInstance(e.getValue().get(), String.class))); }

Target:
protected Map<String, String> readContext(final String property) throws JMSException { final String json = readProperty(property); @SuppressWarnings("unchecked") Map<String, String> context = (Map<String, String>) m_contextDataObjectMapper.readValue(json, HashMap.class); if (context == null) { return Collections.emptyMap(); } return context; }
Source:
public Collection<Sample> listByProjectId(long projectId) throws IOException { @SuppressWarnings("unchecked") List<Sample> records = currentSession().createCriteria(SampleImpl.class).add(Restrictions.like("project.id", projectId)).list(); return records; }

Target:
public Collection<Sample> listByProjectId(long projectId) throws IOException { @SuppressWarnings("unchecked") List<Sample> records = currentSession().createCriteria(SampleImpl.class).add(Restrictions.eq("project.id", projectId)).list(); return records; }
Source:
public Set<String> getIds() { File[] transformerFiles = transformerFolder.toFile().listFiles(); if (transformerFiles == null || transformerFiles.length == 0) { LOGGER.debug("No Input Transformer json files found in {}", transformerFolder); return Collections.emptySet(); } Set<String> allTransformerIds = new HashSet<>(); Gson gson = new Gson(); for (File transformerFile : transformerFiles) { if (!FilenameUtils.getExtension(transformerFile.toString()).equals("json")) { LOGGER.debug("Skipping non-json file {}", transformerFile); continue; } try (FileReader reader = new FileReader(transformerFile)) { List<String> filesTransformerIds = gson.fromJson(reader, new TypeToken<List<String>>() {}.getType()); allTransformerIds.addAll(filesTransformerIds); } catch (IOException e) { LOGGER.debug( "Error reading InputTransformer ids from file {}. The ids returned will not be the full set described in {}.", transformerFile, transformerFolder); } } return ImmutableSet.copyOf(allTransformerIds); }

Target:
public Set<String> getIds() { File[] transformerFiles = transformerFolder.toFile().listFiles(); if (transformerFiles == null || transformerFiles.length == 0) { LOGGER.debug("No Input Transformer json files found in {}", transformerFolder); return Collections.emptySet(); } Set<String> allTransformerIds = new HashSet<>(); Gson gson = new Gson(); boolean malformed = false; for (File transformerFile : transformerFiles) { if (!FilenameUtils.getExtension(transformerFile.toString()).equalsIgnoreCase("json")) { LOGGER.debug("Skipping non-json file {}", transformerFile); continue; } try (FileReader reader = new FileReader(transformerFile)) { List<String> filesTransformerIds = gson.fromJson(reader, new TypeToken<List<String>>() {}.getType()); if (filesTransformerIds != null) { allTransformerIds.addAll(filesTransformerIds); } } catch (IOException e) { LOGGER.debug( "Error reading InputTransformer ids from file {}. The ids returned may not be the full set described in {}.", transformerFile, transformerFolder); } catch (JsonSyntaxException e) { LOGGER.error( "Malformed JSON file {}. Fix or remove the file before continuing. See debug logs for more info.", transformerFile); LOGGER.debug("Malformed InputTransformer JSON file {}", transformerFile, e); malformed = true; } } if (malformed) { throw new IllegalStateException("One or more InputTransformer JSON files were malformed."); } return ImmutableSet.copyOf(allTransformerIds); }
Source:
public void reloadIndex_EXISTING() throws SolrServerException, IOException { when(solrServer.request(any())).thenReturn(buildSuccessResponse()); when(solrServer.request(isCheckStatus())).thenReturn(buildCheckStatusResponse()); IndexConfiguration indexConfiguration = new IndexConfiguration(); indexConfiguration.setName(EXISTING_INDEX_NAME); indexConfiguration.setInstanceDir("indexDirectory"); indexReloader.reloadIndex(indexConfiguration); ArgumentCaptor<SolrRequest> solrRequestArg = ArgumentCaptor.forClass(SolrRequest.class); verify(solrServer, times(2)).request(solrRequestArg.capture()); SolrRequest actualCheckRequest = solrRequestArg.getAllValues().get(0); SolrRequest actualReloadRequest = solrRequestArg.getAllValues().get(1); assertStatusRequest(actualCheckRequest); assertReloadRequest(actualReloadRequest, "indexName"); }

Target:
public void reloadIndex_EXISTING() throws SolrServerException, IOException { when(solrServer.request(any())).thenReturn(buildSuccessResponse()); when(solrServer.request(isCheckStatus())).thenReturn(buildCheckStatusResponse()); IndexConfiguration indexConfiguration = new IndexConfiguration(); indexConfiguration.setName(EXISTING_INDEX_NAME); indexConfiguration.setInstanceDir("indexDirectory"); indexReloader.reloadIndex(indexConfiguration); ArgumentCaptor<SolrRequest> solrRequestArg = ArgumentCaptor.forClass(SolrRequest.class); verify(solrServer, times(2)).request(solrRequestArg.capture()); SolrRequest actualCheckRequest = solrRequestArg.getAllValues().get(0); SolrRequest actualReloadRequest = solrRequestArg.getAllValues().get(1); assertStatusRequest(actualCheckRequest); assertReloadRequest(actualReloadRequest, EXISTING_INDEX_NAME); }