Example usage for org.apache.commons.collections.map ListOrderedMap ListOrderedMap

List of usage examples for org.apache.commons.collections.map ListOrderedMap ListOrderedMap

Introduction

In this page you can find the example usage for org.apache.commons.collections.map ListOrderedMap ListOrderedMap.

Prototype

public ListOrderedMap() 

Source Link

Document

Constructs a new empty ListOrderedMap that decorates a HashMap.

Usage

From source file:net.sf.morph.transform.converters.BeanToPrettyTextConverterTestCase.java

public void testSimpleObject() {
    Map source = new ListOrderedMap();
    source.put("one", new Integer(1));
    source.put("two", new Integer(2));
    source.put("three", new Integer(3));
    String destination = (String) defaultConverter.convert(String.class, source);
    assertEquals("[one=1,two=2,three=3]", destination);
}

From source file:com.doculibre.constellio.spellchecker.SpellChecker.java

public ListOrderedMap suggest(SimpleSearch simpleSearch, Locale locale) {
    ListOrderedMap suggestionsForSentence = new ListOrderedMap();
    String sentence = simpleSearch.getQuery();
    String collectionName = simpleSearch.getCollectionName();
    addSuggestions(sentence, collectionName, suggestionsForSentence, null, locale);
    return suggestionsForSentence;
}

From source file:com.doculibre.constellio.spellchecker.SpellChecker.java

public ListOrderedMap suggest(String sentence, String collectionName) {
    ListOrderedMap suggestionsForSentence = new ListOrderedMap();
    addSuggestions(sentence, collectionName, suggestionsForSentence, null, null);
    return suggestionsForSentence;
}

From source file:info.magnolia.cms.module.ModuleUtil.java

/**
 * registers the properties in the repository
 * @param hm/*from   w  ww .j  a  va  2s  .  c  om*/
 * @param name
 * @throws IOException
 * @throws RepositoryException
 * @throws PathNotFoundException
 * @throws AccessDeniedException
 */
public static void registerProperties(HierarchyManager hm, String name)
        throws IOException, AccessDeniedException, PathNotFoundException, RepositoryException {
    Map map = new ListOrderedMap();

    // not using properties since they are not ordered
    // Properties props = new Properties();
    // props.load(ModuleUtil.class.getResourceAsStream("/" + name.replace('.', '/') + ".properties"));
    InputStream stream = ModuleUtil.class.getResourceAsStream("/" + name.replace('.', '/') + ".properties"); //$NON-NLS-1$ //$NON-NLS-2$
    LineNumberReader lines = new LineNumberReader(new InputStreamReader(stream));

    String line = lines.readLine();
    while (line != null) {
        line = line.trim();
        if (line.length() > 0 && !line.startsWith("#")) { //$NON-NLS-1$
            String key = StringUtils.substringBefore(line, "=").trim(); //$NON-NLS-1$
            String value = StringUtils.substringAfter(line, "=").trim(); //$NON-NLS-1$
            map.put(key, value);
        }
        line = lines.readLine();
    }
    IOUtils.closeQuietly(lines);
    IOUtils.closeQuietly(stream);
    registerProperties(hm, map);
}

From source file:net.sf.morph.transform.converters.BeanToPrettyTextConverterTestCase.java

public void testWithNulls() {
    BeanToPrettyTextConverter converter = new BeanToPrettyTextConverter();
    converter.setSeparator("&");
    converter.setPrefix(null);//from  w  ww.  j av  a  2 s . com
    converter.setSuffix(null);

    Map source = new ListOrderedMap();
    source.put("calendarId", null);
    source.put("calendarPeriodId", new Integer(1));
    source.put("organizationId", new int[] { 2, 3 });
    String destination = (String) converter.convert(String.class, source);
    assertEquals("calendarPeriodId=1&organizationId={2,3}", destination);

    source = new ListOrderedMap();
    source.put("calendarId", null);
    source.put("calendarPeriodId", new Integer(1));
    source.put("organizationId", null);
    destination = (String) converter.convert(String.class, source);
    assertEquals("calendarPeriodId=1", destination);

    source = new ListOrderedMap();
    source.put("calendarId1", null);
    source.put("calendarId2", null);
    source.put("calendarPeriodId", new Integer(1));
    source.put("middleNull", null);
    source.put("organizationId", "hi");
    source.put("organizationId2", null);
    destination = (String) converter.convert(String.class, source);
    assertEquals("calendarPeriodId=1&organizationId=hi", destination);
}

From source file:models.SkillTag.java

public static ListOrderedMap getCategoryTagMap() {
    ListOrderedMap ctmap = new ListOrderedMap();
    List<SkillTag> list = JPA.em().createQuery("from SkillTag s where s.tagType=:tagType  order by s.seq asc")
            .setParameter("tagType", SkillTag.TagType.CATEGORY).setMaxResults(150).getResultList();
    for (SkillTag st : list) {
        ctmap.put(st.id, st.tagName);/*w  w  w.  ja v a2s  . c o m*/
    }
    return ctmap;
}

From source file:com.denksoft.springstarter.util.webflow.ProgressFlowExecutionListener.java

@Override
@SuppressWarnings(value = "unchecked")
public void sessionStarting(RequestContext context, FlowSession session, MutableAttributeMap input) {
    //create or get progressMap from conversational scope
    Map<String, ProgressInfo> progressMap = (Map<String, ProgressInfo>) context.getConversationScope()
            .get(PROGRESS_INFORMATION_MAP_VAR_NAME);
    if (progressMap == null) {
        progressMap = new ListOrderedMap();
    }/*from  ww  w  . j  a v  a 2 s.c o  m*/

    progressMap.put(session.getDefinition().getId(), new ProgressInfo(session.getDefinition().getId()));
    context.getConversationScope().put(PROGRESS_INFORMATION_MAP_VAR_NAME, progressMap);
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.edit.EntityRetryController.java

public void doPost(HttpServletRequest request, HttpServletResponse response) {
    if (!isAuthorizedToDisplayPage(request, response, SimplePermission.DO_BACK_END_EDITING.ACTION)) {
        return;/*from  w ww  .  j a v a 2s .  c  o m*/
    }

    VitroRequest vreq = new VitroRequest(request);
    String siteAdminUrl = vreq.getContextPath() + Controllers.SITE_ADMIN;

    //create an EditProcessObject for this and put it in the session
    EditProcessObject epo = super.createEpo(request);

    epo.setBeanClass(Individual.class);
    epo.setImplementationClass(IndividualImpl.class);

    String action = null;
    if (epo.getAction() == null) {
        action = "insert";
        epo.setAction("insert");
    } else {
        action = epo.getAction();
    }

    LoginStatusBean loginBean = LoginStatusBean.getBean(request);
    WebappDaoFactory myWebappDaoFactory = getWebappDaoFactory(loginBean.getUserURI());

    IndividualDao ewDao = myWebappDaoFactory.getIndividualDao();
    epo.setDataAccessObject(ewDao);
    VClassDao vcDao = myWebappDaoFactory.getVClassDao();
    VClassGroupDao cgDao = myWebappDaoFactory.getVClassGroupDao();
    DataPropertyDao dpDao = myWebappDaoFactory.getDataPropertyDao();

    Individual individualForEditing = null;
    if (epo.getUseRecycledBean()) {
        individualForEditing = (Individual) epo.getNewBean();
    } else {
        String uri = vreq.getParameter("uri");
        if (uri != null) {
            try {
                individualForEditing = (Individual) ewDao.getIndividualByURI(uri);
                action = "update";
                epo.setAction("update");
            } catch (NullPointerException e) {
                log.error("Need to implement 'record not found' error message.");
            }
        } else {
            individualForEditing = new IndividualImpl();
            if (vreq.getParameter("VClassURI") != null) {
                individualForEditing.setVClassURI(vreq.getParameter("VClassURI"));
            }
        }

        epo.setOriginalBean(individualForEditing);

        //make a simple mask for the entity's id
        Object[] simpleMaskPair = new Object[2];
        simpleMaskPair[0] = "URI";
        simpleMaskPair[1] = individualForEditing.getURI();
        epo.getSimpleMask().add(simpleMaskPair);

    }

    //set any validators

    LinkedList lnList = new LinkedList();
    lnList.add(new RequiredFieldValidator());
    epo.getValidatorMap().put("Name", lnList);

    //make a postinsert pageforwarder that will send us to a new entity's fetch screen
    epo.setPostInsertPageForwarder(new EntityInsertPageForwarder());
    epo.setPostDeletePageForwarder(new UrlForwarder(siteAdminUrl));

    //set the getMethod so we can retrieve a new bean after we've inserted it
    try {
        Class[] args = new Class[1];
        args[0] = String.class;
        epo.setGetMethod(ewDao.getClass().getDeclaredMethod("getIndividualByURI", args));
    } catch (NoSuchMethodException e) {
        log.error("EntityRetryController could not find the entityByURI method in the dao");
    }

    epo.setIdFieldName("URI");
    epo.setIdFieldClass(String.class);

    HashMap hash = new HashMap();

    if (individualForEditing.getVClassURI() == null) {
        // we need to do a special thing here to make an option list with option groups for the classgroups.
        List classGroups = cgDao.getPublicGroupsWithVClasses(true, true, false); // order by displayRank, include uninstantiated classes, don't get the counts of individuals
        Iterator classGroupIt = classGroups.iterator();
        ListOrderedMap optGroupMap = new ListOrderedMap();
        while (classGroupIt.hasNext()) {
            VClassGroup group = (VClassGroup) classGroupIt.next();
            List classes = group.getVitroClassList();
            optGroupMap.put(group.getPublicName(), FormUtils.makeOptionListFromBeans(classes, "URI", "Name",
                    individualForEditing.getVClassURI(), null, false));
        }
        hash.put("VClassURI", optGroupMap);
    } else {
        VClass vClass = null;
        Option opt = null;
        try {
            vClass = vcDao.getVClassByURI(individualForEditing.getVClassURI());
        } catch (Exception e) {
        }
        if (vClass != null) {
            opt = new Option(vClass.getURI(), vClass.getName(), true);
        } else {
            opt = new Option(individualForEditing.getVClassURI(), individualForEditing.getVClassURI(), true);
        }
        List<Option> optList = new LinkedList<Option>();
        optList.add(opt);
        hash.put("VClassURI", optList);
    }

    hash.put("HiddenFromDisplayBelowRoleLevelUsingRoleUri",
            RoleLevelOptionsSetup.getDisplayOptionsList(individualForEditing));
    hash.put("ProhibitedFromUpdateBelowRoleLevelUsingRoleUri",
            RoleLevelOptionsSetup.getUpdateOptionsList(individualForEditing));
    hash.put("HiddenFromPublishBelowRoleLevelUsingRoleUri",
            RoleLevelOptionsSetup.getPublishOptionsList(individualForEditing));

    FormObject foo = new FormObject();
    foo.setOptionLists(hash);

    ListOrderedMap dpMap = new ListOrderedMap();

    //make dynamic datatype property fields
    List<VClass> vclasses = individualForEditing.getVClasses(true);
    if (vclasses == null) {
        vclasses = new ArrayList<VClass>();
        if (individualForEditing.getVClassURI() != null) {
            try {
                VClass cls = vreq.getUnfilteredWebappDaoFactory().getVClassDao()
                        .getVClassByURI(individualForEditing.getVClassURI());
                if (cls != null) {
                    vclasses.add(cls);
                }
            } catch (Exception e) {
            }
        }
    }
    List<DataProperty> allApplicableDataprops = new ArrayList<DataProperty>();
    for (VClass cls : vclasses) {
        List<DataProperty> dataprops = dpDao.getDataPropertiesForVClass(cls.getURI());
        for (DataProperty dp : dataprops) {
            boolean notDuplicate = true;
            for (DataProperty existingDp : allApplicableDataprops) {
                if (existingDp.getURI().equals(dp.getURI())) {
                    notDuplicate = false;
                    break;
                }
            }
            if (notDuplicate) {
                allApplicableDataprops.add(dp);
            }
        }
    }
    Collections.sort(allApplicableDataprops);

    if (allApplicableDataprops != null) {
        Iterator<DataProperty> datapropsIt = allApplicableDataprops.iterator();

        while (datapropsIt.hasNext()) {
            DataProperty d = datapropsIt.next();
            if (!dpMap.containsKey(d.getURI())) {
                dpMap.put(d.getURI(), d);
            }

        }

        if (individualForEditing.getDataPropertyList() != null) {
            Iterator<DataProperty> existingDps = individualForEditing.getDataPropertyList().iterator();
            while (existingDps.hasNext()) {
                DataProperty existingDp = existingDps.next();
                // Since the edit form begins with a "name" field, which gets saved as the rdfs:label,
                // do not want to include the label as well. 
                if (!existingDp.getPublicName().equals("label")) {
                    dpMap.put(existingDp.getURI(), existingDp);
                }
            }
        }

        List<DynamicField> dynamicFields = new ArrayList();
        Iterator<String> dpHashIt = dpMap.orderedMapIterator();
        while (dpHashIt.hasNext()) {
            String uri = dpHashIt.next();
            DataProperty dp = (DataProperty) dpMap.get(uri);
            DynamicField dynamo = new DynamicField();
            dynamo.setName(dp.getPublicName());
            dynamo.setTable("DataPropertyStatement");
            dynamo.setVisible(dp.getDisplayLimit());
            dynamo.setDeleteable(true);
            DynamicFieldRow rowTemplate = new DynamicFieldRow();
            Map parameterMap = new HashMap();
            parameterMap.put("DatatypePropertyURI", dp.getURI());
            rowTemplate.setParameterMap(parameterMap);
            dynamo.setRowTemplate(rowTemplate);
            try {
                Iterator<DataPropertyStatement> existingValues = dp.getDataPropertyStatements().iterator();
                while (existingValues.hasNext()) {
                    DataPropertyStatement existingValue = existingValues.next();
                    DynamicFieldRow row = new DynamicFieldRow();
                    //TODO: UGH
                    //row.setId(existingValue.getId());
                    row.setParameterMap(parameterMap);
                    row.setValue(existingValue.getData());
                    if (dynamo.getRowList() == null)
                        dynamo.setRowList(new ArrayList());
                    dynamo.getRowList().add(row);
                }
            } catch (NullPointerException npe) {
                //whatever
            }
            if (dynamo.getRowList() == null)
                dynamo.setRowList(new ArrayList());
            dynamo.getRowList().add(rowTemplate);
            dynamicFields.add(dynamo);
        }
        foo.setDynamicFields(dynamicFields);
    }

    foo.setErrorMap(epo.getErrMsgMap());

    epo.setFormObject(foo);

    // DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    DateFormat minutesOnlyDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    DateFormat dateOnlyFormat = new SimpleDateFormat("yyyy-MM-dd");
    FormUtils.populateFormFromBean(individualForEditing, action, epo, foo, epo.getBadValueMap());

    List cList = new ArrayList();
    cList.add(new IndividualDataPropertyStatementProcessor());
    //cList.add(new SearchReindexer()); // handled for now by SearchReindexingListener on model
    epo.setChangeListenerList(cList);

    epo.getAdditionalDaoMap().put("DataPropertyStatement", myWebappDaoFactory.getDataPropertyStatementDao()); // EntityDatapropProcessor will look for this
    epo.getAdditionalDaoMap().put("DataProperty", myWebappDaoFactory.getDataPropertyDao()); // EntityDatapropProcessor will look for this

    ApplicationBean appBean = vreq.getAppBean();

    RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
    request.setAttribute("bodyJsp", "/templates/edit/formBasic.jsp");
    request.setAttribute("formJsp", "/templates/edit/specific/entity_retry.jsp");
    request.setAttribute("epoKey", epo.getKey());
    request.setAttribute("title", "Individual Editing Form");
    request.setAttribute("css",
            "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + appBean.getThemeDir() + "css/edit.css\"/>");
    request.setAttribute("scripts", "/js/edit/entityRetry.js");
    // NC Commenting this out for now. Going to pass on DWR for moniker and use jQuery instead
    // request.setAttribute("bodyAttr"," onLoad=\"monikerInit()\"");
    request.setAttribute("_action", action);
    request.setAttribute("unqualifiedClassName", "Individual");
    setRequestAttributes(request, epo);
    try {
        rd.forward(request, response);
    } catch (Exception e) {
        log.error("EntityRetryController could not forward to view.");
        log.error(e.getMessage());
        log.error(e.getStackTrace());
    }

}

From source file:cn.fql.utility.CollectionUtility.java

/**
 * Sort collection with order, each group is a arraylist
 *
 * @param source source list//from  w ww  .j  a v a 2s  .c om
 * @param key    specified key which is used to be compared
 * @return <code>MapListAdapter</code>
 */
public static ListOrderedMap sortCollectionWithOrder(List source, Object key) {
    ListOrderedMap lstOrderedMap = new ListOrderedMap();
    for (Iterator it = source.iterator(); it.hasNext();) {
        Map rowMap = (Map) it.next();
        Object keyValue = rowMap.get(key);
        List groupList = (List) lstOrderedMap.get(keyValue);
        if (groupList == null) {
            groupList = new ArrayList();
            lstOrderedMap.put(keyValue, groupList);
        }
        groupList.add(rowMap);
    }
    return lstOrderedMap;
}

From source file:com.doculibre.constellio.wicket.pages.SearchResultsPage.java

private void initComponents() {
    final SimpleSearch simpleSearch = getSimpleSearch();
    String collectionName = simpleSearch.getCollectionName();
    ConstellioUser currentUser = ConstellioSession.get().getUser();
    RecordCollectionServices recordCollectionServices = ConstellioSpringUtils.getRecordCollectionServices();
    RecordCollection collection = recordCollectionServices.get(collectionName);
    boolean userHasPermission = false;
    if (collection != null) {
        userHasPermission = (!collection.hasSearchPermission())
                || (currentUser != null && currentUser.hasSearchPermission(collection));
    }//from  ww w  .  j a  v a 2 s .com
    if (StringUtils.isEmpty(collectionName) || !userHasPermission) {
        setResponsePage(ConstellioApplication.get().getHomePage());
    } else {

        final IModel suggestedSearchKeyListModel = new LoadableDetachableModel() {
            @Override
            protected Object load() {
                ListOrderedMap suggestedSearch = new ListOrderedMap();
                if (simpleSearch.isQueryValid() && simpleSearch.getQuery() != null) {
                    SpellChecker spellChecker = new SpellChecker(ConstellioApplication.get().getDictionaries());
                    try {
                        if (!simpleSearch.getQuery().equals("*:*")) {
                            suggestedSearch = spellChecker.suggest(simpleSearch.getQuery(),
                                    simpleSearch.getCollectionName());
                        }
                    } catch (RuntimeException e) {
                        e.printStackTrace();
                        // chec du spellchecker, pas besoin de faire planter la page
                    }
                }
                return suggestedSearch;
            }
        };

        BaseSearchResultsPageHeaderPanel headerPanel = (BaseSearchResultsPageHeaderPanel) getHeaderComponent();
        headerPanel.setAdvancedForm(simpleSearch.getAdvancedSearchRule() != null);
        SearchFormPanel searchFormPanel = headerPanel.getSearchFormPanel();

        final ThesaurusSuggestionPanel thesaurusSuggestionPanel = new ThesaurusSuggestionPanel(
                "thesaurusSuggestion", simpleSearch, getLocale());
        add(thesaurusSuggestionPanel);

        SpellCheckerPanel spellCheckerPanel = new SpellCheckerPanel("spellChecker",
                searchFormPanel.getSearchTxtField(), searchFormPanel.getSearchButton(),
                suggestedSearchKeyListModel) {
            @SuppressWarnings("unchecked")
            public boolean isVisible() {
                boolean visible = false;
                if (dataProvider != null && !thesaurusSuggestionPanel.isVisible()) {
                    RecordCollectionServices collectionServices = ConstellioSpringUtils
                            .getRecordCollectionServices();
                    RecordCollection collection = collectionServices.get(simpleSearch.getCollectionName());
                    if (collection != null && collection.isSpellCheckerActive()
                            && simpleSearch.getAdvancedSearchRule() == null) {
                        ListOrderedMap spell = (ListOrderedMap) suggestedSearchKeyListModel.getObject();
                        if (spell.size() > 0/* && dataProvider.size() == 0 */) {
                            for (String key : (List<String>) spell.keyList()) {
                                if (spell.get(key) != null) {
                                    return visible = true;
                                }
                            }
                        }
                    }
                }
                return visible;
            }
        };
        add(spellCheckerPanel);

        dataProvider = new SearchResultsDataProvider(simpleSearch, 10);

        WebMarkupContainer searchResultsSection = new WebMarkupContainer("searchResultsSection") {
            @Override
            public boolean isVisible() {
                return StringUtils.isNotBlank(simpleSearch.getLuceneQuery());
            }
        };
        add(searchResultsSection);

        IModel detailsLabelModel = new LoadableDetachableModel() {
            @Override
            protected Object load() {
                String detailsLabel;
                QueryResponse queryResponse = dataProvider.getQueryResponse();
                long start;
                long nbRes;
                double elapsedTimeSeconds;
                if (queryResponse != null) {
                    start = queryResponse.getResults().getStart();
                    nbRes = dataProvider.size();
                    elapsedTimeSeconds = (double) queryResponse.getElapsedTime() / 1000;
                } else {
                    start = 0;
                    nbRes = 0;
                    elapsedTimeSeconds = 0;
                }
                long end = start + 10;
                if (nbRes < end) {
                    end = nbRes;
                }

                String pattern = "#.####";
                DecimalFormat elapsedTimeFormatter = new DecimalFormat(pattern);
                String elapsedTimeStr = elapsedTimeFormatter.format(elapsedTimeSeconds);

                String forTxt = new StringResourceModel("for", SearchResultsPage.this, null).getString();
                String noResultTxt = new StringResourceModel("noResult", SearchResultsPage.this, null)
                        .getString();
                String resultsTxt = new StringResourceModel("results", SearchResultsPage.this, null)
                        .getString();
                String ofTxt = new StringResourceModel("of", SearchResultsPage.this, null).getString();
                String secondsTxt = new StringResourceModel("seconds", SearchResultsPage.this, null)
                        .getString();

                String queryTxt = " ";
                if (simpleSearch.isQueryValid() && simpleSearch.getQuery() != null
                        && simpleSearch.getAdvancedSearchRule() == null) {
                    queryTxt = " " + forTxt + " " + simpleSearch.getQuery() + " ";
                }

                if (nbRes > 0) {
                    Locale locale = getLocale();
                    detailsLabel = resultsTxt + " " + NumberFormatUtils.format(start + 1, locale) + " - "
                            + NumberFormatUtils.format(end, locale) + " " + ofTxt + " "
                            + NumberFormatUtils.format(nbRes, locale) + queryTxt + "(" + elapsedTimeStr + " "
                            + secondsTxt + ")";
                } else {
                    detailsLabel = noResultTxt + " " + queryTxt + "(" + elapsedTimeStr + " " + secondsTxt + ")";
                }

                String collectionName = dataProvider.getSimpleSearch().getCollectionName();
                if (collectionName != null) {
                    RecordCollectionServices collectionServices = ConstellioSpringUtils
                            .getRecordCollectionServices();
                    RecordCollection collection = collectionServices.get(collectionName);
                    Locale displayLocale = collection.getDisplayLocale(getLocale());
                    String collectionTitle = collection.getTitle(displayLocale);
                    detailsLabel = collectionTitle + " > " + detailsLabel;
                }
                return detailsLabel;
            }
        };
        Label detailsLabel = new Label("detailsRes", detailsLabelModel);
        add(detailsLabel);

        final IModel sortOptionsModel = new LoadableDetachableModel() {

            @Override
            protected Object load() {
                List<SortChoice> choices = new ArrayList<SortChoice>();
                choices.add(new SortChoice(null, null, null));
                String collectionName = dataProvider.getSimpleSearch().getCollectionName();
                if (collectionName != null) {
                    IndexFieldServices indexFieldServices = ConstellioSpringUtils.getIndexFieldServices();
                    RecordCollectionServices collectionServices = ConstellioSpringUtils
                            .getRecordCollectionServices();
                    RecordCollection collection = collectionServices.get(collectionName);
                    for (IndexField indexField : indexFieldServices.getSortableIndexFields(collection)) {
                        String label = indexField.getLabel(IndexField.LABEL_TITLE,
                                ConstellioSession.get().getLocale());
                        if (label == null || label.isEmpty()) {
                            label = indexField.getName();
                        }
                        choices.add(new SortChoice(indexField.getName(), label, "asc"));
                        choices.add(new SortChoice(indexField.getName(), label, "desc"));
                    }
                }
                return choices;
            }
        };

        IChoiceRenderer triChoiceRenderer = new ChoiceRenderer() {
            @Override
            public Object getDisplayValue(Object object) {
                SortChoice choice = (SortChoice) object;
                String displayValue;
                if (choice.title == null) {
                    displayValue = new StringResourceModel("sort.relevance", SearchResultsPage.this, null)
                            .getString();
                } else {
                    String order = new StringResourceModel("sortOrder." + choice.order, SearchResultsPage.this,
                            null).getString();
                    displayValue = choice.title + " " + order;
                }
                return displayValue;
            }
        };
        IModel value = new Model(new SortChoice(simpleSearch.getSortField(), simpleSearch.getSortField(),
                simpleSearch.getSortOrder()));
        DropDownChoice sortField = new DropDownChoice("sortField", value, sortOptionsModel, triChoiceRenderer) {
            @Override
            protected boolean wantOnSelectionChangedNotifications() {
                return true;
            }

            @Override
            protected void onSelectionChanged(Object newSelection) {
                SortChoice choice = (SortChoice) newSelection;
                if (choice.name == null) {
                    simpleSearch.setSortField(null);
                    simpleSearch.setSortOrder(null);
                } else {
                    simpleSearch.setSortField(choice.name);
                    simpleSearch.setSortOrder(choice.order);
                }
                simpleSearch.setPage(0);

                PageFactoryPlugin pageFactoryPlugin = PluginFactory.getPlugin(PageFactoryPlugin.class);
                RequestCycle.get().setResponsePage(pageFactoryPlugin.getSearchResultsPage(),
                        SearchResultsPage.getParameters(simpleSearch));
            }

            @Override
            public boolean isVisible() {
                return ((List<?>) sortOptionsModel.getObject()).size() > 1;
            }
        };
        searchResultsSection.add(sortField);
        sortField.setNullValid(false);

        add(new AjaxLazyLoadPanel("facetsPanel") {
            @Override
            public Component getLazyLoadComponent(String markupId) {
                return new FacetsPanel(markupId, dataProvider);
            }
        });

        final IModel featuredLinkModel = new LoadableDetachableModel() {
            @Override
            protected Object load() {
                FeaturedLink suggestion;
                RecordCollectionServices collectionServices = ConstellioSpringUtils
                        .getRecordCollectionServices();
                FeaturedLinkServices featuredLinkServices = ConstellioSpringUtils.getFeaturedLinkServices();
                Long featuredLinkId = simpleSearch.getFeaturedLinkId();
                if (featuredLinkId != null) {
                    suggestion = featuredLinkServices.get(featuredLinkId);
                } else {
                    String collectionName = simpleSearch.getCollectionName();
                    if (simpleSearch.getAdvancedSearchRule() == null) {
                        String text = simpleSearch.getQuery();
                        RecordCollection collection = collectionServices.get(collectionName);
                        suggestion = featuredLinkServices.suggest(text, collection);
                        if (suggestion == null) {
                            SynonymServices synonymServices = ConstellioSpringUtils.getSynonymServices();
                            List<String> synonyms = synonymServices.getSynonyms(text, collectionName);
                            if (!synonyms.isEmpty()) {
                                for (String synonym : synonyms) {
                                    if (!synonym.equals(text)) {
                                        suggestion = featuredLinkServices.suggest(synonym, collection);
                                    }
                                    if (suggestion != null) {
                                        break;
                                    }
                                }
                            }
                        }
                    } else {
                        suggestion = new FeaturedLink();
                    }
                }
                return suggestion;
            }
        };
        IModel featuredLinkTitleModel = new LoadableDetachableModel() {
            @Override
            protected Object load() {
                FeaturedLink featuredLink = (FeaturedLink) featuredLinkModel.getObject();
                return featuredLink.getTitle(getLocale());
            }
        };
        final IModel featuredLinkDescriptionModel = new LoadableDetachableModel() {
            @Override
            protected Object load() {
                FeaturedLink featuredLink = (FeaturedLink) featuredLinkModel.getObject();
                StringBuffer descriptionSB = new StringBuffer();
                String description = featuredLink.getDescription(getLocale());
                if (description != null) {
                    descriptionSB.append(description);
                    String lookFor = "${";
                    int indexOfLookFor = -1;
                    while ((indexOfLookFor = descriptionSB.indexOf(lookFor)) != -1) {
                        int indexOfEnclosingQuote = descriptionSB.indexOf("}", indexOfLookFor);
                        String featuredLinkIdStr = descriptionSB.substring(indexOfLookFor + lookFor.length(),
                                indexOfEnclosingQuote);

                        int indexOfTagBodyStart = descriptionSB.indexOf(">", indexOfEnclosingQuote) + 1;
                        int indexOfTagBodyEnd = descriptionSB.indexOf("</a>", indexOfTagBodyStart);
                        String capsuleQuery = descriptionSB.substring(indexOfTagBodyStart, indexOfTagBodyEnd);
                        if (capsuleQuery.indexOf("<br/>") != -1) {
                            capsuleQuery = StringUtils.remove(capsuleQuery, "<br/>");
                        }
                        if (capsuleQuery.indexOf("<br />") != -1) {
                            capsuleQuery = StringUtils.remove(capsuleQuery, "<br />");
                        }

                        try {
                            String linkedCapsuleURL = getFeaturedLinkURL(new Long(featuredLinkIdStr));
                            descriptionSB.replace(indexOfLookFor, indexOfEnclosingQuote + 1, linkedCapsuleURL);
                        } catch (NumberFormatException e) {
                            // Ignore
                        }
                    }
                }
                return descriptionSB.toString();
            }

            private String getFeaturedLinkURL(Long featuredLinkId) {
                SimpleSearch clone = simpleSearch.clone();
                clone.setFeaturedLinkId(featuredLinkId);
                PageFactoryPlugin pageFactoryPlugin = PluginFactory.getPlugin(PageFactoryPlugin.class);
                String url = RequestCycle.get()
                        .urlFor(pageFactoryPlugin.getSearchResultsPage(), getParameters(clone)).toString();
                return url;
            }
        };

        WebMarkupContainer featuredLink = new WebMarkupContainer("featuredLink", featuredLinkModel) {
            @Override
            public boolean isVisible() {
                boolean visible = super.isVisible();
                if (visible) {
                    if (featuredLinkModel.getObject() != null) {
                        String description = (String) featuredLinkDescriptionModel.getObject();
                        visible = StringUtils.isNotEmpty(description);
                    } else {
                        visible = false;
                    }
                }
                DataView dataView = (DataView) searchResultsPanel.getDataView();
                return visible && dataView.getCurrentPage() == 0;
            }
        };
        searchResultsSection.add(featuredLink);
        featuredLink.add(new Label("title", featuredLinkTitleModel));
        featuredLink.add(new WebMarkupContainer("description", featuredLinkDescriptionModel) {
            @Override
            protected void onComponentTagBody(MarkupStream markupStream, ComponentTag openTag) {
                String descriptionHTML = (String) getModel().getObject();
                replaceComponentTagBody(markupStream, openTag, descriptionHTML);
            }
        });

        searchResultsSection
                .add(searchResultsPanel = new SearchResultsPanel("resultatsRecherchePanel", dataProvider));
    }
}