auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void initExtensions(){ String tmp = getConfigValue("env.extensions", "spl, org.develnext.jphp.zend.ext.ZendExtension").toString(); String[] extensions = StringUtils.split(tmp, ","); for(String ext : extensions){ String className = Information.EXTENSIONS.get(ext.trim().toLowerCase()); if (className == null) className = ext.trim(); try { Extension extension = (Extension) Class.forName(className).newInstance(); compileScope.registerExtension(extension); } catch (Exception e) { throw new LaunchException("Extension load error: " + e.getClass() + " - " + e.getMessage()); } } this.environment = getConfigValue("env.concurrent").toBoolean() ? new ConcurrentEnvironment(compileScope, out) : new Environment(compileScope, out); environment.setErrorFlags(ErrorType.E_ALL.value ^ ErrorType.E_NOTICE.value); environment.getDefaultBuffer().setImplicitFlush(true); }

Target:
protected void initExtensions(){ String tmp = getConfigValue("env.extensions", "spl").toString(); String[] extensions = StringUtils.split(tmp, ","); for(String ext : extensions){ String className = Information.EXTENSIONS.get(ext.trim().toLowerCase()); if (className == null) className = ext.trim(); try { Extension extension = (Extension) Class.forName(className).newInstance(); compileScope.registerExtension(extension); } catch (Exception e) { throw new LaunchException("Extension load error: " + e.getClass() + " - " + e.getMessage()); } } this.environment = getConfigValue("env.concurrent").toBoolean() ? new ConcurrentEnvironment(compileScope, out) : new Environment(compileScope, out); environment.setErrorFlags(ErrorType.E_ALL.value ^ ErrorType.E_NOTICE.value); environment.getDefaultBuffer().setImplicitFlush(true); }
Source:
ReferenceId(@JsonProperty("referenceId") final String referenceId, @JsonProperty("id") final String id, @JsonProperty("errors") final List<RestError> errors) { this.referenceId = referenceId; this.id = id; this.errors = Optional.ofNullable(errors).orElse(Collections.emptyList()); }

Target:
ReferenceId(@JsonProperty("referenceId") final String referenceId, @JsonProperty("id") final String id, @JsonProperty("errors") final List<RestError> errors) { this.referenceId = referenceId; this.id = id; this.errors = errors; }
Source:
public void create(final String name) { try { new JdkRequest(UriBuilder.fromUri(this.home).build()) .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML) .header(HttpHeaders.AUTHORIZATION, this.token) .method(Request.GET) .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(XmlResponse.class) .rel("/page/links/link[@rel='create']/@href") .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML) .body() .set( String.format( "name=%s", URLEncoder.encode(name, CharEncoding.UTF_8) ) ) .back() .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK); } catch (UnsupportedEncodingException ex) { throw new IllegalStateException(ex); } catch (IOException ex) { throw new IllegalStateException(ex); } }

Target:
public void create(final String name) { try { new JdkRequest(this.home) .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML) .header(HttpHeaders.AUTHORIZATION, this.token) .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(XmlResponse.class) .rel("/page/links/link[@rel='create']/@href") .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML) .body() .formParam("name", name) .back() .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK); } catch (UnsupportedEncodingException ex) { throw new IllegalStateException(ex); } catch (IOException ex) { throw new IllegalStateException(ex); } }
Source:
public void testAfrikaans() throws Exception { runTest("af", "afribooms-perceptron", "Betalings aan die SAID kan op enigeen van die volgende maniere gemaak word .", new String[] { "NOUN", "ADP", "DET", "X", "VERB", "ADP", "PRON", "ADP", "DET", "ADJ", "NOUN", "VERB", "VERB", "PUNCT" }, new String[] { "POS_NOUN", "POS_ADP", "POS_DET", "POS_X", "POS_VERB", "POS_ADP", "POS_PRON", "POS_ADP", "POS_DET", "POS_ADJ", "POS_NOUN", "POS_VERB", "POS_VERB", "POS_PUNCT" }); }

Target:
public void testAfrikaans() throws Exception { runTest("af", null, "Betalings aan die SAID kan op enigeen van die volgende maniere gemaak word .", new String[] { "NOUN", "ADP", "DET", "X", "VERB", "ADP", "PRON", "ADP", "DET", "ADJ", "NOUN", "VERB", "VERB", "PUNCT" }, new String[] { "POS_NOUN", "POS_ADP", "POS_DET", "POS_X", "POS_VERB", "POS_ADP", "POS_PRON", "POS_ADP", "POS_DET", "POS_ADJ", "POS_NOUN", "POS_VERB", "POS_VERB", "POS_PUNCT" }); runTest("af", "afribooms-perceptron", "Betalings aan die SAID kan op enigeen van die volgende maniere gemaak word .", new String[] { "NOUN", "ADP", "DET", "X", "VERB", "ADP", "PRON", "ADP", "DET", "ADJ", "NOUN", "VERB", "VERB", "PUNCT" }, new String[] { "POS_NOUN", "POS_ADP", "POS_DET", "POS_X", "POS_VERB", "POS_ADP", "POS_PRON", "POS_ADP", "POS_DET", "POS_ADJ", "POS_NOUN", "POS_VERB", "POS_VERB", "POS_PUNCT" }); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState == null) { new CustomTabsIntent.Builder() .setShowTitle(true) .enableUrlBarHiding() .setToolbarColor(ContextCompat.getColor(this, R.color.colorPrimary)) .build() .launchUrl(this, (Uri) getIntent().getParcelableExtra(ExtraConstants.PARAMS)); mShouldCloseCustomTab = false; } }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState == null) { new CustomTabsIntent.Builder() .setShowTitle(true) .enableUrlBarHiding() .setToolbarColor(ContextCompat.getColor(this, R.color.colorPrimary)) .build() .launchUrl(this, (Uri) getIntent().getParcelableExtra(ExtraConstants.GITHUB_URL)); mShouldCloseCustomTab = false; } else { mShouldCloseCustomTab = savedInstanceState.getBoolean(SHOULD_CLOSE_CCT_KEY); } }
Source:
public void printUsage() { String header = ""; String importFormats = Globals.IMPORT_FORMAT_READER.getImportFormatList(); String importFormatsList = String.format("%s:%n%s%n", Localization.lang("Available import formats"), importFormats); String outFormats = Globals.exportFactory.getExportersAsString(70, 20, ""); String outFormatsList = String.format("%s: %s%n", Localization.lang("Available export formats"), outFormats); String footer = '\n' + importFormatsList + outFormatsList + "\nPlease report issues at <LINK_1>"; HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(100, "jabref [OPTIONS] [BIBTEX_FILE]\n\nOptions:", header, getOptions(), footer, true); }

Target:
public void printUsage() { String header = ""; String importFormats = Globals.IMPORT_FORMAT_READER.getImportFormatList(); String importFormatsList = String.format("%s:%n%s%n", Localization.lang("Available import formats"), importFormats); String outFormats = Globals.exportFactory.getExportersAsString(70, 20, ""); String outFormatsList = String.format("%s: %s%n", Localization.lang("Available export formats"), outFormats); String footer = '\n' + importFormatsList + outFormatsList + "\nPlease report issues at <LINK_1>"; HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(WIDTH, "jabref [OPTIONS] [BIBTEX_FILE]\n\nOptions:", header, getOptions(), footer, true); }
Source:
public void process() { PerformanceMonitor.startActivity("rendering/initialpostprocessing"); disableWireframeIf(renderingDebugConfig.isWireframe()); FBO scenePrePost = frameBuffersManager.getFBO("scenePrePost"); FBO sceneOpaque = frameBuffersManager.getFBO("sceneOpaque"); initialPost.enable(); scenePrePost.bind(); setViewportToSizeOf(scenePrePost); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); renderFullscreenQuad(); bindDisplay(); setViewportToSizeOf(sceneOpaque); PerformanceMonitor.endActivity(); }

Target:
public void process() { PerformanceMonitor.startActivity("rendering/initialPostProcessing"); scenePrePost = frameBuffersManager.getFBO("scenePrePost"); sceneOpaque = frameBuffersManager.getFBO("sceneOpaque"); initialPost.enable(); scenePrePost.bind(); setViewportToSizeOf(scenePrePost); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); renderFullscreenQuad(); bindDisplay(); setViewportToSizeOf(sceneOpaque); PerformanceMonitor.endActivity(); }
Source:
protected MetadataSchemaRest createAndReturn(Context context) throws AuthorizeException, SQLException { MetadataSchemaRest metadataSchemaRest; try { metadataSchemaRest = new ObjectMapper().readValue( getRequestService().getCurrentRequest().getHttpServletRequest().getInputStream(), MetadataSchemaRest.class ); } catch (IOException excIO) { throw new PatchBadRequestException("error parsing the body ..." + excIO.getMessage()); } if (isBlank(metadataSchemaRest.getPrefix())) { throw new UnprocessableEntityException("metadata schema name can be blank not"); } if (isBlank(metadataSchemaRest.getNamespace())) { throw new UnprocessableEntityException("metadata schema namespace can be blank not"); } MetadataSchema metadataSchema; try { metadataSchema = metadataSchemaService.create( context, metadataSchemaRest.getPrefix(), metadataSchemaRest.getNamespace() ); metadataSchemaService.update(context, metadataSchema); } catch (NonUniqueMetadataException e) { throw new UnprocessableEntityException("metadata schema " + metadataSchemaRest.getPrefix() + "." + metadataSchemaRest.getNamespace() + " already exists"); } return converter.convert(metadataSchema); }

Target:
protected MetadataSchemaRest createAndReturn(Context context) throws AuthorizeException, SQLException { MetadataSchemaRest metadataSchemaRest; try { metadataSchemaRest = new ObjectMapper().readValue( getRequestService().getCurrentRequest().getHttpServletRequest().getInputStream(), MetadataSchemaRest.class ); } catch (IOException excIO) { throw new PatchBadRequestException("error parsing request body", excIO); } if (isBlank(metadataSchemaRest.getPrefix())) { throw new UnprocessableEntityException("metadata schema name cannot be blank"); } if (isBlank(metadataSchemaRest.getNamespace())) { throw new UnprocessableEntityException("metadata schema namespace cannot be blank"); } MetadataSchema metadataSchema; try { metadataSchema = metadataSchemaService.create( context, metadataSchemaRest.getPrefix(), metadataSchemaRest.getNamespace() ); metadataSchemaService.update(context, metadataSchema); } catch (NonUniqueMetadataException e) { throw new UnprocessableEntityException("metadata schema " + metadataSchemaRest.getPrefix() + "." + metadataSchemaRest.getNamespace() + " already exists"); } return converter.convert(metadataSchema); }
Source:
public String toString() { return MoreObjects.toStringHelper(this) .add("input", mInput) .add("output", mOutput) .add("maxNumFiles", mMaxNumFiles) .add("minFileSize", mMinFileSize) .add("partitionInfo", mInputPartitionInfo) .toString(); }

Target:
public String toString() { return MoreObjects.toStringHelper(this) .add("input", mInput) .add("output", mOutput) .add("maxNumFiles", mMaxNumFiles) .add("minFileSize", mMinFileSize) .add("inputPartitionInfo", mInputPartitionInfo) .add("outputPartitionInfo", mOutputPartitionInfo) .toString(); }
Source:
protected void refreshDisplayLabels() { String @Nullable categories = fCategories; if (categories == null || categories.length == 0) { return; } IAxis xAxis = getChart().getAxisSet().getXAxis(0); if (!xAxis.getTick().isVisible() || !xAxis.isCategoryEnabled()) { return; } Rectangle rect = getChart().getClientArea(); int lengthLimit = (int) (rect.height * 0.40); GC gc = new GC(getParent()); gc.setFont(xAxis.getTick().getFont()); String longestString = Arrays.stream(categories).max(Comparator.comparingInt(String::length)).orElse(categories[0]); Point pixels = gc.stringExtent(longestString); int cutLen = 5; String[] displayCategories = new String[categories.length]; if (pixels.x > lengthLimit) { for (int i = 0; i < categories.length; i++) { if (categories[i].length() > cutLen) { displayCategories[i] = categories[i].substring(0, cutLen) + ELLIPSIS; } else { displayCategories[i] = categories[i]; } } } else { displayCategories = Arrays.copyOf(categories, categories.length); } xAxis.setCategorySeries(displayCategories); gc.dispose(); }

Target:
protected void refreshDisplayLabels() { String @Nullable categories = fCategories; if (categories == null || categories.length == 0) { return; } IAxis xAxis = getChart().getAxisSet().getXAxis(0); if (!xAxis.getTick().isVisible() || !xAxis.isCategoryEnabled()) { return; } Rectangle rect = getChart().getClientArea(); int lengthLimit = (int) (rect.height * LENGTH_LIMIT); GC gc = new GC(getParent()); gc.setFont(xAxis.getTick().getFont()); String longestString = Arrays.stream(categories).max(Comparator.comparingInt(String::length)).orElse(categories[0]); Point pixels = gc.stringExtent(longestString); int cutLen = 5; String[] displayCategories = new String[categories.length]; if (pixels.x > lengthLimit) { for (int i = 0; i < categories.length; i++) { if (categories[i].length() > cutLen) { displayCategories[i] = categories[i].substring(0, cutLen) + ELLIPSIS; } else { displayCategories[i] = categories[i]; } } } else { displayCategories = Arrays.copyOf(categories, categories.length); } xAxis.setCategorySeries(displayCategories); gc.dispose(); }
Source:
protected boolean updateSelection(IStructuredSelection selection) { if (compareSourceViewer != null) { selectedRange = compareSourceViewer.getSelection(); if (selectedRange != null) { IReviewItem item = getItem(); if (item != null) { return item.getReview() != null && item.getReview().getRepository() != null && item.getReview().getRepository().getAccount() != null; } return true; } } return false; }

Target:
protected boolean updateSelection(IStructuredSelection selection) { if (compareSourceViewer != null) { selectedRange = compareSourceViewer.getSelection(); if (selectedRange != null) { return getItem() != null && !isAnonymous(getItem()); } } return false; }
Source:
public boolean isConsumerSubscribed(String name, DataConsumer consumer) { if (!mConsumers.containsKey(name)) { return false; } List<DataConsumer> processors = mConsumers.get(name); for (DataConsumer registeredProcessor : processors) { if (registeredProcessor.equals(consumer)) { return true; } } return false; }

Target:
public boolean isConsumerSubscribed(String name, DataConsumer consumer) { List<DataConsumer> consumers = getSubscribedConsumers(name); if (null != consumers) { for (DataConsumer registeredConsumer : consumers) { if (registeredConsumer.equals(consumer)) { return true; } } } return false; }
Source:
private boolean isDomainTypeValidForPathEditing(StorageDomain storage) { StorageDomainType storageDomainType = storage.getStorageDomainType(); return (storageDomainType == StorageDomainType.Data || storageDomainType == StorageDomainType.ImportExport || storageDomainType == StorageDomainType.ISO || storageDomainType == StorageDomainType.Master); }

Target:
private boolean isDomainTypeValidForPathEditing(StorageDomain storage) { StorageDomainType storageDomainType = storage.getStorageDomainType(); return (storageDomainType.isInternalDomain() || storageDomainType == StorageDomainType.Master); }
Source:
protected Map<ClaimMapping, String> getSubjectAttributes( OAuthClientResponse token) { Map<ClaimMapping, String> claims = new HashMap<ClaimMapping, String>(); try { String json = sendRequest(token.getParam(GoogleOAuth2AuthenticationConstant.GOOGLE_USERINFO_ENDPOINT), token.getParam(OIDCAuthenticatorConstants.ACCESS_TOKEN)); if (json.length() > 0) { Map<String, Object> jsonObject = JSONUtils.parseJSON(json); if (jsonObject != null) { for (Map.Entry<String, Object> entry : jsonObject.entrySet()) { claims.put(ClaimMapping.build(entry.getKey(), entry.getKey(), null, false), entry.getValue() .toString()); if (log.isDebugEnabled()) { log.debug("Adding claim from end-point data mapping : " + entry.getKey() + " - " + entry.getValue()); } } } } }catch (Exception e) { log.error("Error occurred while accessing google user info endpoint", e); } return claims; }

Target:
protected Map<ClaimMapping, String> getSubjectAttributes( OAuthClientResponse token) { Map<ClaimMapping, String> claims = new HashMap<ClaimMapping, String>(); try { String json = sendRequest(token.getParam(GoogleOAuth2AuthenticationConstant.GOOGLE_USERINFO_ENDPOINT), token.getParam(OIDCAuthenticatorConstants.ACCESS_TOKEN)); if (StringUtils.isNotBlank(json)) { Map<String, Object> jsonObject = JSONUtils.parseJSON(json); if (jsonObject != null) { for (Map.Entry<String, Object> entry : jsonObject.entrySet()) { claims.put(ClaimMapping.build(entry.getKey(), entry.getKey(), null, false), entry.getValue() .toString()); if (log.isDebugEnabled()) { log.debug("Adding claim from end-point data mapping : " + entry.getKey() + " - " + entry.getValue()); } } } } }catch (Exception e) { log.error("Error occurred while accessing google user info endpoint", e); } return claims; }
Source:
private Object remove(InternalReplicatedMapStorage<K, V> storage, Object key) { isNotNull(key, "key"); long time = System.nanoTime(); V oldValue; K marshalledKey = (K) marshall(key); ReplicatedRecord current = storage.get(marshalledKey); if (current == null) { oldValue = null; } else { oldValue = (V) current.getValueInternal(); storage.remove(marshalledKey, current); } if (replicatedMapConfig.isStatisticsEnabled()) { getStats().incrementRemoves(System.nanoTime() - time); } cancelTtlEntry(marshalledKey); return oldValue; }

Target:
private Object remove(InternalReplicatedMapStorage<K, V> storage, Object key) { isNotNull(key, "key"); long time = System.nanoTime(); V oldValue; K marshalledKey = (K) marshall(key); ReplicatedRecord current = storage.get(marshalledKey); if (current == null) { oldValue = null; } else { oldValue = (V) current.getValueInternal(); storage.remove(marshalledKey, current); } if (replicatedMapConfig.isStatisticsEnabled()) { getStats().incrementRemovesNanos(System.nanoTime() - time); } cancelTtlEntry(marshalledKey); return oldValue; }
Source:
public static INVALID_VALUE_TREATMENT_METHOD byName(String name) throws KieEnumException { return Arrays.stream(INVALID_VALUE_TREATMENT_METHOD.values()).filter(value -> name.equals(value.name)).findFirst().orElseThrow(() -> new KieEnumException("Failed to find MINING_FUNCTION with name: " + name)); }

Target:
public static INVALID_VALUE_TREATMENT_METHOD byName(String name) { return Arrays.stream(INVALID_VALUE_TREATMENT_METHOD.values()).filter(value -> Objects.equals(name, value.name)).findFirst().orElseThrow(() -> new KieEnumException("Failed to find MINING_FUNCTION with name: " + name)); }
Source:
private void checkForMemberOfAttribute(List<ExpressionCondition> expressionConditions, List<String> returnedAttributes) { boolean isEQfound = false; boolean otherOperationsFound = false; for (ExpressionCondition expressionCondition : expressionConditions) { if (ExpressionAttribute.ROLE.toString().equals(expressionCondition.getAttributeName()) && ExpressionOperation.EQ.toString().equals(expressionCondition.getOperation())) { isEQfound = true; } else if (ExpressionAttribute.ROLE.toString().equals(expressionCondition.getAttributeName()) && !ExpressionOperation.EQ.toString().equals(expressionCondition.getOperation())) { otherOperationsFound = true; } } if (isEQfound && !otherOperationsFound) { String memberOfProperty = realmConfig.getUserStoreProperty(LDAPConstants.MEMBEROF_ATTRIBUTE); if (StringUtils.isNotEmpty(memberOfProperty)) { this.isMemberOfPropertyFound = true; this.searchBases = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); returnedAttributes.add(realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE)); } } }

Target:
private void checkForMemberOfAttribute(List<ExpressionCondition> expressionConditions, List<String> returnedAttributes) { boolean isEqOperationFound = false; boolean otherOperationsFound = false; for (ExpressionCondition expressionCondition : expressionConditions) { if (ExpressionAttribute.ROLE.toString().equals(expressionCondition.getAttributeName()) && ExpressionOperation.EQ.toString().equals(expressionCondition.getOperation())) { isEqOperationFound = true; } else if (ExpressionAttribute.ROLE.toString().equals(expressionCondition.getAttributeName()) && !ExpressionOperation.EQ.toString().equals(expressionCondition.getOperation())) { otherOperationsFound = true; } } if (isEqOperationFound && !otherOperationsFound) { String memberOfProperty = realmConfig.getUserStoreProperty(LDAPConstants.MEMBEROF_ATTRIBUTE); if (StringUtils.isNotEmpty(memberOfProperty)) { this.isMemberOfPropertyFound = true; this.searchBases = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); returnedAttributes.add(realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE)); } } }
Source:
private void waitNotificationContains(String notificationMessage, String parentWindowHandle) { seleniumWebDriverHelper.waitSuccessCondition( driver -> { if (seleniumWebDriverHelper.isOpenedSomeWin()) { seleniumWebDriver.switchTo().window(parentWindowHandle); theiaIde.switchToIdeFrame(); } return theiaIde.isDisplayedNotificationContains(notificationMessage); }, LOADER_TIMEOUT_SEC); }

Target:
private void waitNotificationContains(String notificationMessage, String parentWindowHandle) { seleniumWebDriverHelper.waitSuccessCondition( driver -> { if (seleniumWebDriverHelper.isTwoOrMoreWindowsOpened()) { driver.switchTo().window(parentWindowHandle); theiaIde.switchToIdeFrame(); } return theiaIde.isNotificationContains(notificationMessage); }, LOADER_TIMEOUT_SEC); }
Source:
protected void waitForCacheToStabilize(Cache<Object, Object> cache, Configuration cacheConfig) throws InterruptedException { ComponentRegistry componentRegistry = cache.getAdvancedCache().getComponentRegistry(); StateTransferManager stateTransferManager = componentRegistry.getStateTransferManager(); StateTransferLock stateTransferLock = componentRegistry.getStateTransferLock(); TimeService timeService = componentRegistry.getTimeService(); long endTime = timeService.expectedEndTime(cacheConfig.clustering().stateTransfer().timeout(), TimeUnit.MILLISECONDS); CacheTopology cacheTopology = stateTransferManager.getCacheTopology(); while (cacheTopology.getMembers().size() < expectedMembers || cacheTopology.getPendingCH() != null) { long remainingTime = timeService.remainingTime(endTime, TimeUnit.NANOSECONDS); try { CompletableFuture<Void> topologyFuture = stateTransferLock.topologyFuture(cacheTopology.getTopologyId() + 1); if (topologyFuture != null) topologyFuture.get(remainingTime, TimeUnit.NANOSECONDS); } catch (ExecutionException e) { throw new CacheException(e.getCause()); } catch (java.util.concurrent.TimeoutException e) { throw log.creatingTmpCacheTimedOut(cacheNameToCreate, cacheManager.getAddress()); } cacheTopology = stateTransferManager.getCacheTopology(); } }

Target:
protected void waitForCacheToStabilize(Cache<Object, Object> cache, Configuration cacheConfig) throws InterruptedException { ComponentRegistry componentRegistry = cache.getAdvancedCache().getComponentRegistry(); StateTransferManager stateTransferManager = componentRegistry.getStateTransferManager(); StateTransferLock stateTransferLock = componentRegistry.getStateTransferLock(); TimeService timeService = componentRegistry.getTimeService(); long endTime = timeService.expectedEndTime(cacheConfig.clustering().stateTransfer().timeout(), TimeUnit.MILLISECONDS); CacheTopology cacheTopology = stateTransferManager.getCacheTopology(); while (cacheTopology.getMembers().size() < expectedMembers || cacheTopology.getPendingCH() != null) { long remainingTime = timeService.remainingTime(endTime, TimeUnit.NANOSECONDS); try { stateTransferLock.waitForTopology(cacheTopology.getTopologyId() + 1, remainingTime, TimeUnit.NANOSECONDS); } catch (TimeoutException ignored) { throw log.creatingTmpCacheTimedOut(cacheNameToCreate, cacheManager.getAddress()); } cacheTopology = stateTransferManager.getCacheTopology(); } }
Source:
public RegisterResponse register(Identity sender, RegisterRequest registerRequest, InetSocketAddress serverEndpoint) { if (registerRequest.getEndpointName() == null || registerRequest.getEndpointName().isEmpty() || sender == null) { return RegisterResponse.badRequest(null); } if (!isAuthorized(registerRequest.getEndpointName(), sender)) { return RegisterResponse.forbidden(null); } Client.Builder builder = new Client.Builder(RegistrationHandler.createRegistrationId(), registerRequest.getEndpointName(), sender.getPeerAddress().getAddress(), sender.getPeerAddress() .getPort(), serverEndpoint); builder = builder.lwm2mVersion(registerRequest.getLwVersion()).lifeTimeInSec(registerRequest.getLifetime()) .bindingMode(registerRequest.getBindingMode()).objectLinks(registerRequest.getObjectLinks()) .smsNumber(registerRequest.getSmsNumber()).registrationDate(new Date()).lastUpdate(new Date()) .additionalRegistrationAttributes(registerRequest.getAdditionalParameters()); Client client = builder.build(); if (clientRegistry.registerClient(client)) { LOG.debug("New registered client: {}", client); return RegisterResponse.success(client.getRegistrationId()); } else { return RegisterResponse.forbidden(null); } }

Target:
public RegisterResponse register(Identity sender, RegisterRequest registerRequest, InetSocketAddress serverEndpoint) { if (registerRequest.getEndpointName() == null || registerRequest.getEndpointName().isEmpty() || sender == null) { return RegisterResponse.badRequest(null); } if (!isAuthorized(registerRequest.getEndpointName(), sender)) { return RegisterResponse.forbidden(null); } Client.Builder builder = new Client.Builder(RegistrationHandler.createRegistrationId(), registerRequest.getEndpointName(), sender.getPeerAddress().getAddress(), sender.getPeerAddress() .getPort(), serverEndpoint); builder.lwm2mVersion(registerRequest.getLwVersion()).lifeTimeInSec(registerRequest.getLifetime()) .bindingMode(registerRequest.getBindingMode()).objectLinks(registerRequest.getObjectLinks()) .smsNumber(registerRequest.getSmsNumber()).registrationDate(new Date()).lastUpdate(new Date()) .additionalRegistrationAttributes(registerRequest.getAdditionalAttributes()); Client client = builder.build(); if (clientRegistry.registerClient(client)) { LOG.debug("New registered client: {}", client); return RegisterResponse.success(client.getRegistrationId()); } else { return RegisterResponse.forbidden(null); } }
Source:
public Builder<TYPE> cfg(TransitionFactory<RuleTransitionData> splitTransitionFactory) { Preconditions.checkState(this.configTransition == NoTransition.INSTANCE, "the configuration transition is already set"); this.splitTransitionFactory = Preconditions.checkNotNull(splitTransitionFactory); return this; }

Target:
public Builder<TYPE> cfg(TransitionFactory<RuleTransitionData> splitTransitionFactory) { Preconditions.checkState(this.configTransition == NoTransition.INSTANCE, "the configuration transition is already set"); Preconditions.checkState( splitTransitionFactory.isSplit(), "cfg(TransitionFactory) is only valid for split transitions at this time."); this.splitTransitionFactory = Preconditions.checkNotNull(splitTransitionFactory); return this; }
Source:
public void testProcessProperlyKilledUnix() throws Exception { ProcessTree.enabled = true; if (Functions.isWindows()) return; FreeStyleProject sleepProject = createFreeStyleProject(); FreeStyleProject processJob = createFreeStyleProject(); sleepProject.getBuildersList().add(new Shell("nohup sleep 100000 &")); assertBuildStatusSuccess(sleepProject.scheduleBuild2(0).get()); processJob.getBuildersList().add(new Shell("ps -ef | grep sleep")); String log = processJob.scheduleBuild2(0).get().getLog(); System.err.println("LOGS: " + log); assertFalse("Did not properly kill task", log.contains("sleep 100000")); }

Target:
public void testProcessProperlyKilledUnix() throws Exception { ProcessTree.enabled = true; if (Functions.isWindows()) return; FreeStyleProject sleepProject = createFreeStyleProject(); FreeStyleProject processJob = createFreeStyleProject(); sleepProject.getBuildersList().add(new Shell("nohup sleep 100000 &")); assertBuildStatusSuccess(sleepProject.scheduleBuild2(0).get()); processJob.getBuildersList().add(new Shell("ps -ef | grep sleep")); assertLogNotContains("sleep 100000", processJob.scheduleBuild2(0).get()); }
Source:
public void testMergeSegments_WithExplicitReleaseOther() throws Exception { initProcessor(TrackingEventProcessorConfiguration.forParallelProcessing(2)); tokenStore.initializeTokenSegments(testSubject.getName(), 2); List<EventMessage<?>> handledEvents = new CopyOnWriteArrayList<>(); List<EventMessage<?>> events = new ArrayList<>(); for (int i = 0; i < 10; i++) { events.add(createEvent(UUID.randomUUID().toString(), 0)); } when(mockHandler.handle(any())).thenAnswer(i -> handledEvents.add(i.getArgument(0))); eventBus.publish(events); testSubject.start(); waitForActiveThreads(2); testSubject.releaseSegment(1); waitForSegmentRelease(1); assertTrue("Expected merge to succeed", testSubject.mergeSegment(0).join()); assertArrayEquals(new int[]{0}, tokenStore.fetchSegments(testSubject.getName())); waitForSegmentStart(0); while (!Optional.ofNullable(testSubject.processingStatus().get(0)).map(EventTrackerStatus::isCaughtUp).orElse(false)) { Thread.sleep(10); } handledEvents.forEach(e -> System.out.println(((TrackedEventMessage) e).trackingToken())); assertEquals(10, handledEvents.size()); }

Target:
public void testMergeSegments_WithExplicitReleaseOther() throws Exception { initProcessor(TrackingEventProcessorConfiguration.forParallelProcessing(2)); tokenStore.initializeTokenSegments(testSubject.getName(), 2); List<EventMessage<?>> handledEvents = new CopyOnWriteArrayList<>(); List<EventMessage<?>> events = new ArrayList<>(); for (int i = 0; i < 10; i++) { events.add(createEvent(UUID.randomUUID().toString(), 0)); } when(mockHandler.handle(any())).thenAnswer(i -> handledEvents.add(i.getArgument(0))); eventBus.publish(events); testSubject.start(); waitForActiveThreads(2); testSubject.releaseSegment(1); waitForSegmentRelease(1); assertTrue("Expected merge to succeed", testSubject.mergeSegment(0).join()); assertArrayEquals(new int[]{0}, tokenStore.fetchSegments(testSubject.getName())); waitForSegmentStart(0); while (!Optional.ofNullable(testSubject.processingStatus().get(0)).map(EventTrackerStatus::isCaughtUp).orElse(false)) { Thread.sleep(10); } assertEquals(10, handledEvents.size()); }
Source:
public void validate(Environment environment) throws NotFoundException, InfrastructureException, ValidationException { String type = environment.getRecipe().getType(); if (!infraByRecipe.containsKey(type)) { throw new NotFoundException("Infrastructure not found for type: " + type); } environmentFactories.get(environment.getRecipe().getType()).create(environment); }

Target:
public void validate(Environment environment) throws NotFoundException, InfrastructureException, ValidationException { String type = environment.getRecipe().getType(); if (!infraByRecipe.containsKey(type)) { throw new NotFoundException("Infrastructure not found for type: " + type); } createInternalEnvironment(environment); }
Source:
public AbstractViewTest() { CorfuRuntime.overrideGetRouterFunction = this::getRouterFunction; final Duration holeFillTimeout = Duration.ofSeconds(5); runtime = CorfuRuntime.fromParameters(CorfuRuntimeParameters.builder() .nettyEventLoop(NETTY_EVENT_LOOP) .holeFillTimeout(holeFillTimeout) .build()); runtime.getParameters().setHoleFillRetry(0); }

Target:
public AbstractViewTest() { CorfuRuntime.overrideGetRouterFunction = this::getRouterFunction; runtime = CorfuRuntime.fromParameters(CorfuRuntimeParameters.builder() .nettyEventLoop(NETTY_EVENT_LOOP) .build()); runtime.getParameters().setHoleFillRetry(0); }
Source:
public void activate(OperatorContext context) { if (getFieldInfos() == null) { Field[] fields = pojoClass.getDeclaredFields(); List<JdbcFieldInfo> fieldInfos = Lists.newArrayList(); for (int i = 0; i < columnNames.size(); i++) { String columnName = columnNames.get(i); String pojoField = getMatchingField(fields, columnName); if (columnNullabilities.get(i) == ResultSetMetaData.columnNoNulls && (pojoField == null || pojoField.length() == 0)) { throw new RuntimeException("Data for a non-nullable field not found in POJO"); } else { if (pojoField != null && pojoField.length() != 0) { JdbcFieldInfo fi = new JdbcFieldInfo(columnName, pojoField, null, null); fieldInfos.add(fi); } else { columnDataTypes.remove(i); columnNames.remove(i); columnNullabilities.remove(i); i--; } } } setFieldInfos(fieldInfos); } for (FieldInfo fi : getFieldInfos()) { columnFieldGetters.add(new JdbcPOJOInputOperator.ActiveFieldInfo(fi)); } StringBuilder columns = new StringBuilder(); StringBuilder values = new StringBuilder(); for (int i = 0; i < columnNames.size(); i++) { columns.append(columnNames.get(i)); values.append("?"); if (i < columnNames.size() - 1) { columns.append(","); values.append(","); } } insertStatement = "INSERT INTO " + getTablename() + " (" + columns.toString() + ")" + " VALUES (" + values.toString() + ")"; LOG.debug("insert statement is {}", insertStatement); super.activate(context); }

Target:
public void activate(OperatorContext context) { if (getFieldInfos() == null) { Field[] fields = pojoClass.getDeclaredFields(); List<JdbcFieldInfo> fieldInfos = Lists.newArrayList(); for (int i = 0; i < columnNames.size(); i++) { String columnName = columnNames.get(i); String pojoField = getMatchingField(fields, columnName); if (columnNullabilities.get(i) == ResultSetMetaData.columnNoNulls && (pojoField == null || pojoField.length() == 0)) { throw new RuntimeException("Data for a non-nullable field: " + columnName + " not found in POJO"); } else { if (pojoField != null && pojoField.length() != 0) { JdbcFieldInfo fi = new JdbcFieldInfo(columnName, pojoField, null, null); fieldInfos.add(fi); } else { columnDataTypes.remove(i); columnNames.remove(i); columnNullabilities.remove(i); i--; } } } setFieldInfos(fieldInfos); } for (FieldInfo fi : getFieldInfos()) { columnFieldGetters.add(new JdbcPOJOInputOperator.ActiveFieldInfo(fi)); } StringBuilder columns = new StringBuilder(); StringBuilder values = new StringBuilder(); for (int i = 0; i < columnNames.size(); i++) { columns.append(columnNames.get(i)); values.append("?"); if (i < columnNames.size() - 1) { columns.append(","); values.append(","); } } insertStatement = "INSERT INTO " + getTablename() + " (" + columns.toString() + ")" + " VALUES (" + values.toString() + ")"; LOG.debug("insert statement is {}", insertStatement); super.activate(context); }
Source:
public HttpURLConnection connect(final URI uri, final String method, final byte[] entity, final Map<String, List<String>> headers) throws HeliosException { final Endpoint endpoint = endpointIterator.next(); final URI ipUri; try { ipUri = toIpUri(endpoint, uri); } catch (URISyntaxException e) { throw new HeliosException(e); } try { log.debug("connecting to {}", ipUri); if (accessTokenOpt.isPresent()) { return connectWithBearerToken(ipUri, method, entity, headers); } else if (clientCertificatePath.isPresent()) { return connectWithCertificateFile(ipUri, method, entity, headers); } else if (agentProxy.isPresent() && !identities.isEmpty()) { return connectWithIdentities(identities, ipUri, method, entity, headers); } else { return doConnect(ipUri, method, entity, headers); } } catch (ConnectException | SocketTimeoutException | UnknownHostException e) { log.debug(e.toString()); throw new HeliosException("Unable to connect to master: " + ipUri, e); } catch (IOException e) { throw new HeliosException("Unexpected error connecting to " + ipUri, e); } }

Target:
public HttpURLConnection connect(final URI uri, final String method, final byte[] entity, final Map<String, List<String>> headers) throws HeliosException { final Endpoint endpoint = endpointIterator.next(); final URI ipUri; try { ipUri = toIpUri(endpoint, uri); } catch (URISyntaxException e) { throw new HeliosException(e); } try { log.debug("connecting to {}", ipUri); if (accessTokenOpt.isPresent()) { final String token = accessTokenOpt.get().getTokenValue(); headers.put("Authorization", singletonList("Bearer " + token)); log.debug("Add Authorization header with bearer token"); } if (clientCertificatePath.isPresent()) { return connectWithCertificateFile(ipUri, method, entity, headers); } else if (agentProxy.isPresent() && !identities.isEmpty()) { return connectWithIdentities(identities, ipUri, method, entity, headers); } else { return doConnect(ipUri, method, entity, headers); } } catch (ConnectException | SocketTimeoutException | UnknownHostException e) { log.debug(e.toString()); throw new HeliosException("Unable to connect to master: " + ipUri, e); } catch (IOException e) { throw new HeliosException("Unexpected error connecting to " + ipUri, e); } }
Source:
private OffHeapChainMap(PageSource source, ChainStorageEngine<K> storageEngine) { this.chainStorage = storageEngine; EvictionListener<K, InternalChain> listener = callable -> { try { Map.Entry<K, InternalChain> entry = callable.call(); try { if (evictionListener != null) { Chain chain = null; if (fireEvents) { chain = entry.getValue().detach(); } evictionListener.onEviction(entry.getKey(), chain); } } finally { entry.getValue().close(); } } catch (Exception e) { throw new AssertionError(e); } }; this.heads = new EvictionListeningReadWriteLockedOffHeapClockCache<>(listener, source, chainStorage); }

Target:
private OffHeapChainMap(PageSource source, ChainStorageEngine<K> storageEngine) { this.chainStorage = storageEngine; EvictionListener<K, InternalChain> listener = callable -> { try { Map.Entry<K, InternalChain> entry = callable.call(); try { if (evictionListener != null) { evictionListener.onEviction(entry.getKey(), entry.getValue()); } } finally { entry.getValue().close(); } } catch (Exception e) { throw new AssertionError(e); } }; this.heads = new EvictionListeningReadWriteLockedOffHeapClockCache<>(listener, source, chainStorage); }
Source:
public void testAttributeSymlink() throws Exception { if (!canCreateSymLinks()) return; IProject project = getWorkspace().getRoot().getProject("Project"); IFile link = project.getFile("link"); ensureExistsInWorkspace(link, getRandomContents()); try { assertTrue("1.0", !link.getResourceAttributes().isSymbolicLink()); setSymlink(link, true); assertTrue("2.0", !link.getResourceAttributes().isSymbolicLink()); setSymlink(link, false); assertTrue("3.0", !link.getResourceAttributes().isSymbolicLink()); } catch (CoreException e1) { fail("4.0", e1); } ensureDoesNotExistInWorkspace(link); IFile target = project.getFile("target"); ensureExistsInFileSystem(target); createSymLink(project.getLocation().toFile(), "link", "target", false); ensureExistsInWorkspace(link, true); assertTrue("5.0", link.getResourceAttributes().isSymbolicLink()); try { setSymlink(link, false); assertTrue("3.0", link.getResourceAttributes().isSymbolicLink()); } catch (CoreException e1) { fail("4.0", e1); } String s = link.getLocation().toOSString(); link.getLocation().toFile().delete(); try { new File(s).createNewFile(); assertTrue("3.0", !link.getResourceAttributes().isSymbolicLink()); } catch (IOException e) { fail("4.99", e); } try { project.delete(true, getMonitor()); } catch (CoreException e) { fail("7.0", e); } }

Target:
public void testAttributeSymlink() { if (!canCreateSymLinks()) return; IProject project = getWorkspace().getRoot().getProject("Project"); IFile link = project.getFile("link"); ensureExistsInWorkspace(link, getRandomContents()); try { assertTrue("1.0", !link.getResourceAttributes().isSymbolicLink()); setSymlink(link, true); assertTrue("2.0", !link.getResourceAttributes().isSymbolicLink()); setSymlink(link, false); assertTrue("3.0", !link.getResourceAttributes().isSymbolicLink()); } catch (CoreException e1) { fail("4.0", e1); } ensureDoesNotExistInWorkspace(link); IFile target = project.getFile("target"); ensureExistsInFileSystem(target); createSymLink(project.getLocation().toFile(), "link", "target", false); ensureExistsInWorkspace(link, true); assertTrue("5.0", link.getResourceAttributes().isSymbolicLink()); try { setSymlink(link, false); assertTrue("3.0", link.getResourceAttributes().isSymbolicLink()); } catch (CoreException e1) { fail("4.0", e1); } String s = link.getLocation().toOSString(); link.getLocation().toFile().delete(); try { new File(s).createNewFile(); assertTrue("3.0", !link.getResourceAttributes().isSymbolicLink()); } catch (IOException e) { fail("4.99", e); } try { project.delete(true, getMonitor()); } catch (CoreException e) { fail("7.0", e); } }
Source:
private int getLength(Object o, int index) { if (o instanceof InstructionList) { Instruction instruction = ((InstructionList) o).get(index); int size; if(instruction instanceof ViaInstruction) size = 0; else size = instruction.getPoints().size(); return size; } if (o instanceof List) { return ((List<PathDetail>) o).get(index).getLength(); } throw new IllegalStateException("We can only handle PathDetails or InstructionList in PathSimplification"); }

Target:
private int getLength(Object o, int index) { if (o instanceof InstructionList) { Instruction instruction = ((InstructionList) o).get(index); return instruction.getLength(); } if (o instanceof List) { return ((List<PathDetail>) o).get(index).getLength(); } throw new IllegalStateException("We can only handle PathDetails or InstructionList in PathSimplification"); }
Source:
public PersistenceManagerImpl() { scheduler = ExpressionThreadPoolManager.getExpressionScheduledPool("persist"); }

Target:
public PersistenceManagerImpl() { }
Source:
protected List<ExecutorDetails> orderExecutors( TopologyDetails td, Collection<ExecutorDetails> unassignedExecutors) { Map<String, Component> componentMap = td.getComponents(); List<ExecutorDetails> execsScheduled = new LinkedList<>(); Map<String, Queue<ExecutorDetails>> compToExecsToSchedule = new HashMap<>(); for (Map.Entry<String, Component> componentEntry: componentMap.entrySet()) { Component component = componentEntry.getValue(); compToExecsToSchedule.put(component.getId(), new LinkedList<>()); for (ExecutorDetails exec : component.getExecs()) { if (unassignedExecutors.contains(exec)) { compToExecsToSchedule.get(component.getId()).add(exec); LOG.info("{} has unscheduled executor {}", component.getId(), exec); } } } List<Component> sortedComponents = topologicalSortComponents(componentMap); for (Component currComp: sortedComponents) { int numExecs = compToExecsToSchedule.get(currComp.getId()).size(); for (int i = 0; i < numExecs; i++) { execsScheduled.addAll(takeExecutors(currComp, numExecs - i, componentMap, compToExecsToSchedule)); } } LOG.info("The ordering result is {}", execsScheduled); return execsScheduled; }

Target:
protected List<ExecutorDetails> orderExecutors( TopologyDetails td, Collection<ExecutorDetails> unassignedExecutors) { Map<String, Component> componentMap = td.getComponents(); List<ExecutorDetails> execsScheduled = new LinkedList<>(); Map<String, Queue<ExecutorDetails>> compToExecsToSchedule = new HashMap<>(); for (Component component : componentMap.values()) { compToExecsToSchedule.put(component.getId(), new LinkedList<>()); for (ExecutorDetails exec : component.getExecs()) { if (unassignedExecutors.contains(exec)) { compToExecsToSchedule.get(component.getId()).add(exec); LOG.info("{} has unscheduled executor {}", component.getId(), exec); } } } List<Component> sortedComponents = topologicalSortComponents(componentMap); for (Component currComp: sortedComponents) { int numExecs = compToExecsToSchedule.get(currComp.getId()).size(); for (int i = 0; i < numExecs; i++) { execsScheduled.addAll(takeExecutors(currComp, componentMap, compToExecsToSchedule)); } } LOG.info("The ordering result is {}", execsScheduled); return execsScheduled; }
Source:
public void testSampleExtremeCoverageVariance(final List<SampleCoverageStats> sampleStats, final double min, final double max) throws IOException { final File samplesFile = createSampleStatsFile(sampleStats); final List<SampleCoverageStats> leftInSamples = sampleStats.stream() .filter(stats -> stats.variance >= min && stats.variance <= max) .collect(Collectors.toList()); final List<SampleCoverageStats> leftOutSamples = sampleStats.stream() .filter(stats -> stats.variance < min || stats.variance > max) .collect(Collectors.toList()); final File outputFile = createTempFile("output", ".tab"); final File rejectionFile = createTempFile("reject", ".tab"); runCommandLine(new String[] { "-" + StandardArgumentDefinitions.INPUT_SHORT_NAME, samplesFile.getPath(), "-" + StandardArgumentDefinitions.OUTPUT_SHORT_NAME, outputFile.getPath(), "-" + FilterSamples.MINIMUM_COVERAGE_VARIANCE_SHORT_NAME, String.valueOf(min), "-" + FilterSamples.MAXIMUM_COVERAGE_VARIANCE_SHORT_NAME, String.valueOf(max), "-" + FilterTargets.REJECT_OUTPUT_FILE_SHORT_NAME, rejectionFile.getPath(), }); checkLeftInTargets(leftInSamples, outputFile); checkRejectedTargets(leftOutSamples, rejectionFile, FilterSamples.SampleFilter.ExtremeCoverageVariance); }

Target:
public void testSampleExtremeCoverageVariance(final List<SampleCoverageStats> sampleStats, final double min, final double max) throws IOException { final File samplesFile = createSampleStatsFile(sampleStats); final List<SampleCoverageStats> leftInSamples = sampleStats.stream() .filter(stats -> stats.variance >= min && stats.variance <= max) .collect(Collectors.toList()); final List<SampleCoverageStats> leftOutSamples = sampleStats.stream() .filter(stats -> stats.variance < min || stats.variance > max) .collect(Collectors.toList()); final File outputFile = createTempFile("output", ".tab"); final File rejectionFile = createTempFile("reject", ".tab"); runCommandLine(new String[] { "-" + StandardArgumentDefinitions.INPUT_SHORT_NAME, samplesFile.getPath(), "-" + StandardArgumentDefinitions.OUTPUT_SHORT_NAME, outputFile.getPath(), "-" + FilterSamples.MINIMUM_COVERAGE_VARIANCE_SHORT_NAME, String.valueOf(min), "-" + FilterSamples.MAXIMUM_COVERAGE_VARIANCE_SHORT_NAME, String.valueOf(max), "-" + FilterSamples.REJECTION_FILE_SHORT_NAME, rejectionFile.getPath(), }); checkLeftInSamples(leftInSamples, outputFile); checkRejectedSamples(leftOutSamples, rejectionFile, FilterSamples.SampleFilter.ExtremeCoverageVariance); }
Source:
public void testMissingIndicesQuery() throws QueryStoreException { List<Document> documents = TestUtils.getQueryDocumentsDifferentDate(mapper, new Date(2014 - 1900, 4, 1).getTime()); documents.addAll(TestUtils.getQueryDocumentsDifferentDate(mapper, new Date(2014 - 1900, 4, 5).getTime())); queryStore.save(TestUtils.TEST_TABLE_NAME, documents); for (Document document : documents) { elasticsearchServer.getClient().admin().indices() .prepareRefresh(ElasticsearchUtils.getCurrentIndex(TestUtils.TEST_TABLE_NAME, document.getTimestamp())) .setForce(true).execute().actionGet(); } GetIndexResponse response = elasticsearchServer.getClient().admin().indices().getIndex(new GetIndexRequest()).actionGet(); assertEquals(3, response.getIndices().length); Query query = new Query(); query.setLimit(20); query.setTable(TestUtils.TEST_TABLE_NAME); BetweenFilter betweenFilter = new BetweenFilter(); betweenFilter.setField("_timestamp"); betweenFilter.setFrom(documents.get(0).getTimestamp()); betweenFilter.setTo(documents.get(documents.size() -1).getTimestamp()); betweenFilter.setTemporal(true); query.setFilters(Lists.<Filter>newArrayList(betweenFilter)); QueryResponse actualResponse = QueryResponse.class.cast(queryExecutor.execute(query)); assertEquals(18, actualResponse.getDocuments().size()); }

Target:
public void testMissingIndicesQuery() throws QueryStoreException { List<Document> documents = TestUtils.getQueryDocumentsDifferentDate(mapper, new Date(2014 - 1900, 4, 1).getTime()); documents.addAll(TestUtils.getQueryDocumentsDifferentDate(mapper, new Date(2014 - 1900, 4, 5).getTime())); queryStore.save(TestUtils.TEST_TABLE_NAME, documents); for (Document document : documents) { elasticsearchServer.getClient().admin().indices() .prepareRefresh(ElasticsearchUtils.getCurrentIndex(TestUtils.TEST_TABLE_NAME, document.getTimestamp())) .setForce(true).execute().actionGet(); } GetIndexResponse response = elasticsearchServer.getClient().admin().indices().getIndex(new GetIndexRequest()).actionGet(); assertEquals(3, response.getIndices().length); Query query = new Query(); query.setLimit(documents.size()); query.setTable(TestUtils.TEST_TABLE_NAME); BetweenFilter betweenFilter = new BetweenFilter(); betweenFilter.setField("_timestamp"); betweenFilter.setFrom(documents.get(0).getTimestamp()); betweenFilter.setTo(documents.get(documents.size() -1).getTimestamp()); betweenFilter.setTemporal(true); query.setFilters(Lists.<Filter>newArrayList(betweenFilter)); QueryResponse actualResponse = QueryResponse.class.cast(queryExecutor.execute(query)); assertEquals(documents.size(), actualResponse.getDocuments().size()); }