auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void addResponseHandlers(ChannelPipeline p, Fulfiller<? super ReceivedResponse> fulfiller) { <START> if (requestSpecBacking.isDecompressResponse()) { <END> p.addLast(new HttpContentDecompressor()); } p.addLast("aggregator", new HttpObjectAggregator(maxContentLengthBytes)); p.addLast("httpResponseHandler", new SimpleChannelInboundHandler<FullHttpResponse>(false) { @Override public void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception { final Headers headers = new NettyHeadersBackedHeaders(msg.headers()); String contentType = headers.get(HttpHeaderConstants.CONTENT_TYPE.toString()); ByteBuf responseBuffer = initBufferReleaseOnExecutionClose(msg.content(), execution); final ByteBufBackedTypedData typedData = new ByteBufBackedTypedData(responseBuffer, DefaultMediaType.get(contentType)); final Status status = new DefaultStatus(msg.status()); success(fulfiller, new DefaultReceivedResponse(status, headers, typedData)); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); error(fulfiller, cause); } }); }</code><technical_language>this in RequestActionSupport</technical_language>

Target:
protected void addResponseHandlers(ChannelPipeline p, Fulfiller<? super ReceivedResponse> fulfiller) { p.addLast("aggregator", new HttpObjectAggregator(maxContentLengthBytes)); p.addLast("httpResponseHandler", new SimpleChannelInboundHandler<FullHttpResponse>(false) { @Override public void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception { final Headers headers = new NettyHeadersBackedHeaders(msg.headers()); String contentType = headers.get(HttpHeaderConstants.CONTENT_TYPE.toString()); ByteBuf responseBuffer = initBufferReleaseOnExecutionClose(msg.content(), execution); final ByteBufBackedTypedData typedData = new ByteBufBackedTypedData(responseBuffer, DefaultMediaType.get(contentType)); final Status status = new DefaultStatus(msg.status()); success(fulfiller, new DefaultReceivedResponse(status, headers, typedData)); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); error(fulfiller, cause); } }); }
Source:
<code><START> public JobManager( final boolean isSupportAsync, final long pollingIntervalMilliseconds, <END> final long dialogThresholdMillisecond ) { if ( !isSupportAsync ) { logger.info( ASYNC_DISABLED ); } this.config = new Config( isSupportAsync, pollingIntervalMilliseconds, dialogThresholdMillisecond, Boolean.FALSE ); }</code><technical_language>Avoid duplicate code (and magically cover more lines in tests) re-routing this constructor 4 parameters</technical_language>

Target:
public JobManager( final boolean isSupportAsync, final long pollingIntervalMilliseconds, final long dialogThresholdMillisecond ) { this( isSupportAsync, pollingIntervalMilliseconds, dialogThresholdMillisecond, false ); }
Source:
<code>public void setNumOfGroups(int numOfGroups) { if (numOfGroups != 0) { this.numOfGroups = numOfGroups; } else { <START> int numGroupsToFill = nameListSize / DEFAULT_NAMES_PER_GROUP; <END> this.numOfGroups = (nameListSize % DEFAULT_NAMES_PER_GROUP) > 0 ? numGroupsToFill + 1 : numGroupsToFill; } }</code><technical_language>I feel overthinking setter. If user is purposely setting 0, I do it. This code this API readable introduces complication 0 mutation reflected in UI well. code die, lol</technical_language>

Target:
public void setNumOfGroups(int numOfGroups) { this.numOfGroups = numOfGroups; }
Source:
<code>public int run() throws Exception { File f = new File(fileName); LockFile lf = new LockFile(f, FS.DETECTED); if (!lf.lock()) { throw new IOException("Cannot lock " + f); } try { JavaSchemaModel jsm = new JavaSchemaModel(ReviewDb.class); PrintWriter out = new PrintWriter(lf.getOutputStream()); try { jsm.generateProto(out); out.flush(); } finally { out.close(); } <START> lf.commit(); <END> } finally { lf.unlock(); } return 0; }</code><technical_language>Please ensure result true</technical_language>

Target:
public int run() throws Exception { LockFile lf = new LockFile(file, FS.DETECTED); if (!lf.lock()) { throw new IOException("Cannot lock " + file); } try { JavaSchemaModel jsm = new JavaSchemaModel(ReviewDb.class); PrintWriter out = new PrintWriter(lf.getOutputStream()); try { jsm.generateProto(out); out.flush(); } finally { out.close(); } if (!lf.commit()) { throw new IOException("Could not write to " + file); } } finally { lf.unlock(); } return 0; }
Source:
<code>public void testGetPartitionsSample() { assertEquals(getPartitionsSample(ImmutableList.of(), 0), ImmutableList.of()); assertEquals(getPartitionsSample(ImmutableList.of(partition("p1")), 0), ImmutableList.of()); <START> assertEquals(getPartitionsSample(ImmutableList.of(partition("p1")), 1), ImmutableList.of(partition("p1"))); <END> assertEquals(getPartitionsSample(ImmutableList.of(partition("p1")), 2), ImmutableList.of(partition("p1"))); assertEquals( getPartitionsSample(ImmutableList.of(partition("p1"), partition("p2")), 2), ImmutableList.of(partition("p1"), partition("p2"))); assertEquals( getPartitionsSample(ImmutableList.of(partition("p1"), partition("p2"), partition("p3")), 2), getPartitionsSample(ImmutableList.of(partition("p1"), partition("p2"), partition("p3")), 2)); assertEquals( getPartitionsSample(ImmutableList.of(partition("p1"), partition("p2"), partition("p3")), 1), getPartitionsSample(ImmutableList.of(partition("p1"), partition("p2"), partition("p3")), 1)); }</code><technical_language>please extract ImmutableList.of(partition("p1") ImmutableList.of(partition("p1"), partition("p2") variables</technical_language>

Target:
public void testGetPartitionsSample() { assertEquals(getPartitionsSample(ImmutableList.of(partition("p1")), 1), ImmutableList.of(partition("p1"))); assertEquals(getPartitionsSample(ImmutableList.of(partition("p1")), 2), ImmutableList.of(partition("p1"))); assertEquals( getPartitionsSample(ImmutableList.of(partition("p1"), partition("p2")), 2), ImmutableList.of(partition("p1"), partition("p2"))); assertEquals( getPartitionsSample(ImmutableList.of(partition("p1"), partition("p2"), partition("p3")), 2), ImmutableList.of(partition("p1"), partition("p3"))); assertEquals( getPartitionsSample(ImmutableList.of(partition("p1"), partition("p2"), partition("p3"), partition("p4")), 1), getPartitionsSample(ImmutableList.of(partition("p1"), partition("p2"), partition("p3"), partition("p4")), 1)); assertEquals( getPartitionsSample(ImmutableList.of(partition("p1"), partition("p2"), partition("p3"), partition("p4")), 3), getPartitionsSample(ImmutableList.of(partition("p1"), partition("p2"), partition("p3"), partition("p4")), 3)); assertThat(getPartitionsSample(ImmutableList.of(partition("p1"), partition("p2"), partition("p3"), partition("p4")), 3)) .contains(partition("p1"), partition("p3")); }
Source:
<code>static void checkAliasFormat(Set<String> aliases, boolean blockAliasesWithZenodoFormat) { List<String> invalidAliases = new ArrayList<>(); invalidAliases = aliases.stream().filter(alias -> StringUtils.startsWithAny(alias, INVALID_PREFIXES)).collect(Collectors.toList()); if (invalidAliases.size() > 0) { String invalidAliasesString = String.join(", ", invalidAliases); String invalidPrefixesString = String.join(", ", INVALID_PREFIXES); throw new CustomWebApplicationException("These aliases: " + invalidAliasesString + " start with a reserved string." + " They cannot be used. Please create aliases without these prefixes: " + invalidPrefixesString, HttpStatus.SC_BAD_REQUEST); } if (blockAliasesWithZenodoFormat) { Pattern pattern = Pattern.compile(ZENDO_DOI_REGEX); List<String> aliasesWithForbiddenFormat = aliases.stream().filter(alias -> pattern.matcher(alias).matches()).collect(Collectors.toList()); if (aliasesWithForbiddenFormat.size() > 0) { String invalidAliasesString = String.join(", ", aliasesWithForbiddenFormat); throw new CustomWebApplicationException("These aliases : " + invalidAliasesString + " have a format that is forbidden." <START> + " They cannot be used. Please create aliases without this format: " + ZENDO_DOI_REGEX, <END> HttpStatus.SC_BAD_REQUEST); } } }</code><technical_language>I a regex is a user-friendly message. people able sense of it. add example regex</technical_language>

Target:
static void checkAliasFormat(Set<String> aliases, boolean blockAliasesWithZenodoFormat) { List<String> invalidAliases = aliases.stream().filter(alias -> StringUtils.startsWithAny(alias, INVALID_PREFIXES)) .collect(Collectors.toList()); if (invalidAliases.size() > 0) { String invalidAliasesString = String.join(", ", invalidAliases); String invalidPrefixesString = String.join(", ", INVALID_PREFIXES); throw new CustomWebApplicationException("These aliases: " + invalidAliasesString + " start with a reserved string." + " They cannot be used. Please create aliases without these prefixes: " + invalidPrefixesString, HttpStatus.SC_BAD_REQUEST); } if (blockAliasesWithZenodoFormat) { List<String> aliasesWithForbiddenFormat = aliases.stream().filter(alias -> ZENODO_DOI_PATTERN.matcher(alias).matches()) .collect(Collectors.toList()); if (aliasesWithForbiddenFormat.size() > 0) { String invalidAliasesString = String.join(", ", aliasesWithForbiddenFormat); throw new CustomWebApplicationException("These aliases : " + invalidAliasesString + " have a format that is forbidden." + " They cannot be used. Please create aliases without this format: " + ZENDO_DOI_REGEX, HttpStatus.SC_BAD_REQUEST); } } }
Source:
<code>private void registerCQ(SlaveState slaveState) { Class<?> clazz; try { clazz = slaveState.getClassLoader().loadClass(queryObjectClass); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Cannot load class " + queryObjectClass, e); } Queryable.QueryBuilder builder = queryable.getBuilder(null, clazz); for (Condition condition : conditions) { condition.apply(builder); } if (orderBy != null) { for (SortElement se : orderBy) { builder.orderBy(new Queryable.SelectExpression(se.attribute), se.asc ? Queryable.SortOrder.ASCENDING : Queryable.SortOrder.DESCENDING); } } <START> if (projection != null) { <END> Queryable.SelectExpression[] projections = new Queryable.SelectExpression[projection.length]; for (int i = 0; i < projection.length; i++) { projections[i] = new Queryable.SelectExpression(projection[i]); } builder.projection(projections); } else if (aggregatedProjection != null && !aggregatedProjection.isEmpty()) { Queryable.SelectExpression[] projections = new Queryable.SelectExpression[aggregatedProjection.size()]; for (int i = 0; i < aggregatedProjection.size(); i++) { projections[i] = aggregatedProjection.get(i).toSelectExpression(); } builder.projection(projections); } if (offset >= 0) { builder.offset(offset); } if (limit >= 0) { builder.limit(limit); } Query query = builder.build(); slaveState.put(ContinuousQuery.QUERY, query); ContinuousQuery.ContinuousQueryListener cqListener = new ContinuousQuery.ContinuousQueryListener() { @Override public void onEntryJoined(Object key, Object value) { statistics.registerRequest(getResponseTime(key), ContinuousQuery.ENTRY_JOINED); log.trace("Entry joined " + key + " -> " + value); } @Override public void onEntryLeft(Object key) { statistics.registerRequest(getResponseTime(key), ContinuousQuery.ENTRY_LEFT); log.trace("Entry left " + key); } }; slaveState.put(ContinuousQuery.LISTENER, cqListener); continuousQueryTrait.createContinuousQuery(cacheName, query, cqListener); }</code><technical_language>Move this logic AbstractQueryStage</technical_language>

Target:
private void registerCQ(SlaveState slaveState) { if ((projectionAggregated != null && !projectionAggregated.isEmpty()) || (groupBy != null && groupBy.length != 0) || (orderByAggregatedColumns != null && !orderByAggregatedColumns.isEmpty())) { throw new IllegalStateException("Aggregations are not supported in continuous queries!"); } Queryable.QueryBuilder builder = constructBuilder(); Query query = builder.build(); slaveState.put(ContinuousQuery.QUERY, query); ContinuousQuery.ContinuousQueryListener cqListener = new ContinuousQuery.ContinuousQueryListener() { @Override public void onEntryJoined(Object key, Object value) { statistics.registerRequest(getResponseTime(key), ContinuousQuery.ENTRY_JOINED); log.trace("Entry joined " + key + " -> " + value); } @Override public void onEntryLeft(Object key) { statistics.registerRequest(getResponseTime(key), ContinuousQuery.ENTRY_LEFT); log.trace("Entry left " + key); } }; slaveState.put(ContinuousQuery.LISTENER, cqListener); continuousQueryTrait.createContinuousQuery(cacheName, query, cqListener); }
Source:
<code>@Override public IgniteInternalFuture<?> removeAllAsync(@Nullable final Collection<? extends K> keys) { if (F.isEmpty(keys)) return new GridFinishedFuture<Object>(); final boolean statsEnabled = ctx.statisticsEnabled(); boolean profilingEnabled = ctx.kernalContext().metric().profilingEnabled(); final long start = statsEnabled || profilingEnabled ? System.nanoTime() : 0L; if (keyCheck) validateCacheKeys(keys); warnIfUnordered(keys, BulkOperation.REMOVE); IgniteInternalFuture<Object> fut = removeAllAsync0(keys); if (statsEnabled) fut.listen(new UpdateRemoveTimeStatClosure<>(metrics0(), start)); if (profilingEnabled) <START> fut.listen(new ProfileClosure<>(CacheOperationType.REMOVE_ALL, start)); <END> return fut; }</code><technical_language>separate class for operations eliminate operation variable ProfileClosure</technical_language>

Target:
@Override public IgniteInternalFuture<?> removeAllAsync(@Nullable final Collection<? extends K> keys) { if (F.isEmpty(keys)) return new GridFinishedFuture<Object>(); final boolean statsEnabled = ctx.statisticsEnabled(); final boolean performanceStatsEnabled = ctx.kernalContext().performanceStatistics().enabled(); final long start = statsEnabled || performanceStatsEnabled ? System.nanoTime() : 0L; if (keyCheck) validateCacheKeys(keys); warnIfUnordered(keys, BulkOperation.REMOVE); IgniteInternalFuture<Object> fut = removeAllAsync0(keys); if (statsEnabled) fut.listen(new UpdateRemoveTimeStatClosure<>(metrics0(), start)); if (performanceStatsEnabled) fut.listen(f -> writeStatistics(OperationType.CACHE_REMOVE_ALL, start)); return fut; }
Source:
<code>public void setRecipients(Person[] list) { this.recipientsCache = list; try { Person to = ZulipApp.get().getDao(Person.class, true).queryBuilder().where().eq(Person.EMAIL_FIELD, list[0].getEmail()).queryForFirst();; if(list.length == 1) { setRecipients(to.getId() + ""); return; } Person from = ZulipApp.get().getDao(Person.class, true).queryBuilder().where().eq(Person.EMAIL_FIELD, list[1].getEmail()).queryForFirst(); if(to == null && from != null) { setRecipients(""+ from.getId()); } if(to != null && from == null) { setRecipients(to.getId() + ""); } setRecipients(to.getId() + "," + from.getId()); return; } catch (Exception e) { <START> e.printStackTrace(); <END> } this.recipients = (recipientId == 0 && senderId == 0) ? recipientList(list) : recipientId + "," + senderId; }</code><technical_language>Zlog log, printStackTrace</technical_language>

Target:
public void setRecipients(Person[] list) { this.recipientsCache = list; try { Person to = ZulipApp.get().getDao(Person.class, true).queryBuilder().where().eq(Person.EMAIL_FIELD, list[0].getEmail()).queryForFirst();; if(list.length == 1) { setRecipients(to.getId() + ""); return; } Person from = ZulipApp.get().getDao(Person.class, true).queryBuilder().where().eq(Person.EMAIL_FIELD, list[1].getEmail()).queryForFirst(); if(to == null && from != null) { setRecipients(""+ from.getId()); } if(to != null && from == null) { setRecipients(to.getId() + ""); } setRecipients(to.getId() + "," + from.getId()); return; } catch (Exception e) { ZLog.logException(e); } this.recipients = (recipientId == 0 && senderId == 0) ? recipientList(list) : recipientId + "," + senderId; }
Source:
<code>public void test_CentOS_6_3() throws Exception { <START> runTest(ImmutableMap.of("skipJcloudsSshing", true, "imageId", "us-east-1/ami-a96b01c0", "hardwareId", SMALL_HARDWARE_ID)); <END> }</code><technical_language>I right assume while #268 is unmerged skipJcloudsSshing property ignored, this test run before</technical_language>

Target:
public void test_CentOS_6_3() throws Exception { super.test_CentOS_6_3(); }
Source:
<code>public Integer nextAction(INDArray input) { <START> synchronized (ACPolicy.class) { <END> INDArray output = actorCritic.outputAll(input)[1]; if (rnd == null) { return Learning.getMaxAction(output); } float rVal = rnd.nextFloat(); for (int i = 0; i < output.length(); i++) { if (rVal < output.getFloat(i)) { return i; } else rVal -= output.getFloat(i); } throw new RuntimeException("Output from network is not a probability distribution: " + output); } }</code><technical_language>I synchronized is necessary here. thread copy of neural net (actorCritic). AsyncThreadDiscrete.trainSubEpoch(): public SubEpochReturn trainSubEpoch(Observation obs, int nstep) { synchronized (getAsyncGlobal()) { current.copy(getAsyncGlobal().getCurrent()); } ..</technical_language>

Target:
public Integer nextAction(INDArray input) { INDArray output = actorCritic.outputAll(input)[1]; if (rnd == null) { return Learning.getMaxAction(output); } float rVal = rnd.nextFloat(); for (int i = 0; i < output.length(); i++) { if (rVal < output.getFloat(i)) { return i; } else rVal -= output.getFloat(i); } throw new RuntimeException("Output from network is not a probability distribution: " + output); }
Source:
<code>public OrcHadoopInputRowParser( @JsonProperty("parseSpec") ParseSpec parseSpec, @Nullable @JsonProperty("binaryAsString") Boolean binaryAsString ) { this.parseSpec = parseSpec; this.binaryAsString = binaryAsString == null ? false : binaryAsString; final JSONPathSpec flattenSpec; if ((parseSpec instanceof OrcParseSpec)) { flattenSpec = ((OrcParseSpec) parseSpec).getFlattenSpec(); } else { flattenSpec = JSONPathSpec.DEFAULT; } <START> this.groupFlattener = ObjectFlatteners.create(flattenSpec, new OrcStructFlattenerMaker(false)); <END> this.parser = new MapInputRowParser(parseSpec); }</code><technical_language>a "group" (c/p Parquet)</technical_language>

Target:
public OrcHadoopInputRowParser( @JsonProperty("parseSpec") ParseSpec parseSpec, @Nullable @JsonProperty("binaryAsString") Boolean binaryAsString ) { this.parseSpec = parseSpec; this.binaryAsString = binaryAsString == null ? false : binaryAsString; final JSONPathSpec flattenSpec; if (parseSpec instanceof OrcParseSpec) { flattenSpec = ((OrcParseSpec) parseSpec).getFlattenSpec(); } else { flattenSpec = JSONPathSpec.DEFAULT; } this.orcStructFlattener = ObjectFlatteners.create(flattenSpec, new OrcStructFlattenerMaker(this.binaryAsString)); this.parser = new MapInputRowParser(parseSpec); }
Source:
<code>protected void checkAccessControlForStudentFeedbackSubmission( StudentAttributes student, FeedbackSessionAttributes feedbackSession) { String moderatedPerson = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_MODERATED_PERSON); String previewAsPerson = getRequestParamValue(Const.ParamsNames.PREVIEWAS); <START> <END> if (!StringHelper.isEmpty(moderatedPerson)) { gateKeeper.verifyAccessible( logic.getInstructorForGoogleId(feedbackSession.getCourseId(), userInfo.getId()), feedbackSession, student.getSection(), Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_SESSION_COMMENT_IN_SECTIONS); } else if (!StringHelper.isEmpty(previewAsPerson)) { gateKeeper.verifyAccessible( logic.getInstructorForGoogleId(feedbackSession.getCourseId(), userInfo.getId()), feedbackSession, Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_SESSION); } else { gateKeeper.verifyAccessible(student, feedbackSession); } }</code><technical_language>If remove null check, results in NPE? (Line 74)</technical_language>

Target:
protected void checkAccessControlForStudentFeedbackSubmission( StudentAttributes student, FeedbackSessionAttributes feedbackSession) { if (student == null) { throw new UnauthorizedAccessException("Trying to access system using a non-existent student entity"); } String moderatedPerson = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_MODERATED_PERSON); String previewAsPerson = getRequestParamValue(Const.ParamsNames.PREVIEWAS); if (!StringHelper.isEmpty(moderatedPerson)) { gateKeeper.verifyAccessible( logic.getInstructorForGoogleId(feedbackSession.getCourseId(), userInfo.getId()), feedbackSession, student.getSection(), Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_SESSION_COMMENT_IN_SECTIONS); } else if (!StringHelper.isEmpty(previewAsPerson)) { gateKeeper.verifyAccessible( logic.getInstructorForGoogleId(feedbackSession.getCourseId(), userInfo.getId()), feedbackSession, Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_SESSION); } else { gateKeeper.verifyAccessible(student, feedbackSession); } }
Source:
<code><START> public SetMonitorServiceCommand() { <END> }</code><technical_language>nit: find public usage I missed</technical_language>

Target:
protected SetMonitorServiceCommand() { }
Source:
<code>public static void main(String[] args) { <START> List<Car> cars = Iterating.createCars(); <END> List<String> modelsImperative = ImperativeProgramming.getModelsAfter2000UsingFor(cars); LOGGER.info(modelsImperative.toString()); List<String> modelsFunctional = FunctionalProgramming.getModelsAfter2000UsingPipeline(cars); LOGGER.info(modelsFunctional.toString()); }</code><technical_language>a name for Iterating class? sounding right</technical_language>

Target:
public static void main(String[] args) { List<Car> cars = CarFactory.createCars(); List<String> modelsImperative = ImperativeProgramming.getModelsAfter2000(cars); LOGGER.info(modelsImperative.toString()); List<String> modelsFunctional = FunctionalProgramming.getModelsAfter2000(cars); LOGGER.info(modelsFunctional.toString()); Map<Category, List<Car>> groupingByCategoryImperative = ImperativeProgramming.getGroupingOfCarsByCategory(cars); LOGGER.info(groupingByCategoryImperative.toString()); Map<Category, List<Car>> groupingByCategoryFunctional = FunctionalProgramming.getGroupingOfCarsByCategory(cars); LOGGER.info(groupingByCategoryFunctional.toString()); Person john = new Person(cars); List<Car> sedansOwnedImperative = ImperativeProgramming.getSedanCarsOwnedSortedByDate(Arrays.asList(john)); LOGGER.info(sedansOwnedImperative.toString()); List<Car> sedansOwnedFunctional = FunctionalProgramming.getSedanCarsOwnedSortedByDate(Arrays.asList(john)); LOGGER.info(sedansOwnedFunctional.toString()); }
Source:
<code>public void executeFSHooksArrayTest() { final String fsName = "dora"; AtomicBoolean executedWithLambda = new AtomicBoolean(false); FileSystemHooks.FileSystemHook hook = spy(new FileSystemHooks.FileSystemHook() { @Override public void execute(FileSystemHookExecutionContext context) { assertEquals(fsName, context.getFsName()); } }); FileSystemHooks.FileSystemHook lambdaHook = context -> { assertEquals(fsName, context.getFsName()); executedWithLambda.set(true); }; JGitFSHooks.executeFSHooks(Arrays.asList(hook, lambdaHook), FileSystemHooks.ExternalUpdate, new FileSystemHookExecutionContext(fsName)); <START> verify(hook).execute(any()); <END> assertTrue(executedWithLambda.get()); }</code><technical_language>please verify execute() called expected FileSystemHookExecutionContext</technical_language>

Target:
public void executeFSHooksArrayTest() { FileSystemHookExecutionContext ctx = new FileSystemHookExecutionContext(FS_NAME); testExecuteFSHooksArray(ctx, FileSystemHooks.ExternalUpdate); ctx.addParam(FileSystemHooksConstants.POST_COMMIT_EXIT_CODE, EXIT_CODE); testExecuteFSHooksArray(ctx, FileSystemHooks.PostCommit); }
Source:
<code>public Function<Result<TopNResultValue>, Result<TopNResultValue>> makePostComputeManipulatorFn( final TopNQuery query, final MetricManipulationFn fn ) { return new Function<Result<TopNResultValue>, Result<TopNResultValue>>() { private String dimension = query.getDimensionSpec().getOutputName(); @Override public Result<TopNResultValue> apply(@Nullable Result<TopNResultValue> result) { List<Map<String, Object>> serializedValues = Lists.newArrayList( Iterables.transform( result.getValue(), new Function<DimensionAndMetricValueExtractor, Map<String, Object>>() { @Override public Map<String, Object> apply(@Nullable DimensionAndMetricValueExtractor input) { final Map<String, Object> values = Maps.newHashMap(); for (PostAggregator postAgg : query.getPostAggregatorSpecs()) { Object calculatedPostAgg = input.getMetric(postAgg.getName()); if (calculatedPostAgg != null) { values.put(postAgg.getName(), calculatedPostAgg); } else { <START> values.put(postAgg.getName(), postAgg.compute(input.getBaseObject())); <END> } } for (AggregatorFactory agg : query.getAggregatorSpecs()) { values.put(agg.getName(), fn.manipulate(agg, input.getMetric(agg.getName()))); } values.put(dimension, input.getDimensionValue(dimension)); return values; } } ) ); return new Result<TopNResultValue>( result.getTimestamp(), new TopNResultValue(serializedValues) ); } }; }</code><technical_language>i understand this work if input.getBaseObject complex metrics</technical_language>

Target:
public Function<Result<TopNResultValue>, Result<TopNResultValue>> makePostComputeManipulatorFn( final TopNQuery query, final MetricManipulationFn fn ) { return new Function<Result<TopNResultValue>, Result<TopNResultValue>>() { private String dimension = query.getDimensionSpec().getOutputName(); @Override public Result<TopNResultValue> apply(Result<TopNResultValue> result) { List<Map<String, Object>> serializedValues = Lists.newArrayList( Iterables.transform( result.getValue(), new Function<DimensionAndMetricValueExtractor, Map<String, Object>>() { @Override public Map<String, Object> apply(DimensionAndMetricValueExtractor input) { final Map<String, Object> values = Maps.newHashMap(); for (PostAggregator postAgg : query.getPostAggregatorSpecs()) { Object calculatedPostAgg = input.getMetric(postAgg.getName()); if (calculatedPostAgg != null) { values.put(postAgg.getName(), calculatedPostAgg); } else { values.put(postAgg.getName(), postAgg.compute(input.getBaseObject())); } } for (AggregatorFactory agg : query.getAggregatorSpecs()) { values.put(agg.getName(), fn.manipulate(agg, input.getMetric(agg.getName()))); } values.put(dimension, input.getDimensionValue(dimension)); return values; } } ) ); return new Result<TopNResultValue>( result.getTimestamp(), new TopNResultValue(serializedValues) ); } }; }
Source:
<code>private OrchestratorStateParams createSshStateParams(Stack stack, String user, KeyPair keyPair, String authKeysComment, String saltState) { Cluster cluster = stack.getCluster(); Set<Node> nodes = stackUtil.collectReachableNodes(stack); OrchestratorStateParams stateParams = new OrchestratorStateParams(); stateParams.setState(saltState); stateParams.setPrimaryGatewayConfig(gatewayConfigService.getGatewayConfig(stack, stack.getPrimaryGatewayInstance(), stack.getCluster().hasGateway())); stateParams.setTargetHostNames(nodes.stream().map(Node::getHostname).collect(Collectors.toSet())); <START> stateParams.setAllNodes(nodes); <END> stateParams.setExitCriteriaModel(ClusterDeletionBasedExitCriteriaModel.clusterDeletionBasedModel(stack.getId(), cluster.getId())); stateParams.setStateParams(createSshParams(user, keyPair, authKeysComment)); return stateParams; }</code><technical_language>saltState is "ssh.remove_ssh_publickey" moved a constant inlined line #54</technical_language>

Target:
private OrchestratorStateParams createSshStateParams(Stack stack, String user, KeyPair keyPair, String authKeysComment, String saltState) { Cluster cluster = stack.getCluster(); Set<Node> nodes = stackUtil.collectReachableNodes(stack); OrchestratorStateParams stateParams = new OrchestratorStateParams(); stateParams.setState(saltState); stateParams.setPrimaryGatewayConfig(gatewayConfigService.getGatewayConfig(stack, stack.getPrimaryGatewayInstance(), stack.getCluster().hasGateway())); stateParams.setTargetHostNames(nodes.stream().map(Node::getHostname).collect(Collectors.toSet())); stateParams.setAllNodes(nodes); stateParams.setExitCriteriaModel(ClusterDeletionBasedExitCriteriaModel.clusterDeletionBasedModel(stack.getId(), cluster.getId())); stateParams.setStateParams(createSshParams(user, keyPair, authKeysComment)); OrchestratorStateRetryParams retryParams = new OrchestratorStateRetryParams(); retryParams.setMaxRetry(SSH_KEY_OPERATION_RETRY_COUNT); stateParams.setStateRetryParams(retryParams); return stateParams; }
Source:
<code>public void runProtected(final Test test, Protectable p) { try { p.protect(); } catch (AssertionFailedError e) { addFailure(test, e); } catch (ThreadDeath e) { throw e; <START> } catch (Throwable t) { <END> addError(test, t); } }</code><technical_language>IMHO, for variable naming, local consistency is arguably more important global consistency, naming this e is best. If a global change, I prefer rename variables of type Throwable e</technical_language>

Target:
public void runProtected(final Test test, Protectable p) { try { p.protect(); } catch (AssertionFailedError e) { addFailure(test, e); } catch (ThreadDeath e) { throw e; } catch (Throwable e) { addError(test, e); } }
Source:
<code>public ISMRGarbageInfo merge(ISMRGarbageInfo other) { if (other instanceof MultiObjectSMREntryGarbageInfo) { MultiObjectSMREntryGarbageInfo deduplicatedGCInfo = new MultiObjectSMREntryGarbageInfo(); ((MultiObjectSMREntryGarbageInfo) other).getStreamIdToGarbageMap().forEach((streamId, garbageMap) -> { if (garbageMap.getAllGarbageInfo(streamId).size() > 0) { if (streamIdToGarbageMap.containsKey(streamId)) { MultiSMREntryGarbageInfo perStreamDeduplicatedGCInfo = (MultiSMREntryGarbageInfo) streamIdToGarbageMap.get(streamId).merge(garbageMap); if (perStreamDeduplicatedGCInfo.getGarbageMap().size() > 0) { deduplicatedGCInfo.add(streamId, perStreamDeduplicatedGCInfo); } } else { deduplicatedGCInfo.add(streamId, garbageMap); this.add(streamId, garbageMap); } } }); return deduplicatedGCInfo; } else { <START> throw new RuntimeException("Different types of ISMRGarbageInfo cannot merge."); <END> } }</code><technical_language>IllegalArgumentException</technical_language>

Target:
public ISMRGarbageInfo merge(ISMRGarbageInfo other) { if (other instanceof MultiObjectSMREntryGarbageInfo) { MultiObjectSMREntryGarbageInfo deduplicatedGCInfo = new MultiObjectSMREntryGarbageInfo(); ((MultiObjectSMREntryGarbageInfo) other).getStreamIdToGarbageMap().forEach((streamId, garbageMap) -> { if (garbageMap.getAllGarbageInfo(streamId).size() > 0) { if (streamIdToGarbageMap.containsKey(streamId)) { MultiSMREntryGarbageInfo perStreamDeduplicatedGCInfo = (MultiSMREntryGarbageInfo) streamIdToGarbageMap.get(streamId).merge(garbageMap); if (perStreamDeduplicatedGCInfo.getGarbageMap().size() > 0) { deduplicatedGCInfo.add(streamId, perStreamDeduplicatedGCInfo); } } else { deduplicatedGCInfo.add(streamId, garbageMap); this.add(streamId, garbageMap); } } }); return deduplicatedGCInfo; } else { throw new IllegalArgumentException("Different types of ISMRGarbageInfo cannot merge."); } }
Source:
<code>public StramLocalCluster(LogicalPlan dag) throws IOException, ClassNotFoundException { dag.validate(); cloneLogicalPlan(dag); final Path pathUri; String appPath = dag.getAttributes().get(LogicalPlan.APPLICATION_PATH); if (appPath == null) { pathUri = new Path(DEFAULT_APP_DIR.toURI()); dag.getAttributes().put(LogicalPlan.APPLICATION_PATH, pathUri.toString()); } else { Path tmp = new Path(appPath); if (!tmp.isAbsolute()) { pathUri = new Path(new File(appPath).toURI()); } else { pathUri = tmp; } } try { FileContext.getLocalFSFileContext().delete(pathUri, true); } catch (IllegalArgumentException e) { throw e; } catch (IOException e) { throw new RuntimeException("could not cleanup test dir", e); } dag.getAttributes().put(LogicalPlan.APPLICATION_ID, "app_local_" + System.currentTimeMillis()); if (dag.getAttributes().get(OperatorContext.STORAGE_AGENT) == null) { dag.setAttribute(OperatorContext.STORAGE_AGENT, new AsyncFSStorageAgent(new Path(pathUri, LogicalPlan.SUBDIR_CHECKPOINTS).toString(), null)); } <START> ifNeededStartBufferServer(); <END> this.dnmgr = new StreamingContainerManager(dag); this.umbilical = new UmbilicalProtocolLocalImpl(); }</code><technical_language>is necessary move this call here</technical_language>

Target:
public StramLocalCluster(LogicalPlan dag) throws IOException, ClassNotFoundException { dag.validate(); cloneLogicalPlan(dag); final Path pathUri; String appPath = dag.getAttributes().get(LogicalPlan.APPLICATION_PATH); if (appPath == null) { pathUri = new Path(DEFAULT_APP_DIR.toURI()); dag.getAttributes().put(LogicalPlan.APPLICATION_PATH, pathUri.toString()); } else { Path tmp = new Path(appPath); if (!tmp.isAbsolute()) { pathUri = new Path(new File(appPath).toURI()); } else { pathUri = tmp; } } try { FileContext.getLocalFSFileContext().delete(pathUri, true); } catch (IllegalArgumentException e) { throw e; } catch (IOException e) { throw new RuntimeException("could not cleanup test dir", e); } dag.getAttributes().put(LogicalPlan.APPLICATION_ID, "app_local_" + System.currentTimeMillis()); if (dag.getAttributes().get(OperatorContext.STORAGE_AGENT) == null) { dag.setAttribute(OperatorContext.STORAGE_AGENT, new AsyncFSStorageAgent(new Path(pathUri, LogicalPlan.SUBDIR_CHECKPOINTS).toString(), null)); } this.dnmgr = new StreamingContainerManager(dag); this.umbilical = new UmbilicalProtocolLocalImpl(); }
Source:
<code>protected AbstractS3ACommitter( Path outputPath, TaskAttemptContext context) throws IOException { super(outputPath, context); Preconditions.checkArgument(outputPath != null, "null output path"); Preconditions.checkArgument(context != null, "null job context"); this.jobContext = context; this.role = "Task committer " + context.getTaskAttemptID(); setConf(context.getConfiguration()); Pair<String, JobUUIDSource> id = buildJobUUID( conf, context.getJobID()); uuid = id.getLeft(); <START> uuidSource = id.getRight(); <END> LOG.info("Job UUID source {}", getUUID(), getUUIDSource().getText()); initOutput(outputPath); LOG.debug("{} instantiated for job \"{}\" ID with destination {}", role, jobName(context), jobIdString(context), outputPath); S3AFileSystem fs = getDestS3AFS(); createJobMarker = context.getConfiguration().getBoolean( CREATE_SUCCESSFUL_JOB_OUTPUT_DIR_MARKER, DEFAULT_CREATE_SUCCESSFUL_JOB_DIR_MARKER); commitOperations = new CommitOperations(fs); }</code><technical_language>Other places this. a prefix setting fields. I find helpful reading instance field is set, a local variable</technical_language>

Target:
protected AbstractS3ACommitter( Path outputPath, TaskAttemptContext context) throws IOException { super(outputPath, context); Preconditions.checkArgument(outputPath != null, "null output path"); Preconditions.checkArgument(context != null, "null job context"); this.jobContext = context; this.role = "Task committer " + context.getTaskAttemptID(); setConf(context.getConfiguration()); Pair<String, JobUUIDSource> id = buildJobUUID( conf, context.getJobID()); this.uuid = id.getLeft(); this.uuidSource = id.getRight(); LOG.info("Job UUID source {}", getUUID(), getUUIDSource().getText()); initOutput(outputPath); LOG.debug("{} instantiated for job \"{}\" ID with destination {}", role, jobName(context), jobIdString(context), outputPath); S3AFileSystem fs = getDestS3AFS(); this.createJobMarker = context.getConfiguration().getBoolean( CREATE_SUCCESSFUL_JOB_OUTPUT_DIR_MARKER, DEFAULT_CREATE_SUCCESSFUL_JOB_DIR_MARKER); this.commitOperations = new CommitOperations(fs); }
Source:
<code>private String sendMessage(String data, int timeout) throws IOException { logger.debug("Sent request...'{}'", data); out.write(data.getBytes()); out.flush(); String resp = ""; long startTime = System.currentTimeMillis(); long elapsedTime = 0; while (elapsedTime < timeout) { int availableBytes = in.available(); if (availableBytes > 0) { byte[] tmpData = new byte[availableBytes]; int readBytes = in.read(tmpData, 0, availableBytes); resp = resp.concat(new String(tmpData, 0, readBytes)); if (resp.length() > 7) { return resp; } } else { try { Thread.sleep(100); } catch (InterruptedException e) { <START> logger.warn("failed reading reesponse"); <END> } } elapsedTime = Math.abs((new Date()).getTime() - startTime); } return resp; }</code><technical_language>"response"</technical_language>

Target:
private String sendMessage(String data, int timeout) throws IOException { logger.debug("Sent request...'{}'", data); out.write(data.getBytes()); out.flush(); String resp = ""; long startTime = System.currentTimeMillis(); long elapsedTime = 0; while (elapsedTime < timeout) { int availableBytes = in.available(); if (availableBytes > 0) { byte[] tmpData = new byte[availableBytes]; int readBytes = in.read(tmpData, 0, availableBytes); resp = resp.concat(new String(tmpData, 0, readBytes)); if (resp.length() > 7) { return resp; } } else { try { Thread.sleep(100); } catch (InterruptedException e) { logger.warn("failed reading response"); } } elapsedTime = Math.abs((new Date()).getTime() - startTime); } return resp; }
Source:
<code>protected void executeQueryCommand() { List<AuthenticationProfile> profiles = AuthenticationProfileRepository.getInstance().getProfiles(); List<String> names = new ArrayList<>(profiles.size()); for (AuthenticationProfile profile : profiles) { names.add(profile.getName()); } <START> sort(names, new LoginDomainComparator(Config.<String> getValue(ConfigValues.AdminDomain))); <END> getQueryReturnValue().setReturnValue(names); }</code><technical_language>if is "internal" profile longer, if name relation ConfigValues.AdminDomain. suggest abandon idea of displaying "internal" last</technical_language>

Target:
protected void executeQueryCommand() { List<AuthenticationProfile> profiles = AuthenticationProfileRepository.getInstance().getProfiles(); List<String> names = new ArrayList<>(profiles.size()); for (AuthenticationProfile profile : profiles) { names.add(profile.getName()); } sort(names); getQueryReturnValue().setReturnValue(names); }
Source:
<code>private void setDSTPointBytes() { <START> int xValue = (relativeX < 0 ? DSTFileConstants.CONVERSION_TABLE[(relativeX * (-1)) + 121] <END> : DSTFileConstants.CONVERSION_TABLE[relativeX]); int yValue = (relativeY < 0 ? DSTFileConstants.CONVERSION_TABLE[(relativeY * (-1)) + 121] : DSTFileConstants.CONVERSION_TABLE[relativeY]); char yPart = (char) ((((yValue & 0x1) << 3) | ((yValue & 0x2) << 1) | ((yValue & 0x10) >>> 3) | ((yValue & 0x20) >>> 5)) << 4); char xPart = (char) (((xValue >>> 2) & 0xC) | (xValue & 0x3)); dstPointBytes[0] = (byte) (yPart | xPart); yPart = (char) ((((yValue & 0x4) << 1) | ((yValue & 0x8) >>> 1) | ((yValue & 0x40) >>> 5) | ((yValue & 0x80) >>> 7)) << 4); xPart = (char) (((xValue >>> 4) & 0xC) | ((xValue >>> 2) & 0x3)); dstPointBytes[1] = (byte) (yPart | xPart); yPart = (char) (((yValue >>> 5) & 0x10) | ((yValue >>> 3) & 0x20)); xPart = (char) ((xValue >>> 6) & 0xC); dstPointBytes[2] = (byte) (dstPointBytes[2] | yPart | xPart); }</code><technical_language>please create a helper function for this</technical_language>

Target:
private byte[] setDSTPointBytes() { byte[] dstPointBytes = new byte[] {0, 0, (char) 0x03}; int xValue = mapToConversionTable(relativeX); int yValue = mapToConversionTable(relativeY); char yPart = (char) ((((yValue & 0x1) << 3) | ((yValue & 0x2) << 1) | ((yValue & 0x10) >>> 3) | ((yValue & 0x20) >>> 5)) << 4); char xPart = (char) (((xValue >>> 2) & 0xC) | (xValue & 0x3)); dstPointBytes[0] = (byte) (yPart | xPart); yPart = (char) ((((yValue & 0x4) << 1) | ((yValue & 0x8) >>> 1) | ((yValue & 0x40) >>> 5) | ((yValue & 0x80) >>> 7)) << 4); xPart = (char) (((xValue >>> 4) & 0xC) | ((xValue >>> 2) & 0x3)); dstPointBytes[1] = (byte) (yPart | xPart); yPart = (char) (((yValue >>> 5) & 0x10) | ((yValue >>> 3) & 0x20)); xPart = (char) ((xValue >>> 6) & 0xC); dstPointBytes[2] = (byte) (dstPointBytes[2] | yPart | xPart); if (jumpPoint) { dstPointBytes[2] = (byte) (dstPointBytes[2] | (0x1 << 7)); } if (colorChangePoint) { dstPointBytes[2] = (byte) ((char) dstPointBytes[2] | (0x1 << 6) | (0x1 << 7)); } return dstPointBytes; }
Source:
<code>public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.archived: <START> if (item.getTitle().equals(getString(R.string.menu_option_archived))) { <END> refresh(true); isarchivedvisible = true; }else if (item.getTitle().equals(getString(R.string.menu_option_unread))) { isarchivedvisible = false; refresh(false); } return true; default: return super.onOptionsItemSelected(item); } }</code><technical_language>call NotificationActivity.startYourself(this, "read"); This is Wikipedia app it. opens a new activity</technical_language>

Target:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.archived: if (item.getTitle().equals(getString(R.string.menu_option_archived))) { NotificationActivity.startYourself(NotificationActivity.this, "read"); }else if (item.getTitle().equals(getString(R.string.menu_option_unread))) { onBackPressed(); } return true; default: return super.onOptionsItemSelected(item); } }
Source:
<code>private List<GlusterServerInfo> getGlusterPeers(Guid upServerId) { List<GlusterServerInfo> glusterServers = new ArrayList<GlusterServerInfo>(); <START> VDSReturnValue returnValue = Backend.getInstance() <END> .getResourceManager() .RunVdsCommand(VDSCommandType.GlusterServersList, new VdsIdVDSCommandParametersBase(upServerId)); if (!returnValue.getSucceeded()) { getReturnValue().getFault().setError(returnValue.getVdsError().getCode()); getReturnValue().getFault().setMessage(returnValue.getVdsError().getMessage()); AuditLogDirector.log(new AuditLogableBase(upServerId), AuditLogType.GLUSTER_SERVERS_LIST_FAILED); } else { glusterServers = (List<GlusterServerInfo>) returnValue.getReturnValue(); } return glusterServers; }</code><technical_language>runVdsCommand() instead of Backend.getInstance().getResourceManager().RunVdsCommand()</technical_language>

Target:
private List<GlusterServerInfo> getGlusterPeers(Guid upServerId) { List<GlusterServerInfo> glusterServers = new ArrayList<GlusterServerInfo>(); VDSReturnValue returnValue = runVdsCommand(VDSCommandType.GlusterServersList, new VdsIdVDSCommandParametersBase(upServerId)); if (!returnValue.getSucceeded()) { getReturnValue().getFault().setError(returnValue.getVdsError().getCode()); getReturnValue().getFault().setMessage(returnValue.getVdsError().getMessage()); AuditLogDirector.log(new AuditLogableBase(upServerId), AuditLogType.GLUSTER_SERVERS_LIST_FAILED); } else { glusterServers = (List<GlusterServerInfo>) returnValue.getReturnValue(); } return glusterServers; }
Source:
<code>private LanguagesAdapter(List<String> languages, WikipediaApp app) { this.originalLanguages = languages; <START> this.languages = languages; <END> this.app = app; }</code><technical_language>A defensive copy of list safer IMO</technical_language>

Target:
private LanguagesAdapter(List<String> languages, WikipediaApp app) { this.originalLanguages = languages; this.languages = new ArrayList<String>(); this.languages.addAll(languages); this.app = app; }
Source:
<code>protected void setUp() throws Exception { loopbackInterface = NetworkInterface.getByInetAddress(InetAddress.getLoopbackAddress()); assertNotNull(loopbackInterface); assertTrue(loopbackInterface.isLoopback()); assertFalse(loopbackInterface.supportsMulticast()); Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements() && (ipv4NetworkInterface == null || ipv6NetworkInterface == null)) { NetworkInterface nextInterface = interfaces.nextElement(); if (willWorkForMulticast(nextInterface)) { Enumeration<InetAddress> addresses = nextInterface.getInetAddresses(); while (addresses.hasMoreElements()) { final InetAddress nextAddress = addresses.nextElement(); if (nextAddress instanceof Inet6Address && ipv6NetworkInterface == null) { ipv6NetworkInterface = nextInterface; } else if (nextAddress instanceof Inet4Address && ipv4NetworkInterface == null) { ipv4NetworkInterface = nextInterface; } } } } <START> if (ipv4NetworkInterface <END> == null || ipv6NetworkInterface == null) { fail("Test environment must have at least one environment capable of multicast"); } }</code><technical_language>Message reflect condition</technical_language>

Target:
protected void setUp() throws Exception { loopbackInterface = NetworkInterface.getByInetAddress(InetAddress.getLoopbackAddress()); assertNotNull(loopbackInterface); assertTrue(loopbackInterface.isLoopback()); assertFalse(loopbackInterface.supportsMulticast()); Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); supportsMulticast = Boolean.parseBoolean( System.getProperty("android.cts.device.multicast", "true")); if (!supportsMulticast) { return; } while (interfaces.hasMoreElements() && (ipv4NetworkInterface == null || ipv6NetworkInterface == null)) { NetworkInterface nextInterface = interfaces.nextElement(); if (willWorkForMulticast(nextInterface)) { Enumeration<InetAddress> addresses = nextInterface.getInetAddresses(); while (addresses.hasMoreElements()) { final InetAddress nextAddress = addresses.nextElement(); if (nextAddress instanceof Inet6Address && ipv6NetworkInterface == null) { ipv6NetworkInterface = nextInterface; } else if (nextAddress instanceof Inet4Address && ipv4NetworkInterface == null) { ipv4NetworkInterface = nextInterface; } } } } if (ipv4NetworkInterface == null) { fail("Test environment must have at least one network interface capable of IPv4" + " multicast"); } if (ipv6NetworkInterface == null) { fail("Test environment must have at least one network interface capable of IPv6" + " multicast"); } }
Source:
<code>JSONObj list(@PathVariable String wsName, @RequestParam(value="sort", required=false) String sort, @RequestParam(value="filter", required=false) String textFilter, HttpServletRequest req) { JSONObj obj = new JSONObj(); Catalog cat = geoServer.getCatalog(); if ("default".equals(wsName)) { WorkspaceInfo def = cat.getDefaultWorkspace(); if (def != null) { wsName = def.getName(); } } Filter filter = equal("resource.namespace.prefix", wsName); if (textFilter != null) { filter = Predicates.and( <START> equal("resource.namespace.prefix", wsName), <END> Predicates.fullTextSearch(textFilter)); } Integer total = cat.count(LayerInfo.class, filter); Integer page = page(req); Integer count = count(req); SortBy sortBy = null; if (sort != null) { String[] sortArr = sort.split(":", 2); if (sortArr.length == 2) { if (sortArr[1].equals("asc")) { sortBy = Predicates.asc(sortArr[0]); } else if (sortArr[1].equals("desc")) { sortBy = Predicates.desc(sortArr[0]); } else { throw new BadRequestException("Sort order must be \"asc\" or \"desc\""); } } else { sortBy = Predicates.asc(sortArr[0]); } } obj.put("total", total); obj.put("page", page != null ? page : 0); obj.put("count", Math.min(total, count != null ? count : total)); JSONArr arr = obj.putArray("layers"); try ( CloseableIterator<LayerInfo> it = cat.list(LayerInfo.class, filter, offset(req), count, sortBy); ) { while (it.hasNext()) { IO.layer(arr.addObject(), it.next()); } } return obj; }</code><technical_language>I this line be: filter = Predicates.and(filter, Predicates.fullTextSearch(textFilter))</technical_language>

Target:
JSONObj list(@PathVariable String wsName, @RequestParam(value="sort", required=false) String sort, @RequestParam(value="filter", required=false) String textFilter, HttpServletRequest req) { JSONObj obj = new JSONObj(); Catalog cat = geoServer.getCatalog(); if ("default".equals(wsName)) { WorkspaceInfo def = cat.getDefaultWorkspace(); if (def != null) { wsName = def.getName(); } } Filter filter = equal("resource.namespace.prefix", wsName); if (textFilter != null) { filter = Predicates.and(filter, Predicates.fullTextSearch(textFilter)); } Integer total = cat.count(LayerInfo.class, filter); Integer page = page(req); Integer count = count(req); SortBy sortBy = null; if (sort != null) { String[] sortArr = sort.split(":", 2); if (sortArr.length == 2) { if (sortArr[1].equals("asc")) { sortBy = Predicates.asc(sortArr[0]); } else if (sortArr[1].equals("desc")) { sortBy = Predicates.desc(sortArr[0]); } else { throw new BadRequestException("Sort order must be \"asc\" or \"desc\""); } } else { sortBy = Predicates.asc(sortArr[0]); } } obj.put("total", total); obj.put("page", page != null ? page : 0); obj.put("count", Math.min(total, count != null ? count : total)); JSONArr arr = obj.putArray("layers"); try ( CloseableIterator<LayerInfo> it = cat.list(LayerInfo.class, filter, offset(req), count, sortBy); ) { while (it.hasNext()) { IO.layer(arr.addObject(), it.next()); } } return obj; }