auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected Deployment createDeployment(ResourceLoader resourceLoader, CDI11Bootstrap bootstrap) { final Iterable<Metadata<Extension>> loadedExtensions = loadExtensions(WeldResourceLoader.getClassLoader(), bootstrap); final TypeDiscoveryConfiguration typeDiscoveryConfiguration = bootstrap.startExtensions(loadedExtensions); Deployment deployment=null; DiscoveryStrategy strategy = DiscoveryStrategyFactory.create(resourceLoader, bootstrap, typeDiscoveryConfiguration); Set<WeldBeanDeploymentArchive> discoveredArchives = strategy.performDiscovery(); String isolation = AccessController.doPrivileged(new GetSystemPropertyAction(ARCHIVE_ISOLATION_SYSTEM_PROPERTY)); if (isolation != null && Boolean.valueOf(isolation).equals(Boolean.FALSE)) { WeldBeanDeploymentArchive archive = WeldBeanDeploymentArchive.merge(bootstrap, discoveredArchives); deployment = new WeldDeployment(resourceLoader, bootstrap, Collections.singleton(archive), loadedExtensions); CommonLogger.LOG.archiveIsolationDisabled(); } else { deployment= new WeldDeployment(resourceLoader, bootstrap, discoveredArchives, loadedExtensions); CommonLogger.LOG.archiveIsolationEnabled(); } WeldSELogger.LOG.multipleIsolation(isolation != null && Boolean.valueOf(isolation)); if(strategy.getClassFileServices() != null) { deployment.getServices().add(ClassFileServices.class, strategy.getClassFileServices()); } return deployment; }

Target:
protected Deployment createDeployment(ResourceLoader resourceLoader, CDI11Bootstrap bootstrap) { final Iterable<Metadata<Extension>> loadedExtensions = loadExtensions(WeldResourceLoader.getClassLoader(), bootstrap); final TypeDiscoveryConfiguration typeDiscoveryConfiguration = bootstrap.startExtensions(loadedExtensions); Deployment deployment=null; DiscoveryStrategy strategy = DiscoveryStrategyFactory.create(resourceLoader, bootstrap, typeDiscoveryConfiguration); Set<WeldBeanDeploymentArchive> discoveredArchives = strategy.performDiscovery(); String isolation = AccessController.doPrivileged(new GetSystemPropertyAction(ARCHIVE_ISOLATION_SYSTEM_PROPERTY)); if (isolation != null && Boolean.valueOf(isolation).equals(Boolean.FALSE)) { WeldBeanDeploymentArchive archive = WeldBeanDeploymentArchive.merge(bootstrap, discoveredArchives); deployment = new WeldDeployment(resourceLoader, bootstrap, Collections.singleton(archive), loadedExtensions); CommonLogger.LOG.archiveIsolationDisabled(); } else { deployment= new WeldDeployment(resourceLoader, bootstrap, discoveredArchives, loadedExtensions); CommonLogger.LOG.archiveIsolationEnabled(); } if(strategy.getClassFileServices() != null) { deployment.getServices().add(ClassFileServices.class, strategy.getClassFileServices()); } return deployment; }
Source:
public List<GlusterGeoRepSession> getAllSessions() { return getCallsHandler().executeReadList("GetAllGlusterGeoRepSessions", georepSessionRowMapper, getCustomMapSqlParameterSource().addValue("user_id", null).addValue("is_filtered", false)); }

Target:
public List<GlusterGeoRepSession> getAllSessions() { return getCallsHandler().executeReadList("GetAllGlusterGeoRepSessions", georepSessionRowMapper, getCustomMapSqlParameterSource()); }
Source:
public boolean registerIfNew(String name, AsyncHttpClient ahc) { AsyncHttpClient value = asyncHttpClientMap.putIfAbsent(name, ahc); if (value == null) return true; else return false; }

Target:
public boolean registerIfNew(String name, AsyncHttpClient ahc) { return asyncHttpClientMap.putIfAbsent(name, ahc)==null; }
Source:
private void updatePaint() { Bitmap bitmap = getBitmap(); if (mLastBitmap == null || mLastBitmap.get() != bitmap) { mLastBitmap = new WeakReference<Bitmap>(bitmap); mPaint.setShader(new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)); mIsShaderTransformDirty = true; } if (mIsShaderTransformDirty) { if (!mTransform.isIdentity()) { mPaint.getShader().setLocalMatrix(mTransform); } mIsShaderTransformDirty = false; } }

Target:
private void updatePaint() { Bitmap bitmap = getBitmap(); if (mLastBitmap == null || mLastBitmap.get() != bitmap) { mLastBitmap = new WeakReference<Bitmap>(bitmap); mPaint.setShader(new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)); mIsShaderTransformDirty = true; } if (mIsShaderTransformDirty) { if (mTransform.isIdentity()) { mPaint.getShader().setLocalMatrix(null); } else { mPaint.getShader().setLocalMatrix(mTransform); } mIsShaderTransformDirty = false; } }
Source:
public void theGetPeriodicMeterReadsRequestIsReceived() throws Throwable { this.correlationUidPattern = Pattern.compile(this.organisationId.getOrganisationId() + "\\|\\|\\|\\S{17}\\|\\|\\|\\S{17}"); this.testCase = this.wsdlProjectFactory.createWsdlTestCase(SOAP_PROJECT_XML, TEST_SUITE_XML, TEST_CASE_XML); final TestCaseResult runTestStepByName = this.testCaseRunner.runWsdlTestCase(this.testCase, this.deviceId.getDeviceId(), this.organisationId.getOrganisationId(), this.correlationUid, TEST_CASE_NAME_REQUEST); final TestStepResult runTestStepByNameResult = runTestStepByName.getRunTestStepByName(); final WsdlTestCaseRunner wsdlTestCaseRunner = runTestStepByName.getResults(); Assert.assertEquals(TestStepStatus.OK, runTestStepByNameResult.getStatus()); for (final TestStepResult tcr : wsdlTestCaseRunner.getResults()) { this.response = ((MessageExchange) tcr).getResponseContent(); this.correlationUidMatcher = this.correlationUidPattern.matcher(this.response); } this.correlationUidMatcher.find(); this.correlationUid = this.correlationUidMatcher.group(); }

Target:
public void theGetPeriodicMeterReadsRequestIsReceived() throws Throwable { this.correlationUidPattern = Pattern.compile(this.organisationId.getOrganisationId() + "\\|\\|\\|\\S{17}\\|\\|\\|\\S{17}"); this.testCase = this.wsdlProjectFactory.createWsdlTestCase(SOAP_PROJECT_XML, TEST_SUITE_XML, TEST_CASE_XML_225); PROPERTIES_MAP.put("DeviceIdentificationE", this.deviceId.getDeviceId()); PROPERTIES_MAP.put("OrganisationIdentification", this.organisationId.getOrganisationId()); final TestCaseResult runTestStepByName = this.testCaseRunner.runWsdlTestCase(this.testCase, PROPERTIES_MAP, TEST_CASE_NAME_REQUEST); final TestStepResult runTestStepByNameResult = runTestStepByName.getRunTestStepByName(); final WsdlTestCaseRunner wsdlTestCaseRunner = runTestStepByName.getResults(); assertEquals(TestStepStatus.OK, runTestStepByNameResult.getStatus()); for (final TestStepResult tcr : wsdlTestCaseRunner.getResults()) { this.response = ((MessageExchange) tcr).getResponseContent(); this.correlationUidMatcher = this.correlationUidPattern.matcher(this.response); } this.correlationUidMatcher.find(); this.correlationUid = this.correlationUidMatcher.group(); }
Source:
public @Nonnull String inspectRequiredField(@Nonnull EnvVars launchEnv, @Nonnull String objectId, @Nonnull String fieldPath) throws IOException, InterruptedException { final LaunchResult result = launch(launchEnv, true, "inspect", "-f", String.format("{{%s}}", fieldPath), objectId); String fieldValue = result.getStatus() == 0 ? hudson.Util.fixEmpty(result.getOut()) : null; if (fieldValue == null) { throw new IOException("Cannot retrieve " + fieldPath + " for id=" +objectId); } return fieldValue; }

Target:
public @Nonnull String inspectRequiredField(@Nonnull EnvVars launchEnv, @Nonnull String objectId, @Nonnull String fieldPath) throws IOException, InterruptedException { final String fieldValue = inspect(launchEnv, objectId, fieldPath); if (fieldValue == null) { throw new IOException("Cannot retrieve " + fieldPath + " from 'docker inspect" + objectId + "'"); } return fieldValue; }
Source:
public static JoinOperatorInfo createJoinOperatorInfo(JoinType joinType, long[] logHistogramCounters) { long[] logHistogramProbes = new long[HISTOGRAM_SIZE]; long[] logHistogramOutput = new long[HISTOGRAM_SIZE]; for (int i = 0; i < HISTOGRAM_SIZE; i++) { logHistogramProbes[i] = logHistogramCounters[2 * i]; logHistogramOutput[i] = logHistogramCounters[2 * i + 1]; } return new JoinOperatorInfo(joinType, logHistogramProbes, logHistogramOutput); }

Target:
public static JoinOperatorInfo createJoinOperatorInfo(JoinType joinType, long[] logHistogramCounters) { long[] logHistogramProbes = new long[HISTOGRAM_BUCKETS]; long[] logHistogramOutput = new long[HISTOGRAM_BUCKETS]; for (int i = 0; i < HISTOGRAM_BUCKETS; i++) { logHistogramProbes[i] = logHistogramCounters[2 * i]; logHistogramOutput[i] = logHistogramCounters[2 * i + 1]; } return new JoinOperatorInfo(joinType, logHistogramProbes, logHistogramOutput); }
Source:
public void delete(final String evalId, @Nullable final EventHandler<AvroElasticMemoryMessage> callback) { final Set<String> dataTypeSet = partitionManager.getDataTypes(evalId); for (final String dataType : dataTypeSet) { final Set<LongRange> rangeSet = partitionManager.getRangeSet(evalId, dataType); if (!rangeSet.isEmpty()) { if (callback != null) { LOG.log(Level.INFO, "{0}", rangeSet.size()); final AvroElasticMemoryMessage msg = AvroElasticMemoryMessage.newBuilder() .setType(Type.ResultMsg) .setResultMsg(ResultMsg.newBuilder().setResult(Result.FAILURE).build()) .setSrcId(evalId) .setDestId("") .build(); callback.onNext(msg); } return; } } if (callback == null) { deleteExecutor.get().execute(evalId, new EventHandler<AvroElasticMemoryMessage>() { @Override public void onNext(final AvroElasticMemoryMessage msg) { } }); } else { deleteExecutor.get().execute(evalId, callback); } }

Target:
public void delete(final String evalId, @Nullable final EventHandler<AvroElasticMemoryMessage> callback) { final Set<String> dataTypeSet = partitionManager.getDataTypes(evalId); for (final String dataType : dataTypeSet) { final Set<LongRange> rangeSet = partitionManager.getRangeSet(evalId, dataType); if (!rangeSet.isEmpty()) { if (callback != null) { final AvroElasticMemoryMessage msg = AvroElasticMemoryMessage.newBuilder() .setType(Type.ResultMsg) .setResultMsg(ResultMsg.newBuilder().setResult(Result.FAILURE).build()) .setSrcId(evalId) .setDestId("") .build(); callback.onNext(msg); } return; } } if (callback == null) { deleteExecutor.get().execute(evalId, new EventHandler<AvroElasticMemoryMessage>() { @Override public void onNext(final AvroElasticMemoryMessage msg) { } }); } else { deleteExecutor.get().execute(evalId, callback); } }
Source:
public void deleteColumn(int columnIndex) { checkSimulation(); final GridColumn<?> toDelete = getColumns().get(columnIndex); deleteColumn(toDelete); simulation.removeFactMappingByIndex(columnIndex); synchronizeFactMappingsWidths(); }

Target:
public void deleteColumn(int columnIndex) { checkSimulation(); final GridColumn<?> toDelete = getColumns().get(columnIndex); deleteColumn(toDelete); simulation.removeFactMappingByIndex(columnIndex); }
Source:
private void addRootProjection(SelectionSet selectionSet) { List<Selection> selections = selectionSet.getSelections(); Selection rootSelection = selections.get(0); if (!(rootSelection instanceof Field)) { throw new InvalidEntityBodyException("Entity selection must be a graphQL field."); } String entityName = ((Field) rootSelection).getName(); if (SCHEMA.equals(entityName) || TYPE.equals(entityName)) { return; } Class<?> entityType = entityDictionary.getEntityClass(entityName); if (entityType == null) { throw new InvalidEntityBodyException(String.format("Unknown entity {%s}.", entityName)); } rootLocation = rootSelection.getSourceLocation(); Field fields = (Field) rootSelection; selections.stream().skip(1).forEach(selection -> { if (!(selection instanceof Field)) { throw new InvalidEntityBodyException("Entity selection must be a graphQL field."); } if (!entityName.equals(((Field) selection).getName())) { throw new InvalidEntityBodyException("Can't select multiple entities in graphQL QUERY operation."); } fields.getSelectionSet().getSelections().addAll(((Field) selection).getSelectionSet().getSelections()); }); rootProjections.add(createProjection(entityType, fields)); }

Target:
private void addRootProjection(SelectionSet selectionSet) { List<Selection> selections = selectionSet.getSelections(); Selection rootSelection = selections.get(0); if (!(rootSelection instanceof Field)) { throw new InvalidEntityBodyException("Entity selection must be a graphQL field."); } String entityName = ((Field) rootSelection).getName(); if (SCHEMA.equals(entityName) || TYPE.equals(entityName)) { return; } Class<?> entityType = entityDictionary.getEntityClass(entityName); if (entityType == null) { throw new InvalidEntityBodyException(String.format("Unknown entity {%s}.", entityName)); } Field fields = (Field) rootSelection; selections.stream().skip(1).forEach(selection -> { if (!(selection instanceof Field)) { throw new InvalidEntityBodyException("Entity selection must be a graphQL field."); } if (!entityName.equals(((Field) selection).getName())) { throw new InvalidEntityBodyException("Can't select multiple entities in graphQL QUERY operation."); } fields.getSelectionSet().getSelections().addAll(((Field) selection).getSelectionSet().getSelections()); }); rootProjections.add(createProjection(entityType, fields)); }
Source:
private MySQLBasicDataSource(String host, int port, String dbName, String user, String password, int numConnections) { super(); String url = "jdbc:mysql://" + (host + ":" + port + "/" + dbName+"?useUnicode=yes&characterEncoding=UTF-8"); setDriverClassName("com.mysql.jdbc.Driver"); setUsername(user); setPassword(password); setUrl(url); setMaxActive(numConnections); setValidationQuery(" select 1"); setTestOnBorrow(true); if(monitorThread == null) { monitorThread = new MonitorThread(this); monitorThread.start(); } }

Target:
private MySQLBasicDataSource(String host, int port, String dbName, String user, String password, int numConnections) { super(); String url = "jdbc:mysql://" + (host + ":" + port + "/" + dbName); addConnectionProperty("useUnicode","yes"); addConnectionProperty("characterEncoding","UTF-8"); setDriverClassName("com.mysql.jdbc.Driver"); setUsername(user); setPassword(password); setUrl(url); setMaxActive(numConnections); setValidationQuery(" select 1"); setTestOnBorrow(true); if(monitorThread == null) { monitorThread = new MonitorThread(this); monitorThread.start(); } }
Source:
public void whenReadEventsThenNakadiException() { final ImmutableList<RuntimeException> exceptions = ImmutableList.of(new NoOffsetForPartitionException( new TopicPartition("", 0)), new KafkaException()); int numberOfNakadiExceptions = 0; for (final Exception exception : exceptions) { final KafkaConsumer<String, String> kafkaConsumerMock = mock(KafkaConsumer.class); when(kafkaConsumerMock.poll(POLL_TIMEOUT)).thenThrow(exception); final KafkaFactory kafkaFactoryMock = createKafkaFactoryMock(kafkaConsumerMock); try { final NakadiKafkaConsumer consumer = new NakadiKafkaConsumer(kafkaFactoryMock, TOPIC, ImmutableMap.of(), POLL_TIMEOUT); consumer.readEvent(); fail("The NakadiException should be thrown"); } catch (Exception e) { numberOfNakadiExceptions++; } } assertThat("We should get a NakadiException for every call", numberOfNakadiExceptions, equalTo(exceptions.size())); }

Target:
public void whenReadEventsThenNakadiException() { final ImmutableList<RuntimeException> exceptions = ImmutableList.of(new NoOffsetForPartitionException( new TopicPartition("", 0)), new KafkaException()); int numberOfNakadiExceptions = 0; for (final Exception exception : exceptions) { final KafkaConsumer<String, String> kafkaConsumerMock = mock(KafkaConsumer.class); when(kafkaConsumerMock.poll(POLL_TIMEOUT)).thenThrow(exception); final KafkaFactory kafkaFactoryMock = createKafkaFactoryMock(kafkaConsumerMock); try { final NakadiKafkaConsumer consumer = new NakadiKafkaConsumer(kafkaFactoryMock, TOPIC, ImmutableMap.of(), POLL_TIMEOUT); consumer.readEvent(); fail("An Exception was expected to be be thrown"); } catch (Exception e) { numberOfNakadiExceptions++; } } assertThat("We should get a NakadiException for every call", numberOfNakadiExceptions, equalTo(exceptions.size())); }
Source:
private void scheduleCheckStatus() { scheduledStatusCheckInProgress = true; Scheduler.get().scheduleFixedDelay( new Scheduler.RepeatingCommand() { @Override public boolean execute() { if (retryCount > MAX_RETRY_COUNTS || reportsWebappDeployed) { scheduledStatusCheckInProgress = false; return false; } retryCount++; checkReportsWebAppStatus(); return true; } }, RETRY_INTERVAL); }

Target:
private void scheduleCheckStatus() { if (scheduledStatusCheckInProgress || retryCount > MAX_RETRY_COUNTS || reportsWebappDeployed) { return; } scheduledStatusCheckInProgress = true; Scheduler.get().scheduleFixedDelay( new Scheduler.RepeatingCommand() { @Override public boolean execute() { if (retryCount > MAX_RETRY_COUNTS || reportsWebappDeployed) { scheduledStatusCheckInProgress = false; return false; } retryCount++; checkReportsWebAppStatus(); return true; } }, RETRY_INTERVAL); }
Source:
public static void parseTimePeriod(Map<Integer, Integer> countOfAreaCodesForYear, JSONObject response) { try { JSONArray data = response.getJSONArray(DATA_KEY); for (int i = 0; i < data.length(); i++) { JSONObject o = (JSONObject) data.get(i); Integer year = getTimeperiodYear(o); if (countOfAreaCodesForYear.containsKey(year)) { Integer count = countOfAreaCodesForYear.get(year); count++; countOfAreaCodesForYear.put(year, count); } else { countOfAreaCodesForYear.put(year, 1); } } } catch (JSONException e) { LOG.error("Error parsing time period selectors for indicator: " + e.getMessage(), e); } }

Target:
public static void parseTimePeriod(Map<Integer, Integer> countOfAreaCodesForYear, JSONObject response) { try { JSONArray data = response.getJSONArray(DATA_KEY); for (int i = 0; i < data.length(); i++) { JSONObject o = (JSONObject) data.get(i); Integer year = o.getInt(TIME_PERIOD_START_KEY); countOfAreaCodesForYear.merge(year, 1, Integer::sum); } } catch (JSONException e) { LOG.error("Error parsing time period selectors for indicator: " + e.getMessage(), e); } }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SettingsFragment.setToChosenLanguage(this); PreferenceManager.setDefaultValues(this, R.xml.preferences, true); ScreenValueHandler.updateScreenWidthAndHeight(this); boolean hasUserAgreedToPrivacyPolicy = PreferenceManager.getDefaultSharedPreferences(this) .getBoolean(AGREED_TO_PRIVACY_POLICY_PREFERENCE_KEY, false); boolean hasUserUpdatedPocketCode = hasUserUpdatedPocketCode(); if (hasUserAgreedToPrivacyPolicy && !hasUserUpdatedPocketCode) { loadContent(); } else { setContentView(R.layout.privacy_policy_view); } }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SettingsFragment.setToChosenLanguage(this); PreferenceManager.setDefaultValues(this, R.xml.preferences, true); ScreenValueHandler.updateScreenWidthAndHeight(this); int oldPrivacyPolicyHash = PreferenceManager.getDefaultSharedPreferences(this) .getInt(AGREED_TO_PRIVACY_POLICY_VERSION, 0); int currentPrivacyPolicyHash = getResources().getString(R.string.dialog_privacy_policy_text) .hashCode(); if (oldPrivacyPolicyHash == currentPrivacyPolicyHash) { loadContent(); } else { setContentView(R.layout.privacy_policy_view); } }
Source:
public void zoomIn() { if (!zoomOutEnabled) { zoomOutEnabled = true; } double maxRange = layoutPanel.getFirstChild().getPlotRepresentation().getMaxRange(); for (PlotContainer pc : layoutPanel.getAllChildren()) { SimplePlot plot = pc.getPlotRepresentation().getSimplePlot(); Zoom zoom = Zoom.create().setAmount(1.1); plot.zoom(zoom); pc.getPlotRepresentation().calculateScrollWidth(); } PlotRepresentation plotRepresentation = layoutPanel.getFirstChild().getPlotRepresentation(); double percent; double minVisible = plotRepresentation.getSimplePlot().getAxes().getX().getMinimumValue(); double maxVisible = plotRepresentation.getSimplePlot().getAxes().getX().getMaximumValue(); percent = minVisible / (maxRange - maxVisible + minVisible); plotRepresentation.panToPercent(percent); }

Target:
public void zoomIn() { zoom(false); }
Source:
protected void handleMissingToken( ServletRequest request, ServletResponse response, FilterChain chain) throws IOException { sendError(response, 401, "Authorization token is missed"); }

Target:
protected void handleMissingToken( ServletRequest request, ServletResponse response, FilterChain chain) throws IOException { sendError(response, 401, "Authorization token is missing"); }
Source:
public Double arrayZero(String sampleName, Integer n ){ double[] sample=null; Integer i=null; try{ Preconditions.checkNotNull(sampleName, "sampleName"); Preconditions.checkNotNull(n, "n"); sample = (double[]) m_context.get("__"+sampleName); if(sample==null) throw new RuntimeException("not in jexl context: __"+sampleName); i = (Integer) m_context.get("__i"); if(i==null) throw new RuntimeException("not in jexl context: __i"); if(i-n < 0) return Double.valueOf(0); return sample[i-n]; } catch (Exception ex){ LOG.error("problem retrieving prior sample "+sampleName+" (i - n) ("+i+"-"+n+")",ex); } return Double.NaN; }

Target:
public Double arrayZero(String sampleName, Integer n ){ double[] sample=null; Integer i=null; try{ Preconditions.checkNotNull(sampleName, "sampleName"); Preconditions.checkNotNull(n, "n"); sample = (double[]) m_context.get("__"+sampleName); if(sample==null) { LOG.warn("fn:arrayZero attribute not in jexl context: __"+sampleName); return Double.NaN; } i = (Integer) m_context.get("__i"); Preconditions.checkNotNull(i, "sample index __i"); if(i-n < 0) return Double.valueOf(0); return sample[i-n]; } catch (Exception ex){ LOG.error("fn:arrayZero problem retrieving prior attribute sample "+sampleName+" (i - n) ("+i+"-"+n+")",ex); } return Double.NaN; }
Source:
private static void copyAssetFileIfNeeded(RealmConfiguration configuration) { if (configuration.hasAssetFile()) { File realmFile = new File(configuration.getRealmDirectory(), configuration.getRealmFileName()); copyFileIfNeeded(configuration.getAssetFilePath(), realmFile); } String syncServerCertificateAssetName = ObjectServerFacade.getFacade(configuration.isSyncConfiguration()).getSyncServerCertificateAssetName(configuration); if (!TextUtils.isEmpty(syncServerCertificateAssetName)) { String syncServerCertificateFilePath = ObjectServerFacade.getFacade(configuration.isSyncConfiguration()).getSyncServerCertificateFilePath(configuration); File certificateFile = new File(syncServerCertificateFilePath); copyFileIfNeeded(syncServerCertificateAssetName, certificateFile); } }

Target:
private static void copyAssetFileIfNeeded(RealmConfiguration configuration) { if (configuration.hasAssetFile()) { File realmFile = new File(configuration.getRealmDirectory(), configuration.getRealmFileName()); copyFileIfNeeded(configuration.getAssetFilePath(), realmFile); } String syncServerCertificateAssetName = ObjectServerFacade.getFacade(configuration.isSyncConfiguration()).getSyncServerCertificateAssetName(configuration); if (!Util.isEmptyString(syncServerCertificateAssetName)) { String syncServerCertificateFilePath = ObjectServerFacade.getFacade(configuration.isSyncConfiguration()).getSyncServerCertificateFilePath(configuration); File certificateFile = new File(syncServerCertificateFilePath); copyFileIfNeeded(syncServerCertificateAssetName, certificateFile); } }
Source:
protected void handleDelete(URL requestUrl, long gracePeriodSeconds, DeletionPropagation propagationPolicy, boolean cascading) throws ExecutionException, InterruptedException, KubernetesClientException, IOException { RequestBody requestBody = null; DeleteOptions deleteOptions = new DeleteOptions(); if (gracePeriodSeconds >= 0) { deleteOptions.setGracePeriodSeconds(gracePeriodSeconds); } if (propagationPolicy != null) { if (Arrays.stream(DeletionPropagation.values()).noneMatch(deletionPropagation -> deletionPropagation.name().equals(propagationPolicy))) { logger.warn("Unknown DeletionPropagation policy used for deletion: {}", propagationPolicy); } deleteOptions.setPropagationPolicy(propagationPolicy.toString()); } else { deleteOptions.setOrphanDependents(!cascading); } requestBody = RequestBody.create(JSON, JSON_MAPPER.writeValueAsString(deleteOptions)); Request.Builder requestBuilder = new Request.Builder().delete(requestBody).url(requestUrl); handleResponse(requestBuilder, null, Collections.<String, String>emptyMap()); }

Target:
protected void handleDelete(URL requestUrl, long gracePeriodSeconds, DeletionPropagation propagationPolicy, boolean cascading) throws ExecutionException, InterruptedException, IOException { RequestBody requestBody = null; DeleteOptions deleteOptions = new DeleteOptions(); if (gracePeriodSeconds >= 0) { deleteOptions.setGracePeriodSeconds(gracePeriodSeconds); } if (propagationPolicy != null) { deleteOptions.setPropagationPolicy(propagationPolicy.toString()); } else { deleteOptions.setOrphanDependents(!cascading); } requestBody = RequestBody.create(JSON, JSON_MAPPER.writeValueAsString(deleteOptions)); Request.Builder requestBuilder = new Request.Builder().delete(requestBody).url(requestUrl); handleResponse(requestBuilder, null, Collections.<String, String>emptyMap()); }
Source:
private void doGetNextBatch() { if (splitsProduced >= totalSplits) { switch (atSplitDepletion) { case FAIL: nextBatchFuture.setException(new IllegalStateException("Mock failure")); break; case FINISH: nextBatchFuture.set(ImmutableList.of()); break; case DO_NOTHING: break; default: throw new UnsupportedOperationException(); } } int splits = Math.min(Math.min(batchSize, nextBatchMaxSize), totalSplits - splitsProduced); if (splits != 0) { splitsProduced += splits; nextBatchFuture.set(Collections.nCopies(splits, SPLIT)); } }

Target:
private void doGetNextBatch() { checkState(splitsProduced <= totalSplits); if (splitsProduced == totalSplits) { switch (atSplitDepletion) { case FAIL: nextBatchFuture.setException(new IllegalStateException("Mock failure")); break; case FINISH: nextBatchFuture.set(ImmutableList.of()); break; case DO_NOTHING: break; default: throw new UnsupportedOperationException(); } } int splits = Math.min(Math.min(batchSize, nextBatchMaxSize), totalSplits - splitsProduced); if (splits != 0) { splitsProduced += splits; nextBatchFuture.set(Collections.nCopies(splits, SPLIT)); } }
Source:
public void deserialize(String name, String value, boolean isSecure, String encryptedValue) throws InvalidCipherTextException { setName(name); setIsSecure(isSecure); if (isSecure) { if (isNotBlank(value) && isNotBlank(encryptedValue)) { System.out.println("lo = "); addError("value", "You may only specify `value` or `encrypted_value`, not both!"); addError("encryptedValue", "You may only specify `value` or `encrypted_value`, not both!"); } if (isNotBlank(value)) { setEncryptedValue(new EncryptedVariableValueConfig(new GoCipher().encrypt(value))); } if (isNotBlank(encryptedValue)) { setEncryptedValue(new EncryptedVariableValueConfig(encryptedValue)); } } else { setValue(new VariableValueConfig(value)); } }

Target:
public void deserialize(String name, String value, boolean isSecure, String encryptedValue) throws InvalidCipherTextException { setName(name); setIsSecure(isSecure); if (isSecure) { if (isNotBlank(value) && isNotBlank(encryptedValue)) { addError("value", "You may only specify `value` or `encrypted_value`, not both!"); addError("encryptedValue", "You may only specify `value` or `encrypted_value`, not both!"); } if (isNotBlank(value)) { setEncryptedValue(new EncryptedVariableValueConfig(new GoCipher().encrypt(value))); } if (isNotBlank(encryptedValue)) { setEncryptedValue(new EncryptedVariableValueConfig(encryptedValue)); } } else { setValue(new VariableValueConfig(value)); } }
Source:
public DataCenterInfoResponseHandler(DateCodecFactory dateCodecFactory) { super(dateCodecFactory); }

Target:
DataCenterInfoResponseHandler(DateCodecFactory dateCodecFactory) { super(dateCodecFactory); }
Source:
public void testOpenJavaEditor() throws Exception { ICompilationUnit unit= createTestCU(); EditorUtility.openInEditor(unit); Set set= new HashSet(); set.addAll(Arrays.asList(inactiveBundles)); checkNotLoaded(set); }

Target:
public void testOpenJavaEditor() throws Exception { ICompilationUnit unit= createTestCU(); EditorUtility.openInEditor(unit); Set<String> set= new HashSet<>(Arrays.asList(inactiveTestBundles)); checkNotLoaded(set); }
Source:
public void logPendingDeletion(String classTag, String reason) { String logMessage = String.format( "Wiping form record with id %1$s and submission ordering number %2$s " + "in class %3$s because %4$s", getInstanceID(), getSubmissionOrderingNumber(), classTag, reason); Logger.log(AndroidLogger.TYPE_FORM_DELETION, logMessage); }

Target:
public void logPendingDeletion(String classTag, String reason) { String logMessage = String.format( "Wiping form record with id %s and submission ordering number %s " + "in class %s because %s", getInstanceID(), getSubmissionOrderingNumber(), classTag, reason); Logger.log(AndroidLogger.TYPE_FORM_DELETION, logMessage); }
Source:
public static void main(String[] args) { final String key = "your key"; final String secret = "your secret"; Token token = new Token("", ""); OAuthService service = new ServiceBuilder().apiKey(key).apiSecret(secret).provider(ECHOApi.class).build(); System.out.println("Now we're going to access a protected resource..."); OAuthRequest request = new OAuthRequest(Verb.POST, PROTECTED_RESOURCE_URL); request.addBodyParameter("content", "your valid activity streams xml"); service.signRequest(token, request); Response response = request.send(); System.out.println(); System.out.println(response.getCode()); System.out.println(response.getBody()); System.out.println(); System.out.println("Thats it man! Go and build something awesome with Scribe! :)"); }

Target:
public static void main(String[] args) { final String key = "your key"; final String secret = "your secret"; Token token = new Token("", ""); OAuthService service = new ServiceBuilder().apiKey(key).apiSecret(secret).provider(EchoApi.class).build(); System.out.println("Now we're going to access a protected resource..."); OAuthRequest request = new OAuthRequest(Verb.POST, PROTECTED_RESOURCE_URL); request.addBodyParameter("content", "your valid activity streams xml"); service.signRequest(token, request); Response response = request.send(); System.out.println(); System.out.println(response.getCode()); System.out.println(response.getBody()); System.out.println(); System.out.println("Thats it man! Go and build something awesome with Scribe! :)"); }
Source:
protected long getClosestDiskSizeInGB(long sizeInBytes) { if (sizeInBytes < 0) { throw new CloudRuntimeException("Disk size should be greater than 0 bytes, received: " + sizeInBytes + " bytes"); } long div = sizeInBytes / GB_UNIT_BYTES; long rest = sizeInBytes % GB_UNIT_BYTES; return rest == 0L ? div : div + 1; }

Target:
protected long getClosestDiskSizeInGB(long sizeInBytes) { if (sizeInBytes < 0) { throw new CloudRuntimeException("Disk size should be greater than 0 bytes, received: " + sizeInBytes + " bytes"); } return (long) Math.ceil(1.0 * sizeInBytes / GB_UNIT_BYTES); }
Source:
public Link getLink(ObjectNode linkNode, String location, ParseResult result) { if (linkNode == null) { return null; } Link link = new Link(); JsonNode ref = linkNode.get("$ref"); if (ref != null) { if (ref.getNodeType().equals(JsonNodeType.STRING)) { } else { result.invalidType(location, "$ref", "string", linkNode); return null; } } String value = getString("operationRef", linkNode, false, location, result); link.setOperationRef(value); value = getString("operationId", linkNode, false, location, result); link.setOperationId(value); ObjectNode parametersObject = getObject("parameters",linkNode,false,location,result); if (parametersObject!= null) { link.setParameters(getLinkParameters(parametersObject, location, result)); } ObjectNode headerObject = getObject("headers",linkNode,false,location,result); if (headerObject!= null) { link.setHeaders(getHeaders(headerObject, location, result)); } ObjectNode serverObject = getObject("server",linkNode,false,location,result); if (serverObject!= null) { link.setServer(getServer(serverObject, location, result)); } value = getString("description", linkNode, false, location, result); link.setDescription(value); link.setExtensions(new LinkedHashMap<>()); Set<String> keys = getKeys(linkNode); for (String key : keys) { if (key.startsWith("x-")) { link.getExtensions().put(key, Json.mapper().convertValue(linkNode.get(key), Object.class)); } } return link; }

Target:
public Link getLink(ObjectNode linkNode, String location, ParseResult result) { if (linkNode == null) { return null; } Link link = new Link(); JsonNode ref = linkNode.get("$ref"); if (ref != null) { if (ref.getNodeType().equals(JsonNodeType.STRING)) { } else { result.invalidType(location, "$ref", "string", linkNode); return null; } } String value = getString("operationRef", linkNode, false, location, result); if(StringUtils.isNotBlank(value)){ link.setOperationRef(value); } value = getString("operationId", linkNode, false, location, result); if(StringUtils.isNotBlank(value)){ link.setOperationId(value); } ObjectNode parametersObject = getObject("parameters",linkNode,false,location,result); if (parametersObject!= null) { link.setParameters(getLinkParameters(parametersObject, location, result)); } ObjectNode headerObject = getObject("headers",linkNode,false,location,result); if (headerObject!= null) { link.setHeaders(getHeaders(headerObject, location, result)); } ObjectNode serverObject = getObject("server",linkNode,false,location,result); if (serverObject!= null) { link.setServer(getServer(serverObject, location, result)); } value = getString("description", linkNode, false, location, result); if(StringUtils.isNotBlank(value)){ link.setDescription(value); } Map <String,Object> extensions = getExtensions(linkNode,location,result); if(extensions != null && extensions.size() > 0) { link.setExtensions(extensions); } return link; }
Source:
public HttpResponse doUpdateResult(@QueryParameter String election) throws IOException { if (!isOpen(election)){ countVotes(election); applySingleTransferableVote( election ); } return new HttpRedirect("/election/results"); }

Target:
public HttpResponse doUpdateResult(@QueryParameter String election) throws IOException { if (!isOpen(election) && isAdmin()){ countVotes(election); applySingleTransferableVote( election ); } return new HttpRedirect("/election/results"); }
Source:
public void updateFeedbackQuestion(FeedbackQuestionAttributes newAttributes, boolean hasResponseRateUpdate) throws InvalidParametersException, EntityDoesNotExistException { FeedbackQuestionAttributes oldQuestion = null; if (newAttributes.getId() == null) { oldQuestion = fqDb.getFeedbackQuestion(newAttributes.feedbackSessionName, newAttributes.courseId, newAttributes.questionNumber); } else { oldQuestion = fqDb.getFeedbackQuestion(newAttributes.getId()); } if (oldQuestion == null) { throw new EntityDoesNotExistException( "Trying to update a feedback question that does not exist."); } if(oldQuestion.isChangesRequiresResponseDeletion(newAttributes)) { frLogic.deleteFeedbackResponsesForQuestionAndCascade(oldQuestion.getId(), hasResponseRateUpdate); } oldQuestion.updateValues(newAttributes); newAttributes.removeIrrelevantVisibilityOptions(); fqDb.updateFeedbackQuestion(newAttributes); }

Target:
private void updateFeedbackQuestion(FeedbackQuestionAttributes newAttributes, boolean hasResponseRateUpdate) throws InvalidParametersException, EntityDoesNotExistException { FeedbackQuestionAttributes oldQuestion = null; if (newAttributes.getId() == null) { oldQuestion = fqDb.getFeedbackQuestion(newAttributes.feedbackSessionName, newAttributes.courseId, newAttributes.questionNumber); } else { oldQuestion = fqDb.getFeedbackQuestion(newAttributes.getId()); } if (oldQuestion == null) { throw new EntityDoesNotExistException( "Trying to update a feedback question that does not exist."); } if(oldQuestion.isChangesRequiresResponseDeletion(newAttributes)) { frLogic.deleteFeedbackResponsesForQuestionAndCascade(oldQuestion.getId(), hasResponseRateUpdate); } oldQuestion.updateValues(newAttributes); newAttributes.removeIrrelevantVisibilityOptions(); fqDb.updateFeedbackQuestion(newAttributes); }
Source:
public void migrateIfNecessary_1_1_to_1_2() throws Exception { String toMigrate = getFileContent("scesim-1-1.scesim"); String migrated = migrationInstance.from1_1to1_2().apply(toMigrate); assertTrue(toMigrate.contains("<ScenarioSimulationModel version=\"1.1\">")); assertFalse(migrated.contains("<ScenarioSimulationModel version=\"1.1\">")); assertTrue(migrated.contains("dmoSession></dmoSession>")); assertTrue(migrated.contains("<type>RULE</type>")); }

Target:
public void migrateIfNecessary_1_1_to_1_2() throws Exception { String toMigrate = getFileContent("scesim-1-1.scesim"); String migrated = migrationInstance.from1_1to1_2().apply(toMigrate); assertTrue(toMigrate.contains("<ScenarioSimulationModel version=\"1.1\">")); assertFalse(migrated.contains("<ScenarioSimulationModel version=\"1.1\">")); assertTrue(migrated.contains("<ScenarioSimulationModel version=\"1.2\">")); assertTrue(migrated.contains("dmoSession></dmoSession>")); assertTrue(migrated.contains("<type>RULE</type>")); }
Source:
public EventJob(String thingUID, String channelID, String event) { checkNotNull(thingUID, "Thing UID cannot be null"); checkNotNull(channelID, "Channel ID cannot be null"); checkNotNull(event, "Event cannot be null"); this.thingUID = thingUID; this.channelID = channelID; this.event = event; }

Target:
public EventJob(String thingUID, String channelID, String event) { checkArgument(thingUID != null, "Thing UID cannot be null"); checkArgument(channelID != null, "Channel ID cannot be null"); checkArgument(event != null, "Event cannot be null"); this.thingUID = thingUID; this.channelID = channelID; this.event = event; }
Source:
public void setup() throws Exception { Field field = JpaUserDao.class.getDeclaredField("managerProvider"); field.setAccessible(true); field.set(userDao, managerProvider); EntityManager entityManager = mock(EntityManager.class); when(entityManager.createNamedQuery(anyString(), anyObject())).thenReturn(typedQuery); when(managerProvider.get()).thenReturn(entityManager); when(typedQuery.setMaxResults(anyInt())).thenReturn(typedQuery); when(typedQuery.setFirstResult(anyInt())).thenReturn(typedQuery); when(typedQuery.setFirstResult(anyInt())).thenReturn(typedQuery); }

Target:
public void setup() throws Exception { EntityManager entityManager = mock(EntityManager.class); when(entityManager.createNamedQuery(anyString(), anyObject())).thenReturn(typedQuery); when(managerProvider.get()).thenReturn(entityManager); when(typedQuery.setMaxResults(anyInt())).thenReturn(typedQuery); when(typedQuery.setFirstResult(anyInt())).thenReturn(typedQuery); when(typedQuery.setFirstResult(anyInt())).thenReturn(typedQuery); }
Source:
public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null) { return false; } if (obj.getClass() != this.getClass()) { return true; } PGrange<T> other = (PGrange<T>) obj; return this.lowerInclusive == other.lowerInclusive && this.upperInclusive == other.upperInclusive && nullSafeEquals(this.lowerBound, other.lowerBound) && nullSafeEquals(this.upperBound, other.upperBound); }

Target:
public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null) { return false; } if (obj.getClass() != this.getClass()) { return false; } PGrange<T> other = (PGrange<T>) obj; return this.lowerInclusive == other.lowerInclusive && this.upperInclusive == other.upperInclusive && nullSafeEquals(this.lowerBound, other.lowerBound) && nullSafeEquals(this.upperBound, other.upperBound); }
Source:
public void anAlarmNotificationIsReceivedFromAKnownDevice() throws Throwable { PROPERTIES_MAP.put(DEVICE_IDENTIFICATION_G_LABEL, this.deviceId.getDeviceIdG()); PROPERTIES_MAP.put(ORGANISATION_IDENTIFICATION_LABEL, this.organisationId.getOrganisationId()); this.RequestRunner(PROPERTIES_MAP, TEST_CASE_NAME_REQUEST, TEST_CASE_XML, TEST_SUITE_XML); }

Target:
public void anAlarmNotificationIsReceivedFromAKnownDevice() throws Throwable { try { SimulatePushedAlarmsHooks.simulateAlarm(KnownDevice, new byte[] { 0x2C, 0x00, 0x00, 0x01, 0x02 }); SimulatePushedAlarmsHooks.simulateAlarm(KnownDevice, new byte[] { 0x2C, 0x04, 0x20, 0x00, 0x00 }); } catch (final Exception e) { LOGGER.error("Error occured simulateAlarm: ", e); } PROPERTIES_MAP.put(DEVICE_IDENTIFICATION_E_LABEL, this.deviceId.getDeviceIdE()); PROPERTIES_MAP.put(ORGANISATION_IDENTIFICATION_LABEL, this.organisationId.getOrganisationId()); this.RequestRunner(PROPERTIES_MAP, TEST_CASE_NAME_REQUEST, TEST_CASE_XML, TEST_SUITE_XML); }
Source:
public static WSResponse startJob(String conf_id, String url) { Configuration runConfig = getConfigurationFromDb(conf_id); Evaluator newEval = getEvaluator(runConfig); List<TextAnnotation> instances = getInstancesFromDb(runConfig); LearnerInterface learner = new LearnerInterface(url); String jsonInfo = learner.getInfo(); System.out.println(jsonInfo); if(jsonInfo.equals("err")) return null; instances = cleanseInstances(instances, jsonInfo); Job newJob = new Job(learner, instances); WSResponse solverResponse = newJob.sendAndReceiveRequestsFromSolver(); Evaluation eval = newJob.evaluateSolver(); return solverResponse; }

Target:
public static WSResponse startJob(String conf_id, String url) { Configuration runConfig = getConfigurationFromDb(conf_id); Evaluator newEval = getEvaluator(runConfig); List<TextAnnotation> instances = getInstancesFromDb(runConfig); LearnerInterface learner = new LearnerInterface(url); String jsonInfo = learner.getInfo(); if(jsonInfo.equals("err")) return null; instances = cleanseInstances(instances, jsonInfo); Job newJob = new Job(learner, instances); WSResponse solverResponse = newJob.sendAndReceiveRequestsFromSolver(); Evaluation eval = newJob.evaluateSolver(); return solverResponse; }
Source:
private boolean isAdvertised(Channel channel) { return channel.getAdvertiseFrom().isBeforeNow() || channel.getAdvertiseFrom().isEqualNow(); }

Target:
private boolean isAdvertised(Channel channel) { return channel.getAdvertiseFrom() == null || !channel.getAdvertiseFrom().isAfterNow(); }
Source:
protected String getEventsFromEventsLogPlugin(IGerritHudsonTriggerConfig config, String url) { logger.info("({}) Going to GET: {}", serverName, url); DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); if (config.getGerritProxy() != null && !config.getGerritProxy().isEmpty()) { try { URL proxyUrl = new URL(config.getGerritProxy()); HttpHost proxy = new HttpHost(proxyUrl.getHost(), proxyUrl.getPort(), proxyUrl.getProtocol()); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } catch (MalformedURLException e) { logger.error("Could not parse proxy URL, attempting without proxy.", e); } } httpclient.getCredentialsProvider().setCredentials(new AuthScope(null, -1), config.getHttpCredentials()); HttpResponse execute; try { execute = httpclient.execute(httpGet); } catch (IOException e) { logger.warn(e.getMessage(), e); return ""; } int statusCode = execute.getStatusLine().getStatusCode(); logger.info("Received status code: for server: {}", statusCode, serverName); if (statusCode == HttpURLConnection.HTTP_OK) { try { InputStream bodyStream = execute.getEntity().getContent(); String body = IOUtils.toString(bodyStream, "UTF-8"); logger.info(body); return body; } catch (IOException ioe) { logger.warn(ioe.getMessage(), ioe); logger.warn("Not successful at requesting missed events from plugin. (errorcode: {})", EVENTS_LOG_PLUGIN_NAME, statusCode); } } else { logger.warn("Not successful at requesting missed events from plugin. (errorcode: {})", EVENTS_LOG_PLUGIN_NAME, statusCode); } return ""; }

Target:
protected String getEventsFromEventsLogPlugin(IGerritHudsonTriggerConfig config, String url) { logger.debug("({}) Going to GET: {}", serverName, url); HttpResponse execute = null; try { execute = HttpUtils.performHTTPGet(config, url); } catch (IOException e) { logger.warn(e.getMessage(), e); return ""; } int statusCode = execute.getStatusLine().getStatusCode(); logger.debug("Received status code: for server: {}", statusCode, serverName); if (statusCode == HttpURLConnection.HTTP_OK) { try { HttpEntity entity = execute.getEntity(); ContentType contentType; if (entity == null) { logger.warn("Not successful at requesting missed events from plugin. Null entity returned)", statusCode); } contentType = ContentType.get(entity); if (contentType == null) { contentType = ContentType.DEFAULT_TEXT; } Charset charset = contentType.getCharset(); if (charset == null) { charset = Charset.defaultCharset(); } InputStream bodyStream = entity.getContent(); String body = IOUtils.toString(bodyStream, charset.name()); logger.debug(body); return body; } catch (IOException ioe) { logger.warn(ioe.getMessage(), ioe); logger.warn("Not successful at requesting missed events from plugin. (errorcode: {})", EVENTS_LOG_PLUGIN_NAME, statusCode); } } else { logger.warn("Not successful at requesting missed events from plugin. (errorcode: {})", EVENTS_LOG_PLUGIN_NAME, statusCode); } return ""; }
Source:
public boolean isInProgress(ChargeStatus chargeStatus) { return List.of(lockState, submittedState).contains(chargeStatus); }

Target:
public boolean isInProgress(ChargeStatus chargeStatus) { return Set.of(lockState, submittedState).contains(chargeStatus); }
Source:
public void testReservedPoolDisabled() throws Exception { Map<String, String> properties = ImmutableMap.<String, String>builder() .put("experimental.legacy-reserved-pool-enabled", "false") .put("query.low-memory-killer.delay", "5s") .put("query.low-memory-killer.policy", "total-reservation") .build(); try (DistributedQueryRunner queryRunner = createQueryRunner(TINY_SESSION, properties)) { QueryId fakeQueryId = new QueryId("fake"); for (TestingPrestoServer server : queryRunner.getServers()) { List<MemoryPool> memoryPools = server.getLocalMemoryManager().getPools(); assertEquals(memoryPools.size(), 1, "Only general pool should exist"); assertTrue(memoryPools.get(0).tryReserve(fakeQueryId, "test", memoryPools.get(0).getMaxBytes())); } List<Future<?>> queryFutures = new ArrayList<>(); for (int i = 0; i < 2; i++) { queryFutures.add(executor.submit(() -> queryRunner.execute("SELECT COUNT(*), clerk FROM orders GROUP BY clerk"))); } waitForQueryToBeKilled(queryRunner); for (TestingPrestoServer server : queryRunner.getServers()) { Optional<MemoryPool> reserved = server.getLocalMemoryManager().getReservedPool(); MemoryPool general = server.getLocalMemoryManager().getGeneralPool(); assertFalse(reserved.isPresent()); assertTrue(general.getReservedBytes() > 0); general.free(fakeQueryId, "test", general.getMaxBytes()); assertTrue(general.getFreeBytes() > 0); } for (Future<?> query : queryFutures) { query.get(); } } }

Target:
public void testReservedPoolDisabled() throws Exception { Map<String, String> properties = ImmutableMap.<String, String>builder() .put("experimental.reserved-pool-enabled", "false") .put("query.low-memory-killer.delay", "5s") .put("query.low-memory-killer.policy", "total-reservation") .build(); try (DistributedQueryRunner queryRunner = createQueryRunner(TINY_SESSION, properties)) { QueryId fakeQueryId = new QueryId("fake"); for (TestingPrestoServer server : queryRunner.getServers()) { List<MemoryPool> memoryPools = server.getLocalMemoryManager().getPools(); assertEquals(memoryPools.size(), 1, "Only general pool should exist"); assertTrue(memoryPools.get(0).tryReserve(fakeQueryId, "test", memoryPools.get(0).getMaxBytes())); } List<Future<?>> queryFutures = new ArrayList<>(); for (int i = 0; i < 2; i++) { queryFutures.add(executor.submit(() -> queryRunner.execute("SELECT COUNT(*), clerk FROM orders GROUP BY clerk"))); } waitForQueryToBeKilled(queryRunner); for (TestingPrestoServer server : queryRunner.getServers()) { Optional<MemoryPool> reserved = server.getLocalMemoryManager().getReservedPool(); MemoryPool general = server.getLocalMemoryManager().getGeneralPool(); assertFalse(reserved.isPresent()); assertTrue(general.getReservedBytes() > 0); general.free(fakeQueryId, "test", general.getMaxBytes()); assertTrue(general.getFreeBytes() > 0); } for (Future<?> query : queryFutures) { query.get(); } } }