auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void popUp(SessionDataDto sessionDataDto, String userComment, SessionComparisonPanel.TreeItem item) { getApplyButton().removeFromParent(); currentTreeItem = item; currentSessionDataDto = sessionDataDto; setText("Session " + sessionDataDto.getSessionId()); textArea.setText(userComment); onTextAreaContentChanged(); show(); textArea.setFocus(true); }

Target:
public void popUp(SessionDataDto sessionDataDto, String userComment, SessionComparisonPanel.TreeItem item) { if (sessionDataDto==null){ new ExceptionPanel("The session data has a value null. The session's id is wrong."); } getApplyButton().removeFromParent(); currentTreeItem = item; currentSessionDataDto = sessionDataDto; setText("Session " + sessionDataDto.getSessionId()); textArea.setText(userComment); onTextAreaContentChanged(); show(); textArea.setFocus(true); }
Source:
public void shouldSetMd5AndSSLPortHeaders() throws Exception { ServerBinaryDownloader downloader = new ServerBinaryDownloader(ServerUrlGeneratorMother.generatorFor("localhost", 9090), null, SslVerificationMode.NONE); downloader.downloadIfNecessary(DownloadableFile.AGENT); assertThat(downloader.getMd5(), is(md5DigestOfStream(new FileInputStream(DownloadableFile.AGENT.getLocalFile())))); assertThat(downloader.getSslPort(), is("9091")); }

Target:
public void shouldSetMd5AndSSLPortHeaders() throws Exception { ServerBinaryDownloader downloader = new ServerBinaryDownloader(ServerUrlGeneratorMother.generatorFor("localhost", 9090), null, SslVerificationMode.NONE); downloader.downloadIfNecessary(DownloadableFile.AGENT); try(BufferedInputStream stream = new BufferedInputStream(new FileInputStream(DownloadableFile.AGENT.getLocalFile()))) { assertThat(downloader.getMd5(), is(md5DigestOfStream(stream))); } assertThat(downloader.getSslPort(), is("9091")); }
Source:
public Set<String> getSourceIds() { return audioSources.keySet(); }

Target:
public Set<String> getSourceIds() { return new HashSet<>(audioSources.keySet()); }
Source:
protected void onPostExecute(String response) { String decodedString = ""; Log.d("WOOTRIC_SDK", "response: " + response); try { decodedString = new String(response.getBytes("ISO-8859-1"), "UTF-8"); onSuccess(decodedString); } catch (UnsupportedEncodingException e) { onSuccess(response); } catch (NullPointerException e) { onSuccess(response); } }

Target:
protected void onPostExecute(String response) { String decodedString = ""; Log.d("WOOTRIC_SDK", "response: " + response); if (response != null) { try { decodedString = new String(response.getBytes("ISO-8859-1"), "UTF-8"); onSuccess(decodedString); } catch (UnsupportedEncodingException e) { onSuccess(response); } } }
Source:
public void shutdown() throws IOException { if ( index != null ) { index.close(); } }

Target:
public void shutdown() throws IOException { if ( index != null ) { index.close(); index = null; } }
Source:
private ServiceAccount findService(HttpServletRequest request) throws IOException { String authorizationHeader = request.getHeader(AUTHORIZATION_HEADER); if (StringUtils.isEmpty(authorizationHeader)) { warn().log("service auth header is empty returning null"); return null; } authorizationHeader = authorizationHeader.toLowerCase(); if (!authorizationHeader.startsWith("bearer ")) { warn().log("authorization header does not begin with the required bearer prefix returning null"); return null; } String serviceToken = removeBearerPrefix(authorizationHeader); ServiceAccount serviceAccount = null; try { serviceAccount = getServiceStore().get(serviceToken); } catch (IOException ex) { error().exception(ex).log("unexpected error getting service account"); throw ex; } if (serviceAccount == null) { warn().log("service account not found"); return null; } info().log("identified valid service account"); return serviceAccount; }

Target:
private ServiceAccount findService(HttpServletRequest request) throws IOException { info().log("identity: handling service identity request"); String authorizationHeader = request.getHeader(AUTHORIZATION_HEADER); if (!isValidAuthorizationHeader(authorizationHeader)) { return null; } String serviceToken = removeBearerPrefix(authorizationHeader); ServiceAccount serviceAccount = null; try { serviceAccount = serviceStore.get(serviceToken); } catch (Exception ex) { error().exception(ex).log("unexpected error getting service account"); throw new IOException(ex); } if (serviceAccount == null) { warn().log("service account not found for service token"); return null; } info().data("service_id", serviceAccount.getID()).log("identified valid service account"); return serviceAccount; }
Source:
private void testNoSupportForIterationsInBatchHelper(final Transformation<?>... transformations) { final List<Transformation<?>> registeredTransformations = new ArrayList<>(); Collections.addAll(registeredTransformations, transformations); StreamGraphGenerator streamGraphGenerator = new StreamGraphGenerator( registeredTransformations, new ExecutionConfig(), new CheckpointConfig()); streamGraphGenerator.setRuntimeExecutionMode(RuntimeExecutionMode.AUTOMATIC); expectedException.expect(UnsupportedOperationException.class); expectedException.expectMessage("Iterations are not supported in BATCH execution mode."); streamGraphGenerator.generate(); }

Target:
private void testNoSupportForIterationsInBatchHelper(final Transformation<?>... transformations) { final List<Transformation<?>> registeredTransformations = new ArrayList<>(); Collections.addAll(registeredTransformations, transformations); StreamGraphGenerator streamGraphGenerator = new StreamGraphGenerator( registeredTransformations, new ExecutionConfig(), new CheckpointConfig()); streamGraphGenerator.setRuntimeExecutionMode(RuntimeExecutionMode.BATCH); expectedException.expect(UnsupportedOperationException.class); expectedException.expectMessage("Iterations are not supported in BATCH execution mode."); streamGraphGenerator.generate(); }
Source:
public void runTask() { int dispatched = 0; for (final Message message : MessagingSystem.getInstance().getMessagePendingDispatchSet()) { long start = System.currentTimeMillis(); MessageDispatchReport report = MessagingSystem.dispatch(message); getLogger().info("Dispatched message: in {}ms for emails", message.getExternalId(), System.currentTimeMillis() - start, report.getTotalCount()); dispatched++; } taskLog("Dispatched %d messages\n", dispatched); MessagingSystem.deleteOldMessages(); }

Target:
public void runTask() { MessagingSystem.deleteOldMessages(); int dispatched = 0; for (final Message message : MessagingSystem.getInstance().getMessagePendingDispatchSet()) { long start = System.currentTimeMillis(); MessageDispatchReport report = MessagingSystem.dispatch(message); getLogger().info("Dispatched message: in {}ms for emails", message.getExternalId(), System.currentTimeMillis() - start, report.getTotalCount()); dispatched++; } taskLog("Dispatched %d messages\n", dispatched); }
Source:
public Set<DiscoveryDruidNode> getAllNodes() { return new ImmutableSet.Builder().addAll(nodes.values()).build(); }

Target:
public Collection<DiscoveryDruidNode> getAllNodes() { return Collections.unmodifiableCollection(nodes.values()); }
Source:
protected static int parseSquashFixupSequenceCount(String currSquashMessage) { String regex = "This is a combination of (.*) commits"; String firstLine = currSquashMessage.substring(0, currSquashMessage.indexOf("\n")); Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(firstLine); if (!matcher.find()) throw new IllegalArgumentException(); return Integer.parseInt(matcher.group(1)); }

Target:
static int parseSquashFixupSequenceCount(String currSquashMessage) { String regex = "This is a combination of (.*) commits"; String firstLine = currSquashMessage.substring(0, currSquashMessage.indexOf("\n")); Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(firstLine); if (!matcher.find()) throw new IllegalArgumentException(); return Integer.parseInt(matcher.group(1)); }
Source:
public ForkingTaskRunner( ForkingTaskRunnerConfig config, TaskConfig taskConfig, WorkerConfig workerConfig, Properties props, TaskLogPusher taskLogPusher, ObjectMapper jsonMapper, @Self DruidNode node ) { this.config = config; this.taskConfig = taskConfig; this.props = props; this.taskLogPusher = taskLogPusher; this.jsonMapper = jsonMapper; this.node = node; this.portFinder = new PortFinder(config.getStartPort()); this.exec = MoreExecutors.listeningDecorator( Executors.newFixedThreadPool( workerConfig.getCapacity(), new ThreadFactoryBuilder() .setNameFormat("forking-task-runner-%d") .setDaemon(true) .build() ) ); }

Target:
public ForkingTaskRunner( ForkingTaskRunnerConfig config, TaskConfig taskConfig, WorkerConfig workerConfig, Properties props, TaskLogPusher taskLogPusher, ObjectMapper jsonMapper, @Self DruidNode node ) { this.config = config; this.taskConfig = taskConfig; this.props = props; this.taskLogPusher = taskLogPusher; this.jsonMapper = jsonMapper; this.node = node; this.portFinder = new PortFinder(config.getStartPort()); this.exec = MoreExecutors.listeningDecorator( Execs.multiThreaded(workerConfig.getCapacity(), "forking-task-runner-%d") ); }
Source:
@Override public Pair<RelTraitSet, List<RelTraitSet>> passThroughTraits( final RelTraitSet required) { RelCollation collation = required.getCollation(); if (collation == null || collation == RelCollations.EMPTY) { return null; } List<Integer> requiredKeys = RelCollations.ordinals(collation); ImmutableBitSet requiredKeySet = ImmutableBitSet.of(requiredKeys); ImmutableBitSet leftKeySet = ImmutableBitSet.of(joinInfo.leftKeys); ImmutableBitSet rightKeySet = ImmutableBitSet.of(joinInfo.rightKeys) .shift(left.getRowType().getFieldCount()); if (joinType == JoinRelType.LEFT) { if (requiredKeySet.equals(leftKeySet)) { return Pair.of( required, ImmutableList.of( required, required.replace(RelCollations.EMPTY))); } } else if (joinType == JoinRelType.RIGHT) { if (requiredKeySet.equals(rightKeySet)) { RelCollation rightCollation = RelCollations.shift(collation, -left.getRowType().getFieldCount()); return Pair.of( required, ImmutableList.of( required.replace(RelCollations.EMPTY), required.replace(rightCollation))); } } return null; }

Target:
@Override public Pair<RelTraitSet, List<RelTraitSet>> passThroughTraits( final RelTraitSet required) { RelCollation collation = required.getCollation(); if (collation == null || collation == RelCollations.EMPTY || joinType == JoinRelType.FULL || joinType == JoinRelType.RIGHT) { return null; } for (RelFieldCollation fc : collation.getFieldCollations()) { if (fc.getFieldIndex() >= getLeft().getRowType().getFieldCount()) { return null; } } RelTraitSet passthroughTraitSet = traitSet.replace(collation); return Pair.of(passthroughTraitSet, ImmutableList.of( passthroughTraitSet, passthroughTraitSet.replace(RelCollations.EMPTY))); }
Source:
public void testObjectConstruction() { ClassObj clazz = mState.findClass("java.lang.Thread$State"); assertNotNull(clazz); Object object = clazz.getStaticField(Type.OBJECT, "$VALUES").getValue(); assertTrue(object instanceof ArrayInstance); ArrayInstance array = (ArrayInstance) object; Value[] values = array.getValues(); assertEquals(6, values.length); Collection<Instance> instances = clazz.getInstances(); for (Value value : values) { assertTrue(value.getValue() instanceof Instance); assertTrue(instances.contains(value.getValue())); } Object blocked = clazz.getStaticField(Type.OBJECT, "NEW").getValue(); assertTrue(blocked instanceof ClassInstance); ClassInstance instance = (ClassInstance) blocked; assertSame(clazz, instance.getClassObj()); Object name = instance.getField(Type.OBJECT, "name").getValue(); assertTrue(name instanceof ClassInstance); ClassInstance string = (ClassInstance) name; assertEquals("java.lang.String", string.getClassObj().getClassName()); Object value = string.getField(Type.OBJECT, "value").getValue(); assertTrue(value instanceof ArrayInstance); Value[] data = ((ArrayInstance) value).getValues(); assertEquals(3, data.length); assertEquals('N', data[0].getValue()); assertEquals('E', data[1].getValue()); assertEquals('W', data[2].getValue()); Object ordinal = instance.getField(Type.INT, "ordinal").getValue(); assertEquals(0, ordinal); }

Target:
public void testObjectConstruction() { ClassObj clazz = mState.findClass("java.lang.Thread$State"); assertNotNull(clazz); Object object = clazz.getStaticField(Type.OBJECT, "$VALUES").getValue(); assertTrue(object instanceof ArrayInstance); ArrayInstance array = (ArrayInstance) object; Value[] values = array.getValues(); assertEquals(6, values.length); Collection<Instance> instances = clazz.getInstances(); for (Value value : values) { assertTrue(value.getValue() instanceof Instance); assertTrue(instances.contains(value.getValue())); } Object enumValue = clazz.getStaticField(Type.OBJECT, "NEW").getValue(); assertTrue(enumValue instanceof ClassInstance); ClassInstance instance = (ClassInstance) enumValue; assertSame(clazz, instance.getClassObj()); Object name = instance.getField(Type.OBJECT, "name").getValue(); assertTrue(name instanceof ClassInstance); ClassInstance string = (ClassInstance) name; assertEquals("java.lang.String", string.getClassObj().getClassName()); Object value = string.getField(Type.OBJECT, "value").getValue(); assertTrue(value instanceof ArrayInstance); Value[] data = ((ArrayInstance) value).getValues(); assertEquals(3, data.length); assertEquals('N', data[0].getValue()); assertEquals('E', data[1].getValue()); assertEquals('W', data[2].getValue()); Object ordinal = instance.getField(Type.INT, "ordinal").getValue(); assertEquals(0, ordinal); }
Source:
public Result doWork() { final boolean isImmediate = getInputData() != null ? getInputData().getBoolean(PARAM_RUN_IMMEDIATE, false) : false; Log.d(TAG, "doWork() : isImmediate = " + isImmediate); ClientConfig.initialize(getApplicationContext()); AtomicBoolean finished = new AtomicBoolean(false); if (NetworkUtils.networkAvailable() && NetworkUtils.isFeedRefreshAllowed()) { DBTasks.refreshAllFeeds(getApplicationContext(), null, () -> finished.set(true)); } else { Log.d(TAG, "Blocking automatic update: no wifi available / no mobile updates allowed"); } Awaitility.await().until(finished::get); if (!isImmediate && UserPreferences.isAutoUpdateTimeOfDay()) { UserPreferences.restartUpdateAlarm(); } return Result.success(); }

Target:
public Result doWork() { final boolean isRunOnce = getInputData().getBoolean(PARAM_RUN_ONCE, false); Log.d(TAG, "doWork() : isRunOnce = " + isRunOnce); ClientConfig.initialize(getApplicationContext()); if (NetworkUtils.networkAvailable() && NetworkUtils.isFeedRefreshAllowed()) { DBTasks.refreshAllFeeds(getApplicationContext()); } else { Log.d(TAG, "Blocking automatic update: no wifi available / no mobile updates allowed"); } if (!isRunOnce && UserPreferences.isAutoUpdateTimeOfDay()) { AutoUpdateManager.restartUpdateAlarm(); } return Result.success(); }
Source:
private void writePackedRefs(String content) throws IOException { File pr = new File(diskRepo.getDirectory(), "packed-refs"); write(pr, content); final long now = SystemReader.getInstance().getCurrentTime(); final int oneHourAgo = 3600 * 1000; pr.setLastModified(now - oneHourAgo); }

Target:
private void writePackedRefs(String content) throws IOException { File pr = new File(diskRepo.getDirectory(), "packed-refs"); write(pr, content); final long now = System.currentTimeMillis(); final int oneHourAgo = 3600 * 1000; pr.setLastModified(now - oneHourAgo); }
Source:
public void testUnsubscription() { final AtomicBoolean wasCalled = new AtomicBoolean(false); PublishSubject<Integer> source = PublishSubject.create(); Subscription subscription = source.doOnEmpty(new Action0() { @Override public void call() { wasCalled.set(true); } }).take(3).subscribe(); assertTrue(source.hasObservers()); source.onNext(0); source.onNext(1); assertTrue(source.hasObservers()); source.onNext(2); assertTrue(!source.hasObservers()); subscription.unsubscribe(); assertTrue(!wasCalled.get()); }

Target:
public void testUnsubscription() { final AtomicBoolean wasCalled = new AtomicBoolean(false); PublishSubject<Integer> source = PublishSubject.create(); Subscription subscription = source.doOnEmpty(new Action0() { @Override public void call() { wasCalled.set(true); } }).take(3).subscribe(); assertTrue(source.hasObservers()); source.onNext(0); source.onNext(1); assertTrue(source.hasObservers()); source.onNext(2); assertFalse(source.hasObservers()); subscription.unsubscribe(); assertFalse(wasCalled.get()); }
Source:
private Boolean executeRequest(URIBuilder builder) throws Exception { try { HttpGet request = new HttpGet(builder.build()); HttpClient client = HttpClientBuilder.create().build(); HttpResponse response = client.execute(request); int status = response.getStatusLine().getStatusCode(); if (status < 200 || status > 300) { return false; } return true; } catch (Exception ex) { Thread.sleep(1000); throw ex; } }

Target:
private Boolean executeRequest(URIBuilder builder) throws Exception { try { HttpGet request = new HttpGet(builder.build()); HttpClient client = HttpClientBuilder.create().build(); HttpResponse response = client.execute(request); int status = response.getStatusLine().getStatusCode(); if (status < 200 || status >= 300) { return false; } return true; } catch (Exception ex) { Thread.sleep(1000); throw ex; } }
Source:
public String toString() { return String.format("SMALL_RECT[%s,%s,%s,%s]", Left, Top, Right, Bottom); }

Target:
public String toString() { return String.format("SMALL_RECT(%s,%s)(%s,%s)", Left, Top, Right, Bottom); }
Source:
public byte[] encode(final LinearModel model) { final ByteArrayOutputStream baos = new ByteArrayOutputStream(getNumBytes(model)); final DataOutputStream dos = new DataOutputStream(baos); encodeToStream(model, dos); return baos.toByteArray(); }

Target:
public byte[] encode(final LinearModel model) { try (final ByteArrayOutputStream baos = new ByteArrayOutputStream(getNumBytes(model)); final DataOutputStream dos = new DataOutputStream(baos)) { encodeToStream(model, dos); return baos.toByteArray(); } catch (final IOException e) { throw new RuntimeException(e.getCause()); } }
Source:
public static Flag valueOf(String internalName) throws IllegalArgumentException { try { return (Flag)(Flag.class.getField(internalName).get(null)); } catch (NoSuchFieldException e) { if (internalName.startsWith(USER_PREFIX)) { return Flag.createFlag(internalName.substring(USER_PREFIX.length())); } else { return Flag.createFlag(internalName); } } catch (IllegalAccessException e) { throw new IllegalArgumentException(e); } }

Target:
public static Flag valueOf(String internalName) throws IllegalArgumentException { for (Flag f : KNOWN_FLAGS) { if (f.mName.equalsIgnoreCase(internalName)) { return f; } } if (internalName.startsWith(USER_PREFIX)) { return Flag.createFlag(internalName.substring(USER_PREFIX.length())); } else { return Flag.createFlag(internalName); } }
Source:
public GroupType(Repetition repetition, String name, OriginalType originalType, List<Type> fields) { super( checkNotNull(name, "name"), checkNotNull(repetition, "repetition"), originalType ); checkNotNull(fields, "fields"); this.fields = fields; this.indexByName = new HashMap<String, Integer>(); for (int i = 0; i < fields.size(); i++) { indexByName.put(fields.get(i).getName(), i); } }

Target:
public GroupType(Repetition repetition, String name, OriginalType originalType, List<Type> fields) { super( checkNotNull(name, "name"), checkNotNull(repetition, "repetition"), originalType ); this.fields = checkNotNull(fields, "fields"); this.indexByName = new HashMap<String, Integer>(); for (int i = 0; i < fields.size(); i++) { indexByName.put(fields.get(i).getName(), i); } }
Source:
public TmfCoalescedEventRequest(Class<? extends ITmfEvent> dataType, TmfTimeRange range, long index, int nbRequested, ExecutionType priority) { super(ITmfEvent.class, null, index, nbRequested, priority); fRange = range; }

Target:
public TmfCoalescedEventRequest(Class<? extends ITmfEvent> dataType, TmfTimeRange range, long index, int nbRequested, ExecutionType priority) { super(ITmfEvent.class, null, index, nbRequested, priority); fRange = range; if (TmfCoreTracer.isRequestTraced()) { String type = getClass().getName(); type = type.substring(type.lastIndexOf('.') + 1); @SuppressWarnings("nls") String message = "CREATED " + (getExecType() == ITmfEventRequest.ExecutionType.BACKGROUND ? "(BG)" : "(FG)") + " Type=" + type + " Index=" + getIndex() + " NbReq=" + getNbRequested() + " Range=" + getRange() + " DataType=" + getDataType().getSimpleName(); TmfCoreTracer.traceRequest(this, message); } }
Source:
public TopNNumericResultBuilder( DateTime timestamp, DimensionSpec dimSpec, String metricName, int threshold, final Comparator comparator, List<AggregatorFactory> aggFactories, List<PostAggregator> postAggs ) { this.timestamp = timestamp; this.dimSpec = dimSpec; this.metricName = metricName; this.aggFactories = aggFactories; this.postAggs = AggregatorUtil.pruneDependentPostAgg(postAggs, this.metricName); this.threshold = threshold; this.metricComparator = comparator; this.dimNameComparator = new Comparator<String>() { @Override public int compare(String o1, String o2) { int retval; if (o1 == null) { retval = -1; } else if (o2 == null) { retval = 1; } else { retval = o1.compareTo(o2); } return retval; } }; this.dimValComparator = new Comparator<DimValHolder>() { @Override public int compare(DimValHolder d1, DimValHolder d2) { int retVal = metricComparator.compare(d1.getTopNMetricVal(), d2.getTopNMetricVal()); if (retVal == 0) { retVal = dimNameComparator.compare(d1.getDimName(), d2.getDimName()); } return retVal; } }; pQueue = new PriorityQueue<>(this.threshold + 1, this.dimValComparator); }

Target:
public TopNNumericResultBuilder( DateTime timestamp, DimensionSpec dimSpec, String metricName, int threshold, final Comparator comparator, List<AggregatorFactory> aggFactories, List<PostAggregator> postAggs ) { this.timestamp = timestamp; this.dimSpec = dimSpec; this.metricName = metricName; this.aggFactories = aggFactories; this.postAggs = AggregatorUtil.pruneDependentPostAgg(postAggs, this.metricName); this.threshold = threshold; this.metricComparator = comparator; this.dimValComparator = new Comparator<DimValHolder>() { @Override public int compare(DimValHolder d1, DimValHolder d2) { int retVal = metricComparator.compare(d1.getTopNMetricVal(), d2.getTopNMetricVal()); if (retVal == 0) { retVal = dimNameComparator.compare(d1.getDimName(), d2.getDimName()); } return retVal; } }; pQueue = new PriorityQueue<>(this.threshold + 1, this.dimValComparator); }
Source:
public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) { enforceNetworkStackPackagePermission(); mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, new Pair<>(mNai, networkMonitor))); }

Target:
public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) { mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, new Pair<>(mNai, networkMonitor))); }
Source:
public GroupResource parse(TopLevelResource parent, IdString id) throws ResourceNotFoundException, Exception { final CurrentUser user = self.get(); if (user instanceof AnonymousUser) { throw new AuthException("Authentication required"); } else if(!(user instanceof IdentifiedUser)) { throw new ResourceNotFoundException(id); } GroupDescription.Basic d = parse(id.get()); AccountGroup group = GroupDescriptions.toAccountGroup(d); if (group == null) { throw new ResourceNotFoundException(id); } GroupControl ctl = groupControlFactory.controlFor(group); if (!ctl.isVisible()) { throw new ResourceNotFoundException(id); } return new GroupResource(ctl); }

Target:
public GroupResource parse(TopLevelResource parent, IdString id) throws ResourceNotFoundException, Exception { final CurrentUser user = self.get(); if (user instanceof AnonymousUser) { throw new AuthException("Authentication required"); } else if(!(user instanceof IdentifiedUser)) { throw new ResourceNotFoundException(id); } GroupControl ctl = groupControlFactory.controlFor(parse(id.get())); if (!ctl.isVisible()) { throw new ResourceNotFoundException(id); } return new GroupResource(ctl); }
Source:
public static void main(String[] args) throws Exception { VerifiableProperties properties = ToolUtils.getVerifiableProperties(args); CopierConfig config = new CopierConfig(properties); StoreConfig storeConfig = new StoreConfig(properties); ClusterMapConfig clusterMapConfig = new ClusterMapConfig(properties); HelixPropertyStoreConfig helixPropertyStoreConfig = new HelixPropertyStoreConfig(properties); ClusterAgentsFactory clusterAgentsFactory = Utils.getObj(clusterMapConfig.clusterMapClusterAgentsFactory, clusterMapConfig, helixPropertyStoreConfig, config.hardwareLayoutFilePath, config.partitionLayoutFilePath); try (ClusterMap clusterMap = clusterAgentsFactory.getClusterMap()) { StoreKeyFactory storeKeyFactory = Utils.getObj(storeConfig.storeKeyFactory, clusterMap); File srcDir = new File(config.srcStoreDirPath); File tgtDir = new File(config.tgtStoreDirPath); StoreMetrics metrics = new StoreMetrics(clusterMap.getMetricRegistry()); DiskSpaceAllocator diskSpaceAllocator = new DiskSpaceAllocator(false, null, 0, new StorageManagerMetrics(clusterMap.getMetricRegistry())); try (StoreCopier storeCopier = new StoreCopier("src", srcDir, tgtDir, config.storeCapacity, config.fetchSizeInBytes, storeConfig, metrics, storeKeyFactory, new DiskIOScheduler(null), diskSpaceAllocator, Collections.emptyList(), SystemTime.getInstance())) { storeCopier.copy(new StoreFindTokenFactory(storeKeyFactory).getNewFindToken()); } } }

Target:
public static void main(String[] args) throws Exception { VerifiableProperties properties = ToolUtils.getVerifiableProperties(args); CopierConfig config = new CopierConfig(properties); StoreConfig storeConfig = new StoreConfig(properties); ClusterMapConfig clusterMapConfig = new ClusterMapConfig(properties); ClusterAgentsFactory clusterAgentsFactory = Utils.getObj(clusterMapConfig.clusterMapClusterAgentsFactory, clusterMapConfig, config.hardwareLayoutFilePath, config.partitionLayoutFilePath); try (ClusterMap clusterMap = clusterAgentsFactory.getClusterMap()) { StoreKeyFactory storeKeyFactory = Utils.getObj(storeConfig.storeKeyFactory, clusterMap); File srcDir = new File(config.srcStoreDirPath); File tgtDir = new File(config.tgtStoreDirPath); StoreMetrics metrics = new StoreMetrics(clusterMap.getMetricRegistry()); DiskSpaceAllocator diskSpaceAllocator = new DiskSpaceAllocator(false, null, 0, new StorageManagerMetrics(clusterMap.getMetricRegistry())); try (StoreCopier storeCopier = new StoreCopier("src", srcDir, tgtDir, config.storeCapacity, config.fetchSizeInBytes, storeConfig, metrics, storeKeyFactory, new DiskIOScheduler(null), diskSpaceAllocator, Collections.emptyList(), SystemTime.getInstance())) { storeCopier.copy(new StoreFindTokenFactory(storeKeyFactory).getNewFindToken()); } } }
Source:
private ReportRunner<ReportTemplate> getReportRunner(ReportTemplate reportTemplate) { if (reportTemplate instanceof TradeReportTemplate) { ReportRunner<? extends ReportTemplate> runner = new TradeReportRunner(); return (ReportRunner<ReportTemplate>) runner; } throw new IllegalArgumentException(Messages.format("Unsupported report type: {}", reportTemplate.getClass().getSimpleName())); }

Target:
private ReportRunner<ReportTemplate> getReportRunner(ReportTemplate reportTemplate) { if (reportTemplate instanceof TradeReportTemplate) { return (ReportRunner) new TradeReportRunner(); } throw new IllegalArgumentException(Messages.format("Unsupported report type: {}", reportTemplate.getClass().getSimpleName())); }
Source:
public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 37 * result + getSketchValue().hashCode(); return result; }

Target:
public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 37 * result + sketchValue.hashCode(); return result; }
Source:
private void detectComplexOrderby() { if (! hasOrderByColumns() || (! m_hasAggregateExpression && m_groupByColumns.isEmpty())) { return; } Set<AbstractExpression> missingGroupBySet = new HashSet<>(); for (ParsedColInfo col : m_groupByColumns) { if (col.groupByInDisplay) { continue; } if (col.expression.hasAnySubexpressionOfClass( ParameterValueExpression.class)) { assert(hasComplexGroupby()); m_isComplexOrderBy = true; return; } missingGroupBySet.add(col.expression); } for (ParsedColInfo orderCol : m_orderColumns) { AbstractExpression expr = orderCol.expression; if (expr.hasAnySubexpressionOfClass(ParameterValueExpression.class)) { m_isComplexOrderBy = true; return; } if (expr.hasSubExpressionFrom(missingGroupBySet)) { m_isComplexOrderBy = true; return; } } }

Target:
private void detectComplexOrderby() { m_isComplexOrderBy = false; if (! hasOrderByColumns() || (! m_hasAggregateExpression && !isGrouped())) { return; } Set<AbstractExpression> missingGroupBySet = new HashSet<>(); for (ParsedColInfo col : m_groupByColumns) { if (col.groupByInDisplay) { continue; } if (col.expression.hasAnySubexpressionOfClass( ParameterValueExpression.class)) { assert(hasComplexGroupby()); m_isComplexOrderBy = true; return; } missingGroupBySet.add(col.expression); } for (ParsedColInfo orderCol : m_orderColumns) { AbstractExpression expr = orderCol.expression; if (expr.hasAnySubexpressionOfClass(ParameterValueExpression.class)) { m_isComplexOrderBy = true; return; } if (expr.hasSubExpressionFrom(missingGroupBySet)) { m_isComplexOrderBy = true; return; } } }
Source:
private void applyVmInterfaceSpecificStyles() { mainInfoPanel.getElement().getStyle().setPaddingBottom(0, Style.Unit.PX); mainInfoPanel.getElement().getStyle().setPaddingTop(0, Style.Unit.PX); detailedInfoContainer.getElement().getStyle().setMarginLeft(0, Style.Unit.PX); detailedInfoContainer.getElement().getStyle().setWidth(100, Style.Unit.PCT); descriptionPanel.getElement().getStyle().setWidth(10, Style.Unit.PCT); descriptionHeaderPanel.getElement().getStyle().setWidth(100, Style.Unit.PCT); descriptionHeaderPanel.getElement().getStyle().setFontSize(20, Style.Unit.PX); descriptionPanel.removeStyleName(PatternflyConstants.PF_LIST_VIEW_DESCRIPTION); }

Target:
private void applyVmInterfaceSpecificStyles() { listGroupItem.addStyleName(NETWORK_LIST_ITEM); descriptionPanel.getElement().getStyle().setWidth(10, Style.Unit.PCT); descriptionPanel.removeStyleName(PatternflyConstants.PF_LIST_VIEW_DESCRIPTION); }
Source:
public void setUp() { db = fongo.getDB(); experiment = Submission.SrlExperiment.newBuilder() .setProblemId(PROBLEM_ID) .setAssignmentId(new ObjectId().toString()) .setCourseId(new ObjectId().toString()) .setUserId(USER_USER) .setSubmission(Submission.SrlSubmission.getDefaultInstance()) .build(); try { AuthenticationHelper.setMockPermissions(authChecker, null, null, null, null, Authentication.AuthResponse.PermissionLevel.NO_PERMISSION); when(optionChecker.authenticateDate(any(AuthenticationDataCreator.class), anyLong())) .thenReturn(false); when(optionChecker.isItemPublished(any(AuthenticationDataCreator.class))) .thenReturn(false); when(optionChecker.isItemRegistrationRequired(any(AuthenticationDataCreator.class))) .thenReturn(true); } catch (DatabaseAccessException e) { e.printStackTrace(); } catch (AuthenticationException e) { e.printStackTrace(); } authenticator = new Authenticator(authChecker, optionChecker); }

Target:
public void setUp() throws Exception { db = fongo.getDB(); experiment = Submission.SrlExperiment.newBuilder() .setProblemId(PROBLEM_ID) .setAssignmentId(new ObjectId().toString()) .setCourseId(new ObjectId().toString()) .setUserId(USER_USER) .setSubmission(Submission.SrlSubmission.getDefaultInstance()) .build(); AuthenticationHelper.setMockPermissions(authChecker, null, null, null, null, Authentication.AuthResponse.PermissionLevel.NO_PERMISSION); when(optionChecker.authenticateDate(any(AuthenticationDataCreator.class), anyLong())) .thenReturn(false); when(optionChecker.isItemPublished(any(AuthenticationDataCreator.class))) .thenReturn(false); when(optionChecker.isItemRegistrationRequired(any(AuthenticationDataCreator.class))) .thenReturn(true); authenticator = new Authenticator(authChecker, optionChecker); }
Source:
private void checkDuplicateRegistration(String name, Set<String> items, String type) { if(items.contains(name)) { LOGGER.warn("Overriding the existing registered with the name: {}", type, name); } items.add(name); }

Target:
private void checkDuplicateRegistration(String name, Set<String> items, String type) { if(!items.add(name)) { LOGGER.warn("Overriding the existing registered with the name: {}", type, name); } }
Source:
public CompletableFuture<URL> getAddress(final String namespace, final String name) { final URL cachedURL = cache.get(namespace + ":" + name); if(cachedURL != null) { final CompletableFuture<URL> future = new CompletableFuture<>(); future.complete(cachedURL); return future; } else { return httpClient.get(discoveryServiceEndpoint + "/services/" + namespace + "/" + name).withoutContent().readString().execute().handle((r, e) -> { if (e != null) { throw new DolphinRuntimeException("Can not get address for namespace " + namespace + " and name " + name, e); } try { URL url = new URL(r.getContent()); cache.put(namespace + ":" + name, url); return url; } catch (MalformedURLException e1) { throw new DolphinRuntimeException("Can not get address for namespace " + namespace + " and name " + name, e); } }); } }

Target:
public CompletableFuture<URL> getAddress(final String namespace, final String name) { final URL cachedURL = cache.get(namespace + ":" + name); if(cachedURL != null) { final CompletableFuture<URL> future = new CompletableFuture<>(); future.complete(cachedURL); return future; } else { return httpClient.get(discoveryServiceEndpoint + "/services/" + namespace + "/" + name).withoutContent().readString().execute().handle((r, e) -> { if (e != null) { throw new DolphinRuntimeException("Can not get address for namespace " + namespace + " and name " + name, e); } try { final URL url = new URL(r.getContent()); cache.put(namespace + ":" + name, url); return url; } catch (final MalformedURLException e1) { throw new DolphinRuntimeException("Can not get address for namespace " + namespace + " and name " + name, e); } }); } }
Source:
public boolean isTrue() { return (RandomUtils.nextInt() * pct / 100) == 1; }

Target:
public boolean isTrue() { return (RandomUtils.nextInt(0, 100) <= pct); }
Source:
private void addTokenToResponse(final HttpServletResponse response, final String token, final Boolean addCookie) throws IOException { if (addCookie) { Cookie cookie = new Cookie(AUTHORIZATION_COOKIE, token); cookie.setHttpOnly(true); response.addCookie(cookie); } response.setHeader(AUTHORIZATION_HEADER, String.format("%s %s", AUTHORIZATION_TYPE, token)); }

Target:
private void addTokenToResponse(final HttpServletResponse response, final String token, final Boolean addCookie) throws IOException { if (addCookie) { Cookie cookie = new Cookie(AUTHORIZATION_COOKIE, token); cookie.setHttpOnly(true); cookie.setSecure(true); response.addCookie(cookie); } response.setHeader(AUTHORIZATION_HEADER, String.format("%s %s", AUTHORIZATION_TYPE, token)); }
Source:
public boolean isFeedbackSessionCompletedByStudent(FeedbackSessionAttributes fsa, String userEmail) throws EntityDoesNotExistException { if (fsa == null) { throw new EntityDoesNotExistException( "Trying to check a feedback session that does not exist."); } if (fsa.respondingStudentList.contains(userEmail)) { return true; } String feedbackSessionName = fsa.feedbackSessionName; String courseId = fsa.courseId; List<FeedbackQuestionAttributes> allQuestions = fqLogic.getFeedbackQuestionsForStudents(feedbackSessionName, courseId); return allQuestions.isEmpty(); }

Target:
public boolean isFeedbackSessionCompletedByStudent(FeedbackSessionAttributes fsa, String userEmail) throws EntityDoesNotExistException { Assumption.assertNotNull(fsa); if (fsa.respondingStudentList.contains(userEmail)) { return true; } String feedbackSessionName = fsa.feedbackSessionName; String courseId = fsa.courseId; List<FeedbackQuestionAttributes> allQuestions = fqLogic.getFeedbackQuestionsForStudents(feedbackSessionName, courseId); return allQuestions.isEmpty(); }
Source:
public <K, V> Cache<K, V> getCache(String cacheName) { Cache<K, V> cache = super.getCache(cacheName); if (dataType == DataType.UTF8) { return (Cache<K, V>) cache.getAdvancedCache().withEncoder(UTF8Encoder.INSTANCE).withSubject(subject); } Encoder encoder = marshaller.isPresent() ? new MarshallerEncoder(marshaller.get()) : IdentityEncoder.INSTANCE; AdvancedCache<K, V> advancedCache = (AdvancedCache<K, V>) cache.getAdvancedCache().withEncoder(encoder).withSubject(subject); return advancedCache; }

Target:
public <K, V> Cache<K, V> getCache(String cacheName) { Cache<K, V> cache = super.getCache(cacheName); return (AdvancedCache<K, V>) cache.getAdvancedCache().withEncoding(encoderClass).withSubject(subject); }
Source:
public static ByteBuf encodeMetadata( ByteBufAllocator allocator, String customAuthType, ByteBuf metadata) { int actualASCIILength = ByteBufUtil.utf8Bytes(customAuthType); if (actualASCIILength != customAuthType.length()) { throw new IllegalArgumentException("custom auth type must be US_ASCII characters only"); } if (actualASCIILength < 1 || actualASCIILength > 128) { throw new IllegalArgumentException( "custom auth type must have a strictly positive length that fits on 7 unsigned bits, ie" + " 1-128"); } int capacity = 1 + actualASCIILength; ByteBuf headerBuffer = allocator.buffer(capacity, capacity); headerBuffer.writeByte(actualASCIILength - 1); ByteBufUtil.reserveAndWriteUtf8(headerBuffer, customAuthType, actualASCIILength); return allocator.compositeBuffer(2).addComponents(true, headerBuffer, metadata); }

Target:
public static ByteBuf encodeMetadata( ByteBufAllocator allocator, String customAuthType, ByteBuf metadata) { int actualASCIILength = ByteBufUtil.utf8Bytes(customAuthType); if (actualASCIILength != customAuthType.length()) { throw new IllegalArgumentException("custom auth type must be US_ASCII characters only"); } if (actualASCIILength < 1 || actualASCIILength > 128) { throw new IllegalArgumentException( "custom auth type must have a strictly positive length that fits on 7 unsigned bits, ie 1-128"); } int capacity = 1 + actualASCIILength; ByteBuf headerBuffer = allocator.buffer(capacity, capacity); headerBuffer.writeByte(actualASCIILength - 1); ByteBufUtil.reserveAndWriteUtf8(headerBuffer, customAuthType, actualASCIILength); return allocator.compositeBuffer(2).addComponents(true, headerBuffer, metadata); }
Source:
public Component getContent(Project project, ExtensionUtil util) { Layout layout = new CssLayout(); layout.addStyleName(STYLE_MAILING_INFOBOX); layout.setSizeFull(); HtmlBuilder html = new HtmlBuilder(); InfoExtension ext = project.getExtension(InfoExtension.class); if (ext != null) { Set<String> mailingLists = ext.getMailingLists(); if (mailingLists.size() > 0) { MailingListMapper mapper = new MailingListMapper(); html.append("<ul>"); for (String mailingList : ext.getMailingLists()) { html.append("<li>"); html.appendMailToLink(mailingList); List<Link> mappedLinks = mapper.getMappedLinks(configService, project.getProjectId(), mailingList, LinkMapper.ALL_PURPOSES); if (!mappedLinks.isEmpty()) { html.appendLineBreak(); html.appendLinks(mappedLinks); } html.append("</li>"); } html.append("</ul>"); } } if (html.length() > 0) { createLabel(layout, html.toString()); addLastModifiedInfo(layout, ext); } else { createLabel(layout, "This project has no mailing lists."); } addLastModifiedInfo(layout, ext); return layout; }

Target:
public Component getContent(Project project, ExtensionUtil util) { Layout layout = new CssLayout(); layout.addStyleName(STYLE_MAILING_INFOBOX); layout.setSizeFull(); HtmlBuilder html = new HtmlBuilder(); InfoExtension ext = project.getExtension(InfoExtension.class); if (ext != null) { Set<String> mailingLists = ext.getMailingLists(); if (mailingLists.size() > 0) { MailingListMapper mapper = new MailingListMapper(); html.append("<ul>"); for (String mailingList : ext.getMailingLists()) { html.append("<li>"); html.appendMailToLink(mailingList); List<Link> mappedLinks = mapper.getMappedLinks(configService, project.getProjectId(), mailingList, LinkMapper.ALL_PURPOSES); if (!mappedLinks.isEmpty()) { html.appendLineBreak(); html.appendLinks(mappedLinks); } html.append("</li>"); } html.append("</ul>"); } } if (html.length() > 0) { createLabel(layout, html.toString()); } else { createLabel(layout, "This project has no mailing lists."); } return layout; }
Source:
public void testEnableStatistics() throws IntrospectionException, InstanceNotFoundException, MalformedObjectNameException, ReflectionException, AttributeNotFoundException, MBeanException { String mBeanName = getMBeanName(enableStatisticsTestCacheName); try { cacheManager.enableStatistics(enableStatisticsTestCacheName, false); } catch (NullPointerException npe) { npe.printStackTrace(); fail("NullPointerException thrown while attempting to disable statistics"); } assertTrue("Statistics register as enabled after disabling", !(Boolean) mBeanServer.getAttribute(new ObjectName(mBeanName), "StatisticsEnabled")); try { cacheManager.enableStatistics(enableStatisticsTestCacheName, true); } catch (NullPointerException npe) { npe.printStackTrace(); fail("NullPointerException thrown while attempting to enable statistics"); } assertTrue("Statistics register as disabled after enabling", (Boolean) mBeanServer.getAttribute(new ObjectName(mBeanName), "StatisticsEnabled")); }

Target:
public void testEnableStatistics() throws Exception { ObjectName mBeanName = getMBeanName(enableStatisticsTestCacheName, "Statistics"); cacheManager.enableStatistics(enableStatisticsTestCacheName, true); assertTrue("Statistics register as disabled after enabling", mBeanServer.isRegistered(mBeanName)); cacheManager.enableStatistics(enableStatisticsTestCacheName, false); assertFalse("Statistics register as enabled after disabling", mBeanServer.isRegistered(mBeanName)); }
Source:
private void setCorrelationId(HttpContext httpContext, SourceRequest request) { String externalCorrelationId = request.getHeaders().get(PassThroughConstants.CORRELATION_ID); String corId; long corTime = System.currentTimeMillis(); if (externalCorrelationId == null) { corId = UUID.randomUUID().toString(); } else { corId = externalCorrelationId; } httpContext.setAttribute(PassThroughConstants.CORRELATION_ID, corId); httpContext.setAttribute(PassThroughConstants.CORRELATION_REQUEST_ARRIVED_TIME, corTime); }

Target:
private void setCorrelationId(HttpContext httpContext, SourceRequest request) { String externalCorrelationId = request.getHeaders().get(PassThroughConstants.CORRELATION_ID); String corId; if (externalCorrelationId == null) { corId = UUID.randomUUID().toString(); } else { corId = externalCorrelationId; } httpContext.setAttribute(PassThroughConstants.CORRELATION_ID, corId); }
Source:
private PgClassTable.Entry relationToPgClassEntry(RelationInfo info) { return new PgClassTable.Entry(OidHash.relationOid(info), OidHash.schemaOid(info.ident().schema()), info.ident(), info.ident().name(), info.relationType(), info.columns().size(), info.primaryKey().size() > 0); }

Target:
private PgClassTable.Entry relationToPgClassEntry(RelationInfo info) { return new PgClassTable.Entry( OidHash.relationOid(info), OidHash.schemaOid(info.ident().schema()), info.ident(), info.ident().name(), toEntryType(info.relationType()), info.columns().size(), info.primaryKey().size() > 0); }
Source:
public void closeDirty() { try { close(false); } catch (final RuntimeException e) { log.warn(String.format("Ignoring uncaught error in unclean close of active task %s", id), e); } log.info("Closed dirty"); }

Target:
public void closeDirty() { close(false); log.info("Closed dirty"); }
Source:
public Attribute loadAttribute(String name, String attName) throws EntityNotFoundException { Product product = null; try { product = productManager.load(name); } catch (EntityNotFoundException e) { log.warning("The product: " + name + " is not in the database"); throw new APIException(new EntityNotFoundException(Product.class,name, e)); } try { return product.getAttribute(attName); } catch (Exception e) { log.warning("Attribute not found : " + attName); throw new APIException(new EntityNotFoundException(Metadata.class, "Attribute not found : " + attName, attName)); } }

Target:
public Attribute loadAttribute(String name, String attName) throws APIException { Product product = null; try { product = productManager.load(name); } catch (EntityNotFoundException e) { log.warning("The product: " + name + " is not in the database"); throw new APIException(new EntityNotFoundException(Product.class,name, e)); } try { return product.getAttribute(attName); } catch (Exception e) { log.warning("Attribute not found : " + attName); throw new APIException(new EntityNotFoundException(Metadata.class, "Attribute not found : " + attName, attName)); } }
Source:
public static SeasonalityDefinition of(DoubleArray seasonalityMonthOnMonth, ShiftType adjustmentType) { return SeasonalityDefinition.builder() .seasonalityMonthOnMonth(seasonalityMonthOnMonth) .adjustmentType(adjustmentType).build(); }

Target:
public static SeasonalityDefinition of(DoubleArray seasonalityMonthOnMonth, ShiftType adjustmentType) { ArgChecker.isTrue(seasonalityMonthOnMonth.size() == 12, "seasonality must be of length 12"); return new SeasonalityDefinition(seasonalityMonthOnMonth, adjustmentType); }
Source:
public String getText(final Object element) { if (element == null) { return ""; } return ((FileDiff) element).getLabel(element); }

Target:
public String getText(final Object element) { if (element == null) { return null; } return ((FileDiff) element).getLabel(element); }
Source:
public synchronized void updateMemoryPoolAssignments(MemoryPoolAssignmentsRequest assignments) { if (coordinatorId != null && coordinatorId.equals(assignments.getCoordinatorId()) && assignments.getVersion() <= currentMemoryPoolAssignmentVersion) { return; } currentMemoryPoolAssignmentVersion = assignments.getVersion(); if (coordinatorId != null && !coordinatorId.equals(assignments.getCoordinatorId())) { log.warn("Switching coordinator affinity from " + coordinatorId + " to " + assignments.getCoordinatorId()); } coordinatorId = assignments.getCoordinatorId(); for (MemoryPoolAssignment assignment : assignments.getAssignments()) { if (assignment.getPoolId().equals(GENERAL_POOL)) { queryContexts.getUnchecked(assignment.getQueryId()).setMemoryPool(localMemoryManager.getGeneralPool()); } else if (assignment.getPoolId().equals(RESERVED_POOL)) { MemoryPool reservedPool = localMemoryManager.getReservedPool() .orElseThrow(() -> new IllegalArgumentException(format("Cannot move %s to the reserved pool as the reserved pool is not enabled", assignment.getQueryId()))); queryContexts.getUnchecked(assignment.getQueryId()).setMemoryPool(reservedPool); } else { new IllegalArgumentException(format("Cannot move %s to %s as the given memory pool id is invalid", assignment.getQueryId(), assignment.getPoolId())); } } }

Target:
public synchronized void updateMemoryPoolAssignments(MemoryPoolAssignmentsRequest assignments) { if (coordinatorId != null && coordinatorId.equals(assignments.getCoordinatorId()) && assignments.getVersion() <= currentMemoryPoolAssignmentVersion) { return; } currentMemoryPoolAssignmentVersion = assignments.getVersion(); if (coordinatorId != null && !coordinatorId.equals(assignments.getCoordinatorId())) { log.warn("Switching coordinator affinity from " + coordinatorId + " to " + assignments.getCoordinatorId()); } coordinatorId = assignments.getCoordinatorId(); for (MemoryPoolAssignment assignment : assignments.getAssignments()) { if (assignment.getPoolId().equals(GENERAL_POOL)) { queryContexts.getUnchecked(assignment.getQueryId()).setMemoryPool(localMemoryManager.getGeneralPool()); } else if (assignment.getPoolId().equals(RESERVED_POOL)) { MemoryPool reservedPool = localMemoryManager.getReservedPool() .orElseThrow(() -> new IllegalArgumentException(format("Cannot move %s to the reserved pool as the reserved pool is not enabled", assignment.getQueryId()))); queryContexts.getUnchecked(assignment.getQueryId()).setMemoryPool(reservedPool); } else { new IllegalArgumentException(format("Cannot move %s to %s as the target memory pool id is invalid", assignment.getQueryId(), assignment.getPoolId())); } } }