Example usage for org.apache.solr.client.solrj.util ClientUtils escapeQueryChars

List of usage examples for org.apache.solr.client.solrj.util ClientUtils escapeQueryChars

Introduction

In this page you can find the example usage for org.apache.solr.client.solrj.util ClientUtils escapeQueryChars.

Prototype


public static String escapeQueryChars(String s) 

Source Link

Document

See: <a href="https://www.google.com/?gws_rd=ssl#q=lucene+query+parser+syntax">Lucene query parser syntax</a> for more information on Escaping Special Characters

Usage

From source file:org.dspace.app.cris.integration.RPAuthority.java

/**
 * Return a list of choices performing an exact query on the RP names (full,
 * Chinese, academinc, variants). For any matching RP will be returned
 * choices for every variants form, the default choice will be which that
 * match with the "query" string. This method is used by unattended
 * submssion only, interactive submission will use the
 * {@link RPAuthority#getMatches(String, String, int, int, int, String)}.
 * The confidence value of the returned Choices will be
 * {@link Choices#CF_UNCERTAIN} if there is only a RP that match with the
 * lookup string or {@link Choices#CF_AMBIGUOUS} if there are more RPs.
 * //from ww w  . j  av  a2s  .  co m
 * {@link ChoiceAuthority#getMatches(String, String, int, int, int, String)}
 * 
 * @param field
 *            (not used by this Authority)
 * @param text
 *            the lookup string
 * @param collection
 *            (not used by this Authority)
 * @param locale
 *            (not used by this Authority)
 * @return a Choices of RPs that have an exact string match between a name
 *         forms and the text lookup string
 */
@Override
public Choices getBestMatch(String field, String text, int collection, String locale) {

    try {
        init();
        List<Choice> choiceList = new ArrayList<Choice>();
        int totalResult = 0;
        if (text != null && text.length() > 2) {
            DiscoverQuery discoverQuery = new DiscoverQuery();
            discoverQuery.setDSpaceObjectFilter(CrisConstants.RP_TYPE_ID);
            String filter = configurationService.getProperty("cris." + RP_AUTHORITY_NAME + ".filter");
            if (filter != null) {
                discoverQuery.addFilterQueries(filter);
            }

            discoverQuery.setQuery("{!lucene q.op=AND df=crisauthoritylookup}\""
                    + ClientUtils.escapeQueryChars(text.trim()) + "\"");
            discoverQuery.setMaxResults(50);
            DiscoverResult result = searchService.search(null, discoverQuery, true);
            totalResult = (int) result.getTotalSearchResults();
            for (DSpaceObject dso : result.getDspaceObjects()) {
                ResearcherPage rp = (ResearcherPage) dso;
                choiceList.add(
                        new Choice(rp.getCrisID(), text, ResearcherPageUtils.getLabel(rp.getFullName(), rp)));
            }
        }

        Choice[] results = new Choice[choiceList.size()];
        if (choiceList.size() > 0) {
            results = choiceList.toArray(results);

            if (totalResult == 1) {
                return new Choices(results, 0, totalResult, Choices.CF_UNCERTAIN, false, 0);
            } else {
                return new Choices(results, 0, totalResult, Choices.CF_AMBIGUOUS, false, 0);
            }
        } else {
            return new Choices(false);
        }
    } catch (Exception e) {
        log.error("Error quering the HKUAuthority - " + e.getMessage(), e);
        return new Choices(true);
    }
}

From source file:org.dspace.app.cris.network.AVisualizationGraph.java

private String buildQuery(String authority, String name, boolean showSameDept, String dept, Integer modeEntity,
        Integer level) {//  w  w w .  ja  v a 2  s .  com
    String query = "";
    if (authority != null && !authority.isEmpty()) {
        query += "focus_auth:" + authority;
    } else {
        query += "focus_val:\"" + ClientUtils.escapeQueryChars(name) + "\"";
    }

    if (showSameDept) {
        if (modeEntity == ConstantNetwork.ENTITY_RP) {
            query += " AND focus_dept:\"" + ClientUtils.escapeQueryChars(dept) + "|||"
                    + ClientUtils.escapeQueryChars(dept) + "\"";
        }
    }
    return query;
}

From source file:org.dspace.app.cris.network.AVisualizationGraphModeTwo.java

@Override
public List<VisualizationGraphNode> load(List<String[]> discardedNode, Integer importedNodes,
        Boolean otherError) throws Exception {
    // load all publications
    SolrQuery solrQuery = new SolrQuery();
    solrQuery.setQuery(getQuery());//from   w w w  . j a v a  2  s.  c o m
    solrQuery.addFacetField(getFacetFieldQuery());
    // solrQuery.addFilterQuery("authors_fauthority:rp00001");
    solrQuery.setFacetLimit(Integer.MAX_VALUE);
    solrQuery.setFacetMinCount(1);
    solrQuery.setRows(0);
    QueryResponse rsp = getService().getSearcher().search(solrQuery);
    FacetField facets = rsp.getFacetField(getFacetFieldQuery());
    System.out.println(facets.getValueCount());
    // for each interests get authority's authors
    List<VisualizationGraphNode> result = null;
    int counter = 0;
    external: for (Count facetElement : facets.getValues()) {
        counter++;

        log.debug(getConnectionName() + " - " + counter + " of " + facets.getValueCount());
        System.out.println(getConnectionName() + " - " + counter + " of " + facets.getValueCount());
        result = new LinkedList<VisualizationGraphNode>();
        try {

            String facetValue = facetElement.getName();

            solrQuery = new SolrQuery();
            String query = (useJoin() ? getJoin() : "") + getFacetFieldQuery() + ":\""
                    + ClientUtils.escapeQueryChars(facetValue) + "\"";
            solrQuery.setQuery(query);
            solrQuery.addFacetField(getFacet(facetValue));
            solrQuery.setFacetMinCount(1);
            solrQuery.setFacetLimit(getFacetLimit());
            solrQuery.setRows(0);

            rsp = getService().getSearcher().search(solrQuery);
            FacetField relations = rsp.getFacetField(getFacet(facetValue));
            int i = 0;
            internal: for (Count relation : relations.getValues()) {

                log.debug("" + counter + " works on " + i + " of " + relations.getValueCount());
                System.out.println(getConnectionName() + " - " + counter + " of " + facets.getValueCount()
                        + " works on " + i + " of " + relations.getValueCount());
                String aaa = relation.getName();
                String[] split = aaa.split("\\|\\|\\|");

                String a = aaa;
                String a_authority = null;
                String a_dept = null;
                String a_displayValue = "";

                if (split.length > 1) {

                    String[] splitAuthority = split[1].split(splitterAuthority);

                    a_displayValue = splitAuthority[0];
                    if (splitAuthority.length > 1) {
                        a_authority = splitAuthority[1];
                        // a_dept = ResearcherPageUtils
                        // .getDepartment(a_authority);
                        a_dept = getDepartmentFromSOLR(a_authority);
                    }

                }

                internalprivate: for (int j = i; j < relations.getValues().size(); j++) {
                    List<String> values = new LinkedList<String>();
                    values.add(facetValue);

                    String bbb = relations.getValues().get(j).getName();
                    split = bbb.split("\\|\\|\\|");

                    String b = bbb;
                    String b_authority = null;
                    String b_dept = null;
                    String b_displayValue = "";

                    if (split.length > 1) {
                        String[] splitAuthority = split[1].split(splitterAuthority);

                        b_displayValue = splitAuthority[0];
                        if (splitAuthority.length > 1) {
                            b_authority = splitAuthority[1];
                            // a_dept = ResearcherPageUtils
                            // .getDepartment(a_authority);
                            b_dept = getDepartmentFromSOLR(b_authority);
                        }
                    }

                    if (j == i) {
                        buildRow(result, a, a_authority, a_displayValue, b, b_authority, b_displayValue, values,
                                buildExtra(facetValue), a_dept, b_dept, ConstantNetwork.ENTITY_PLACEHOLDER_RP);
                    } else {
                        if (!a.equals(b)) {
                            buildRow(result, a, a_authority, a_displayValue, b, b_authority, b_displayValue,
                                    values, buildExtra(facetValue), a_dept, b_dept, ConstantNetwork.ENTITY_RP);
                        }
                    }
                }

                i++;

            }

        } catch (Exception e) {
            log.error("Error try to build object to index with ID:" + "");
            log.error(e.getMessage(), e);
            otherError = true;
            continue;
        }
        importedNodes = indexNode(discardedNode, importedNodes, result);
    }

    log.debug("commit " + getType());
    getIndexer().commit();
    return result;
}

From source file:org.dspace.app.cris.network.DepartmentNetworkPlugin.java

public List<VisualizationGraphNode> load(List<String[]> discardedNode, Integer importedNodes,
        Boolean otherError, List<String> connections) throws Exception {

    for (String connection : connections) {
        SolrQuery solrQuery = new SolrQuery();
        solrQuery.setQuery("type:" + connection);
        solrQuery.addFacetField(FACET);/*  w w  w . j av  a  2s .  c o m*/
        solrQuery.setFacetLimit(Integer.MAX_VALUE);
        solrQuery.setFacetMinCount(1);
        solrQuery.setRows(0);
        QueryResponse rsp = service.search(solrQuery);
        FacetField facets = rsp.getFacetField(FACET);

        // for each interests get authority's authors
        List<VisualizationGraphNode> result = null;
        int counter = 0;
        external: for (Count facetElement : facets.getValues()) {

            counter++;
            log.debug("" + counter + " of " + facets.getValueCount());
            result = new LinkedList<VisualizationGraphNode>();
            try {
                String facetValue = facetElement.getName();
                String[] splittedFacetValue = facetValue.split("\\|\\|\\|");
                if (!splittedFacetValue[0].equals("null")
                        && splittedFacetValue[0].equals(splittedFacetValue[1])) {
                    SolrQuery solrQuery2 = new SolrQuery();
                    solrQuery2.setQuery("type:" + connection + " AND " + FACET + ":\""
                            + ClientUtils.escapeQueryChars(facetValue)
                            + "\" AND a_auth:[* TO *] AND b_auth:[* TO *]");

                    solrQuery2.addFacetField(FACET_AUTHOR);
                    solrQuery2.setFacetMinCount(1);
                    solrQuery2.setFacetLimit(Integer.MAX_VALUE);
                    solrQuery2.setRows(0);

                    QueryResponse rsp2 = service.search(solrQuery2);
                    FacetField relations = rsp2.getFacetField(FACET_AUTHOR);
                    int i = 0;
                    internal: for (Count relation : relations.getValues()) {
                        log.debug("" + counter + " works on " + i + " of " + relations.getValueCount());
                        List<String> values = new LinkedList<String>();
                        values.add(splittedFacetValue[0]);

                        String aaa = relation.getName();
                        String[] split = aaa.split("\\|\\|\\|");

                        String a = aaa;
                        String a_authority = null;
                        String a_displayValue = "";

                        if (split.length > 1) {
                            a_displayValue = split[1];
                        }

                        if (split.length > 2) {
                            a_authority = split[2];
                        }

                        buildRow(result, splittedFacetValue[0], null, splittedFacetValue[1], a, a_authority,
                                a_displayValue, values, buildExtra(splittedFacetValue[0]), connection);

                        i++;

                    }

                    importedNodes = importNode(discardedNode, importedNodes, result);
                    log.debug("commit DEPARTMENT " + facetValue);
                    indexer.getSolr().commit();
                }

            } catch (Exception e) {
                log.error("Error try to build object to index with ID:" + "");
                log.error(e.getMessage(), e);
                otherError = true;
                continue;
            }

        }

    }

    return null;
}

From source file:org.dspace.app.webui.cris.controller.ExportFormController.java

private void addToTempQuery(String fieldName, String value, List<String> f, List<String> q, boolean escape) {
    if (StringUtils.isNotBlank(value)) {
        q.add(escape ? ClientUtils.escapeQueryChars(value) : value);
        f.add(fieldName);/*from   w  w  w.j av a2s. co  m*/
    }
}

From source file:org.dspace.app.webui.cris.util.RelationPreferenceUtil.java

public RelatedObjects getRelatedObject(Context context, ACrisObject cris, String relationType, String userQuery,
        String status, List<Sort> sorts, int rpp, int offset) throws SearchServiceException, SQLException {
    String uuid = cris.getUuid();
    String configurationName = preferenceService.getConfigurationName(cris, relationType);
    RelationPreferenceConfiguration configuration = preferenceService.getConfigurationService()
            .getRelationPreferenceConfiguration(configurationName);
    List<ColumnVisualizationConfiguration> columns = configuration.getColumnsVisualizationConfiguration();
    RelatedObjects result = new RelatedObjects();
    List<RelatedObject> related = result.getObjects();

    String query = MessageFormat.format(configuration.getRelationConfiguration().getQuery(), cris.getCrisID(),
            cris.getUuid());/*w  w  w . ja va 2  s.c o m*/

    boolean sysAdmin = AuthorizeManager.isAdmin(context);

    SolrQuery solrQuery = new SolrQuery();
    if (StringUtils.isNotEmpty(userQuery)) {
        solrQuery.addFilterQuery("{!tag=user}" + ClientUtils.escapeQueryChars(userQuery) + "*");
        solrQuery.addFacetQuery("{!ex=user}*:*");
    }

    if (!configuration.isActionEnabled(RelationPreference.HIDED, sysAdmin)) {
        solrQuery.addFilterQuery(getHiddenFilter(cris, configurationName));
    }
    if (!configuration.isActionEnabled(RelationPreference.SELECTED, sysAdmin)) {
        solrQuery.addFilterQuery(getSelectedFilter(cris, configurationName));
    }
    if (configuration.isActionEnabled(RelationPreference.UNLINKED, sysAdmin)) {
        query = getUnlinkedFilter(cris, configurationName, query);
    }

    solrQuery.setQuery(query);

    if (StringUtils.isNotEmpty(status)) {

        solrQuery.addFilterQuery(RelationPreference.PREFIX_RELATIONPREFERENCES + configurationName + "."
                + status.toLowerCase() + ":\"" + cris.getUuid() + "\"");

    }

    if (sorts != null) {
        for (Sort s : sorts) {
            if (s.col < 0) {
                solrQuery.addSortField("cris-uuid", s.asc ? ORDER.asc : ORDER.desc);
                solrQuery.addSortField("search.resourceid", s.asc ? ORDER.asc : ORDER.desc);
            } else {
                solrQuery.addSortField(columns.get(s.col).getSortField(), s.asc ? ORDER.asc : ORDER.desc);
            }
        }
    }

    solrQuery.setRows(rpp);
    solrQuery.setStart(offset);
    solrQuery.setFields("search.resourceid", "cris-uuid",
            RelationPreference.PREFIX_RELATIONPREFERENCES + configurationName + "."
                    + RelationPreference.UNLINKED,
            RelationPreference.PREFIX_RELATIONPREFERENCES + configurationName + "." + RelationPreference.HIDED,
            RelationPreference.PREFIX_RELATIONPREFERENCES + configurationName + "."
                    + RelationPreference.SELECTED);
    QueryResponse qRes = searcher.search(solrQuery);
    result.setFilterRecords((int) qRes.getResults().getNumFound());
    if (StringUtils.isNotEmpty(userQuery)) {
        result.setTotalRecords(qRes.getFacetQuery().get("{!ex=user}*:*"));
    } else {
        result.setTotalRecords((int) qRes.getResults().getNumFound());
    }
    List<Object[]> dsoList = new ArrayList<Object[]>();
    for (SolrDocument doc : qRes.getResults()) {
        List<String> unlinked = (List<String>) doc.getFieldValue(RelationPreference.PREFIX_RELATIONPREFERENCES
                + configurationName + "." + RelationPreference.UNLINKED);
        List<String> hided = (List<String>) doc.getFieldValue(RelationPreference.PREFIX_RELATIONPREFERENCES
                + configurationName + "." + RelationPreference.HIDED);
        List<String> selected = (List<String>) doc.getFieldValue(RelationPreference.PREFIX_RELATIONPREFERENCES
                + configurationName + "." + RelationPreference.SELECTED);
        String relStatus = null;
        if (unlinked != null && unlinked.contains(uuid)) {
            relStatus = RelationPreference.UNLINKED;
        } else if (hided != null && hided.contains(uuid)) {
            relStatus = RelationPreference.HIDED;
        } else if (selected != null && selected.contains(uuid)) {
            relStatus = RelationPreference.SELECTED;
        }
        if (doc.getFieldValue("cris-uuid") == null) {
            try {
                dsoList.add(new Object[] { Item.find(context, (Integer) doc.getFieldValue("search.resourceid")),
                        relStatus });
            } catch (SQLException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        } else {
            dsoList.add(new Object[] {
                    applicationService.getEntityByUUID((String) doc.getFieldValue("cris-uuid")), relStatus });
        }
    }
    for (Object[] dso : dsoList) {
        related.add(convert(context, (DSpaceObject) dso[0], configuration, (String) dso[1]));
    }
    return result;
}

From source file:org.dspace.app.webui.discovery.DiscoverUtility.java

License:BSD License

/**
* Escape some solr special characters from the user's query.
* 
* 1 - when a query ends with one of solr's special characters (^, \,!, +, -,:, ||, && (,),{,},[,]) 
*     (a space in between or not) (e.g. "keyword3 :") the user gets 
*     an erroneous notification or the search doesn't produce results. 
*     Those characters at the end of the query should be escaped.
* 
* 2 - escape every colon, followed by a space (e.g. "title: subtitle")
*     in a user's query. This is intended to let end users to pass 
*     in a title containing colon-space without requiring them to escape the colon.
* 
* @param query user-entered query string
* @return query escaping some of solr's special characters at the end and 
*         with a colon in colon-space sequence escaped if they occur.
*///from  w w w.jav a 2  s .  c om
private static String escapeQueryChars(String query) {
    query = query.trim();

    // [+\\-&|!()\\s{}\\[\\]\\^\"\\\\:]: ome of the solr's special characters that need to be escaped for regex as well as for string.
    //                                   Regex representation of \ is \\. Therefore the string representation of \\ is \\\\).
    //                                   \\s is in case withespaces is in between the characters.
    // + : Match or more of the preceding token
    // (?=\s+$|$): Matches all solr's special characters at the end of a string independently of any whitespace characters 
    //            - ?= is a positive lookahead. Matches a group after the main expression without including it in the result
    //            - \s: Matches any whitespace character (spaces, tabs, line breaks )
    //            - $: Matches the end of a string
    String regx = "[+\\-&|!()\\s{}\\[\\]\\^\"\\\\:]+(?=\\s+$|$)";
    Pattern pattern = Pattern.compile(regx);
    Matcher matcher = pattern.matcher(query);

    if (matcher.find()) {
        String matcherGroup = matcher.group();
        String escapedMatcherGroup = ClientUtils.escapeQueryChars(matcherGroup);

        // Do not escape brackets if they are properly opened and closed.
        if (matcherGroup.equals(")") || matcherGroup.equals("]") || matcherGroup.equals("}")
                || matcherGroup.equals("\"")) {
            String closingBracket = matcher.group();
            String openingBracket = new String();

            switch (closingBracket) {
            case "}":
                openingBracket = "{";
                break;
            case ")":
                openingBracket = "(";
                break;
            case "]":
                openingBracket = "[";
                break;
            case "\"":
                openingBracket = "\"";
                break;
            }

            String bracketsRegex = "\\".concat(openingBracket).concat("(.*?)\\").concat(closingBracket);

            if (!Pattern.compile(bracketsRegex).matcher(query).find()) {
                query = StringUtils.replace(query, matcherGroup, escapedMatcherGroup);
            }
        } else {
            query = StringUtils.replace(query, matcherGroup, escapedMatcherGroup);
        }
    }

    query = StringUtils.replace(query, ": ", "\\:");
    return query;
}

From source file:org.dspace.app.xmlui.aspect.discovery.AbstractFiltersTransformer.java

License:Open Source License

@Override
public void addOptions(Options options)
        throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException {
    Request request = ObjectModelHelper.getRequest(objectModel);

    DSpaceObject dso = HandleUtil.obtainHandle(objectModel);

    java.util.List fqs = Arrays.asList(
            request.getParameterValues("fq") != null ? request.getParameterValues("fq") : new String[0]);

    if (this.queryResults != null) {
        java.util.List<FacetField> facetFields = this.queryResults.getFacetFields();
        if (facetFields == null)
            facetFields = new ArrayList<FacetField>();

        if (queryResults.getFacetDates() != null)
            facetFields.addAll(this.queryResults.getFacetDates());

        if (facetFields.size() > 0) {
            addDiscoveryLocation(options, request, fqs, dso);

            ////////////
            List browse = options.addList("discovery");
            boolean firstSubList = true;

            for (FacetField field : facetFields) {

                // Skip location filter, since this is handled above.
                if (field.getName().equals("location")) {
                    continue;
                }/*from   w  ww  .j a  va2 s  .  co m*/

                java.util.List<FacetField.Count> values = field.getValues();

                //This is needed for a dirty hack to make sure that the date filters do not remain empty
                boolean valueAdded = false;
                if (values != null) {

                    if (firstSubList) {
                        browse.setHead(message("xmlui.ArtifactBrowser.AdvancedSearch.filter_by.head"));
                        firstSubList = false;
                    }
                    List facet = browse.addList(field.getName());

                    facet.setHead(message("xmlui.ArtifactBrowser.AdvancedSearch.type_"
                            + field.getName().replace("_lc", "").replace("_dt", "")));

                    Iterator<FacetField.Count> iter = values.iterator();
                    for (int i = 0; i < this.queryArgs.getFacetLimit(); i++) {
                        if (!iter.hasNext())
                            break;
                        FacetField.Count value = iter.next();

                        if (i < this.queryArgs.getFacetLimit() - 1) {
                            String displayedValue = value.getName();
                            String filterQuery = value.getAsFilterQuery();
                            String itemName = null;
                            String itemRend = null;
                            if (field.getName().equals("location.comm")
                                    || field.getName().equals("location.coll")) {
                                //We have a community/collection, resolve it to a dspaceObject
                                //                                    displayedValue = SolrServiceImpl.locationToName(context, field.getName(), displayedValue);
                                int type = field.getName().equals("location.comm") ? Constants.COMMUNITY
                                        : Constants.COLLECTION;
                                DSpaceObject commColl = DSpaceObject.find(context, type,
                                        Integer.parseInt(displayedValue));
                                if (commColl != null) {
                                    displayedValue = commColl.getName();
                                    itemName = commColl.getHandle();
                                }
                            }
                            if (field.getGap() != null) {
                                //We have a date field
                                //Since we currently only support years, get the year
                                //PS: date looks something like this: 2005-01-01T00:00:00Z
                                displayedValue = displayedValue.split("-")[0];
                                filterQuery = ClientUtils.escapeQueryChars(value.getFacetField().getName())
                                        + ":" + displayedValue + "*";
                                // What we do now is, if we have a date and we have selected one as a filter query, do not show the other values
                                // There is no need to this since we can only have one date at a time
                                // What we do show however is the current date.
                                boolean skipValue = false;
                                for (Object fq1 : fqs) {
                                    String fq = (String) fq1;
                                    if (fq.startsWith(value.getFacetField().getName() + ":")
                                            && !fq.equals(filterQuery))
                                        skipValue = true;
                                }
                                //Skipt these vals, there are not relevant, they are required to indicate if we need a view more url
                                if (displayedValue.equals(FacetParams.FacetDateOther.AFTER.toString())
                                        || displayedValue.equals(FacetParams.FacetDateOther.BEFORE.toString())
                                        || displayedValue.equals(FacetParams.FacetDateOther.BETWEEN.toString()))
                                    skipValue = true;

                                if (value.getCount() == 0)
                                    skipValue = ConfigurationManager.getBooleanProperty("solr.date.skip.empty",
                                            true);

                                if (skipValue)
                                    continue;
                            }

                            if (fqs.contains(filterQuery)) {
                                valueAdded = true;
                                facet.addItem(Math.random() + "", "selected")
                                        .addContent(displayedValue + " (" + value.getCount() + ")");
                            } else {
                                valueAdded = true;
                                facet.addItem(itemName, itemRend).addXref(
                                        contextPath + (dso == null ? "" : "/handle/" + dso.getHandle())
                                                + "/search?" + request.getQueryString() + "&fq="
                                                + URLEncoder.encode(filterQuery, "UTF-8"),
                                        displayedValue + " (" + value.getCount() + ")" // + "TESTE"
                                );
                            }
                        }
                        if (i == this.queryArgs.getFacetLimit() - 1 && field.getGap() == null) {

                            addViewMoreUrl(facet, dso, request, field.getName());
                        }
                    }
                    if (field.getGap() != null) {
                        if (!valueAdded) {
                            /** THIS IS A DIRTY HACK TO MAKE SURE WE DO NOT HAVE AN EMPTY DATE FILTER
                             * THIS WILL NOT WORK IF THE DATE FIELD SHOULD BE REPEATABLE ! **/
                            /** Add a field using this content **/
                            /** Locate the value in the filter **/
                            for (Object fq1 : fqs) {
                                String fq = (String) fq1;
                                if (fq.startsWith(field.getName() + ":")) {
                                    String valShown = fq.substring(fq.indexOf(":") + 1);
                                    //Remove the * at the end
                                    valShown = valShown.substring(0, valShown.length() - 1);
                                    facet.addItem().addContent(
                                            valShown + " (" + queryResults.getResults().getNumFound() + ")");
                                }
                            }
                        }

                        // We have a date check if we need a view more
                        // We need a view more if we have values that come after OR before our shown dates
                        boolean showMoreUrl = false;
                        for (FacetField.Count facetValue : values) {
                            if (facetValue.getName().equals(FacetParams.FacetDateOther.AFTER.toString())
                                    || facetValue.getName()
                                            .equals(FacetParams.FacetDateOther.BEFORE.toString().toString()))
                                if (0 < facetValue.getCount())
                                    showMoreUrl = true;
                        }
                        // Add the _dt postfix to make sure that our browse is shown as a date
                        if (showMoreUrl)
                            addViewMoreUrl(facet, dso, request, field.getName() + "_dt");
                    }
                    // If we have no value added
                }
            }
        }
    }
}

From source file:org.dspace.app.xmlui.aspect.discovery.BrowseFacet.java

License:Open Source License

private void renderFacetField(Request request, DSpaceObject dso, FacetField field, Table singleTable,
        List<String> filterQueries, FacetField.Count value)
        throws SQLException, WingException, UnsupportedEncodingException {
    String displayedValue = value.getName();
    String filterQuery = value.getAsFilterQuery();
    if (field.getName().equals("location.comm") || field.getName().equals("location.coll")) {
        //We have a community/collection, resolve it to a dspaceObject
        //            displayedValue = SolrServiceImpl.locationToName(context, field.getName(), displayedValue);
        int type = field.getName().equals("location.comm") ? Constants.COMMUNITY : Constants.COLLECTION;
        DSpaceObject commColl = DSpaceObject.find(context, type, Integer.parseInt(displayedValue));
        if (commColl != null) {
            displayedValue = commColl.getName() + "TEST";
        }//w  w  w  .j a va  2s  . c om
    }
    if (field.getGap() != null) {
        //We have a date get the year so we can display it
        DateFormat simpleDateformat = new SimpleDateFormat("yyyy");
        displayedValue = simpleDateformat.format(SolrServiceImpl.toDate(displayedValue));
        //displayedValue = displayedValue.substring(0, 4);
        filterQuery = ClientUtils.escapeQueryChars(value.getFacetField().getName()) + ":" + displayedValue
                + "*";
    }

    Cell cell = singleTable.addRow().addCell();

    //No use in selecting the same filter twice
    if (filterQueries.contains(filterQuery)) {
        //            cell.addContent(displayedValue + " (" + value.getCount() + ")");
        cell.addContent(displayedValue + " (" + value.getCount() + ")");
    } else {
        cell.addXref(contextPath + (dso == null ? "" : "/handle/" + dso.getHandle()) + "/search?" + "&fq="
                + URLEncoder.encode(filterQuery, "UTF-8")
        //+ (request.getQueryString() != null ? "&" + request.getQueryString() : "")
                ,
                //                    displayedValue + " (" + value.getCount() + ")");
                displayedValue, String.valueOf(value.getCount()));
    }
}

From source file:org.dspace.app.xmlui.aspect.discovery.DiscoveryUIUtils.java

License:BSD License

/**
 * Escape some solr special characters from the user's query.
 * //from   ww w.j a  va2 s  .  co m
 * 1 - when a query ends with one of solr's special characters (^, \,!, +, -,:, ||, && (,),{,},[,]) 
 *     (a space in between or not) (e.g. "keyword3 :") the user gets 
 *     an erroneous notification or the search doesn't produce results. 
 *     Those characters at the end of the query should be escaped.
 * 
 * 2 - escape every colon, followed by a space (e.g. "title: subtitle")
 *     in a user's query. This is intended to let end users to pass 
 *     in a title containing colon-space without requiring them to escape the colon.
 * 
 * @param query user-entered query string
 * @return query escaping some of solr's special characters at the end and 
 *         with a colon in colon-space sequence escaped if they occur.
 */
public static String escapeQueryChars(String query) {
    query = query.trim();

    // [+\\-&|!()\\s{}\\[\\]\\^\"\\\\:]: ome of the solr's special characters that need to be escaped for regex as well as for string.
    //                                   Regex representation of \ is \\. Therefore the string representation of \\ is \\\\).
    //                                   \\s is in case withespaces is in between the characters.
    // + : Match or more of the preceding token
    // (?=\s+$|$): Matches all solr's special characters at the end of a string independently of any whitespace characters 
    //            - ?= is a positive lookahead. Matches a group after the main expression without including it in the result
    //            - \s: Matches any whitespace character (spaces, tabs, line breaks )
    //            - $: Matches the end of a string
    String regx = "[+\\-&|!()\\s{}\\[\\]\\^\"\\\\:]+(?=\\s+$|$)";
    Pattern pattern = Pattern.compile(regx);
    Matcher matcher = pattern.matcher(query);

    if (matcher.find()) {
        String matcherGroup = matcher.group();
        String escapedMatcherGroup = ClientUtils.escapeQueryChars(matcherGroup);

        // Do not escape brackets if they are properly opened and closed.
        if (matcherGroup.equals(")") || matcherGroup.equals("]") || matcherGroup.equals("}")
                || matcherGroup.equals("\"")) {
            String closingBracket = matcher.group();
            String openingBracket = new String();

            switch (closingBracket) {
            case "}":
                openingBracket = "{";
                break;
            case ")":
                openingBracket = "(";
                break;
            case "]":
                openingBracket = "[";
                break;
            case "\"":
                openingBracket = "\"";
                break;
            }

            String bracketsRegex = "\\".concat(openingBracket).concat("(.*?)\\").concat(closingBracket);

            if (!Pattern.compile(bracketsRegex).matcher(query).find()) {
                query = StringUtils.replace(query, matcherGroup, escapedMatcherGroup);
            }
        } else {
            query = StringUtils.replace(query, matcherGroup, escapedMatcherGroup);
        }
    }

    query = StringUtils.replace(query, ": ", "\\:");
    return query;
}