Example usage for java.lang StringBuffer replace

List of usage examples for java.lang StringBuffer replace

Introduction

In this page you can find the example usage for java.lang StringBuffer replace.

Prototype

@Override
public synchronized StringBuffer replace(int start, int end, String str) 

Source Link

Usage

From source file:usbong.android.utils.UsbongUtils.java

public static ArrayList<String> extractKanjiPhrasesFromString(String s) {
    ArrayList<String> output = new ArrayList<String>();
    StringBuffer kanjiPhrase = new StringBuffer();

    //go through character by character
    for (int i = 0; i < s.length(); i++) {
        //Reference: http://www.rikai.com/library/kanjitables/kanji_codes.unicode.shtml;
        //last accessed: 4 Oct. 2014
        //Reference: http://stackoverflow.com/questions/3826918/how-to-classify-japanese-characters-as-either-kanji-or-kana;
        //last accessed: 4 Oct. 2014;
        //answer by Jack, Sept. 30, 2010
        //while Kanji Char
        for (int value = (int) s.charAt(i); value >= 0x4e00 && value <= 0x9faf;) {
            kanjiPhrase.append(s.charAt(i));
            i++;// w  ww . ja v a 2 s .co  m
            value = (int) s.charAt(i);
        }

        if (!kanjiPhrase.equals("")) {
            output.add(kanjiPhrase.toString());
            kanjiPhrase.replace(0, kanjiPhrase.length(), "");
        }
    }

    return output;
}

From source file:mesquite.chromaseq.InterpretASNGenBank.InterpretASNGenBank.java

public StringBuffer getDataAsFileText(CharacterData data) {
    Taxa taxa = data.getTaxa();/*from  ww w . j a  va 2  s .  co m*/

    int numTaxa = taxa.getNumTaxa();
    int numChars = data.getNumChars();
    StringBuffer outputBuffer = new StringBuffer(numTaxa * (20 + numChars));
    outputBuffer.append("Seq-submit ::= {" + getLineEnding());

    ASNNode rootNode = new ASNNode("root");
    rootNode.setLineEnding(getLineEnding());
    ASNNode subNode = rootNode.addChild("sub");
    addSubmissionInfo(subNode);

    ASNNode dataNode = rootNode.addChild("data");
    ASNNode entrysNode = dataNode.addChild("entrys");
    ASNNode setNode = entrysNode.addChild("set");
    ASNNode classNode = setNode.addChild("class", "phy-set", false);
    ASNNode descrNode = setNode.addChild("descr");
    ASNNode seqSetNode = entrysNode.addChild("seq-set");
    for (int it = 0; it < numTaxa; it++)
        if (!addSequence(seqSetNode, data, it))
            return null;

    outputBuffer.append(rootNode.toString());
    outputBuffer.append(" }" + getLineEnding());

    String wrapped = WordUtils.wrap(outputBuffer.toString(), 100, null, true);
    outputBuffer.replace(0, outputBuffer.length(), wrapped);

    return outputBuffer;
}

From source file:org.wso2.carbon.is.migration.MigrationDatabaseCreator.java

/**
 * executes content in SQL script/*from   w  w w  .j  ava2s  .  c  o m*/
 *
 * @return StringBuffer
 * @throws Exception
 */
private void executeSQLScript(String dbscriptName) throws Exception {

    String databaseType = DatabaseCreator.getDatabaseType(this.conn);
    boolean oracleUserChanged = true;
    boolean keepFormat = false;
    if ("oracle".equals(databaseType)) {
        delimiter = "/";
        oracleUserChanged = false;
    } else if ("db2".equals(databaseType)) {
        delimiter = "/";
    } else if ("openedge".equals(databaseType)) {
        delimiter = "/";
        keepFormat = true;
    }

    StringBuffer sql = new StringBuffer();
    BufferedReader reader = null;

    try {
        InputStream is = new FileInputStream(dbscriptName);
        reader = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            if (!keepFormat) {
                if (line.startsWith("//")) {
                    continue;
                }
                if (line.startsWith("--")) {
                    continue;
                }
                StringTokenizer st = new StringTokenizer(line);
                if (st.hasMoreTokens()) {
                    String token = st.nextToken();
                    if ("REM".equalsIgnoreCase(token)) {
                        continue;
                    }
                }
            }
            //add the oracle database owner
            if (!oracleUserChanged && "oracle".equals(databaseType) && line.contains("databasename :=")) {
                line = "databasename := '" + ISMigrationServiceDataHolder.getIdentityOracleUser() + "';";
                oracleUserChanged = true;
            }
            sql.append(keepFormat ? "\n" : " ").append(line);

            // SQL defines "--" as a comment to EOL
            // and in Oracle it may contain a hint
            // so we cannot just remove it, instead we must end it
            if (!keepFormat && line.indexOf("--") >= 0) {
                sql.append("\n");
            }
            if ((DatabaseCreator.checkStringBufferEndsWith(sql, delimiter))) {
                executeSQL(sql.substring(0, sql.length() - delimiter.length()));
                sql.replace(0, sql.length(), "");
            }
        }
        // Catch any statements not followed by ;
        if (sql.length() > 0) {
            executeSQL(sql.toString());
        }
    } catch (Exception e) {
        log.error("Error occurred while executing SQL script for migrating database", e);
        throw new Exception("Error occurred while executing SQL script for migrating database", e);

    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:com.topsec.tsm.sim.report.web.TopoReportController.java

/**
 * ?/*from  w  w  w.ja  v  a 2 s. com*/
 */
public Object getSubTitle(SID sid, HttpServletRequest request, HttpServletResponse response) {
    try {
        SID.setCurrentUser(sid);
        String subId = request.getParameter(ReportUiConfig.subrptid);
        String sTime = request.getParameter(ReportUiConfig.sTime);
        String eTime = request.getParameter(ReportUiConfig.eTime);
        String nodeType = request.getParameter("nodeType");
        String chartTableId = request.getParameter("chartTableId");
        RptMasterTbService rptMasterTbImp = (RptMasterTbService) SpringContextServlet.springCtx
                .getBean(ReportUiConfig.MstBean);
        List<Map> subList = rptMasterTbImp.queryTmpList(ReportUiConfig.SubTitleSql,
                new Object[] { StringUtil.toInt(subId, 0) });
        JSONObject json = null;
        if (subList.size() > 0) {
            Map subMap = (Map) subList.get(0);
            Map<String, Object> rsMap = null;
            Map params = new HashMap();
            if (dataSourceService == null) {
                dataSourceService = (DataSourceService) FacadeUtil.getFacadeBean(request, null,
                        "dataSourceService");
            }
            if (!GlobalUtil.isNullOrEmpty(nodeType)) {
                SID.setCurrentUser(sid);
                params.put("nodeType", nodeType);
            }
            String dvctype = request.getParameter("dvctype");
            String realdvctype = dvctype.replace("Comprehensive", "");

            List<String> deviceTypes = ReportModel.getDeviceTypeList(dataSourceService, SID.currentUser());
            List<String> deviceIps = ReportModel.getDeviceIpList(dataSourceService, SID.currentUser());
            if (!GlobalUtil.isNullOrEmpty(deviceTypes) && deviceTypes.contains(realdvctype)) {
                deviceTypes.clear();
                deviceTypes.add(realdvctype);
                List<SimDatasource> realSimDatasources = dataSourceService.getDataSourceByDvcType(realdvctype);
                List<String> nowIPList = new ArrayList<String>();
                for (SimDatasource simDatasource : realSimDatasources) {
                    if (deviceIps.contains(simDatasource.getDeviceIp())) {
                        nowIPList.add(simDatasource.getDeviceIp());
                    }
                }
                deviceIps = null;
                deviceIps = nowIPList;
            }
            rsMap = ReportModel.getSubTitleData(rptMasterTbImp, deviceTypes, deviceIps, subMap, sTime, eTime,
                    subId, false, request);

            Map<Object, Object> data = ReportModel.reformingResult(subMap, rsMap);

            params.put("dvcType", dvctype);
            params.put("talTop", request.getParameter("talTop"));
            params.put("sTime", sTime);
            params.put("eTime", eTime);

            String chartLink = StringUtil.toString(subMap.get("chartLink"), "0");
            int _chartLink = Integer.valueOf(chartLink);

            /************************************************/
            String logQueryUrl = null;
            if (!GlobalUtil.isNullOrEmpty(subMap.get("logQueryCondition"))) {
                logQueryUrl = getLogQueryUrl();
            }
            /************************************************/
            if (("Esm/Topsec/SystemRunLog".equals(dvctype)
                    || "ComprehensiveEsm/Topsec/SystemRunLog".equals(dvctype)) && !sid.isOperator()) {
                logQueryUrl = null;
            }
            String[] talCategory = null;
            String[] categoryValues = request.getParameterValues(ReportUiConfig.talCategory);
            if (categoryValues != null) {
                talCategory = new String[categoryValues.length];
                for (int i = 0, len = categoryValues.length; i < len; i++) {
                    talCategory[i] = ChangePageEncode.IsoToUtf8(categoryValues[i]);
                }
            }
            String reportType = request.getParameter("reportType");
            if (!GlobalUtil.isNullOrEmpty(reportType)) {
                params.put("reportType", reportType);
            }
            StringBuffer url = getUrl(ReportUiConfig.reportEvtUrl, request, params, talCategory, true);
            ;
            String surl = url.toString();
            if (_chartLink > 0) {
                url.append("&superiorId=").append(subList.get(0).get("mstId")).append("&")
                        .append(ReportUiConfig.mstrptid).append("=").append(chartLink).append("&drill=true");
            }
            data.put("url", _chartLink > 0 ? url.toString() : "");
            url.replace(0, url.length(), surl).replace(0, ReportUiConfig.reportEvtUrl.length(),
                    ReportUiConfig.moreEvtUrl);
            url.append("&").append(ReportUiConfig.mstrptid).append("=").append(subList.get(0).get("mstId"))
                    .append("&").append(ReportUiConfig.subrptid).append("=").append(subId);
            data.put("moreUrl", url.toString());

            /**********************************************************************/
            if (!GlobalUtil.isNullOrEmpty(logQueryUrl)) {
                data.put("logQueryUrl", logQueryUrl);
                String nodeId = request.getParameter("nodeId");
                String onlyTable = request.getParameter("onlyTable");
                if (!GlobalUtil.isNullOrEmpty(nodeId)) {
                    params.put("nodeId", nodeId);
                }
                if (!GlobalUtil.isNullOrEmpty(onlyTable)) {
                    params.put("onlyTable", onlyTable);
                }
                data.put("frontEndParams", params);
            }
            /**********************************************************************/

            int type = StringUtil.toInt(StringUtil.toString(subMap.get("chartType"), "1"));
            Map<String, Object> rstMap = CreateChartFactory.getInstance().createChart(type, data);

            if (rstMap != null) {
                json = new JSONObject();
                if (null != chartTableId) {
                    json.put("chartTableId", chartTableId);
                }
                json.put("subID", subId);
                json.put("type", StringUtil.toString(rstMap.get("type"), ""));
                json.put("chart", rstMap.get("chart"));
                json.put("table", rstMap.get("table"));
            }
        }
        return json;
    } finally {
        if (!GlobalUtil.isNullOrEmpty(SID.currentUser())) {
            SID.removeCurrentUser();
        }
    }
}

From source file:org.wso2.carbon.is.migration.service.SchemaMigrator.java

/**
 * executes content in SQL script/* w ww .j  a  v  a 2 s . c  o m*/
 *
 * @return StringBuffer
 * @throws Exception
 */
private void executeSQLScript(String dbscriptName) throws Exception {

    String databaseType = DatabaseCreator.getDatabaseType(this.conn);
    boolean keepFormat = false;

    if ("oracle".equals(databaseType)) {
        delimiter = "/";
    } else if ("db2".equals(databaseType)) {
        delimiter = "/";
    } else if ("openedge".equals(databaseType)) {
        delimiter = "/";
        keepFormat = true;
    }

    StringBuffer sql = new StringBuffer();
    BufferedReader reader = null;

    try {
        InputStream is = new FileInputStream(dbscriptName);
        reader = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            if (!keepFormat) {
                if (line.startsWith("//")) {
                    continue;
                }
                if (line.startsWith("--")) {
                    continue;
                }
                StringTokenizer st = new StringTokenizer(line);
                if (st.hasMoreTokens()) {
                    String token = st.nextToken();
                    if ("REM".equalsIgnoreCase(token)) {
                        continue;
                    }
                }
            }
            //add the oracle database owner
            if ("oracle".equals(databaseType) && line.contains("databasename :=")) {
                if (dbscriptName.contains(IDENTITY_DB_SCRIPT)) {
                    line = "databasename := '" + ISMigrationServiceDataHolder.getIdentityOracleUser() + "';";
                } else if (dbscriptName.contains(UM_DB_SCRIPT)) {
                    line = "databasename := '" + ISMigrationServiceDataHolder.getUmOracleUser() + "';";
                }
            }
            sql.append(keepFormat ? "\n" : " ").append(line);

            // SQL defines "--" as a comment to EOL
            // and in Oracle it may contain a hint
            // so we cannot just remove it, instead we must end it
            if (!keepFormat && line.indexOf("--") >= 0) {
                sql.append("\n");
            }
            if ((DatabaseCreator.checkStringBufferEndsWith(sql, delimiter))) {
                executeSQL(sql.substring(0, sql.length() - delimiter.length()));
                sql.replace(0, sql.length(), "");
            }
        }
        // Catch any statements not followed by ;
        if (sql.length() > 0) {
            executeSQL(sql.toString());
        }
    } catch (Exception e) {
        log.error("Error occurred while executing SQL script for migrating database", e);
        throw new Exception("Error occurred while executing SQL script for migrating database", e);
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:org.eclipse.birt.report.engine.emitter.ppt.PPTWriter.java

protected String getEscapedStr(String s) {
    StringBuffer result = null;
    int spacePos = 1;
    char[] s2char = s.toCharArray();

    for (int i = 0, max = s2char.length, delta = 0; i < max; i++) {
        char c = s2char[i];
        String replacement = null;
        if (c == ' ') {
            if (spacePos % 2 != 0 || i == max - 1) {
                replacement = "&#160;"; //$NON-NLS-1$
            }/* ww  w .  ja v  a  2  s . c  o m*/
            spacePos++;
        } else {
            spacePos = 0;
        }

        // Filters the char not defined.
        if (!(c == 0x9 || c == 0xA || c == 0xD || (c >= 0x20 && c <= 0xD7FF) || (c >= 0xE000 && c <= 0xFFFD))) {
            // Ignores the illegal character.
            replacement = ""; //$NON-NLS-1$
        } else if (c == '&') {
            replacement = "&amp;"; //$NON-NLS-1$
        } else if (c == '<') {
            replacement = "&lt;"; //$NON-NLS-1$
        } else if (c == '>') {
            replacement = "&gt;"; //$NON-NLS-1$
        } else if (c == '\t') {
            replacement = " "; //$NON-NLS-1$
        } else if (c == '=') {
            replacement = "=3D";
        } else if (c >= 0x80) {
            replacement = "&#x" + Integer.toHexString(c) + ';'; //$NON-NLS-1$ 
        }
        if (replacement != null) {
            if (result == null) {
                result = new StringBuffer(s);
            }
            result.replace(i + delta, i + delta + 1, replacement);
            delta += (replacement.length() - 1);
        }
    }
    if (result == null) {
        return s;
    }
    return result.toString();
}

From source file:org.agnitas.beans.impl.MailingImpl.java

@Override
public String personalizeText(String input, int customerID, ApplicationContext con) throws Exception {
    StringBuffer output = new StringBuffer(input);
    TagDetails aDetail = null;/*w w w .j  a  va  2s.c o  m*/
    searchPos = 0;
    String aValue = null;

    while ((aDetail = this.getOneTag(output.toString(), "agn", searchPos, con)) != null) {
        searchPos = aDetail.getStartPos() + 1;
        aDetail.findTagName();
        if (!aDetail.getTagName().equals("agnDYN") && !aDetail.getTagName().equals("agnDVALUE")) {
            if (!aDetail.findTagParameters()) {
                throw new Exception("error.personalization_tag_parameter");
            }
            aValue = this.processTag(aDetail, customerID, con);
            if (aValue != null) {
                output.replace(aDetail.getStartPos(), aDetail.getEndPos(), aValue);
            }
            if (logger.isInfoEnabled())
                logger.info("personalizeText: Tag value from DB '" + aValue + "'");
        }
    }
    return output.toString();
}

From source file:org.wso2.carbon.is.migration.service.v530.MigrationDatabaseCreator.java

/**
 * executes content in SQL script/*from  ww w.  j ava 2  s  .  c om*/
 *
 * @return StringBuffer
 * @throws Exception
 */
private void executeSQLScript(String dbscriptName) throws Exception {

    String databaseType = DatabaseCreator.getDatabaseType(this.conn);
    boolean keepFormat = false;
    if ("oracle".equals(databaseType)) {
        delimiter = "/";
    } else if ("db2".equals(databaseType)) {
        delimiter = "/";
    } else if ("openedge".equals(databaseType)) {
        delimiter = "/";
        keepFormat = true;
    }

    StringBuffer sql = new StringBuffer();
    BufferedReader reader = null;

    try {
        InputStream is = new FileInputStream(dbscriptName);
        reader = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            if (!keepFormat) {
                if (line.startsWith("//")) {
                    continue;
                }
                if (line.startsWith("--")) {
                    continue;
                }
                StringTokenizer st = new StringTokenizer(line);
                if (st.hasMoreTokens()) {
                    String token = st.nextToken();
                    if ("REM".equalsIgnoreCase(token)) {
                        continue;
                    }
                }
            }
            //add the oracle database owner
            if ("oracle".equals(databaseType) && line.contains("databasename :=")) {
                if (dbscriptName.contains(IDENTITY_DB_SCRIPT)) {
                    line = "databasename := '" + ISMigrationServiceDataHolder.getIdentityOracleUser() + "';";
                } else if (dbscriptName.contains(UM_DB_SCRIPT)) {
                    line = "databasename := '" + ISMigrationServiceDataHolder.getUmOracleUser() + "';";
                }
            }
            sql.append(keepFormat ? "\n" : " ").append(line);

            // SQL defines "--" as a comment to EOL
            // and in Oracle it may contain a hint
            // so we cannot just remove it, instead we must end it
            if (!keepFormat && line.indexOf("--") >= 0) {
                sql.append("\n");
            }
            if ((DatabaseCreator.checkStringBufferEndsWith(sql, delimiter))) {
                executeSQL(sql.substring(0, sql.length() - delimiter.length()));
                sql.replace(0, sql.length(), "");
            }
        }
        // Catch any statements not followed by ;
        if (sql.length() > 0) {
            executeSQL(sql.toString());
        }
    } catch (Exception e) {
        log.error("Error occurred while executing SQL script for migrating database", e);
        throw new Exception("Error occurred while executing SQL script for migrating database", e);

    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:org.pentaho.di.core.Const.java

/**
 * Alternate faster version of string replace using a stringbuffer as input.
 *
 * @param str/*from   w ww . j  a v a 2  s  .c om*/
 *          The string where we want to replace in
 * @param code
 *          The code to search for
 * @param repl
 *          The replacement string for code
 */
public static void repl(StringBuffer str, String code, String repl) {
    int clength = code.length();

    int i = str.length() - clength;

    while (i >= 0) {
        String look = str.substring(i, i + clength);
        // Look for a match!
        if (look.equalsIgnoreCase(code)) {
            str.replace(i, i + clength, repl);
        }
        i--;
    }
}

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 w  w w  .j  a v a  2  s . c  o m*/
    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));
    }
}