Example usage for java.util Comparator comparing

List of usage examples for java.util Comparator comparing

Introduction

In this page you can find the example usage for java.util Comparator comparing.

Prototype

public static <T, U extends Comparable<? super U>> Comparator<T> comparing(
        Function<? super T, ? extends U> keyExtractor) 

Source Link

Document

Accepts a function that extracts a java.lang.Comparable Comparable sort key from a type T , and returns a Comparator that compares by that sort key.

Usage

From source file:org.cgiar.ccafs.marlo.action.annualReport.ProgramVarianceAction.java

@Override
public void prepare() throws Exception {
    // Get current CRP
    loggedCrp = (GlobalUnit) this.getSession().get(APConstants.SESSION_CRP);
    loggedCrp = crpManager.getGlobalUnitById(loggedCrp.getId());
    Phase phase = this.getActualPhase();

    // If there is a history version being loaded
    if (this.getRequest().getParameter(APConstants.TRANSACTION_ID) != null) {
        transaction = StringUtils.trim(this.getRequest().getParameter(APConstants.TRANSACTION_ID));
        ReportSynthesis history = (ReportSynthesis) auditLogManager.getHistory(transaction);
        if (history != null) {
            reportSynthesis = history;//from w  w w  .ja v a2  s.c om
            synthesisID = reportSynthesis.getId();
        } else {
            this.transaction = null;
            this.setTransaction("-1");
        }
    } else {
        // Get Liaison institution ID Parameter
        try {
            liaisonInstitutionID = Long.parseLong(StringUtils
                    .trim(this.getRequest().getParameter(APConstants.LIAISON_INSTITUTION_REQUEST_ID)));
        } catch (NumberFormatException e) {
            User user = userManager.getUser(this.getCurrentUser().getId());
            if (user.getLiasonsUsers() != null || !user.getLiasonsUsers().isEmpty()) {
                List<LiaisonUser> liaisonUsers = new ArrayList<>(user.getLiasonsUsers().stream()
                        .filter(lu -> lu.isActive() && lu.getLiaisonInstitution().isActive()
                                && lu.getLiaisonInstitution().getCrp().getId() == loggedCrp.getId()
                                && lu.getLiaisonInstitution().getInstitution() == null)
                        .collect(Collectors.toList()));
                if (!liaisonUsers.isEmpty()) {
                    boolean isLeader = false;
                    for (LiaisonUser liaisonUser : liaisonUsers) {
                        LiaisonInstitution institution = liaisonUser.getLiaisonInstitution();
                        if (institution.isActive()) {
                            if (institution.getCrpProgram() != null) {
                                if (institution.getCrpProgram()
                                        .getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue()) {
                                    liaisonInstitutionID = institution.getId();
                                    isLeader = true;
                                    break;
                                }
                            } else {
                                if (institution.getAcronym().equals("PMU")) {
                                    liaisonInstitutionID = institution.getId();
                                    isLeader = true;
                                    break;
                                }
                            }
                        }
                    }
                    if (!isLeader) {
                        liaisonInstitutionID = this.firstFlagship();
                    }
                } else {
                    liaisonInstitutionID = this.firstFlagship();
                }
            } else {
                liaisonInstitutionID = this.firstFlagship();
            }
        }

        try {
            synthesisID = Long.parseLong(
                    StringUtils.trim(this.getRequest().getParameter(APConstants.REPORT_SYNTHESIS_ID)));
            reportSynthesis = reportSynthesisManager.getReportSynthesisById(synthesisID);

            if (!reportSynthesis.getPhase().equals(phase)) {
                reportSynthesis = reportSynthesisManager.findSynthesis(phase.getId(), liaisonInstitutionID);
                if (reportSynthesis == null) {
                    reportSynthesis = this.createReportSynthesis(phase.getId(), liaisonInstitutionID);
                }
                synthesisID = reportSynthesis.getId();
            }
        } catch (Exception e) {

            reportSynthesis = reportSynthesisManager.findSynthesis(phase.getId(), liaisonInstitutionID);
            if (reportSynthesis == null) {
                reportSynthesis = this.createReportSynthesis(phase.getId(), liaisonInstitutionID);
            }
            synthesisID = reportSynthesis.getId();

        }
    }

    if (reportSynthesis != null) {

        ReportSynthesis reportSynthesisDB = reportSynthesisManager.getReportSynthesisById(synthesisID);
        synthesisID = reportSynthesisDB.getId();
        liaisonInstitutionID = reportSynthesisDB.getLiaisonInstitution().getId();
        liaisonInstitution = liaisonInstitutionManager.getLiaisonInstitutionById(liaisonInstitutionID);

        Path path = this.getAutoSaveFilePath();
        // Verify if there is a Draft file
        if (path.toFile().exists() && this.getCurrentUser().isAutoSave()) {
            BufferedReader reader;
            reader = new BufferedReader(new FileReader(path.toFile()));
            Gson gson = new GsonBuilder().create();
            JsonObject jReader = gson.fromJson(reader, JsonObject.class);
            reader.close();
            AutoSaveReader autoSaveReader = new AutoSaveReader();
            reportSynthesis = (ReportSynthesis) autoSaveReader.readFromJson(jReader);
            synthesisID = reportSynthesis.getId();
            this.setDraft(true);
        } else {
            this.setDraft(false);
            // Check if ProgramVariance relation is null -create it
            if (reportSynthesis.getReportSynthesisProgramVariance() == null) {
                ReportSynthesisProgramVariance programVariance = new ReportSynthesisProgramVariance();
                // create one to one relation
                reportSynthesis.setReportSynthesisProgramVariance(programVariance);
                programVariance.setReportSynthesis(reportSynthesis);
                // save the changes
                reportSynthesis = reportSynthesisManager.saveReportSynthesis(reportSynthesis);
            }
        }
    }

    // Get the list of liaison institutions Flagships and PMU.
    liaisonInstitutions = loggedCrp.getLiaisonInstitutions().stream()
            .filter(c -> c.getCrpProgram() != null && c.isActive()
                    && c.getCrpProgram().getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue())
            .collect(Collectors.toList());
    liaisonInstitutions.sort(Comparator.comparing(LiaisonInstitution::getAcronym));

    // ADD PMU as liaison Institution too
    liaisonInstitutions.addAll(loggedCrp.getLiaisonInstitutions().stream()
            .filter(c -> c.getCrpProgram() == null && c.isActive() && c.getAcronym().equals("PMU"))
            .collect(Collectors.toList()));

    if (this.isFlagship()) {
        LiaisonInstitution pmuInstitution = loggedCrp.getLiaisonInstitutions().stream()
                .filter(c -> c.getCrpProgram() == null && c.getAcronym().equals("PMU"))
                .collect(Collectors.toList()).get(0);
        ReportSynthesis reportSynthesisDB = reportSynthesisManager.findSynthesis(phase.getId(),
                pmuInstitution.getId());
        if (reportSynthesisDB != null) {
            if (reportSynthesisDB.getReportSynthesisProgramVariance() != null) {
                pmuText = reportSynthesisDB.getReportSynthesisProgramVariance().getDescription();
            }
        }
    }

    // Base Permission
    String params[] = { loggedCrp.getAcronym(), reportSynthesis.getId() + "" };
    this.setBasePermission(this.getText(Permission.REPORT_SYNTHESIS_PROGRAM_VARIANCE_BASE_PERMISSION, params));
}

From source file:spdxedit.PackageEditor.java

/**
 * Opens the modal package editor for the provided package.
 *
 * @param pkg               The package to edit.
 * @param relatablePackages Packages to which the edited package may optionally have defined relationships
 * @param parentWindow      The parent window.
 */// ww  w.  j a  v  a 2 s .  c o  m
public static void editPackage(final SpdxPackage pkg, final List<SpdxPackage> relatablePackages,
        SpdxDocumentContainer documentContainer, Window parentWindow) {

    final PackageEditor packageEditor = new PackageEditor(pkg, relatablePackages, documentContainer);
    final Stage dialogStage = new Stage();
    dialogStage.setTitle("Edit SPDX Package: " + pkg.getName());
    dialogStage.initStyle(StageStyle.DECORATED);
    dialogStage.initModality(Modality.APPLICATION_MODAL);
    dialogStage.setY(parentWindow.getX() + parentWindow.getWidth() / 2);
    dialogStage.setY(parentWindow.getY() + parentWindow.getHeight() / 2);
    dialogStage.setResizable(false);
    try {
        FXMLLoader loader = new FXMLLoader(NewPackageDialog.class.getResource("/PackageEditor.fxml"));
        loader.setController(packageEditor);
        Pane pane = loader.load();
        Scene scene = new Scene(pane);
        dialogStage.setScene(scene);
        dialogStage.getIcons().clear();
        dialogStage.getIcons().add(UiUtils.ICON_IMAGE_VIEW.getImage());
        //Populate the file list on appearance
        dialogStage.setOnShown(event -> {
            try {
                final SpdxFile dummyfile = new SpdxFile(pkg.getName(), null, null, null, null, null, null, null,
                        null, null, null, null, null);
                TreeItem<SpdxFile> root = new TreeItem<>(dummyfile);
                packageEditor.filesTable.setRoot(root);
                //Assume a package without is external
                //TODO: replace with external packages or whatever alternate mechanism in 2.1
                packageEditor.btnAddFile.setDisable(pkg.getFiles().length == 0);
                root.getChildren()
                        .setAll(Stream.of(pkg.getFiles())
                                .sorted(Comparator.comparing(file -> StringUtils.lowerCase(file.getName()))) //Sort by file name
                                .map(TreeItem<SpdxFile>::new).collect(Collectors.toList()));
            } catch (InvalidSPDXAnalysisException e) {
                logger.error("Unable to get files for package " + pkg.getName(), e);
            }

            packageEditor.tabFiles.setExpanded(true);

        });

        //Won't assign this event through FXML - don't want to propagate the stage beyond this point.
        packageEditor.btnOk.setOnMouseClicked(event -> dialogStage.close());
        dialogStage.showAndWait();

    } catch (IOException ioe) {
        throw new RuntimeException("Unable to load dialog", ioe);
    }
}

From source file:de.unihannover.l3s.mws.bean.Hackathon.java

public <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
    Map<K, V> result = new LinkedHashMap<>();
    Stream<Entry<K, V>> st = map.entrySet().stream();

    st.sorted(Comparator.comparing(e -> e.getValue()))
            .forEachOrdered(e -> result.put(e.getKey(), e.getValue()));

    return result;
}

From source file:org.keycloak.models.jpa.JpaRealmProvider.java

@Override
public List<GroupModel> getTopLevelGroups(RealmModel realm) {
    RealmEntity ref = em.getReference(RealmEntity.class, realm.getId());

    return ref.getGroups().stream().filter(g -> g.getParent() == null)
            .map(g -> session.realms().getGroupById(g.getId(), realm))
            .sorted(Comparator.comparing(GroupModel::getName))
            .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
}

From source file:com.microfocus.application.automation.tools.octane.configuration.JobConfigurationProxy.java

@JavaScriptMethod
public JSONObject loadJobConfigurationFromServer(String instanceId) {
    OctaneClient octaneClient = OctaneSDK.getClientByInstanceId(instanceId);

    JSONObject ret = new JSONObject();
    JSONObject workspaces = new JSONObject();
    JSONArray fieldsMetadata = new JSONArray();
    try {//from   w w w. j  a va  2 s.com
        boolean isUftJob = false;
        List<CIParameter> parameters = ParameterProcessors.getConfigs(job);
        if (parameters != null) {
            for (CIParameter parameter : parameters) {
                if (parameter != null && parameter.getName() != null && parameter.getName().equals("suiteId")) {
                    isUftJob = true;
                    break;
                }
            }
        }
        ret.put("isUftJob", isUftJob);

        final String jobCiId = JobProcessorFactory.getFlowProcessor(job).getTranslateJobName();
        PipelineContextList pipelineContextList = octaneClient.getPipelineContextService()
                .getJobConfiguration(octaneClient.getInstanceId(), jobCiId);

        if (!pipelineContextList.getData().isEmpty()) {
            Map<Long, List<PipelineContext>> workspacesMap = pipelineContextList.buildWorkspace2PipelinesMap();
            //WORKAROUND BEGIN
            //getting workspaceName - because the workspaceName is not returned from configuration API
            Map<Long, String> relatedWorkspaces = new HashMap<>();
            List<Entity> workspaceList = getWorkspacesById(octaneClient, workspacesMap.keySet());
            for (Entity workspace : workspaceList) {
                relatedWorkspaces.put(Long.parseLong(workspace.getId()), workspace.getName());
            }
            //WORKAROUND END

            Map<Entity, List<PipelineContext>> sortedWorkspacesMap = new TreeMap<>(
                    Comparator.comparing(Entity::getName));
            Comparator<PipelineContext> pipelineComparator = Comparator
                    .comparing(PipelineContext::getContextEntityName);

            //create workspaces JSON Object
            for (Entry<Long, List<PipelineContext>> workspacePipelines : workspacesMap.entrySet()) {
                Entity relatedWorkspace = dtoFactory.newDTO(Entity.class);

                relatedWorkspace.setId(workspacePipelines.getKey().toString());
                relatedWorkspace.setName(relatedWorkspaces.get(workspacePipelines.getKey()));

                JSONObject relatedPipelinesJSON = new JSONObject();

                for (PipelineContext relatedPipeline : workspacePipelines.getValue()) {
                    JSONObject pipelineJSON = fromPipeline(relatedPipeline, relatedWorkspace);
                    enrichPipelineInstanceId(pipelineJSON, instanceId);
                    relatedPipelinesJSON.put(String.valueOf(relatedPipeline.getContextEntityId()),
                            pipelineJSON);
                }
                JSONObject workspaceJSON = new JSONObject();
                workspaceJSON.put("id", relatedWorkspace.getId());
                workspaceJSON.put("name", relatedWorkspace.getName());
                workspaceJSON.put("pipelines", relatedPipelinesJSON);
                workspaces.put(String.valueOf(relatedWorkspace.getId()), workspaceJSON);

                //inserting this workspace into sortedMap (sorted by workspaceName and by pipelineName, so that we can pick first workspace and its first pipeline as preselected values
                LinkedList<PipelineContext> workspacePipelinesList = new LinkedList<>(
                        workspacePipelines.getValue());
                workspacePipelinesList.sort(pipelineComparator);
                sortedWorkspacesMap.put(relatedWorkspace, workspacePipelinesList);
            }

            //create currentPipeline JSON Object
            //currently the first pipeline in the first workspace is picked
            Entity preSelectedWorkspace = sortedWorkspacesMap.keySet().iterator().next();
            PipelineContext preSelectedPipeline = sortedWorkspacesMap.get(preSelectedWorkspace).get(0);
            JSONObject preSelectedPipelineJSON = fromPipeline(preSelectedPipeline, preSelectedWorkspace);
            enrichPipelineInstanceId(preSelectedPipelineJSON, instanceId);
            //WORKAROUND BEGIN
            //all metadata have to be loaded in separate REST calls for this pipeline: releaseName, taxonomyNames and listFieldNames are not returned from configuration API
            enrichPipelineInternal(preSelectedPipelineJSON, octaneClient);
            //WORKAROUND END
            ret.put("currentPipeline", preSelectedPipelineJSON);

            //retrieving metadata fields for preselected workspace
            fieldsMetadata = convertToJsonMetadata(getPipelineListNodeFieldsMetadata(octaneClient,
                    Long.parseLong(preSelectedWorkspace.getId())));
        }

        ret.put("workspaces", workspaces);
        ret.put("fieldsMetadata", fieldsMetadata);

    } catch (Exception e) {
        logger.warn("Failed to retrieve job configuration", e);
        return error("Unable to retrieve job configuration");
    }

    return ret;
}

From source file:org.apache.sysml.hops.codegen.template.PlanSelectionFuseCostBased.java

private void createAndAddMultiAggPlans(CPlanMemoTable memo, ArrayList<Hop> roots) {
    //collect full aggregations as initial set of candidates
    HashSet<Long> fullAggs = new HashSet<Long>();
    Hop.resetVisitStatus(roots);/*from  w  ww  .j a v  a 2  s .com*/
    for (Hop hop : roots)
        rCollectFullAggregates(hop, fullAggs);
    Hop.resetVisitStatus(roots);

    //remove operators with assigned multi-agg plans
    fullAggs.removeIf(p -> memo.contains(p, TemplateType.MultiAggTpl));

    //check applicability for further analysis
    if (fullAggs.size() <= 1)
        return;

    if (LOG.isTraceEnabled()) {
        LOG.trace("Found across-partition ua(RC) aggregations: "
                + Arrays.toString(fullAggs.toArray(new Long[0])));
    }

    //collect information for all candidates 
    //(subsumed aggregations, and inputs to fused operators) 
    List<AggregateInfo> aggInfos = new ArrayList<AggregateInfo>();
    for (Long hopID : fullAggs) {
        Hop aggHop = memo._hopRefs.get(hopID);
        AggregateInfo tmp = new AggregateInfo(aggHop);
        for (int i = 0; i < aggHop.getInput().size(); i++) {
            Hop c = HopRewriteUtils.isMatrixMultiply(aggHop) && i == 0
                    ? aggHop.getInput().get(0).getInput().get(0)
                    : aggHop.getInput().get(i);
            rExtractAggregateInfo(memo, c, tmp, TemplateType.CellTpl);
        }
        if (tmp._fusedInputs.isEmpty()) {
            if (HopRewriteUtils.isMatrixMultiply(aggHop)) {
                tmp.addFusedInput(aggHop.getInput().get(0).getInput().get(0).getHopID());
                tmp.addFusedInput(aggHop.getInput().get(1).getHopID());
            } else
                tmp.addFusedInput(aggHop.getInput().get(0).getHopID());
        }
        aggInfos.add(tmp);
    }

    if (LOG.isTraceEnabled()) {
        LOG.trace("Extracted across-partition ua(RC) aggregation info: ");
        for (AggregateInfo info : aggInfos)
            LOG.trace(info);
    }

    //sort aggregations by num dependencies to simplify merging
    //clusters of aggregations with parallel dependencies
    aggInfos = aggInfos.stream().sorted(Comparator.comparing(a -> a._inputAggs.size()))
            .collect(Collectors.toList());

    //greedy grouping of multi-agg candidates
    boolean converged = false;
    while (!converged) {
        AggregateInfo merged = null;
        for (int i = 0; i < aggInfos.size(); i++) {
            AggregateInfo current = aggInfos.get(i);
            for (int j = i + 1; j < aggInfos.size(); j++) {
                AggregateInfo that = aggInfos.get(j);
                if (current.isMergable(that)) {
                    merged = current.merge(that);
                    aggInfos.remove(j);
                    j--;
                }
            }
        }
        converged = (merged == null);
    }

    if (LOG.isTraceEnabled()) {
        LOG.trace("Merged across-partition ua(RC) aggregation info: ");
        for (AggregateInfo info : aggInfos)
            LOG.trace(info);
    }

    //construct and add multiagg template plans (w/ max 3 aggregations)
    for (AggregateInfo info : aggInfos) {
        if (info._aggregates.size() <= 1)
            continue;
        Long[] aggs = info._aggregates.keySet().toArray(new Long[0]);
        MemoTableEntry me = new MemoTableEntry(TemplateType.MultiAggTpl, aggs[0], aggs[1],
                (aggs.length > 2) ? aggs[2] : -1);
        for (int i = 0; i < aggs.length; i++) {
            memo.add(memo._hopRefs.get(aggs[i]), me);
            addBestPlan(aggs[i], me);
            if (LOG.isTraceEnabled())
                LOG.trace("Added multiagg* plan: " + aggs[i] + " " + me);

        }
    }
}

From source file:org.silverpeas.web.jobstartpage.control.JobStartPagePeasSessionController.java

public SpaceInst[] getUserManageableSpacesIds() {
    List<SpaceInst> vManageableSpaces = new ArrayList<SpaceInst>();
    String[] sids = getUserManageableSpaceIds();
    SpaceInst currentSpace = getSpaceInstById();
    String currentSpaceId = (currentSpace == null) ? "-1" : currentSpace.getId();

    for (String sid : sids) {
        if (isSpaceInMaintenance(sid.substring(2)) || sid.equals(currentSpaceId)) {
            vManageableSpaces.add(adminController.getSpaceInstById(sid));
        }//w w  w.  j ava 2 s  . c  o m
    }

    SpaceInst[] aManageableSpaces = vManageableSpaces.toArray(new SpaceInst[vManageableSpaces.size()]);
    Arrays.sort(aManageableSpaces, Comparator.comparing(SpaceInst::getOrderNum));
    return aManageableSpaces;
}

From source file:diffhunter.Indexer.java

public static <K extends Comparable<? super K>, V> Map<K, V> sortByKey(Map<K, V> map) {
    Map<K, V> result = new LinkedHashMap<>();
    map.entrySet().stream().sorted(Comparator.comparing(E -> E.getKey()))
            .forEach((entry) -> result.put(entry.getKey(), entry.getValue()));

    List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
    Collections.sort(list, (Map.Entry<K, V> o1, Map.Entry<K, V> o2) -> (o1.getKey()).compareTo(o2.getKey()));

    list.stream().forEach((entry) -> {
        result.put(entry.getKey(), entry.getValue());
    });/*from  ww  w  .  j av a 2 s  .c om*/
    return result;
}

From source file:org.thingsboard.server.dao.entityview.EntityViewServiceImpl.java

@Override
public ListenableFuture<List<EntitySubtype>> findEntityViewTypesByTenantId(TenantId tenantId) {
    log.trace("Executing findEntityViewTypesByTenantId, tenantId [{}]", tenantId);
    validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
    ListenableFuture<List<EntitySubtype>> tenantEntityViewTypes = entityViewDao
            .findTenantEntityViewTypesAsync(tenantId.getId());
    return Futures.transform(tenantEntityViewTypes, entityViewTypes -> {
        entityViewTypes.sort(Comparator.comparing(EntitySubtype::getType));
        return entityViewTypes;
    });/*from  ww w  . ja  v a  2s .  c  o  m*/
}

From source file:io.spring.initializr.generator.ProjectGenerator.java

/**
 * Resolve the specified {@link ProjectRequest} and return the model to use to
 * generate the project/*  w w  w . j  a v  a  2 s .c  o  m*/
 * @param originalRequest the request to handle
 * @return a model for that request
 */
protected Map<String, Object> resolveModel(ProjectRequest originalRequest) {
    Assert.notNull(originalRequest.getBootVersion(), "boot version must not be null");
    Map<String, Object> model = new LinkedHashMap<>();
    InitializrMetadata metadata = metadataProvider.get();

    ProjectRequest request = requestResolver.resolve(originalRequest, metadata);

    // request resolved so we can log what has been requested
    List<Dependency> dependencies = request.getResolvedDependencies();
    List<String> dependencyIds = dependencies.stream().map(Dependency::getId).collect(Collectors.toList());
    log.info("Processing request{type=" + request.getType() + ", dependencies=" + dependencyIds);

    if (isWar(request)) {
        model.put("war", true);
    }

    if (isMavenBuild(request)) {
        model.put("mavenBuild", true);
        ParentPom parentPom = metadata.getConfiguration().getEnv().getMaven()
                .resolveParentPom(request.getBootVersion());
        if (parentPom.isIncludeSpringBootBom() && !request.getBoms().containsKey("spring-boot")) {
            request.getBoms().put("spring-boot",
                    metadata.createSpringBootBom(request.getBootVersion(), "spring-boot.version"));
        }

        model.put("mavenParentGroupId", parentPom.getGroupId());
        model.put("mavenParentArtifactId", parentPom.getArtifactId());
        model.put("mavenParentVersion", parentPom.getVersion());
        model.put("includeSpringBootBom", parentPom.isIncludeSpringBootBom());
    }

    model.put("repositoryValues", request.getRepositories().entrySet());
    if (!request.getRepositories().isEmpty()) {
        model.put("hasRepositories", true);
    }

    List<BillOfMaterials> resolvedBoms = request.getBoms().values().stream()
            .sorted(Comparator.comparing(BillOfMaterials::getOrder)).collect(Collectors.toList());
    model.put("resolvedBoms", resolvedBoms);
    ArrayList<BillOfMaterials> reversedBoms = new ArrayList<>(resolvedBoms);
    Collections.reverse(reversedBoms);
    model.put("reversedBoms", reversedBoms);

    model.put("compileDependencies", filterDependencies(dependencies, Dependency.SCOPE_COMPILE));
    model.put("runtimeDependencies", filterDependencies(dependencies, Dependency.SCOPE_RUNTIME));
    model.put("compileOnlyDependencies", filterDependencies(dependencies, Dependency.SCOPE_COMPILE_ONLY));
    model.put("providedDependencies", filterDependencies(dependencies, Dependency.SCOPE_PROVIDED));
    model.put("testDependencies", filterDependencies(dependencies, Dependency.SCOPE_TEST));

    request.getBoms().forEach((k, v) -> {
        if (v.getVersionProperty() != null) {
            request.getBuildProperties().getVersions().computeIfAbsent(v.getVersionProperty(),
                    key -> v::getVersion);
        }
    });

    Map<String, String> versions = new LinkedHashMap<>();
    model.put("buildPropertiesVersions", versions.entrySet());
    request.getBuildProperties().getVersions().forEach((k, v) -> versions.put(k, v.get()));
    Map<String, String> gradle = new LinkedHashMap<>();
    model.put("buildPropertiesGradle", gradle.entrySet());
    request.getBuildProperties().getGradle().forEach((k, v) -> gradle.put(k, v.get()));
    Map<String, String> maven = new LinkedHashMap<>();
    model.put("buildPropertiesMaven", maven.entrySet());
    request.getBuildProperties().getMaven().forEach((k, v) -> maven.put(k, v.get()));

    // Add various versions
    model.put("dependencyManagementPluginVersion",
            metadata.getConfiguration().getEnv().getGradle().getDependencyManagementPluginVersion());
    model.put("kotlinVersion", metadata.getConfiguration().getEnv().getKotlin().getVersion());
    if ("kotlin".equals(request.getLanguage())) {
        model.put("kotlin", true);
    }
    if ("groovy".equals(request.getLanguage())) {
        model.put("groovy", true);
    }

    model.put("isRelease", request.getBootVersion().contains("RELEASE"));
    // @SpringBootApplication available as from 1.2.0.RC1
    model.put("useSpringBootApplication",
            VERSION_1_2_0_RC1.compareTo(Version.safeParse(request.getBootVersion())) <= 0);

    // Gradle plugin has changed as from 1.3.0
    model.put("bootOneThreeAvailable",
            VERSION_1_3_0_M1.compareTo(Version.safeParse(request.getBootVersion())) <= 0);

    // Gradle plugin has changed again as from 1.4.2
    model.put("springBootPluginName",
            (VERSION_1_4_2_M1.compareTo(Version.safeParse(request.getBootVersion())) <= 0
                    ? "org.springframework.boot"
                    : "spring-boot"));

    // New testing stuff
    model.put("newTestInfrastructure", isNewTestInfrastructureAvailable(request));

    // New Servlet Initializer location
    model.put("newServletInitializer", isNewServletInitializerAvailable(request));

    // Java versions
    model.put("isJava6", isJavaVersion(request, "1.6"));
    model.put("isJava7", isJavaVersion(request, "1.7"));
    model.put("isJava8", isJavaVersion(request, "1.8"));

    // Append the project request to the model
    BeanWrapperImpl bean = new BeanWrapperImpl(request);
    for (PropertyDescriptor descriptor : bean.getPropertyDescriptors()) {
        if (bean.isReadableProperty(descriptor.getName())) {
            model.put(descriptor.getName(), bean.getPropertyValue(descriptor.getName()));
        }
    }
    if (!request.getBoms().isEmpty()) {
        model.put("hasBoms", true);
    }

    return model;
}