auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void locationChanged(Item item, String oldName, String newName) { <START> if (item instanceof AbstractProject) { <END> AbstractProject p = Jenkins.getInstance().getItemByFullName(newName, AbstractProject.class); if (p != null) { RunList<? extends Run> builds = p.getBuilds(); for (Run build : builds) { Collection<Fingerprint> fingerprints = build.getBuildFingerprints(); for (Fingerprint f : fingerprints) { try { f.rename(oldName, newName); } catch (IOException e) { logger.log(Level.WARNING, "Failed to update fingerprint record " + f.getFileName() + " when " + oldName + " was renamed to " + newName, e); } } } } } }</code><technical_language>this is wrong. limited AbstractProject I missing something</technical_language>

Target:
private void locationChanged(Item item, String oldName, String newName) { if (item instanceof Job) { Job p = Jenkins.getInstance().getItemByFullName(newName, Job.class); if (p != null) { RunList<? extends Run> builds = p.getBuilds(); for (Run build : builds) { Collection<Fingerprint> fingerprints = build.getBuildFingerprints(); for (Fingerprint f : fingerprints) { try { f.rename(oldName, newName); } catch (IOException e) { logger.log(Level.WARNING, "Failed to update fingerprint record " + f.getFileName() + " when " + oldName + " was renamed to " + newName, e); } } } } } }
Source:
<code>public MaintenanceConfiguration convert(MaintenanceRequest request) { MaintenanceConfiguration.Builder builder = new MaintenanceConfiguration.Builder(); <START> ofNullable(request.archiveWorkflows).ifPresent(config -> apply(config, builder.withArchiveWorkflows())); <END> ofNullable(request.deleteArchivedWorkflows).ifPresent(config -> apply(config, builder.withDeleteArchivedWorkflows())); ofNullable(request.deleteWorkflows).ifPresent(config -> apply(config, builder.withDeleteWorkflows())); return builder.build(); }</code><technical_language>public MaintenanceConfiguration convert(MaintenanceRequest request) { MaintenanceConfiguration.Builder builder = new MaintenanceConfiguration.Builder(); apply(request.archiveWorkflows, () -> builder.withArchiveWorkflows()); apply(request.deleteArchivedWorkflows, () -> builder.withDeleteArchivedWorkflows()); apply(request.deleteWorkflows, () -> builder.withDeleteWorkflows()); return builder.build(); } private void apply(MaintenanceRequestItem requestItem, Supplier<Builder> builderSupplier) { ofNullable(requestItem).ifPresent(item -> builderSupplier.get() // .setOlderThanPeriod(item.olderThanPeriod) // .setBatchSize(item.batchSize) // .setWorkflowTypes(ofNullable(item.workflowTypes).orElse(emptySet())) // .done()); }</technical_language>

Target:
public MaintenanceConfiguration convert(MaintenanceRequest request) { MaintenanceConfiguration.Builder builder = new MaintenanceConfiguration.Builder(); apply(request.archiveWorkflows, builder::withArchiveWorkflows); apply(request.deleteArchivedWorkflows, builder::withDeleteArchivedWorkflows); apply(request.deleteWorkflows, builder::withDeleteWorkflows); return builder.build(); }
Source:
<code>public static Object[] provideQueryContexts() { return new Object[] { QUERY_CONTEXT_DEFAULT, new ImmutableMap.Builder<String, Object>() .putAll(QUERY_CONTEXT_DEFAULT) .put(QueryContexts.JOIN_FILTER_REWRITE_VALUE_COLUMN_FILTERS_ENABLE_KEY, true) <START> .build(), <END> new ImmutableMap.Builder<String, Object>() .putAll(QUERY_CONTEXT_DEFAULT) .put(QueryContexts.JOIN_FILTER_REWRITE_VALUE_COLUMN_FILTERS_ENABLE_KEY, true) .put(QueryContexts.JOIN_FILTER_REWRITE_ENABLE_KEY, false) .build(), new ImmutableMap.Builder<String, Object>() .putAll(QUERY_CONTEXT_DEFAULT) .put(QueryContexts.JOIN_FILTER_REWRITE_ENABLE_KEY, false) .build(), }; }</code><technical_language>worth explicitly setting JOIN_FILTER_REWRITE_ENABLE_KEY true in case default changes in future</technical_language>

Target:
public static Object[] provideQueryContexts() { return new Object[] { QUERY_CONTEXT_DEFAULT, new ImmutableMap.Builder<String, Object>() .putAll(QUERY_CONTEXT_DEFAULT) .put(QueryContexts.JOIN_FILTER_REWRITE_VALUE_COLUMN_FILTERS_ENABLE_KEY, true) .put(QueryContexts.JOIN_FILTER_REWRITE_ENABLE_KEY, true) .build(), new ImmutableMap.Builder<String, Object>() .putAll(QUERY_CONTEXT_DEFAULT) .put(QueryContexts.JOIN_FILTER_REWRITE_VALUE_COLUMN_FILTERS_ENABLE_KEY, true) .put(QueryContexts.JOIN_FILTER_REWRITE_ENABLE_KEY, false) .build(), new ImmutableMap.Builder<String, Object>() .putAll(QUERY_CONTEXT_DEFAULT) .put(QueryContexts.JOIN_FILTER_REWRITE_ENABLE_KEY, false) .build(), }; }
Source:
<code>protected void persistTestData() throws IOException, HttpRequestFailedException { DataBundle dataBundle = loadDataBundle(getJsonDataPath()); String responseBody = ""; responseBody = BackDoor.removeAndRestoreDataBundle(dataBundle); String pathToResultFile = createFileAndDirectory(TestProperties.LNP_TEST_DATA_FOLDER, getJsonDataPath()); <START> String jsonValue = JsonUtils.parse(responseBody).getAsJsonObject().get("message").getAsString(); <END> try (BufferedWriter bw = Files.newBufferedWriter(Paths.get(pathToResultFile))) { bw.write(jsonValue); bw.flush(); } }</code><technical_language>a nit: message body json. a specific field hold (magic "message" field)</technical_language>

Target:
protected void persistTestData() throws IOException, HttpRequestFailedException { DataBundle dataBundle = loadDataBundle(getJsonDataPath()); String responseBody = ""; responseBody = BackDoor.removeAndRestoreDataBundle(dataBundle); String pathToResultFile = createFileAndDirectory(TestProperties.LNP_TEST_DATA_FOLDER, getJsonDataPath()); String jsonValue = JsonUtils.parse(responseBody).getAsJsonObject().get("message").getAsString(); FileHelper.saveFile(pathToResultFile, jsonValue); }
Source:
<code>public static Method getMethodIfAvailable(Class<?> clazz, String methodName, @Nullable Class<?>... paramTypes) { Assert.notNull(clazz, "Class must not be null"); Assert.notNull(methodName, "Method name must not be null"); if (paramTypes == null) { return findSingleMethod(clazz, methodName); } Method[] methods = clazz.getMethods(); for (Method method : methods) { if (method.getName().equals(methodName) <START> && Arrays.equals(method.getParameterTypes(), paramTypes)) { <END> return method; } } return null; }</code><technical_language>I suggest a pre-check for getParameterCount() == paramTypes.length in order avoid allocations coming getParameterTypes()</technical_language>

Target:
public static Method getMethodIfAvailable(Class<?> clazz, String methodName, @Nullable Class<?>... paramTypes) { Assert.notNull(clazz, "Class must not be null"); Assert.notNull(methodName, "Method name must not be null"); if (paramTypes == null) { return findSingleMethod(clazz, methodName); } Method[] methods = clazz.getMethods(); for (Method method : methods) { if (method.getName().equals(methodName) && method.getParameterCount() == paramTypes.length && Arrays.equals(method.getParameterTypes(), paramTypes)) { return method; } } return null; }
Source:
<code>public double pidGet() { if (pidSource == PIDSourceType.kDisplacement) { return getDistance(); <START> } else { <END> return getRate(); } }</code><technical_language>else if for quality code</technical_language>

Target:
public double pidGet() { try { return pidGetSafely(); } catch (InvalidSensorException e) { LogKitten.e(e); return 0.0; } }
Source:
<code>public void shouldListAllUsers() { when(userDao.listAll()).thenReturn(Arrays.asList(user, anotherUser)); controller.list(); <START> assertEquals(Arrays.asList(user, anotherUser), result.included().get("users")); <END> }</code><technical_language>change Matchers.contains I previously</technical_language>

Target:
public void shouldListAllUsers() { when(userDao.listAll()).thenReturn(Arrays.asList(user, anotherUser)); controller.list(); assertThat((List<User>)result.included().get("users"), contains(user, anotherUser)); }
Source:
<code>protected void refNameSelected(String refName) { boolean tagSelected = refName != null && refName.startsWith(Constants.R_TAGS); boolean branchSelected = refName != null && (refName.startsWith(Constants.R_HEADS) || refName .startsWith(Constants.R_REMOTES)); Button okButton = getButton(Window.OK); if (((TreeSelection) branchTree.getSelection()).size() > 1) { TreeSelection selection = (TreeSelection) branchTree .getSelection(); renameButton.setEnabled(false); deleteButton .setEnabled(onlyBranchesExcludingCurrentAreSelected(selection)); newButton.setEnabled(false); } else { okButton.setEnabled(branchSelected || tagSelected); renameButton.setEnabled(branchSelected && !tagSelected); deleteButton.setEnabled(branchSelected && !tagSelected && !isCurrentBranch(refName)); newButton.setEnabled(true); } if (BranchOperationUI.checkoutWillShowQuestionDialog(refName)) okButton.setText(UIText.CheckoutDialog_OkCheckoutWithQuestion); else okButton.setText(UIText.CheckoutDialog_OkCheckout); <START> okButton.setEnabled(!isCurrentBranch(refName)); <END> }</code><technical_language>This breaks disabling button in case of multi selection. In this case refName is null. this is clear. put statements if/else block above: if { ... okButton.setEnabled(false); } else { ... okButton.setEnabled(!isCurrentBranch(refName)); }</technical_language>

Target:
protected void refNameSelected(String refName) { boolean tagSelected = refName != null && refName.startsWith(Constants.R_TAGS); boolean branchSelected = refName != null && (refName.startsWith(Constants.R_HEADS) || refName .startsWith(Constants.R_REMOTES)); Button okButton = getButton(Window.OK); if (((TreeSelection) branchTree.getSelection()).size() > 1) { TreeSelection selection = (TreeSelection) branchTree .getSelection(); renameButton.setEnabled(false); deleteButton .setEnabled(onlyBranchesExcludingCurrentAreSelected(selection)); newButton.setEnabled(false); okButton.setEnabled(false); } else { renameButton.setEnabled(branchSelected && !tagSelected); deleteButton.setEnabled(branchSelected && !tagSelected && !isCurrentBranch(refName)); newButton.setEnabled(true); okButton.setEnabled((branchSelected || tagSelected) && !isCurrentBranch(refName)); } if (BranchOperationUI.checkoutWillShowQuestionDialog(refName)) okButton.setText(UIText.CheckoutDialog_OkCheckoutWithQuestion); else okButton.setText(UIText.CheckoutDialog_OkCheckout); }
Source:
<code>private SnapshotComparer() { options = new Options(); options.addOption( OptionBuilder .hasArg() .isRequired(true) .withLongOpt(leftOption) .withDescription("the left snapshot file") .withArgName("LEFT") .withType(File.class) .create("l")); options.addOption( OptionBuilder .hasArg() .isRequired(true) .withLongOpt(rightOption) .withDescription("the right snapshot file") .withArgName("RIGHT") .withType(File.class) .create("r")); options.addOption( OptionBuilder .hasArg() .isRequired(true) .withLongOpt(byteThresholdOption) .withDescription("the node data delta size threshold, in bytes, for printing the node") .withArgName("BYTETHRESHOLD") .withType(File.class) <START> .create("b")); <END> options.addOption( OptionBuilder .hasArg() .isRequired(true) .withLongOpt(nodeThresholdOption) .withDescription("the descendant node delta size threshold, in nodes, for printing the node") .withArgName("NODETHRESHOLD") .withType(String.class) .create("n")); options.addOption( OptionBuilder .hasArg() .withLongOpt(debugOption) .withDescription("use debug output") .withArgName("DEBUG") .withType(String.class) .create("d")); options.addOption( OptionBuilder .hasArg() .withLongOpt(interactiveOption) .withDescription("interactive mode") .withArgName("INTERACTIVE") .withType(String.class) .create("i")); }</code><technical_language>sure</technical_language>

Target:
private SnapshotComparer() { options = new Options(); options.addOption( OptionBuilder .hasArg() .isRequired(true) .withLongOpt(leftOption) .withDescription("(Required) The left snapshot file.") .withArgName("LEFT") .withType(File.class) .create("l")); options.addOption( OptionBuilder .hasArg() .isRequired(true) .withLongOpt(rightOption) .withDescription("(Required) The right snapshot file.") .withArgName("RIGHT") .withType(File.class) .create("r")); options.addOption( OptionBuilder .hasArg() .isRequired(true) .withLongOpt(byteThresholdOption) .withDescription("(Required) The node data delta size threshold, in bytes, for printing the node.") .withArgName("BYTETHRESHOLD") .withType(String.class) .create("b")); options.addOption( OptionBuilder .hasArg() .isRequired(true) .withLongOpt(nodeThresholdOption) .withDescription("(Required) The descendant node delta size threshold, in nodes, for printing the node.") .withArgName("NODETHRESHOLD") .withType(String.class) .create("n")); options.addOption("d", debugOption, false, "Use debug output."); options.addOption("i", interactiveOption, false, "Enter interactive mode."); }
Source:
<code>private List<Pair<Resource, Member>> getAffectedMemberResourceObjects(PerunSessionImpl perunSession, User user, Facility facility) throws InternalErrorException { List<Pair<Resource, Member>> listOfAffectedObjects = new ArrayList<>(); List<Resource> assignedResources = perunSession.getPerunBl().getFacilitiesManagerBl().getAssignedResources(perunSession, facility); <START> List<Member> userMembers = perunSession.getPerunBl().getMembersManagerBl().getMembersByUser(perunSession, user); <END> for(Resource resource: assignedResources) { List<Member> assignedMembers = perunSession.getPerunBl().getResourcesManagerBl().getAssignedMembers(perunSession, resource); for(Member member: userMembers) { if(assignedMembers.contains(member)) { listOfAffectedObjects.add(new Pair(resource, member)); break; } } } return listOfAffectedObjects; }</code><technical_language>retrieve user members, Member contains userId, check assigned members for resource</technical_language>

Target:
private List<Pair<Resource, Member>> getAffectedMemberResourceObjects(PerunSessionImpl perunSession, User user, Facility facility) throws InternalErrorException { List<Pair<Resource, Member>> listOfAffectedObjects = new ArrayList<>(); List<Resource> assignedResources = perunSession.getPerunBl().getFacilitiesManagerBl().getAssignedResources(perunSession, facility); for(Resource resource: assignedResources) { List<Member> assignedMembers = perunSession.getPerunBl().getResourcesManagerBl().getAssignedMembers(perunSession, resource); for(Member member: assignedMembers) { if(member.getUserId() == user.getId()) { listOfAffectedObjects.add(new Pair(resource, member)); break; } } } return listOfAffectedObjects; }
Source:
<code>private void finishAndReportAsync(Map<OperatorID, OperatorSnapshotFutures> snapshotFutures, CheckpointMetaData metadata, CheckpointMetrics metrics) { final Future<?> channelWrittenFuture; if (unalignedCheckpointEnabled) { ChannelStateWriteResult writeResult = channelStateWriter.getWriteResult(metadata.getCheckpointId()); channelWrittenFuture = writeResult.getJointFuture() .whenComplete((dummy, ex) -> channelStateWriter.notifyCheckpointComplete(metadata.getCheckpointId())); } else { <START> channelWrittenFuture = FutureUtils.completedVoidFuture(); <END> } executorService.execute(new AsyncCheckpointRunnable( snapshotFutures, metadata, metrics, channelWrittenFuture, System.nanoTime(), taskName, closeableRegistry, env, asyncExceptionHandler)); }</code><technical_language>nit: I guess longer notifyCheckpointComplete, finishedWriting(...)</technical_language>

Target:
private void finishAndReportAsync(Map<OperatorID, OperatorSnapshotFutures> snapshotFutures, CheckpointMetaData metadata, CheckpointMetrics metrics) { final Future<?> channelWrittenFuture; if (unalignedCheckpointEnabled) { ChannelStateWriteResult writeResult = channelStateWriter.getWriteResult(metadata.getCheckpointId()); channelWrittenFuture = CompletableFuture.allOf( writeResult.getInputChannelStateHandles(), writeResult.getResultSubpartitionStateHandles()) .whenComplete((dummy, ex) -> channelStateWriter.stop(metadata.getCheckpointId())); } else { channelWrittenFuture = FutureUtils.completedVoidFuture(); } executorService.execute(new AsyncCheckpointRunnable( snapshotFutures, metadata, metrics, channelWrittenFuture, System.nanoTime(), taskName, closeableRegistry, env, asyncExceptionHandler)); }
Source:
<code>public void writeAstyanaxReadDatastax() throws Exception { astyanaxExcessEnumIO.insertExcessEnumMetric(testLocators.get(0)); astyanaxExcessEnumIO.insertExcessEnumMetric(testLocators.get(1)); astyanaxExcessEnumIO.insertExcessEnumMetric(testLocators.get(2)); <START> astyanaxExcessEnumIO.insertExcessEnumMetric(testLocators.get(3)); <END> Set<Locator> excessEnums = datastaxExcessEnumIO.getExcessEnumMetrics(); String excessEnumLocators = ""; for ( Iterator<Locator> it = excessEnums.iterator(); it.hasNext(); ) { excessEnumLocators += it.next().toString() + ","; } assertTrue("excess enum does not contain " + testLocators.get(0), excessEnumLocators.contains(testLocators.get(0).toString())); assertTrue("excess enum does not contain " + testLocators.get(1), excessEnumLocators.contains(testLocators.get(1).toString())); assertTrue("excess enum does not contain " + testLocators.get(2), excessEnumLocators.contains(testLocators.get(2).toString())); assertTrue("excess enum does not contain " + testLocators.get(3), excessEnumLocators.contains(testLocators.get(3).toString())); }</code><technical_language>Put in loop</technical_language>

Target:
public void writeAstyanaxReadDatastax() throws Exception { for (Locator testLocator : testLocators) { astyanaxExcessEnumIO.insertExcessEnumMetric(testLocator); } Set<Locator> excessEnums = datastaxExcessEnumIO.getExcessEnumMetrics(); assertEquals("Unexpected number of excessEnums", testLocators.size(), excessEnums.size()); for (Locator expectedLocator : testLocators) { assertTrue("excess enum does not contain " + expectedLocator, excessEnums.contains(expectedLocator)); } }
Source:
<code>protected boolean contains(ArrayContainer arrayContainer) { final int cardinality = getCardinality(); final int runCount = numberOfRuns(); if (arrayContainer.getCardinality() > cardinality) { return false; } int ia = 0, ir = 0; while(ia < arrayContainer.getCardinality() && ir < runCount) { <START> int start = getValue(ir); <END> int stop = start + toIntUnsigned(getLength(ir)); if(arrayContainer.content[ia] < start) { return false; } else if (arrayContainer.content[ia] > stop) { ++ir; } else { ++ia; } } return ia == arrayContainer.getCardinality(); }</code><technical_language>is another error here: this java int start = Util.toIntUnsigned(getValue(ir));</technical_language>

Target:
protected boolean contains(ArrayContainer arrayContainer) { final int cardinality = getCardinality(); final int runCount = numberOfRuns(); if (arrayContainer.getCardinality() > cardinality) { return false; } int ia = 0, ir = 0; while(ia < arrayContainer.getCardinality() && ir < runCount) { int start = toIntUnsigned(this.getValue(ir)); int stop = start + toIntUnsigned(getLength(ir)); int ac = toIntUnsigned(arrayContainer.content[ia]); if(ac < start) { return false; } else if (ac > stop) { ++ir; } else { ++ia; } } return ia == arrayContainer.getCardinality(); }
Source:
<code>public final Field getLookupFieldByName(String name) { for (Field field : getFields()) { if (StringUtils.equals(name, field.getName())) { return field; } } <START> LOGGER.info("Can't get field with name {}", name); <END> return null; }</code><technical_language>this a warn</technical_language>

Target:
public final Field getLookupFieldByName(String name) { for (Field field : getFields()) { if (StringUtils.equals(name, field.getName())) { return field; } } LOGGER.warn("Can't get field with name {}", name); return null; }
Source:
<code>private void setColor() { this.textColor.setValue(this.color); this.smallIcon.getValue().setColorFilter(color, PorterDuff.Mode.SRC_ATOP); <START> for (int i = 0; i < this.actionImage.getValue().size(); i++) { <END> this.actionImage.getValue().get(i).setColorFilter(color, PorterDuff.Mode.SRC_ATOP); } }</code><technical_language>This loop is iterating multiple images name needs adjusted: this.actionImages</technical_language>

Target:
private void setColor() { this.textColor.setValue(this.color); if (this.smallIcon.getValue() != null) { this.smallIcon.getValue().setColorFilter(color, PorterDuff.Mode.SRC_ATOP); } if (this.actionImages.getValue() != null) { for (int i = 0; i < this.actionImages.getValue().size(); i++) { this.actionImages.getValue().get(i).setColorFilter(color, PorterDuff.Mode.SRC_ATOP); } } }
Source:
<code>public ApplicationMail getMailById(PerunSession sess, Integer id) throws ApplicationMailNotExistsException, PrivilegeException { ApplicationMail mail; try { List<ApplicationMail> mails = jdbc.query("select id,app_type,form_id,mail_type,send from application_mails where id=?", (resultSet, arg1) -> new ApplicationMail(resultSet.getInt("id"), AppType.valueOf(resultSet.getString("app_type")), resultSet.getInt("form_id"), MailType.valueOf(resultSet.getString("mail_type")), resultSet.getBoolean("send")), id); if (mails.size() != 1) { log.error("[MAIL MANAGER] Wrong number of mail definitions returned by unique params, expected 1 but was: {}.", mails.size()); <START> throw new ApplicationMailNotExistsException("Wrong number of mail definitions returned by unique params, expected 1 but was: "+mails.size()); <END> } mail = mails.get(0); } catch (EmptyResultDataAccessException ex) { throw new InternalErrorException("Mail definition with ID="+id+" doesn't exists."); } List<MailText> texts; try { texts = jdbc.query(MAIL_TEXTS_SELECT_BY_MAIL_ID, (resultSet, arg1) -> new MailText(new Locale(resultSet.getString("locale")), resultSet.getString("subject"), resultSet.getString("text")), mail.getId()); } catch (EmptyResultDataAccessException ex) { log.error("[MAIL MANAGER] Mail do not contains any text message.", ex); return mail; } for (MailText text : texts) { mail.getMessage().put(text.getLocale(), text); } return mail; }</code><technical_language>This is case mail exists. Exists case is catched in handling EmptyResultDataAccessException. This covers cases, more 1 mail definitions, consistency error (probably). fix condition more specific >1</technical_language>

Target:
public ApplicationMail getMailById(PerunSession sess, Integer id) throws ApplicationMailNotExistsException { ApplicationMail mail; try { List<ApplicationMail> mails = jdbc.query("select id,app_type,form_id,mail_type,send from application_mails where id=?", (resultSet, arg1) -> new ApplicationMail(resultSet.getInt("id"), AppType.valueOf(resultSet.getString("app_type")), resultSet.getInt("form_id"), MailType.valueOf(resultSet.getString("mail_type")), resultSet.getBoolean("send")), id); if (mails.size() > 1) { log.error("[MAIL MANAGER] Wrong number of mail definitions returned by unique params, expected 1 but was: {}.", mails.size()); throw new ConsistencyErrorException("Wrong number of mail definitions returned by unique params, expected 1 but was: "+mails.size()); } mail = mails.get(0); } catch (EmptyResultDataAccessException ex) { throw new ApplicationMailNotExistsException("Mail definition with ID="+id+" doesn't exists."); } List<MailText> texts; try { texts = jdbc.query(MAIL_TEXTS_SELECT_BY_MAIL_ID, (resultSet, arg1) -> new MailText(new Locale(resultSet.getString("locale")), resultSet.getString("subject"), resultSet.getString("text")), mail.getId()); } catch (EmptyResultDataAccessException ex) { log.error("[MAIL MANAGER] Mail do not contains any text message.", ex); return mail; } for (MailText text : texts) { mail.getMessage().put(text.getLocale(), text); } return mail; }
Source:
<code>public void setItems(final Collection value, final Guid storageDomainId) { <START> Frontend.getInstance().runQuery(VdcQueryType.GetAllVms, <END> new VdcQueryParametersBase(), new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { vms = ((VdcQueryReturnValue) returnValue).getReturnValue(); List<ImportVmData> vmDataList = new ArrayList<>(); for (VM vm : (Iterable<VM>) value) { ImportVmData vmData = new ImportVmData(vm); if (vms.contains(vm)) { vmData.setExistsInSystem(true); vmData.getClone().setEntity(true); vmData.getClone().setChangeProhibitionReason(ConstantsManager.getInstance() .getConstants() .importVMThatExistsInSystemMustClone()); vmData.getClone().setIsChangable(false); } else { vms.add(vm); } vmDataList.add(vmData); } ImportVmFromExportDomainModel.super.setItems(vmDataList); doInit(storageDomainId); } })); }</code><technical_language>getAllVms? hundreds thousands. This kill browser completely. able search query returns need (e.g. name id) write a new query this for you. this query is expensive say</technical_language>

Target:
public void setItems(final Collection value, final Guid storageDomainId) { Frontend.getInstance().runQuery(VdcQueryType.Search, new SearchParameters(createSearchPattern(value), SearchType.VM), new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { List<VM> vms = ((VdcQueryReturnValue) returnValue).getReturnValue(); Set<String> existingNames = new HashSet<>(); for (VM vm : vms) { existingNames.add(vm.getName()); } List<ImportVmData> vmDataList = new ArrayList<>(); for (VM vm : (Iterable<VM>) value) { ImportVmData vmData = new ImportVmData(vm); if (vms.contains(vm)) { vmData.setExistsInSystem(true); vmData.getClone().setEntity(true); vmData.getClone().setChangeProhibitionReason(ConstantsManager.getInstance() .getConstants() .importVMThatExistsInSystemMustClone()); vmData.getClone().setIsChangable(false); } if (!vmData.getClone().getEntity() && existingNames.contains(vm.getName())) { vmData.setError(ConstantsManager.getInstance().getConstants().nameMustBeUniqueInvalidReason()); } vmDataList.add(vmData); } ImportVmFromExportDomainModel.super.setItems(vmDataList); doInit(storageDomainId); } })); }
Source:
<code>private static File getFromHomeDir (String subDir) { Function<Path, Boolean> createDirIfNotExists = path -> { try { <START> if (!Files.exists(path)) Files.createDirectory(path); <END> return true; } catch (IOException e) return false; }; Path path = Paths.get(Constant.getZapHome(), subDir); Boolean pathExists = createDirIfNotExists.apply(path); if (pathExists && Files.isDirectory(path) && Files.isWritable(path)) { return path.toFile(); } return Model.getSingleton().getOptionsParam().getUserDirectory(); }</code><technical_language>While this is syntactically correct read more curly braces formatting other ifs. Other goid yo me</technical_language>

Target:
private static File getFromHomeDir (String subDir) { Path path = Paths.get(Constant.getZapHome(), subDir); try { if (Files.notExists(path)) { Files.createDirectory(path); } } catch (IOException e) if (Files.isDirectory(path) && Files.isWritable(path)) { return path.toFile(); } return Model.getSingleton().getOptionsParam().getUserDirectory(); }
Source:
<code>private BinaryContent getBinaryContentFromZip(String filePath) <START> throws CatalogTransformerException { <END> BinaryContent binaryContent; try { File zipFile = new File(filePath); InputStream fileInputStream = new ZipInputStream(new FileInputStream(zipFile)); binaryContent = new BinaryContentImpl(fileInputStream); jarSigner.signJar( zipFile, System.getProperty(SystemBaseUrl.EXTERNAL_HOST), System.getProperty("javax.net.ssl.keyStorePassword"), System.getProperty("javax.net.ssl.keyStore"), System.getProperty("javax.net.ssl.keyStorePassword")); } catch (FileNotFoundException e) { throw new CatalogTransformerException("Unable to get ZIP file from ZipInputStream.", e); } return binaryContent; }</code><technical_language>Properties retrieved privileged actions</technical_language>

Target:
private BinaryContent getBinaryContentFromZip(String filePath) throws CatalogTransformerException { BinaryContent binaryContent; InputStream fileInputStream; File zipFile = new File(filePath); try { fileInputStream = new ZipInputStream(new FileInputStream(zipFile)); binaryContent = new BinaryContentImpl(fileInputStream); } catch (FileNotFoundException e) { throw new CatalogTransformerException("Unable to get ZIP file from ZipInputStream.", e); } jarSigner.signJar( zipFile, AccessController.doPrivileged( (PrivilegedAction<String>) () -> System.getProperty(SystemBaseUrl.EXTERNAL_HOST)), AccessController.doPrivileged( (PrivilegedAction<String>) () -> System.getProperty("javax.net.ssl.keyStorePassword")), AccessController.doPrivileged( (PrivilegedAction<String>) () -> System.getProperty("javax.net.ssl.keyStore")), AccessController.doPrivileged( (PrivilegedAction<String>) () -> System.getProperty("javax.net.ssl.keyStorePassword"))); return binaryContent; }
Source:
<code>private void removeCinderVolume() { CinderDisk <START> cinderSnapshotForRemove = <END> (CinderDisk) getDiskImageDao().getSnapshotById(getParameters().getImageId()); cinderSnapshotForRemove.setActive(false); getImageDao().update(cinderSnapshotForRemove.getImage()); removeDescendentSnapshots(cinderSnapshotForRemove); removeCinderVolume(cinderSnapshotForRemove.getStorageIds().get(0), 0); }</code><technical_language>s/cinderSnapshotForRemove/cinderSnapshotToRemove</technical_language>

Target:
private void removeCinderVolume() { CinderDisk cinderSnapshotToRemove = (CinderDisk) getDiskImageDao().getSnapshotById(getParameters().getImageId()); cinderSnapshotToRemove.setActive(false); getImageDao().update(cinderSnapshotToRemove.getImage()); removeDescendentSnapshots(cinderSnapshotToRemove); removeCinderVolume(cinderSnapshotToRemove.getStorageIds().get(0), 0); }
Source:
<code>public GenericShuffleProducer construct(Server server) throws MyriaApiException { int numCells = 1; for (int d : hyperCubeDimensions) { numCells = numCells * d; } for (int[] partition : cellPartition) { for (int cellId : partition) { <START> if (cellId >= getRealWorkerIds().size()) { <END> throw new MyriaApiException(Status.BAD_REQUEST, "cellId in cellPartition must be smaller than worker number " + getRealWorkerIds().size() + "( " + cellId + " is found)"); } } } MFMDHashPartitionFunction pf = new MFMDHashPartitionFunction(cellPartition.length, hyperCubeDimensions, hashedColumns, mappedHCDimensions); return new GenericShuffleProducer(null, MyriaUtils.getSingleElement(getRealOperatorIds()), cellPartition, MyriaUtils.integerCollectionToIntArray(server.getAliveWorkers(numCells)), pf); }</code><technical_language>cellId negative? Preconditions.checkElementIndex(cellId, getRealWorkerIds().size()) IllegalArgumentException is caught QueryResource thrown a 400 error, I is</technical_language>

Target:
public GenericShuffleProducer construct(Server server) throws MyriaApiException { int numCells = 1; for (int d : hyperCubeDimensions) { numCells = numCells * d; } for (int[] partition : cellPartition) { for (int cellId : partition) { Preconditions.checkElementIndex(cellId, getRealWorkerIds().size()); } } MFMDHashPartitionFunction pf = new MFMDHashPartitionFunction(cellPartition.length, hyperCubeDimensions, hashedColumns, mappedHCDimensions); return new GenericShuffleProducer(null, MyriaUtils.getSingleElement(getRealOperatorIds()), cellPartition, MyriaUtils.integerCollectionToIntArray(server.getRandomWorkers(numCells)), pf); }
Source:
<code>public void prepareBuffers() { <START> if (nullsBuffer == null) { <END> nullsBuffer = new byte[DEFAULT_MAX_ELEMENT_COUNT / 8]; } nullsBufferIndex = ARRAY_BYTE_BASE_OFFSET; if (offsetsBuffer == null) { offsetsBuffer = new byte[DEFAULT_MAX_ELEMENT_COUNT * Integer.BYTES]; } offsetsBufferIndex = ARRAY_BYTE_BASE_OFFSET; rawBlockBuffer.prepareBuffers(); }</code><technical_language>I find a place initializes rawBlockBuffer. give a pointer</technical_language>

Target:
protected void prepareBuffers() { if (nullsBuffer == null) { nullsBuffer = new byte[DEFAULT_MAX_ELEMENT_COUNT / ARRAY_BYTE_INDEX_SCALE]; } nullsBufferIndex = ARRAY_BYTE_BASE_OFFSET; if (offsetsBuffer == null) { offsetsBuffer = new byte[DEFAULT_MAX_ELEMENT_COUNT * ARRAY_LONG_INDEX_SCALE]; } offsetsBufferIndex = ARRAY_BYTE_BASE_OFFSET; rawBlockBuffer.prepareBuffers(); }
Source:
<code>private static JsonArray getClientCertificateContentAndMetaData(List<ClientCertificateDTO> clientCertificateDTOs, String certDirectoryPath) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonArray certificatesList = new JsonArray(); clientCertificateDTOs.forEach(metadataDTO -> { <START> ByteArrayInputStream certificate = null; <END> try { String certificateContent = metadataDTO.getCertificate(); String certificateContentEncoded = APIConstants.BEGIN_CERTIFICATE_STRING .concat(certificateContent).concat("\n") .concat(APIConstants.END_CERTIFICATE_STRING); CommonUtil.writeFile(certDirectoryPath + File.separator + metadataDTO.getAlias() + ".crt", certificateContentEncoded); metadataDTO.setCertificate(metadataDTO.getAlias() + ".crt"); JsonObject certificateMetadata = (JsonObject) gson.toJsonTree(metadataDTO); certificatesList.add(certificateMetadata); } catch (APIImportExportException e) { log.error("Error while writing the certificate content. For alias: " + metadataDTO.getAlias(), e); } finally { if (certificate != null) { IOUtils.closeQuietly(certificate); } } }); return certificatesList; }</code><technical_language>stream try resources</technical_language>

Target:
private static JsonArray getClientCertificateContentAndMetaData(List<ClientCertificateDTO> clientCertificateDTOs, String certDirectoryPath) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonArray certificatesList = new JsonArray(); clientCertificateDTOs.forEach(metadataDTO -> { try { String certificateContent = metadataDTO.getCertificate(); String certificateContentEncoded = APIConstants.BEGIN_CERTIFICATE_STRING .concat(certificateContent).concat("\n") .concat(APIConstants.END_CERTIFICATE_STRING); CommonUtil.writeFile(certDirectoryPath + File.separator + metadataDTO.getAlias() + ".crt", certificateContentEncoded); metadataDTO.setCertificate(metadataDTO.getAlias() + ".crt"); JsonObject certificateMetadata = (JsonObject) gson.toJsonTree(metadataDTO); certificatesList.add(certificateMetadata); } catch (APIImportExportException e) { log.error("Error while writing the certificate content. For alias: " + metadataDTO.getAlias(), e); } }); return certificatesList; }
Source:
<code>public void setUp() throws IOException { MockitoAnnotations.initMocks(this); this.userSelection = new UserSelection(); this.fillObservationInfoOfUserSelection(this.userSelection); Mockito.when(this.contextUtil.getCurrentProgramUUID()).thenReturn(PROGRAM_UUID); Mockito.when(this.fileService.retrieveWorkbook(Mockito.anyString())).thenReturn(this.workbook); this.measurementVariableTestDataInitializer = new MeasurementVariableTestDataInitializer(); this.measurementDataTestDataInitializer = new MeasurementDataTestDataInitializer(); StandardVariable standardVariable = Mockito.mock(StandardVariable.class); Mockito.when(this.ontologyService.getStandardVariable(TermId.ENTRY_TYPE.getId(), PROGRAM_UUID)).thenReturn(standardVariable); <START> Mockito.when(standardVariable.getEnumerations()).thenReturn(Arrays.asList(new Enumeration(TermId.ENTRY_TYPE.getId(), TermId.ENTRY_TYPE.name(), "", 0))); <END> }</code><technical_language>For enumeration, ENTRY_TYPE id test data? confusing standard variable returned (we interested in enumerations of this standard variable). TermId.CHECK instead enumeration</technical_language>

Target:
public void setUp() throws IOException { MockitoAnnotations.initMocks(this); this.userSelection = new UserSelection(); this.fillObservationInfoOfUserSelection(this.userSelection); Mockito.when(this.contextUtil.getCurrentProgramUUID()).thenReturn(ETLServiceTest.PROGRAM_UUID); Mockito.when(this.fileService.retrieveWorkbook(Matchers.anyString())).thenReturn(this.workbook); this.measurementVariableTestDataInitializer = new MeasurementVariableTestDataInitializer(); this.measurementDataTestDataInitializer = new MeasurementDataTestDataInitializer(); final StandardVariable standardVariable = Mockito.mock(StandardVariable.class); Mockito.when(this.ontologyService.getStandardVariable(TermId.ENTRY_TYPE.getId(), ETLServiceTest.PROGRAM_UUID)) .thenReturn(standardVariable); Mockito.when(standardVariable.getEnumerations()) .thenReturn(Arrays.asList(new Enumeration(TermId.CHECK.getId(), TermId.CHECK.name(), "", 0))); }
Source:
<code>void copyDockerfileDirectory(Class<? extends DockerContainer> fixture, DockerFixture f, File dir) throws IOException { String dockerfilePath = resolveDockerfileLocation(fixture, f); <START> if(dockerfilePath.startsWith(FILE_SCHEMA)) { <END> String dockerfileLocation = dockerfilePath.substring(dockerfilePath.indexOf(FILE_SCHEMA) + FILE_SCHEMA.length()); copyDockerfileDirectoryFromDisk(dir, dockerfileLocation); } else { String dockerfileLocation = dockerfilePath; if(dockerfilePath.startsWith(CLASSPATH_SCHEMA)) { dockerfileLocation = dockerfilePath.substring( dockerfilePath.indexOf(CLASSPATH_SCHEMA) + CLASSPATH_SCHEMA.length()); } copyDockerfileDirectoryFromClasspath(fixture, dockerfileLocation, dir); } }</code><technical_language>FileUtils.copyURLToFile(URL source, File destination) simpler use, get support for http e.al. time</technical_language>

Target:
void copyDockerfileDirectory(Class<? extends DockerContainer> fixture, DockerFixture f, File dir) throws IOException { String dockerfilePath = resolveDockerfileLocation(fixture, f); copyDockerfileDirectoryFromClasspath(fixture, dockerfilePath, dir); }
Source:
<code>UpdateHandler(Class<?> sqlObjectType, Method method) { super(sqlObjectType, method); this.sqlObjectType = sqlObjectType; boolean isGetGeneratedKeys = method.isAnnotationPresent(GetGeneratedKeys.class); Type returnType = GenericTypes.resolveType(method.getGenericReturnType(), sqlObjectType); <START> if (!isGetGeneratedKeys) { <END> if (isNumeric(method.getReturnType())) { this.returner = (update, handle) -> update.execute(); } else if (isBoolean(method.getReturnType())) { this.returner = (update, handle) -> update.execute() > 0; } else { throw new UnableToCreateSqlObjectException(invalidReturnTypeMessage(method, returnType)); } } else { final ResultReturnThing magic = ResultReturnThing.forMethod(sqlObjectType, method); final GetGeneratedKeys ggk = method.getAnnotation(GetGeneratedKeys.class); final RowMapper<?> mapper; if (DefaultGeneratedKeyMapper.class.equals(ggk.value())) { mapper = new DefaultGeneratedKeyMapper(returnType, ggk.columnName()); } else { try { mapper = ggk.value().newInstance(); } catch (Exception e) { throw new UnableToCreateStatementException("Unable to instantiate row mapper for statement", e, null); } } this.returner = (update, handle) -> { GeneratedKeys<?> o = update.executeAndReturnGeneratedKeys(mapper, ggk.columnName()); return magic.result(o, handle); }; } }</code><technical_language>If invert this condition (and swap if/else blocks) if/else chain if/else chain instead of a nested one</technical_language>

Target:
UpdateHandler(Class<?> sqlObjectType, Method method) { super(sqlObjectType, method); this.sqlObjectType = sqlObjectType; boolean isGetGeneratedKeys = method.isAnnotationPresent(GetGeneratedKeys.class); Type returnType = GenericTypes.resolveType(method.getGenericReturnType(), sqlObjectType); if (isGetGeneratedKeys) { final ResultReturnThing magic = ResultReturnThing.forMethod(sqlObjectType, method); final GetGeneratedKeys ggk = method.getAnnotation(GetGeneratedKeys.class); final RowMapper<?> mapper; if (DefaultGeneratedKeyMapper.class.equals(ggk.value())) { mapper = new DefaultGeneratedKeyMapper(returnType, ggk.columnName()); } else { try { mapper = ggk.value().newInstance(); } catch (Exception e) { throw new UnableToCreateStatementException("Unable to instantiate row mapper for statement", e, null); } } this.returner = (update, handle) -> { GeneratedKeys<?> o = update.executeAndReturnGeneratedKeys(mapper, ggk.columnName()); return magic.result(o, handle); }; } else if (isNumeric(method.getReturnType())) { this.returner = (update, handle) -> update.execute(); } else if (isBoolean(method.getReturnType())) { this.returner = (update, handle) -> update.execute() > 0; } else { throw new UnableToCreateSqlObjectException(invalidReturnTypeMessage(method, returnType)); } }
Source:
<code>String userDetails(HttpServletRequest req, Model model) { Account account = accountResolver.getAccount(req); Map<String, Set<Permission>> springSecurityPermissions = new HashMap<>(); List<Group> groups = new ArrayList<>(); for (Group group : account.getGroups()) { groups.add(group); springSecurityPermissions.put( "group:" + group.getName(), stormpathGroupPermissionResolver.resolvePermissions(group) ); } model.addAttribute("groups", groups); springSecurityPermissions.put( "account", stormpathAccountPermissionResolver.resolvePermissions(account) ); <START> model.addAttribute("springSecurityPermissions", springSecurityPermissions); <END> return "userdetails"; }</code><technical_language>thing, key for permission modified user. instead of hardcoded do: model.addAttribute(stormpathAccountPermissionResolver.getCustomDataFieldName(), springSecurityPermissions); in order access operation class AccountCustomDataPermissionResolver instead of AccountPermissionResolver (the is a class, interface)</technical_language>

Target:
String userDetails(HttpServletRequest req, Model model) { Account account = accountResolver.getAccount(req); Map<String, Set<Permission>> aggregatePermissionsModel = new HashMap<>(); List<Group> groups = new ArrayList<>(); for (Group group : account.getGroups()) { groups.add(group); aggregatePermissionsModel.put( "group:" + group.getName(), stormpathGroupPermissionResolver.resolvePermissions(group) ); } model.addAttribute("groups", groups); aggregatePermissionsModel.put( "account", stormpathAccountPermissionResolver.resolvePermissions(account) ); model.addAttribute("aggregatePermissionsModel", aggregatePermissionsModel); return "userdetails"; }
Source:
<code>protected void setText(String newText) { <START> firePropertyChange("text", text, text = newText); <END> }</code><technical_language>If do logic of adding spacing behave for maximised/minimised in do else text is changed</technical_language>

Target:
protected void setText(String newText) { firePropertyChange("text", "", text = newText); }
Source:
<code>void auditRateOf(String key) { try { auditCache.get(key, () -> new RateLimit(auditRate, perMillis)).updateAllowance(); } catch (RateLimitException e) { LOGGER.info(String.format( <START> "Rate limit reached for rate limit key %s using rate of %d requests per %d ms", <END> key, auditRate, perMillis) ); } catch (ExecutionException e) { LOGGER.error("Unexpected error creating a Rate Limiter object in cache", e); } }</code><technical_language>this log bearer tokens</technical_language>

Target:
void auditRateOf(String key) { try { auditCache.get(key, () -> new RateLimit(auditRate, perMillis)).updateAllowance(); } catch (RateLimitException e) { LOGGER.info(String.format( "Rate limit reached for a service using rate of %d requests per %d ms", auditRate, perMillis) ); } catch (ExecutionException e) { LOGGER.error("Unexpected error creating a Rate Limiter object in cache", e); } }
Source:
<code>public boolean onOptionsItemSelected(MenuItem item) { Intent intent = null; switch (item.getItemId()) { case R.id.actionEntourage: intent = new Intent(this, CreatingAccountActivity.class); break; case R.id.actionDiscover: intent = new Intent(this, CreatingAccountActivity.class); break; case R.id.actionCreate: intent = new Intent(this, CreateGroupSelectNameActivity.class); break; case R.id.actionSettings: intent = new Intent(this, CreatingAccountActivity.class); break; default: return super.onOptionsItemSelected(item); } if (intent == null){ <START> Log.d(TAG, "Error : intent should never be null at this point"); END> } else { startActivity(intent); } return intent == null; }</code><technical_language>I right, exception fits this case :)</technical_language>

Target:
public boolean onOptionsItemSelected(MenuItem item) { Intent intent = null; switch (item.getItemId()) { case R.id.actionEntourage: intent = new Intent(this, CreatingAccountActivity.class); break; case R.id.actionDiscover: intent = new Intent(this, CreatingAccountActivity.class); break; case R.id.actionCreate: intent = new Intent(this, CreateGroupSelectNameActivity.class); break; case R.id.actionSettings: intent = new Intent(this, CreatingAccountActivity.class); break; default: return super.onOptionsItemSelected(item); } if (intent == null){ throw new IllegalStateException("Itent should never be null at this point"); } else { startActivity(intent); } return intent != null; }
Source:
<code>public String generate(String sessionId, Path logFile) throws IOException { String uidDir = System.getProperty("nativeDir", "lib"); <START> Files.setPosixFilePermissions(Paths.get(uidDir, "/faf-uid"), Sets.immutableEnumSet(PosixFilePermission.OTHERS_READ)); <END> return OsUtils.execAndGetOutput(String.format("%s/faf-uid %s", uidDir, sessionId)); }</code><technical_language>path separator required/desired in "/faf-uid"</technical_language>

Target:
public String generate(String sessionId, Path logFile) throws IOException { String uidDir = System.getProperty("nativeDir", "lib"); return OsUtils.execAndGetOutput(String.format("%s/faf-uid %s", uidDir, sessionId)); }
Source:
<code>public void approve(String uuid) { AgentInstance agentInstance = findAgentAndRefreshStatus(uuid); boolean hasAgent = hasAgent(agentInstance.getUuid()); agentInstance.enable(); if (hasAgent) { LOGGER.warn("Registered agent with the same uuid already approved.", agentInstance); } else { Agent agent = agentInstance.getAgent(); generateCookieForAgentIfAgentDoesNotHaveACookie(agent); saveOrUpdate(agent); <START> } <END> }</code><technical_language>agentInstance.isRegistered() return true, this method is called if agent is registered requestRegistration method</technical_language>

Target:
public void approve(String uuid) { AgentInstance agentInstance = findAgentAndRefreshStatus(uuid); boolean doesAgentExistAndIsRegistered = isRegistered(agentInstance.getUuid()); agentInstance.enable(); if (doesAgentExistAndIsRegistered) { LOGGER.warn("Registered agent with the same uuid already approved.", agentInstance); } else { Agent agent = agentInstance.getAgent(); if (!agent.cookieAssigned()) { generateAndAddCookie(agent); } saveOrUpdate(agent); } }
Source:
<code>public List<String> sourceTopicsForStore(final String storeName) { final List<String> results = new ArrayList<>(); for (final Map.Entry<String, Set<String>> entry : stateStoreNameToSourceTopics.entrySet()) { if (entry.getKey().equals(storeName)) { results.addAll(maybeDecorateInternalSourceTopics(entry.getValue())); return results; } } <START> return null; <END> }</code><technical_language>reason empty list for sentinel</technical_language>

Target:
public Collection<String> sourceTopicsForStore(final String storeName) { return maybeDecorateInternalSourceTopics(stateStoreNameToSourceTopics.get(storeName)); }
Source:
<code>public GlobalView() { Button remove = new Button("Remove from global and reload", event -> { ApplicationRouteRegistry .getInstance(VaadinServlet.getCurrent().getServletContext()) .removeRoute("global"); UI.getCurrent().getPage().reload(); }); RouterLink tologin = new RouterLink("To login", Login.class); <START> add(new Span( <END> "This is a view registered from the admin view to the global servlet scope."), remove, tologin); }</code><technical_language>![MAJOR](<LINK_0> 'Severity: MAJOR') Remove this call a constructor overridable "add" method. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
public GlobalView() { Button remove = new Button("Remove from global and reload", event -> { RouteConfiguration.forApplicationScope().removeRoute("global"); UI.getCurrent().getPage().reload(); }); remove.setId("remove-global"); RouterLink tologin = new RouterLink("To login", Login.class); tologin.setId("to-root-link"); add(new Span( "This is a view registered from the admin view to the global servlet scope."), remove, tologin); }