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.sakaiproject.nakamura.calendar.search.CalendarIndexingHandler.java

License:Apache License

/**
 * {@inheritDoc}/*from   w  ww  . java2  s .c  om*/
 *
 * @see org.sakaiproject.nakamura.api.solr.IndexingHandler#getDeleteQueries(org.sakaiproject.nakamura.api.solr.RepositorySession,
 *      org.osgi.service.event.Event)
 */
public Collection<String> getDeleteQueries(RepositorySession repositorySession, Event event) {
    List<String> retval = Collections.emptyList();
    logger.debug("GetDelete for {} ", event);
    String path = (String) event.getProperty(FIELD_PATH);
    String resourceType = (String) event.getProperty("resourceType");
    if (RESOURCE_TYPES.contains(resourceType)) {
        retval = ImmutableList.of("id:" + ClientUtils.escapeQueryChars(path));
    }
    return retval;
}

From source file:org.sakaiproject.nakamura.calendar.search.CalenderSearchPropertyProvider.java

License:Apache License

/**
 * @param request/* ww w  . j a v  a 2  s.c  o  m*/
 * @param propertiesMap
 */
protected void addCalendarEventPath(SlingHttpServletRequest request, Map<String, String> propertiesMap) {
    try {
        RequestParameter eventParam = request.getRequestParameter("event-path");
        if (eventParam != null) {
            String eventPath = eventParam.getString("UTF-8");
            propertiesMap.put("_event-path", ClientUtils.escapeQueryChars(eventPath));
        }
    } catch (UnsupportedEncodingException e) {
        LOGGER.error(
                "Caught an UnsupportedEncodingException when trying to provide properties for the calendar search templates.",
                e);
    }
}

From source file:org.sakaiproject.nakamura.calendar.search.CalenderSearchPropertyProvider.java

License:Apache License

/**
 * Adds the date range values to the search template.
 *
 * <pre>/*  w  w w .  j  a  v a 2 s .  c  om*/
 * {@code
 *  - _date-start
 *  - _date-end
 *  }
 * </pre>
 *
 * If there is no 'start' and 'end' request parameter, then the current day is used. A
 * day starts at 00:00 and ends the next day at 00:00
 *
 * @param request
 *          The request that has been done on the search node.
 * @param propertiesMap
 *          The map where the key-values should be added to.
 */
protected void addStartEnd(SlingHttpServletRequest request, Map<String, String> propertiesMap) {
    try {
        // Default is today
        Calendar cStart = getDayCalendar();
        Calendar cEnd = getDayCalendar();
        cEnd.add(Calendar.DAY_OF_MONTH, 1);

        // If a parameter is specified, we try to parse it and use that one.
        RequestParameter startParam = request.getRequestParameter(START_DAY_PARAM);
        RequestParameter endParam = request.getRequestParameter(END_DAY_PARAM);
        if (startParam != null && endParam != null) {
            String start = startParam.getString("UTF-8");
            String end = endParam.getString("UTF-8");
            cStart.setTime(format.parse(start));
            cEnd.setTime(format.parse(end));
        }

        // Calculate the beginning and the end date.
        String beginning = DateUtils.iso8601jcr(cStart);
        String end = DateUtils.iso8601jcr(cEnd);

        // Add to map.
        propertiesMap.put("_date-start", ClientUtils.escapeQueryChars(beginning));
        propertiesMap.put("_date-end", ClientUtils.escapeQueryChars(end));
    } catch (UnsupportedEncodingException e) {
        LOGGER.error(
                "Caught an UnsupportedEncodingException when trying to provide properties for the calendar search templates.",
                e);
    } catch (ParseException e) {
        LOGGER.error(
                "Caught a ParseException when trying to provide properties for the calendar search templates.",
                e);
    }

}

From source file:org.sakaiproject.nakamura.calendar.search.CalenderSearchPropertyProvider.java

License:Apache License

/**
 * @param request//from   w  w w . j a v  a 2 s  .  c  om
 * @param propertiesMap
 */
protected void addCalendarPath(SlingHttpServletRequest request, Map<String, String> propertiesMap) {
    try {
        String user = request.getRemoteUser();
        String path = LitePersonalUtils.getHomePath(user) + "/" + CalendarConstants.SAKAI_CALENDAR_NODENAME;

        RequestParameter pathParam = request.getRequestParameter(PATH_PARAM);
        if (pathParam != null) {
            path = pathParam.getString("UTF-8");
        }

        propertiesMap.put("_calendar-path", ClientUtils.escapeQueryChars(path));

    } catch (UnsupportedEncodingException e) {
        LOGGER.error(
                "Caught an UnsupportedEncodingException when trying to provide properties for the calendar search templates.",
                e);
    }
}

From source file:org.sakaiproject.nakamura.chat.ChatMessageSearchPropertyProvider.java

License:Apache License

/**
 * {@inheritDoc}//from   w w  w. j a v a2s . c  o m
 *
 * @see org.sakaiproject.nakamura.api.search.SearchPropertyProvider#loadUserProperties(org.apache.sling.api.SlingHttpServletRequest,
 *      java.util.Map)
 */
public void loadUserProperties(SlingHttpServletRequest request, Map<String, String> propertiesMap) {
    try {
        final String user = request.getRemoteUser();
        final Session session = StorageClientUtils
                .adaptToSession(request.getResourceResolver().adaptTo(javax.jcr.Session.class));
        final String fullPathToStore = ClientUtils
                .escapeQueryChars(messagingService.getFullPathToStore(user, session));
        propertiesMap.put(MessageConstants.SEARCH_PROP_MESSAGESTORE, fullPathToStore + "*");

        final RequestParameter usersParam = request.getRequestParameter("_from");
        if (usersParam != null && !usersParam.getString().equals("")) {
            final StringBuilder solr = new StringBuilder(" AND (");
            final String[] users = StringUtils.split(usersParam.getString(), ',');

            solr.append("from:(");
            for (final String u : users) {
                if ("*".equals(u))
                    continue;
                solr.append(ClientUtils.escapeQueryChars(u)).append(" OR ");
                // sql.append("@sakai:from=\"").append(escapeString(u, Query.XPATH))
                // .append("\" or ");
            }
            solr.append(ClientUtils.escapeQueryChars(user));
            // sql.append("@sakai:from=\"").append(escapeString(user, Query.XPATH))
            // .append("\") or (");
            solr.append(")"); // close from:

            solr.append(" AND to:(");
            for (final String u : users) {
                if ("*".equals(u))
                    continue;
                solr.append(ClientUtils.escapeQueryChars(u)).append(" OR ");
                // sql.append("@sakai:to=\"").append(escapeString(u, Query.XPATH))
                // .append("\" or ");
            }
            solr.append(ClientUtils.escapeQueryChars(user));
            // sql.append("@sakai:to=\"").append(escapeString(user,
            // Query.XPATH)).append("\"))");
            solr.append(")"); // close to:

            solr.append(")"); // close AND
            propertiesMap.put("_from", solr.toString());
        }

        // convert iso8601jcr to Long for solr query parser
        final RequestParameter t = request.getRequestParameter("t");
        if (t != null && !"".equals(t.getString())) {
            final Date date = DateUtils.parseDate(t.getString(),
                    new String[] { "yyyy-MM-dd'T'HH:mm:ss.SSSZZ" });
            propertiesMap.put("t", String.valueOf(date.getTime()));
        }
    } catch (MessagingException e) {
        LOG.error(e.getLocalizedMessage(), e);
    } catch (ParseException e) {
        LOG.warn(e.getLocalizedMessage(), e);
    }
}

From source file:org.sakaiproject.nakamura.connections.search.ConnectionByUserSearchPropertyProvider.java

License:Apache License

/**
 * {@inheritDoc}//from  w w w .  j a va 2 s. com
 *
 * @see org.sakaiproject.nakamura.api.search.SearchPropertyProvider#loadUserProperties(org.apache.sling.api.SlingHttpServletRequest,
 *      java.util.Map)
 */
public void loadUserProperties(SlingHttpServletRequest request, Map<String, String> propertiesMap) {
    RequestParameter userParameter = request.getRequestParameter("userid");
    if (userParameter != null) {
        String user = userParameter.getString();
        String connectionPath = ClientUtils.escapeQueryChars(ConnectionUtils.getConnectionPathBase(user));
        if (connectionPath.startsWith("/")) {
            connectionPath = connectionPath.substring(1);
        }
        propertiesMap.put(SEARCH_PROP_CONNECTIONSTORE, connectionPath);
    }
}

From source file:org.sakaiproject.nakamura.connections.search.ConnectionIndexingHandler.java

License:Apache License

/**
 * {@inheritDoc}/*from   w w  w . j  a  v  a  2s .c  o m*/
 *
 * @see org.sakaiproject.nakamura.api.solr.IndexingHandler#getDeleteQueries(org.sakaiproject.nakamura.api.solr.RepositorySession,
 *      org.osgi.service.event.Event)
 */
public Collection<String> getDeleteQueries(RepositorySession repositorySession, Event event) {
    List<String> retval = Collections.emptyList();
    logger.debug("GetDelete for {} ", event);
    String path = (String) event.getProperty(IndexingHandler.FIELD_PATH);
    String resourceType = (String) event.getProperty("resourceType");
    if (CONTENT_TYPES.contains(resourceType)) {
        retval = ImmutableList.of("id:" + ClientUtils.escapeQueryChars(path));
    }
    return retval;
}

From source file:org.sakaiproject.nakamura.connections.search.ConnectionSearchPropertyProvider.java

License:Apache License

/**
 * {@inheritDoc}/*from   ww w. j  ava2  s  . co m*/
 *
 * @see org.sakaiproject.nakamura.api.search.SearchPropertyProvider#loadUserProperties(org.apache.sling.api.SlingHttpServletRequest,
 *      java.util.Map)
 */
public void loadUserProperties(SlingHttpServletRequest request, Map<String, String> propertiesMap) {
    // KERN-2350 allow requesters to search contacts that are not their own
    String user = request.getParameter("userid");
    if (!StringUtils.isBlank(user)) {
        // if searching other contacts, user should only see the accepted contacts
        propertiesMap.put("state", "ACCEPTED");
    } else {
        // lookup contacts for the currently logged in user
        user = request.getRemoteUser();
    }
    String connectionPath = ClientUtils.escapeQueryChars(ConnectionUtils.getConnectionPathBase(user));
    if (connectionPath.startsWith("/")) {
        connectionPath = connectionPath.substring(1);
    }
    propertiesMap.put(SEARCH_PROP_CONNECTIONSTORE, connectionPath);
}

From source file:org.sakaiproject.nakamura.connections.search.MyRelatedGroupsPropertyProvider.java

License:Apache License

/**
 * Loads properties needed for myrelatedgroups.json.
 *
 * _groupQuery == a (partial) query for the IDs of recommended groups.
 *
 * {@inheritDoc}// w ww  . ja  v  a2s. c  o m
 *
 * @see org.sakaiproject.nakamura.api.search.solr.SolrSearchPropertyProvider#loadUserProperties(org.apache.sling.api.SlingHttpServletRequest, java.util.Map)
 */
public void loadUserProperties(SlingHttpServletRequest request, Map<String, String> propertiesMap) {
    try {
        String user = request.getRemoteUser();

        LOGGER.debug("Recommending groups for: " + user);

        // Perform a MoreLikeThis query for this user's groups
        String suggestedIds = SolrSearchUtil.getMoreLikeThis(request, searchServiceFactory,
                String.format("type:g AND " + "resourceType:authorizable AND " + "readers:\"%s\"",
                        ClientUtils.escapeQueryChars(user)),
                "fl", "*,score", "rows", "10", "mlt", "true", "mlt.fl", "type,readers,title,name,tagname",
                "mlt.count", "10", "mlt.maxntp", "0", "mlt.mintf", "1", "mlt.mindf", "1", "mlt.boost", "true",
                "mlt.qf", "type^100 readers^3 name^2 tagname^1 title^1");

        if (suggestedIds != null) {
            propertiesMap.put("_groupQuery", String.format(" AND %s AND -readers:\"%s\"", suggestedIds,
                    ClientUtils.escapeQueryChars(user)));
        } else {
            propertiesMap.put("_groupQuery", "");
        }

        LOGGER.debug("Query: " + propertiesMap.get("_groupQuery"));
    } catch (SolrSearchException e) {
        LOGGER.error(e.getMessage(), e);
        throw new IllegalStateException(e);
    }
}

From source file:org.sakaiproject.nakamura.connections.search.MyRelatedGroupsSearchBatchResultProcessor.java

License:Apache License

/**
 * {@inheritDoc}//from w w w.ja v  a  2 s.com
 * 
 * @see org.sakaiproject.nakamura.api.search.solr.SolrSearchBatchResultProcessor#writeResults(org.apache.sling.api.SlingHttpServletRequest,
 *      org.apache.sling.commons.json.io.JSONWriter, java.util.Iterator)
 */
public void writeResults(final SlingHttpServletRequest request, final JSONWriter writer,
        final Iterator<Result> iterator) throws JSONException {
    long startTicks = System.currentTimeMillis();
    long firstQueryTicks = 0;
    long secondQueryTicks = 0;
    final Session session = StorageClientUtils
            .adaptToSession(request.getResourceResolver().adaptTo(javax.jcr.Session.class));
    final String user = session.getUserId();
    final long nitems = SolrSearchUtil.longRequestParameter(request, PARAMS_ITEMS_PER_PAGE,
            DEFAULT_PAGED_ITEMS);
    // TODO add proper paging support
    // final long page = SolrSearchUtil.longRequestParameter(request, PARAMS_PAGE, 0);

    final Set<String> processedGroups = new HashSet<String>();
    try {
        /* first render search results */
        final AuthorizableManager authMgr = session.getAuthorizableManager();
        while (iterator.hasNext() && processedGroups.size() < nitems) {
            final Result result = iterator.next();
            final String path = (String) result.getFirstValue("path");
            final Group g = (Group) authMgr.findAuthorizable(path);
            renderAuthorizable(request, writer, g, processedGroups);
        }
        firstQueryTicks = System.currentTimeMillis();
        if (LOG.isDebugEnabled())
            LOG.debug("writeResults() first query processing took {} seconds",
                    new Object[] { (float) (firstQueryTicks - startTicks) / 1000 });
        if (processedGroups.size() < nitems) {
            /* Not enough results, add some random groups per spec */
            final StringBuilder sourceQuery = new StringBuilder("resourceType:");
            sourceQuery.append(AUTHORIZABLE_RT);
            sourceQuery.append(" AND type:g AND -readers:");
            sourceQuery.append(ClientUtils.escapeQueryChars(user));

            final Iterator<Result> i = SolrSearchUtil.getRandomResults(request, defaultSearchProcessor,
                    sourceQuery.toString(), "items", String.valueOf(VOLUME), "page", "0");

            if (i != null) {
                while (i.hasNext() && processedGroups.size() <= nitems) {
                    final Result result = i.next();
                    final String path = (String) result.getFirstValue("path");
                    final Group g = (Group) authMgr.findAuthorizable(path);
                    renderAuthorizable(request, writer, g, processedGroups);
                }
            }
        }
        secondQueryTicks = System.currentTimeMillis();
        if (LOG.isDebugEnabled())
            LOG.debug("writeResults() second query processing took {} seconds",
                    new Object[] { (float) (secondQueryTicks - firstQueryTicks) / 1000 });
        if (processedGroups.size() < VOLUME) {
            LOG.info(
                    "Did not meet functional specification. There should be at least {} results; actual size was: {}",
                    VOLUME, processedGroups.size());
        }
    } catch (AccessDeniedException e) {
        // quietly swallow access denied
        LOG.debug(e.getLocalizedMessage(), e);
    } catch (SolrSearchException e) {
        LOG.error(e.getLocalizedMessage(), e);
        throw new IllegalStateException(e);
    } catch (StorageClientException e) {
        throw new IllegalStateException(e);
    }
    long endTicks = System.currentTimeMillis();
    if (LOG.isDebugEnabled())
        LOG.debug("writeResults() took {} seconds", new Object[] { (float) (endTicks - startTicks) / 1000 });
}