auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static boolean areAllUnitsSameType(Vector<Unit> units, int unitType) { <START> double firstUnitWeight = units.get(0).getEntity() != null ? units.get(0).getEntity().getWeight() : 0; <END> boolean light = firstUnitWeight > 0 && firstUnitWeight <= 50; boolean heavy = firstUnitWeight > 50 && firstUnitWeight <= 100; boolean superheavy = firstUnitWeight > 100 && firstUnitWeight <= 200; for (Unit unit : units) { if (unit.getEntity() == null) { continue; } if (unitType == UnitType.TANK || unitType == UnitType.VTOL || unitType == UnitType.NAVAL) { if (light && unit.getEntity().getWeight() > 50) { return false; } if (heavy && (unit.getEntity().getWeight() <= 50 || unit.getEntity().getWeight() > 100)) { return false; } if (superheavy && (unit.getEntity().getWeight() <= 100 || unit.getEntity().getWeight() > 200)) { return false; } } if (unit.getEntity().getUnitType() != unitType) { return false; } } return true; }</code><technical_language>This exit early if units is empty</technical_language>

Target:
public static boolean areAllUnitsSameType(Vector<Unit> units, int unitType) { if (units.isEmpty()) { return false; } double firstUnitWeight = units.get(0).getEntity() != null ? units.get(0).getEntity().getWeight() : 0; boolean light = firstUnitWeight > 0 && firstUnitWeight <= 50; boolean heavy = firstUnitWeight > 50 && firstUnitWeight <= 100; boolean superheavy = firstUnitWeight > 100 && firstUnitWeight <= 200; for (Unit unit : units) { if (unit.getEntity() == null) { continue; } if (unitType == UnitType.TANK || unitType == UnitType.VTOL || unitType == UnitType.NAVAL) { if (light && unit.getEntity().getWeight() > 50) { return false; } if (heavy && (unit.getEntity().getWeight() <= 50 || unit.getEntity().getWeight() > 100)) { return false; } if (superheavy && (unit.getEntity().getWeight() <= 100 || unit.getEntity().getWeight() > 200)) { return false; } } if (unit.getEntity().getUnitType() != unitType) { return false; } } return true; }
Source:
<code>protected void onExportToCsv() { <START> GWT.log(this.toString() + "onExportToCsv"); <END> scenarioSimulationEditorWrapper.onExportToCsv(getExportCallBack(), new ScenarioSimulationHasBusyIndicatorDefaultErrorCallback(view), context.getStatus().getSimulation()); }</code><technical_language>Is this log necessary</technical_language>

Target:
protected void onExportToCsv() { scenarioSimulationEditorWrapper.onExportToCsv(getExportCallBack(), new ScenarioSimulationHasBusyIndicatorDefaultErrorCallback(view), context.getStatus().getSimulation()); }
Source:
<code>public void deleteFeedbackResponseComment(String commentIdSuffix) { WebElement commentRow = browser.driver.findElement(By.id("responseCommentRow" + commentIdSuffix)); final WebElement deleteCommentButton = <START> commentRow.findElement(By.tagName("div")).findElement(By.id("commentdelete" + commentIdSuffix)); <END> click(deleteCommentButton); waitForConfirmationModalAndClickOk(); }</code><technical_language>id is unique element in a HTML page. Therefore, is need a chain locate it. Check if similar case in PR</technical_language>

Target:
public void deleteFeedbackResponseComment(String commentIdSuffix) { WebElement deleteCommentButton = browser.driver.findElement(By.id("commentdelete" + commentIdSuffix)); click(deleteCommentButton); waitForConfirmationModalAndClickOk(); }
Source:
<code>public ConstrainedTerm(Term term, ConjunctiveFormula constraint, TermContext context) { this.data = new Data(term, constraint); <START> this.context = context.fork(); <END> }</code><technical_language>creating new contexts here</technical_language>

Target:
public ConstrainedTerm(Term term, ConjunctiveFormula constraint, TermContext context) { this.data = new Data(term, constraint); this.context = context; }
Source:
<code>public InMemoryObservationStore(NetworkConfig config) { <START> if (LOGGER.isInfoEnabled()) { <END> int healthStatusInterval = config.getInt(NetworkConfig.Keys.HEALTH_STATUS_INTERVAL, 60); ScheduledExecutorService scheduler = Executors .newSingleThreadScheduledExecutor(new DaemonThreadFactory("ObservationStore")); scheduler.scheduleAtFixedRate(new Runnable() { @Override public void run() { if (enableStatus) { LOGGER.info("{} observes", map.size()); Iterator<Token> iterator = map.keySet().iterator(); int max = 5; while (iterator.hasNext()) { LOGGER.info(" observe {}", iterator.next()); --max; if (max == 0) { break; } } } } }, healthStatusInterval, healthStatusInterval, TimeUnit.SECONDS); } }</code><technical_language>INFO of adequate production log levels FMPOV. do prevent excessive logging in this case? a flag in NetworkConfig for enabling/disabling this more guarding log level</technical_language>

Target:
public InMemoryObservationStore(NetworkConfig config) { int healthStatusInterval = config.getInt(NetworkConfig.Keys.HEALTH_STATUS_INTERVAL, 60); if (healthStatusInterval > 0 && LOGGER.isInfoEnabled()) { ScheduledExecutorService scheduler = Executors .newSingleThreadScheduledExecutor(new DaemonThreadFactory("ObservationStore")); scheduler.scheduleAtFixedRate(new Runnable() { @Override public void run() { if (enableStatus) { LOGGER.info("{} observes", map.size()); Iterator<Token> iterator = map.keySet().iterator(); int max = 5; while (iterator.hasNext()) { LOGGER.info(" observe {}", iterator.next()); --max; if (max == 0) { break; } } } } }, healthStatusInterval, healthStatusInterval, TimeUnit.SECONDS); } }
Source:
<code>public void setOldClusterVersionOfSnapshotWithMemory(VM vm) { if (!isVMWithMemoryCompatible(vm)) { Version originalClusterVersion = vm.getClusterCompatibilityVersionOrigin(); originalClusterVersion = (originalClusterVersion == null) ? Version.v3_6 : originalClusterVersion; <START> this.oldClusterVersionOfSnapshotWithMemory <END> = originalClusterVersion; } else { this.oldClusterVersionOfSnapshotWithMemory = null; } }</code><technical_language>Feel free ignore: Do want this there</technical_language>

Target:
public void setOldClusterVersionOfSnapshotWithMemory(VM vm) { if (!isVMWithMemoryCompatible(vm)) { Version originalClusterVersion = vm.getClusterCompatibilityVersionOrigin(); originalClusterVersion = (originalClusterVersion == null) ? Version.v3_6 : originalClusterVersion; oldClusterVersionOfSnapshotWithMemory = originalClusterVersion; } else { oldClusterVersionOfSnapshotWithMemory = null; } }
Source:
<code>private String getScoreHolderDrlFileContent( Class<? extends Score> scoreType ) { String lineSeparator = System.lineSeparator(); <START> StringBuilder contentStringBuilder = new StringBuilder(); <END> contentStringBuilder .append( "import " ).append( scoreType.getName() ).append( ";" ).append( lineSeparator ) .append( lineSeparator ) .append( " .append( lineSeparator ) .append( "global " ).append( scoreType.getSimpleName() ).append( "Holder" ).append( " scoreHolder;" ).append( lineSeparator ); return contentStringBuilder.toString(); }</code><technical_language>Soft suggestion: need a StringBuilder explicitly here, plain String concatenation slower loops, javac compiler a StringBuilder for plain String concatenation (again, loops)</technical_language>

Target:
private String getScoreHolderDrlFileContent( Class<? extends Score> scoreType ) { return String.format( "import %s;%n" + "%n" + " "%n" + "global %sHolder scoreHolder;%n", scoreType.getName(), scoreType.getSimpleName() ); }
Source:
<code>private String HTTPAuthenticate() { HttpPost httpPost; CloseableHttpResponse response; BufferedReader rd; String line; StringEntity stringEntity; String cookie = null; try { httpPost = new HttpPost(baseUrl + "/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/"); httpPost.addHeader("SOAPAction", "urn:login"); httpPost.addHeader("Content-Type", "text/xml"); String payload = "<soapenv:Envelope xmlns:soapenv=\"<LINK_1>\" " + "xmlns:aut=\"<LINK_0>" + ".org\"><soapenv:Header/><soapenv:Body><aut:login><aut:username>admin</aut:username" + "><aut:password>admin</aut:password></aut:login></soapenv:Body></soapenv:Envelope>"; stringEntity = new StringEntity(payload, "UTF-8"); stringEntity.setChunked(true); httpPost.setEntity(stringEntity); response = client.execute(httpPost); <START> rd = new BufferedReader( <END> new InputStreamReader(response.getEntity().getContent(), Charset.defaultCharset())); StringBuffer result = new StringBuffer(); while ((line = rd.readLine()) != null) { result.append(line); } int returnStart = result.indexOf("<ns:return>") + "<ns:return>".length(); int returnEnd = result.indexOf("</ns:return>"); String isLoginSuccess = result.substring(returnStart, returnEnd); if (isLoginSuccess.equals("true")) { String str = response.getHeaders("Set-Cookie")[0].toString().split(";")[0]; cookie = str.split(" ")[1]; } } catch (ClientProtocolException e) { log.error("Exception : ", e); } catch (IOException e) { log.error("Exception : ", e); } return cookie; }</code><technical_language>try resource statement auto close streams <LINK_2></technical_language>

Target:
private String HTTPAuthenticate() throws IOException { HttpPost httpPost; String line; StringEntity stringEntity; String cookie = null; try (CloseableHttpResponse response = null; BufferedReader rd = null) { httpPost = new HttpPost(baseUrl + "/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/"); httpPost.addHeader(Constants.SOAP_ACTION, Constants.SOAP_ACTION_LOGIN); httpPost.addHeader(Constants.CONTENT_TYPE, Constants.XML_CONTENT_TYPE); String payload = "<soapenv:Envelope xmlns:soapenv=\"<LINK_1>\" " + "xmlns:aut=\"<LINK_0>" + ".org\"><soapenv:Header/><soapenv:Body><aut:login><aut:username>admin</aut:username" + "><aut:password>admin</aut:password></aut:login></soapenv:Body></soapenv:Envelope>"; stringEntity = new StringEntity(payload, Constants.UTF_8_ENCODING); stringEntity.setChunked(true); httpPost.setEntity(stringEntity); response = client.execute(httpPost); rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), Charset.defaultCharset())); StringBuffer result = new StringBuffer(); while ((line = rd.readLine()) != null) { result.append(line); } int returnStart = result.indexOf("<ns:return>") + "<ns:return>".length(); int returnEnd = result.indexOf("</ns:return>"); String isLoginSuccess = result.substring(returnStart, returnEnd); if (isLoginSuccess.equals("true")) { String str = response.getHeaders("Set-Cookie")[0].toString().split(";")[0]; cookie = str.split(" ")[1]; } } catch (ClientProtocolException e) { log.error(Constants.CLIENT_PROTOCOL_EX, e); } return cookie; }
Source:
<code>public LockServerOptions getLockServerOptions() { LockServerOptions options = new LockServerOptions() { private static final long serialVersionUID = 0x3ffa5b160e838725l; @Override public boolean isStandaloneServer() { return isStandaloneServer; } @Override public TimeDuration getMaxAllowedLockTimeout() { return maxAllowedLockTimeout; } @Override public TimeDuration getMaxAllowedClockDrift() { return maxAllowedClockDrift; } @Override public int getRandomBitCount() { return randomBitCount; } }; if (log.isTraceEnabled()) { <START> log.trace(".getLockServerOptions() returns {}", options); <END> } return options; }</code><technical_language>Mention this option is replaced a config parameter in atlas config</technical_language>

Target:
public LockServerOptions getLockServerOptions() { LockServerOptions options = new LockServerOptions() { private static final long serialVersionUID = 0x3ffa5b160e838725l; @Override public boolean isStandaloneServer() { return isStandaloneServer; } @Override public TimeDuration getMaxAllowedLockTimeout() { return maxAllowedLockTimeout; } @Override public TimeDuration getMaxAllowedClockDrift() { return maxAllowedClockDrift; } @Override public int getRandomBitCount() { return RANDOM_BIT_COUNT; } }; if (log.isTraceEnabled()) { log.trace(".getLockServerOptions() returns {}", options); } return options; }
Source:
<code>private void performCheckOnSpecificClientUnsafe(Client client) { for (int attempt = 1; attempt <= REQUIRED_CONSECUTIVE_VIOLATIONS_BEFORE_FAIL; attempt++) { long numberOfNodesServingTimestamps = timeLockActivityCheckers.stream() <START> .map(timeLockActivityChecker -> <END> timeLockActivityChecker.isThisNodeActivelyServingTimestampsForClient(client.value())) .filter(x -> x) .count(); if (numberOfNodesServingTimestamps <= 1) { log.info("We don't think services were simultaneously serving timestamps for client {}", SafeArg.of("client", client)); return; } if (attempt < REQUIRED_CONSECUTIVE_VIOLATIONS_BEFORE_FAIL) { log.info("We observed on attempt of that multiple services were serving timestamps. We'll try" + " again in ms to see if this remains the case.", SafeArg.of("attemptNumber", attempt), SafeArg.of("maximumAttempts", REQUIRED_CONSECUTIVE_VIOLATIONS_BEFORE_FAIL), SafeArg.of("backoffMillis", BACKOFF.toMillis())); Uninterruptibles.sleepUninterruptibly(BACKOFF.toMillis(), TimeUnit.MILLISECONDS); } else { failureMechanism.accept(client.value()); } } }</code><technical_language>filter instead of map + filter</technical_language>

Target:
private void performCheckOnSpecificClientUnsafe(Client client) { long timestampBound = Long.MIN_VALUE; for (int attempt = 1; attempt <= REQUIRED_ATTEMPTS_BEFORE_GIVING_UP; attempt++) { List<Long> timestamps = timeLockActivityCheckers.stream() .map(timeLockActivityChecker -> timeLockActivityChecker.getFreshTimestampFromNodeForClient(client.value())) .filter(OptionalLong::isPresent) .map(OptionalLong::getAsLong) .collect(Collectors.toList()); if (timestamps.size() <= 1) { log.info("We don't think services were simultaneously serving timestamps for client {}", SafeArg.of("client", client)); return; } if (!Ordering.natural().isStrictlyOrdered(timestamps) || timestamps.get(0) <= timestampBound) { failureMechanism.accept(client.value()); return; } timestampBound = timestamps.get(timestamps.size() - 1); log.info("We observed on attempt that multiple services were serving timestamps, but the timestamps were" + " served in an increasing order. We'll try again in ms to see if this remains the" + " case.", SafeArg.of("backoffMillis", backoff.toMillis())); Uninterruptibles.sleepUninterruptibly(backoff.toMillis(), TimeUnit.MILLISECONDS); } log.warn("We observed multiple services apparently serving timestamps simultaneously, but the timestamps" + " were consistently served in increasing order."); }
Source:
<code>public UserOptions build() { UserOptions options = new UserOptions(); if ( limit != null ) { options.queryParameters.put("numResults", String.valueOf(limit)); limit = null; } if ( page != null ) { options.queryParameters.put("page", String.valueOf(page)); <START> } <END> return addFilterOptions(options); }</code><technical_language>avoid if statements simply declaring UserOptions instance in builder directly, modifying that: public Builder { private final UserOptions options = new UserOptions(); public Builder page(int page) { options.queryParameters.put("page", String.valueOf(page)); return this; } ... public UserOptions build() { return addFilterOptions(options); } }</technical_language>

Target:
public UserOptions build() { return addFilterOptions(this.options); }
Source:
<code><START> public List<ActivationKeyDTO> ownerActivationKeys( <END> @PathParam("owner_key") @Verify(Owner.class) String ownerKey, @QueryParam("name") String keyName) { Owner owner = findOwner(ownerKey); if (keyName == null) { List<ActivationKey> keys = this.activationKeyCurator.listByOwner(owner); List<ActivationKeyDTO> keyDTOs = new ArrayList<ActivationKeyDTO>(); for (ActivationKey key : keys) { keyDTOs.add(translator.translate(key, ActivationKeyDTO.class)); } return keyDTOs; } else { List<ActivationKeyDTO> results = new ArrayList<ActivationKeyDTO>(); results.add(translator.translate( activationKeyCurator.lookupForOwner(keyName, owner), ActivationKeyDTO.class)); return results; } }</code><technical_language>this opportunity upgrade this CandlepinQuery framework. need update ActivationKeyCurator.listByOwner, able clean this method substantially while some added benefits paging faster iteration</technical_language>

Target:
public CandlepinQuery<ActivationKeyDTO> ownerActivationKeys( @PathParam("owner_key") @Verify(Owner.class) String ownerKey, @QueryParam("name") String keyName) { Owner owner = findOwner(ownerKey); CandlepinQuery<ActivationKey> keys = this.activationKeyCurator.listByOwner(owner, keyName); return translator.translateQuery(keys, ActivationKeyDTO.class); }
Source:
<code>public void testInitialNamedDeployments() { final String urlSubPathToWebApp = APP_NAME; final String urlSubPathToPageToQuery = ""; LOG.info("test=testInitialNamedDeployments; entity="+entity+"; app="+entity.getApplication()); Entities.start(entity.getApplication(), ImmutableList.of(loc)); <START> Asserts.succeedsEventually(MutableMap.of("timeout", Duration.minutes(2)), new Runnable() { <END> public void run() { String url = Urls.mergePaths(entity.getAttribute(WebAppService.ROOT_URL), urlSubPathToWebApp, urlSubPathToPageToQuery); HttpTestUtils.assertHttpStatusCodeEquals(url, 200); }}); }</code><technical_language>Is timeout changed purpose minutes</technical_language>

Target:
public void testInitialNamedDeployments() { final String urlSubPathToWebApp = APP_NAME; final String urlSubPathToPageToQuery = ""; LOG.info("test=testInitialNamedDeployments; entity="+entity+"; app="+entity.getApplication()); Entities.start(entity.getApplication(), ImmutableList.of(loc)); Asserts.succeedsEventually(MutableMap.of("timeout", Duration.minutes(1)), new Runnable() { public void run() { String url = Urls.mergePaths(entity.getAttribute(WebAppService.ROOT_URL), urlSubPathToWebApp, urlSubPathToPageToQuery); HttpTestUtils.assertHttpStatusCodeEquals(url, 200); }}); }
Source:
<code>public ResponseEntity<?> readTicketTypes() { Collection<TicketType> ticketTypes = ticketService.getAllTicketTypes(); <START> return createResponseEntity(HttpStatus.OK, "TicketTypes successfully retrieved.", ticketTypes); <END> }</code><technical_language>a collection here, return those. need for a wrapping response entity</technical_language>

Target:
public Collection<TicketType> readTicketTypes() { return ticketService.getAllTicketTypes(); }
Source:
<code>private void doTheTest(UserGroup g0) { String s = MARSHALER.marshal(g0); UserGroup ug = MARSHALER.unmarshal(s); <START> System.out.println(g0); <END> System.out.println(ug); System.out.println(s); assertTrue(g0.equals(ug)); }</code><technical_language>Remove this</technical_language>

Target:
private void doTheTest(UserGroup g0) { String s = MARSHALER.marshal(g0); UserGroup ug = MARSHALER.unmarshal(s); assertTrue(g0.equals(ug)); }
Source:
<code>public void registerModuleMusic(String shipName) { <START> Set<ResourceUrn> configUrnList = Assets.getAssetHelper().list(Json.class, "[a-zA-Z]*:playerSpawnConfig"); <END> for (ResourceUrn configUrn : configUrnList) { Json json = Assets.getJson(configUrn.toString()); JSONObject rootNode = json.getJsonValue(); if (rootNode.keySet().contains(shipName) && rootNode.get(shipName) instanceof JSONObject) { JSONObject shipNode = rootNode.getJSONObject(shipName); String moduleName = shipNode.getString("hull").split(":")[0]; Json musicJson; try { musicJson = Assets.getJson(moduleName + ":musicConfig"); } catch (RuntimeException e) { logger.warn("Music config not found for module " + moduleName + ":musicConfig"); return; } MusicConfig musicConfig = MusicConfig.load(moduleName, musicJson.getJsonValue()); Map<String, List<String>> musicMap = musicConfig.getMusicMap(); for (String music : musicMap.get(MENU_MUSIC_SET)) { registerMusic(MENU_MUSIC_SET, music); } for (String music : musicMap.get(GAME_MUSIC_SET)) { registerMusic(GAME_MUSIC_SET, music); } } json.dispose(); } }</code><technical_language>wut Okay, I fail understand this. retrieving spawnConfigs, instead of retrieving musicConfigs soundConfigs</technical_language>

Target:
public void registerModuleMusic(String shipName) { Set<ResourceUrn> configUrnList = Assets.getAssetHelper().list(Json.class, "[a-zA-Z]*:playerSpawnConfig"); for (ResourceUrn configUrn : configUrnList) { Json json = Assets.getJson(configUrn.toString()); JSONObject rootNode = json.getJsonValue(); if (rootNode.keySet().contains(shipName) && rootNode.get(shipName) instanceof JSONObject) { String moduleName = configUrn.toString().split(":")[0]; Json musicJson; try { musicJson = Assets.getJson(moduleName + ":musicConfig"); } catch (RuntimeException e) { logger.warn("Music config not found for module " + moduleName + ":musicConfig"); return; } MusicConfig musicConfig = MusicConfig.load(moduleName, musicJson.getJsonValue()); Map<String, List<String>> musicMap = musicConfig.getMusicMap(); this.musicMap.remove(MENU_MUSIC_SET); for (String music : musicMap.get(MENU_MUSIC_SET)) { registerMusic(MENU_MUSIC_SET, music); } for (String music : musicMap.get(GAME_MUSIC_SET)) { registerMusic(GAME_MUSIC_SET, music); logger.info("Registered " + music); } } json.dispose(); } registerMusic(GAME_MUSIC_SET, "engine:cimmerianDawn"); registerMusic(GAME_MUSIC_SET, "engine:intoTheDark"); registerMusic(GAME_MUSIC_SET, "engine:spaceTheatre"); }
Source:
<code><START> public Response add(Command entity) throws RecoverablePduException, UnrecoverablePduException, <END> SmppTimeoutException, SmppChannelException, InterruptedException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkDevice(getUserId(), entity.getDeviceId()); Context.getDeviceManager().sendCommand(entity); return Response.ok(entity).build(); }</code><technical_language>declare generic exception here</technical_language>

Target:
public Response add(Command entity) throws Exception { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkDevice(getUserId(), entity.getDeviceId()); Context.getDeviceManager().sendCommand(entity); return Response.ok(entity).build(); }
Source:
<code>public Stream<EventInformation> loadEventLogFileAsStream(File eventLogFile) throws IOException { <START> List<String> lines = FileUtils.readLines(eventLogFile, ENCODING_UTF_8); <END> return lines.stream().map(line -> { try { return (EventInformation) objectMapper.readValue(line, new TypeReference<EventInformation>() {}); } catch (IOException e) { throw new RuntimeException(e); } }); }</code><technical_language>java.nio.Files.lines method returns a stream dont want read entire file here</technical_language>

Target:
public Stream<EventInformation> loadEventLogFileAsStream(File eventLogFile) throws IOException { Stream<String> lines = Files.lines(eventLogFile.toPath(), ENCODING_UTF_8); return lines.map(line -> { try { return (EventInformation) objectMapper.readValue(line, new TypeReference<EventInformation>() {}); } catch (IOException e) { throw new RuntimeException(e); } }); }
Source:
<code>public LookupExtractionFn( @JsonProperty("lookup") final LookupExtractor lookup, @JsonProperty("retainMissingValue") final boolean retainMissingValue, @Nullable @JsonProperty("replaceMissingValueWith") final String replaceMissingValueWith, @JsonProperty("injective") final boolean injective ) { super( new Function<String, String>() { @Nullable @Override public String apply(@Nullable String input) { if (Strings.isNullOrEmpty(input)) { <START> return null; <END> } return lookup.apply(input); } }, retainMissingValue, replaceMissingValueWith, injective ); this.lookup = lookup; }</code><technical_language>this is Strings.emptyToNull, no</technical_language>

Target:
public LookupExtractionFn( @JsonProperty("lookup") final LookupExtractor lookup, @JsonProperty("retainMissingValue") final boolean retainMissingValue, @Nullable @JsonProperty("replaceMissingValueWith") final String replaceMissingValueWith, @JsonProperty("injective") final boolean injective ) { super( new Function<String, String>() { @Nullable @Override public String apply(String input) { return lookup.apply(Strings.nullToEmpty(input)); } }, retainMissingValue, replaceMissingValueWith, injective ); this.lookup = lookup; }
Source:
<code>public void delete(HttpServletRequest request, HttpServletResponse response) throws ZebedeeException, IOException { Session session = zebedeeCmsService.getSession(request); if (!zebedeeCmsService.getPermissions().canEdit(session)) { logInfo("Forbidden request made to the collection endpoint").log(); response.setStatus(HttpStatus.SC_FORBIDDEN); return; } Path path = Path.newInstance(request); List<String> segments = path.segments(); <START> if (segments.size() < 4 || <END> !segments.get(2).equalsIgnoreCase("instances")) { logInfo("Endpoint for colletions not found").addParameter("path", path).log(); response.setStatus(HttpStatus.SC_NOT_FOUND); return; } String collectionID = segments.get(1); String instanceID = segments.get(3); logInfo("DELETE called on /collections/{collection_id}/instances/{instance_id} endpoint") .addParameter("collectionID", collectionID) .addParameter("instanceID", instanceID) .log(); datasetService.deleteInstanceFromCollection(collectionID, instanceID); }</code><technical_language>Pull this uri logic out a separate method call methods</technical_language>

Target:
public void delete(HttpServletRequest request, HttpServletResponse response) throws ZebedeeException, IOException { Session session = zebedeeCmsService.getSession(request); if (!zebedeeCmsService.getPermissions().canEdit(session)) { logInfo("Forbidden request made to the collection endpoint").log(); response.setStatus(HttpStatus.SC_FORBIDDEN); return; } Path path = Path.newInstance(request); List<String> segments = path.segments(); if (!isValidPath(response, path, segments)) return; String collectionID = segments.get(1); String instanceID = segments.get(3); logInfo("DELETE called on /collections/{collection_id}/instances/{instance_id} endpoint") .addParameter("collectionID", collectionID) .addParameter("instanceID", instanceID) .log(); datasetService.deleteInstanceFromCollection(collectionID, instanceID); }
Source:
<code>public Dataset wrap(String datasourceName, boolean shouldEmitMessage, Dataset dataset) { String datasourceURI = String.format("%s/%s", deltaServerURL, datasourceName); Id dsRef = deltaLink.newDataSource(datasourceName, datasourceURI); deltaClient.attachExternal(dsRef, dataset.asDatasetGraph()); deltaClient.connect(dsRef, SyncPolicy.TXN_W); try (DeltaConnection dConn = deltaClient.get(dsRef)) { if (shouldEmitMessage && jmsMessagingClient != null) { dConn.addListener(new DeltaLinkListener() { @Override public void append(Id dsRef, Version version, RDFPatch patch) { try { jmsMessagingClient.send(RDFPatchOps.str(patch)); } catch (JMSException e) { log.error(e, e); } } }); } else { if (jmsMessagingClient == null) { <START> log.warn("Can not emit messaged without message client"); <END> } } log.info(String.format("Wrapped dataset using datasource %s with reference %s", datasourceName, dsRef)); return dConn.getDataset(); } catch (Exception e) { log.error(e, e); throw e; } }</code><technical_language>typo -> message</technical_language>

Target:
public Dataset wrap(String datasourceName, boolean shouldEmitMessage, Dataset dataset) { String datasourceURI = String.format("%s/%s", deltaServerURL, datasourceName); Id dsRef = deltaLink.newDataSource(datasourceName, datasourceURI); deltaClient.attachExternal(dsRef, dataset.asDatasetGraph()); deltaClient.connect(dsRef, SyncPolicy.TXN_W); try (DeltaConnection dConn = deltaClient.get(dsRef)) { if (shouldEmitMessage && jmsMessagingClient != null) { dConn.addListener(new DeltaLinkListener() { @Override public void append(Id dsRef, Version version, RDFPatch patch) { try { jmsMessagingClient.send(RDFPatchOps.str(patch)); } catch (JMSException e) { log.error(e, e); } } }); } else { if (jmsMessagingClient == null) { log.warn("Can not emit message without client"); } } log.info(String.format("Wrapped dataset using datasource %s with reference %s", datasourceName, dsRef)); return dConn.getDataset(); } }
Source:
<code>public void shoudNotSaveItem_withAlreadyExistingUniqueConstraintValueButDifferentCase() { final StubItem stubItem = dataGenerator.randomStubItem(); final StubItem secondItem = dataGenerator.randomStubItem(); final String uniqueConstraintAttributeName = "stringProperty"; final String stubItemIndexAttributeValue = stubItem.getStringProperty(); <START> final ItemConfiguration stubItemConfigurationWithUniqueConstratints = new ItemConfiguration( <END> stubItem.getClass(), "stubTable"); stubItemConfigurationWithUniqueConstratints.registerUniqueConstraints(Arrays.asList(new UniqueConstraint( uniqueConstraintAttributeName))); final DatabaseSchemaHolder databaseSchemaHolderWithUniqueConstraints = databaseSchemaHolderWithItemConfiguration(stubItemConfigurationWithUniqueConstratints); final InMemoryDatabaseTemplate databaseTemplate = new InMemoryDatabaseTemplate( databaseSchemaHolderWithUniqueConstraints); databaseTemplate.create(stubItem); secondItem.setStringProperty(stubItemIndexAttributeValue.toUpperCase()); ItemConstraintViolationException actualException = null; try { databaseTemplate.create(secondItem); } catch (final ItemConstraintViolationException e) { actualException = e; } assertNotNull(actualException); assertEquals(stubItem, databaseTemplate.read(new ItemId(stubItem.getId()), stubItem.getClass())); }</code><technical_language>Typo in variable name</technical_language>

Target:
public void shoudNotSaveItem_withAlreadyExistingUniqueConstraintValueButDifferentCase() { final StubItem stubItem = dataGenerator.randomStubItem(); final StubItem secondItem = dataGenerator.randomStubItem(); final String uniqueConstraintAttributeName = "stringProperty"; final String stubItemIndexAttributeValue = stubItem.getStringProperty(); final ItemConfiguration stubItemConfigurationWithUniqueConstraints = new ItemConfiguration(stubItem.getClass(), "stubTable"); stubItemConfigurationWithUniqueConstraints.registerUniqueConstraints(Arrays.asList(new UniqueConstraint( uniqueConstraintAttributeName))); final DatabaseSchemaHolder databaseSchemaHolderWithUniqueConstraints = databaseSchemaHolderWithItemConfiguration(stubItemConfigurationWithUniqueConstraints); final InMemoryDatabaseTemplate databaseTemplate = new InMemoryDatabaseTemplate( databaseSchemaHolderWithUniqueConstraints); databaseTemplate.create(stubItem); secondItem.setStringProperty(stubItemIndexAttributeValue.toUpperCase()); ItemConstraintViolationException actualException = null; try { databaseTemplate.create(secondItem); } catch (final ItemConstraintViolationException e) { actualException = e; } assertNotNull(actualException); assertEquals(stubItem, databaseTemplate.read(new ItemId(stubItem.getId()), stubItem.getClass())); }
Source:
<code>public String update(Request req, Response res) throws IOException { AdminsConfig adminsConfigFromRequest = getEntityFromRequestBody(req); AdminsConfig adminsConfigFromServer = adminsConfigService.systemAdmins(); if (!isPutRequestFresh(req, adminsConfigFromServer)) { throw haltBecauseEtagDoesNotMatch("system_admins", ""); } HttpLocalizedOperationResult result = new HttpLocalizedOperationResult(); <START> adminsConfigService.update(SessionUtils.currentUsername(), adminsConfigFromRequest, etagFor(adminsConfigFromServer), result); <END> return handleCreateOrUpdateResponse(req, res, adminsConfigFromRequest, result); }</code><technical_language>currentUsername() instead of duplicating SessionUtils.currentUsername()</technical_language>

Target:
public String update(Request req, Response res) throws IOException { AdminsConfig adminsConfigFromRequest = getEntityFromRequestBody(req); AdminsConfig adminsConfigFromServer = adminsConfigService.systemAdmins(); if (!isPutRequestFresh(req, adminsConfigFromServer)) { throw haltBecauseEtagDoesNotMatch(); } HttpLocalizedOperationResult result = new HttpLocalizedOperationResult(); adminsConfigService.update(currentUsername(), adminsConfigFromRequest, etagFor(adminsConfigFromServer), result); return handleCreateOrUpdateResponse(req, res, adminsConfigFromRequest, result); }
Source:
<code><START> private String handleAggregationFunction(CallExpression aggregation, Map<VariableReferenceExpression, Selection> inputSelections) <END> { String prestoAggregation = aggregation.getDisplayName().toLowerCase(ENGLISH); List<RowExpression> parameters = aggregation.getArguments(); switch (prestoAggregation) { case "count": if (parameters.size() <= 1) { return format("count(%s)", parameters.isEmpty() ? "*" : inputSelections.get(getVariableReference(parameters.get(0)))); } break; default: if (UNARY_AGGREGATION_MAP.containsKey(prestoAggregation) && aggregation.getArguments().size() == 1) { return format("%s(%s)", UNARY_AGGREGATION_MAP.get(prestoAggregation), inputSelections.get(getVariableReference(parameters.get(0)))); } } throw new PrestoException(DRUID_PUSHDOWN_UNSUPPORTED_EXPRESSION, "Unsupported pushdown for Druid connector. Aggregation function:" + aggregation + " not supported"); }</code><technical_language>Move end of class</technical_language>

Target:
private String handleAggregationFunction(CallExpression aggregation, Map<VariableReferenceExpression, Selection> inputSelections) { String prestoAggregation = aggregation.getDisplayName().toLowerCase(ENGLISH); List<RowExpression> parameters = aggregation.getArguments(); if (prestoAggregation.equals("count")) { if (parameters.size() <= 1) { return format("count(%s)", parameters.isEmpty() ? "*" : inputSelections.get(getVariableReference(parameters.get(0)))); } } else if (UNARY_AGGREGATION_MAP.containsKey(prestoAggregation) && aggregation.getArguments().size() == 1) { return format("%s(%s)", UNARY_AGGREGATION_MAP.get(prestoAggregation), inputSelections.get(getVariableReference(parameters.get(0)))); } throw new PrestoException(DRUID_PUSHDOWN_UNSUPPORTED_EXPRESSION, "Unsupported pushdown for Druid connector. Aggregation function: " + aggregation + " not supported"); }
Source:
<code>public T put(HttpServletRequest request, String apiCategory, String model, ID uuid, JsonNode jsonNode) { Context context = obtainContext(); try { thisRepository.put(context, request, apiCategory, model, uuid, jsonNode); context.commit(); } catch (SQLException | AuthorizeException e) { <START> throw new RuntimeException(e.getMessage(), e); <END> } return findOne(uuid); }</code><technical_language>e.getMessage() null, this RuntimeException uninformative. Please replace e.getMessage() a more useful error message</technical_language>

Target:
public T put(HttpServletRequest request, String apiCategory, String model, ID uuid, JsonNode jsonNode) { Context context = obtainContext(); try { thisRepository.put(context, request, apiCategory, model, uuid, jsonNode); context.commit(); } catch (SQLException e) { throw new RuntimeException("Unable to update DSpace object " + model + " with id=" + uuid, e); } catch (AuthorizeException e) { throw new RuntimeException("Unable to perform PUT request as the " + "current user does not have sufficient rights", e); } return findOne(uuid); }
Source:
<code>private boolean shouldAddToRunningIntervalList(final long idealSplitLength, final long projectedSize, final double projectedSizeOfRemainingDivisions) { switch (mode) { case INTERVAL_SUBDIVISION: case BALANCING_WITHOUT_INTERVAL_SUBDIVISION: return (projectedSize <= idealSplitLength); case BALANCING_WITHOUT_INTERVAL_SUBDIVISION_WITH_OVERFLOW: return (projectedSize <= idealSplitLength || idealSplitLength < projectedSizeOfRemainingDivisions); default: <START> throw new PicardException("Unknown mode: " + mode.name()); <END> } }</code><technical_language>This default happen. structure case BALANCING_WITHOUT_INTERVAL_SUBDIVISION_WITH_OVERFLOW: return (projectedSize <= idealSplitLength || idealSplitLength < projectedSizeOfRemainingDivisions); default: return (projectedSize <= idealSplitLength);</technical_language>

Target:
private boolean shouldAddToRunningIntervalList(final long idealSplitLength, final long projectedSize, final double projectedSizeOfRemainingDivisions) { switch (mode) { case BALANCING_WITHOUT_INTERVAL_SUBDIVISION_WITH_OVERFLOW: return (projectedSize <= idealSplitLength || idealSplitLength < projectedSizeOfRemainingDivisions); default: return (projectedSize <= idealSplitLength); } }
Source:
<code>public static EndpointContext extractContext(Identity identity) { Principal peerIdentity = null; if (identity != null) { if (identity.isPSK()) { peerIdentity = new PreSharedKeyIdentity(identity.getPskIdentity()); } else if (identity.isRPK()) { peerIdentity = new RawPublicKeyIdentity(identity.getRawPublicKey()); } else if (identity.isX509()) { if (identity.getCertificates() != null) { peerIdentity = new X509CertPath(identity.getCertificates()); } else { <START> peerIdentity = new X500Principal("CN=" + identity.getX509CommonName()); <END> } } } return new AddressEndpointContext(identity.getPeerAddress(), peerIdentity); }</code><technical_language>I suggest create a separate method in X509Util create CN part</technical_language>

Target:
public static EndpointContext extractContext(Identity identity) { Principal peerIdentity = null; if (identity != null) { if (identity.isPSK()) { peerIdentity = new PreSharedKeyIdentity(identity.getPskIdentity()); } else if (identity.isRPK()) { peerIdentity = new RawPublicKeyIdentity(identity.getRawPublicKey()); } else if (identity.isX509()) { if (identity.getCertificates() != null) { peerIdentity = new X509CertPath(identity.getCertificates()); } else { peerIdentity = new X500Principal(X509Util.createDN(identity.getX509CommonName())); } } } return new AddressEndpointContext(identity.getPeerAddress(), peerIdentity); }
Source:
<code>private void setListeners() { enterPinBox.addTextChangedListener(getPinTextWatcher(continueButton)); enterPinBox.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NEXT) { <START> if (enterPinBox.getText().toString().length() != 4) { <END> Toast.makeText(CreatePinActivity.this, Localization.get("pin.length.error"), Toast.LENGTH_LONG).show(); } else { continueButton.performClick(); } return true; } return false; } }); cancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setResult(RESULT_CANCELED); finish(); } }); continueButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!inConfirmMode) { processInitialPinEntry(); } else { processConfirmPinEntry(); } } }); }</code><technical_language>@amstone326 I missing something, confusing validation logic replicated here, v. unified in continueButton.performClick() is called. Is a reason pattern is hard here</technical_language>

Target:
private void setListeners() { enterPinBox.addTextChangedListener(getPinTextWatcher(continueButton)); enterPinBox.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NEXT) { if (pinLengthIsValid(enterPinBox.getText())) { continueButton.performClick(); } else { Toast.makeText(CreatePinActivity.this, Localization.get("pin.length.error"), Toast.LENGTH_LONG).show(); } return true; } return false; } }); cancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setResult(RESULT_CANCELED); finish(); } }); continueButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!inConfirmMode) { processInitialPinEntry(); } else { processConfirmPinEntry(); } } }); }
Source:
<code>public void init(FilterConfig filterConfig) throws ServletException { String hashPrivateData = firstNonNull(filterConfig.getInitParameter("hash-private-data"), "true"); if (parseBoolean(hashPrivateData)) { <START> this.rewrite = (String s) -> sha256().hashString(s, UTF_8).toString(); <END> } else { this.rewrite = (String s) -> s; } }</code><technical_language>sha256 hashes huge... shorter? need strong crypto I logs public rotate anyway</technical_language>

Target:
public void init(FilterConfig filterConfig) throws ServletException { }
Source:
<code>public static SQLDatabase createSQLDatabase(String dbFilename, KeyProvider provider) throws IOException { boolean runningOnAndroid = Misc.isRunningOnAndroid(); boolean useSqlCipher = (provider.getEncryptionKey() != null); makeSureFileExists(dbFilename); try { if (runningOnAndroid) { if (useSqlCipher) { return (SQLDatabase) Class.forName("com.cloudant.sync.sqlite.android.AndroidSQLCipherSQLite") .getMethod("createAndroidSQLite", String.class, KeyProvider.class) .invoke(null, new Object[]{dbFilename, provider}); } else { return (SQLDatabase) Class.forName("com.cloudant.sync.sqlite.android.AndroidSQLite") .getMethod("createAndroidSQLite", String.class) .invoke(null, dbFilename); } } else { if (useSqlCipher) { <START> throw new IOException("No SQLCipher-based database implementation for Java SE"); <END> } else { return (SQLDatabase) Class.forName("com.cloudant.sync.sqlite.sqlite4java.SQLiteWrapper") .getMethod("openSQLiteWrapper", String.class) .invoke(null, dbFilename); } } } catch (Exception e) { logger.log(Level.SEVERE, "Failed to load database module", e); return null; } }</code><technical_language>is this IOException? i is type in throws clause extended throw unchecked exception</technical_language>

Target:
public static SQLDatabase createSQLDatabase(String dbFilename, KeyProvider provider) throws IOException { boolean runningOnAndroid = Misc.isRunningOnAndroid(); boolean useSqlCipher = (provider.getEncryptionKey() != null); makeSureFileExists(dbFilename); try { if (runningOnAndroid) { if (useSqlCipher) { return (SQLDatabase) Class.forName("com.cloudant.sync.sqlite.android.AndroidSQLCipherSQLite") .getMethod("createAndroidSQLite", String.class, KeyProvider.class) .invoke(null, new Object[]{dbFilename, provider}); } else { return (SQLDatabase) Class.forName("com.cloudant.sync.sqlite.android.AndroidSQLite") .getMethod("createAndroidSQLite", String.class) .invoke(null, dbFilename); } } else { if (useSqlCipher) { throw new UnsupportedOperationException("No SQLCipher-based database implementation for Java SE"); } else { return (SQLDatabase) Class.forName("com.cloudant.sync.sqlite.sqlite4java.SQLiteWrapper") .getMethod("openSQLiteWrapper", String.class) .invoke(null, dbFilename); } } } catch (Exception e) { logger.log(Level.SEVERE, "Failed to load database module", e); return null; } }
Source:
<code>public boolean isAnnotationPresent(Class<? extends Annotation> annotationType) { <START> return annotationType.equals(ActivateThreadScope.class) ? false : delegate.isAnnotationPresent(annotationType); <END> }</code><technical_language>return getAnnotation(annotationType) != null</technical_language>

Target:
public boolean isAnnotationPresent(Class<? extends Annotation> annotationType) { return getAnnotation(annotationType) != null; }
Source:
<code>protected Map<String,?> createModel(HttpServletRequest request, HttpServletResponse response) { List<ErrorModel> errors = null; <START> String errorQueryString = request.getQueryString(); <END> boolean requestContainsError = request.getParameter("error") != null || (errorQueryString != null && errorQueryString.contains("error")); if (requestContainsError) { errors = new ArrayList<>(); ErrorModel error = null; HttpSession session = request.getSession(false); if (session != null && session.getAttribute(SPRING_SECURITY_AUTHENTICATION_FAILED_KEY) != null) { error = (ErrorModel) session.getAttribute(SPRING_SECURITY_AUTHENTICATION_FAILED_KEY); } else { error = ErrorModel.builder() .setStatus(HttpStatus.SC_BAD_REQUEST).setMessage(request.getParameter("error")).build(); } errors.add(error); } return createModel(request, response, null, errors); }</code><technical_language>variable name queryString - if contains error</technical_language>

Target:
protected Map<String,?> createModel(HttpServletRequest request, HttpServletResponse response) { List<ErrorModel> errors = null; String queryString = request.getQueryString(); boolean requestContainsError = request.getParameter("error") != null || (queryString != null && queryString.contains("error")); if (requestContainsError) { errors = new ArrayList<>(); ErrorModel error = null; HttpSession session = request.getSession(false); if (session != null && session.getAttribute(SPRING_SECURITY_AUTHENTICATION_FAILED_KEY) != null) { error = (ErrorModel) session.getAttribute(SPRING_SECURITY_AUTHENTICATION_FAILED_KEY); } else { error = ErrorModel.builder() .setStatus(HttpStatus.SC_BAD_REQUEST).setMessage(request.getParameter("error")).build(); } errors.add(error); } return createModel(request, response, null, errors); }
Source:
<code>public ExtractionFn getExtractionFn() { final LookupExtractor lookupExtractor = Strings.isNullOrEmpty(name) ? this.lookup <START> : (LookupExtractor) Preconditions.checkNotNull( <END> this.lookupReferencesManager.get(name).get(), "can not find lookup with name [%s]", name ); return new LookupExtractionFn( lookupExtractor, retainMissingValue, replaceMissingValueWith, lookupExtractor.isOneToOne(), optimize ); }</code><technical_language>is this needed</technical_language>

Target:
public ExtractionFn getExtractionFn() { final LookupExtractor lookupExtractor = Strings.isNullOrEmpty(name) ? this.lookup : Preconditions.checkNotNull( lookupReferencesManager.get(name), "Lookup [%s] not found", name ).get(); return new LookupExtractionFn( lookupExtractor, retainMissingValue, replaceMissingValueWith, lookupExtractor.isOneToOne(), optimize ); }
Source:
<code>private String unescape(String s) throws URISyntaxException { if (s == null) return null; if (getScheme() == null) return s; if (s.indexOf('%') < 0) return s; <START> byte[] bytes; <END> try { bytes = s.getBytes(Constants.CHARACTER_ENCODING); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } ByteArrayOutputStream os = new ByteArrayOutputStream(); for (int i = 0; i < bytes.length; ++i) { byte c = bytes[i]; if (c == '%') { if (i + 1 > bytes.length) throw new URISyntaxException(s, JGitText.get().cannotParseGitURIish); int ascValue = Integer.parseInt(s.substring(i+1,i+3),16); os.write(ascValue); i += 2; } else os.write(c); } return RawParseUtils.decode(os.toByteArray()); }</code><technical_language>(optional) I prefer a blank line a long try/finally block this declares a new local variable</technical_language>

Target:
private static String unescape(String s) throws URISyntaxException { if (s == null) return null; if (s.indexOf('%') < 0) return s; byte[] bytes; try { bytes = s.getBytes(Constants.CHARACTER_ENCODING); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } ByteArrayOutputStream os = new ByteArrayOutputStream(bytes.length); for (int i = 0; i < bytes.length; ++i) { byte c = bytes[i]; if (c == '%') { if (i + 2 > bytes.length) throw new URISyntaxException(s, JGitText.get().cannotParseGitURIish); int ascValue = Integer.parseInt(s.substring(i + 1, i + 3), 16); os.write(ascValue); i += 2; } else os.write(c); } return RawParseUtils.decode(os.toByteArray()); }
Source:
<code>public void stackCommand(DocumentEventContext docCtx, String eventId) { DocumentModel doc = docCtx.getSourceDocument(); if (doc == null) { return; } if ("/".equals(doc.getPathAsString())) { if (log.isDebugEnabled()) { log.debug("Skip indexing command for root document"); } if (eventId.equals(DOCUMENT_SECURITY_UPDATED)) { if (log.isDebugEnabled()) { log.debug("Indexing root document children to update their permissions"); } DocumentModelList children = doc.getCoreSession().getChildren(doc.getRef()); <START> children.forEach(child -> stackCommand(doc, docCtx, eventId)); <END> } } else { stackCommand(doc, docCtx, eventId); } }</code><technical_language>For stackCommand param child doc</technical_language>

Target:
public void stackCommand(DocumentEventContext docCtx, String eventId) { DocumentModel doc = docCtx.getSourceDocument(); if (doc == null) { return; } if ("/".equals(doc.getPathAsString())) { if (log.isDebugEnabled()) { log.debug("Skip indexing command for root document"); } if (eventId.equals(DOCUMENT_SECURITY_UPDATED)) { if (log.isDebugEnabled()) { log.debug("Indexing root document children to update their permissions"); } DocumentModelList children = doc.getCoreSession().getChildren(doc.getRef()); children.forEach(child -> stackCommand(child, docCtx, eventId)); } } else { stackCommand(doc, docCtx, eventId); } }