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.files.search.RelatedContentSearchPropertyProvider.java

License:Apache License

/**
 * {@inheritDoc}/* w  w  w . ja  va  2 s  .c  o  m*/
 * 
 * @see org.sakaiproject.nakamura.files.search.MeManagerViewerSearchPropertyProvider#loadUserProperties(org.apache.sling.api.SlingHttpServletRequest,
 *      java.util.Map)
 */
public void loadUserProperties(final SlingHttpServletRequest request, final Map<String, String> propertiesMap) {

    /* phase one - find source content to match against */

    final String user = super.getUser(request);
    if (User.ANON_USER.equals(user)) {
        // stop here, anonymous is not a manager or a viewer of anything
        return;
    }

    final Session session = StorageClientUtils
            .adaptToSession(request.getResourceResolver().adaptTo(javax.jcr.Session.class));
    final Set<String> managers = super.getPrincipals(session, user, 1);
    final Set<String> viewers = new HashSet<String>(managers);

    final StringBuilder sourceQuery = new StringBuilder("resourceType:sakai/pooled-content AND (manager:(");
    sourceQuery.append(Joiner.on(" OR ").join(managers));
    sourceQuery.append(") OR viewer:(");
    sourceQuery.append(Joiner.on(" OR ").join(viewers));
    sourceQuery.append("))");
    final Query query = new Query(Query.SOLR, sourceQuery.toString(), SOURCE_QUERY_OPTIONS);

    SolrSearchResultSet rs = null;
    try {
        rs = defaultSearchProcessor.getSearchResultSet(request, query);
    } catch (SolrSearchException e) {
        LOG.error(e.getLocalizedMessage(), e);
        throw new IllegalStateException(e);
    }
    if (rs != null) {
        try {
            final ContentManager contentManager = session.getContentManager();
            final Iterator<Result> i = rs.getResultSetIterator();
            Set<String> allFileNames = new HashSet<String>();
            Set<String> allTags = new HashSet<String>();
            int count = 0;
            while (i.hasNext() && count < MAX_SOURCE_LIMIT) {
                final Result result = i.next();
                final String path = (String) result.getFirstValue("path");
                final Content content = contentManager.get(path);
                if (content != null) {
                    // grab the unique file name tokens
                    String fileName = (String) content.getProperty(FilesConstants.POOLED_CONTENT_FILENAME);
                    if (fileName != null) {
                        final String fileExtension = (String) content.getProperty("sakai:fileextension");
                        if (fileExtension != null) {
                            final int extensionIndex = fileName.lastIndexOf(fileExtension);
                            if (extensionIndex > 0) {
                                fileName = fileName.substring(0, extensionIndex);
                            }
                        }
                        final String[] foundFileNames = REGEX_PATTERN.split(fileName);
                        for (String foundFileName : foundFileNames) {
                            if (!StringUtils.isBlank(foundFileName)) {
                                allFileNames.add(foundFileName);
                            }
                        }
                    }

                    // grab all the unique tags
                    final String[] tags = PropertiesUtil
                            .toStringArray(content.getProperty(FilesConstants.SAKAI_TAGS));
                    if (tags != null) {
                        allTags.addAll(Arrays.asList(tags));
                    }
                } else {
                    // fail quietly in this edge case
                    LOG.debug("Content not found: {}", path);
                }
                count++;
            }

            /* phase two - provide properties for final search */

            final List<String> connections = connectionManager.getConnectedUsers(request, user,
                    ConnectionState.ACCEPTED);
            if (connections != null) {
                for (final String connection : connections) {
                    managers.add(ClientUtils.escapeQueryChars(connection));
                }
            }
            managers.remove(user); // do not display my own content
            viewers.remove(user); // do not display my own content
            if (managers.isEmpty()) { // to prevent solr parse errors
                managers.add(AVOID_FALSE_POSITIVE_MATCHES);
            }
            propertiesMap.put("managers", Joiner.on(" OR ").join(managers));
            if (viewers.isEmpty()) { // to prevent solr parse errors
                viewers.add(AVOID_FALSE_POSITIVE_MATCHES);
            }
            propertiesMap.put("viewers", Joiner.on(" OR ").join(viewers));

            if (allFileNames.isEmpty()) { // to prevent solr parse errors
                allFileNames.add(AVOID_FALSE_POSITIVE_MATCHES);
            }
            if (allFileNames.size() > 1024) {
                /*
                 * solr allows a maximum of 1024. Performance will likely be an issue by this
                 * point.
                 */
                LOG.warn("Exceeded maximum number of solr binary operations: {}. Reduced size to 1024.",
                        allFileNames.size());
                final String[] tooLarge = (String[]) allFileNames.toArray();
                final String[] justRight = Arrays.copyOf(tooLarge, 1024);
                allFileNames = new HashSet<String>(Arrays.asList(justRight));
            }
            propertiesMap.put("fileNames", Joiner.on(" OR ").join(allFileNames));

            if (allTags.isEmpty()) { // to prevent solr parse errors
                allTags.add(AVOID_FALSE_POSITIVE_MATCHES);
            }
            if (allTags.size() > 1024) {
                /*
                 * solr allows a maximum of 1024. Performance will likely be an issue by this
                 * point.
                 */
                LOG.warn("Exceeded maximum number of solr binary operations: {}. Reduced size to 1024.",
                        allTags.size());
                final String[] tooLarge = (String[]) allTags.toArray();
                final String[] justRight = Arrays.copyOf(tooLarge, 1024);
                allTags = new HashSet<String>(Arrays.asList(justRight));
            }
            propertiesMap.put("tags", Joiner.on(" OR ").join(allTags));

        } catch (AccessDeniedException e) {
            LOG.error(e.getLocalizedMessage(), e);
        } catch (StorageClientException e) {
            LOG.error(e.getLocalizedMessage(), e);
        }
    }
}

From source file:org.sakaiproject.nakamura.files.search.SearchRequestUtils.java

License:Apache License

/**
 * Get all groups to which the user has access, at a recursion of {@code levels}
 * /* w w  w.j ava  2 s. c  o m*/
 * @param session
 * @param authorizable
 * @return An empty list if the user cannot be found. Values will be solr query escaped.
 */
public static Set<String> getPrincipals(final Session session, final String authorizable, int levels) {
    final Set<String> viewerAndManagerPrincipals = new HashSet<String>();
    try {
        final AuthorizableManager authManager = session.getAuthorizableManager();
        final Authorizable anAuthorizable = authManager.findAuthorizable(authorizable);
        if (anAuthorizable != null) {
            if (levels > 0) {
                levels--;
                for (final String principal : anAuthorizable.getPrincipals()) {
                    if (!Group.EVERYONE.equals(principal)) {
                        viewerAndManagerPrincipals.addAll(getPrincipals(session, principal, levels));
                    }
                }
            }
            viewerAndManagerPrincipals.add(ClientUtils.escapeQueryChars(authorizable));
            viewerAndManagerPrincipals.remove(Group.EVERYONE);
        }
    } catch (StorageClientException e) {
        throw new IllegalStateException(e);
    } catch (AccessDeniedException e) {
        // quietly trap access denied exceptions
    }
    return viewerAndManagerPrincipals;
}

From source file:org.sakaiproject.nakamura.files.search.TagIndexingHandler.java

License:Apache License

/**
 * {@inheritDoc}//  w w  w .ja  v  a  2  s  .  co m
 *
 * @see org.sakaiproject.nakamura.api.solr.IndexingHandler#getDeleteQueries(org.sakaiproject.nakamura.api.solr.RepositorySession, org.osgi.service.event.Event)
 */
@Override
public Collection<String> getDeleteQueries(RepositorySession repoSession, Event event) {
    List<String> retval = Collections.emptyList();
    LOGGER.debug("getDeleteQueries 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.files.servlets.DirectoryTagFeedServlet.java

License:Apache License

private List<String> getTagsForDirectoryBranch(Content branch, ContentManager cm,
        SlingHttpServletRequest request) throws SolrSearchException {
    String queryString = "path:" + ClientUtils.escapeQueryChars(branch.getPath()) + " AND resourceType:"
            + ClientUtils.escapeQueryChars(RT_SAKAI_TAG);
    ArrayList<String> rv = new ArrayList<String>();

    Query solrQuery = new Query(queryString, ImmutableMap.<String, Object>of());
    SolrSearchResultSet rs = solrSearchServiceFactory.getSearchResultSet(request, solrQuery);
    Iterator<Result> results = rs.getResultSetIterator();
    while (results.hasNext()) {
        Result result = results.next();
        rv.add(String.valueOf(result.getFirstValue("tagname")));
    }/*from  www.  j  a  v a2  s . c o m*/

    return rv;
}

From source file:org.sakaiproject.nakamura.files.servlets.DirectoryTagFeedServlet.java

License:Apache License

private void writeOneTaggedItemForTags(SlingHttpServletRequest request, List<String> tags, JSONWriter write)
        throws JSONException, SolrSearchException {
    if (tags == null || tags.size() == 0) {
        write.object().endObject();//from  ww  w. j  ava 2  s  .co m
        return;
    }

    // BL120 KERN-1617 Need to include Content tagged with tag uuid
    final StringBuilder sb = new StringBuilder();
    sb.append("tag:(");
    String sep = "";
    for (String tag : tags) {
        sb.append(sep).append(ClientUtils.escapeQueryChars(tag));
        sep = " ";
    }
    sb.append(") AND resourceType:").append(ClientUtils.escapeQueryChars(FilesConstants.POOLED_CONTENT_RT));
    final int random = (int) (Math.random() * 10000);
    String sortRandom = "random_" + String.valueOf(random) + " asc";
    final String queryString = sb.toString();
    Query solrQuery = new Query(queryString, ImmutableMap.of("sort", (Object) sortRandom));
    final SolrSearchBatchResultProcessor rp = new LiteFileSearchBatchResultProcessor(solrSearchServiceFactory,
            profileService);
    final SolrSearchResultSet srs = rp.getSearchResultSet(request, solrQuery);
    if (srs.getResultSetIterator().hasNext()) {
        rp.writeResults(request, write, selectOneResult(srs.getResultSetIterator()));
    } else {
        // write an empty result
        write.object().endObject();
    }
}

From source file:org.sakaiproject.nakamura.files.servlets.TagServlet.java

License:Apache License

/**
 * @param tag//from   ww  w  .j a  va2 s  . com
 * @param request
 * @throws RepositoryException
 * @throws JSONException
 * @throws SearchException
 * @throws SolrSearchException
 */
protected void sendFiles(String uuid, SlingHttpServletRequest request, JSONWriter write, int depth)
        throws RepositoryException, JSONException, SearchException, SolrSearchException {

    // We expect tags to be referencable, if this tag is not..
    // it will throw an exception.

    // Tagging on any item will be performed by adding a weak reference to the content
    // item. Put simply a sakai:tag-uuid property with the UUID of the tag node. We use
    // the UUID to uniquely identify the tag in question, a string of the tag name is not
    // sufficient. This allows the tag to be renamed and moved without breaking the
    // relationship.
    String statement = "//*[@sakai:tag-uuid='" + uuid + "']";
    Session session = request.getResourceResolver().adaptTo(Session.class);
    QueryManager qm = session.getWorkspace().getQueryManager();
    @SuppressWarnings("deprecation")
    Query query = qm.createQuery(statement, Query.XPATH);

    FileSearchBatchResultProcessor proc = new FileSearchBatchResultProcessor(searchServiceFactory);

    SearchResultSet rs = proc.getSearchResultSet(request, query);
    write.array();
    proc.writeNodes(request, write, null, rs.getRowIterator());

    // BL120 KERN-1617 Need to include Content tagged with tag uuid
    final StringBuilder sb = new StringBuilder();
    sb.append("taguuid:");
    sb.append(ClientUtils.escapeQueryChars(uuid));
    final RequestParameter typeP = request.getRequestParameter("type");
    if (typeP != null) {
        final String type = typeP.getString();
        sb.append(" AND ");
        if ("user".equals(type)) {
            sb.append("type:u");
        } else if ("group".equals(type)) {
            sb.append("type:g");
        } else {
            if ("content".equals(type)) {
                sb.append("resourceType:");
                sb.append(ClientUtils.escapeQueryChars(FilesConstants.POOLED_CONTENT_RT));
            } else {
                LOG.info("Unknown type parameter specified: type={}", type);
                write.endArray();
                return;
            }
        }
    }
    final String queryString = sb.toString();
    org.sakaiproject.nakamura.api.search.solr.Query solrQuery = new org.sakaiproject.nakamura.api.search.solr.Query(
            queryString, ImmutableMap.of("sort", (Object) "score desc"));
    final SolrSearchBatchResultProcessor rp = new LiteFileSearchBatchResultProcessor(solrSearchServiceFactory,
            profileService);
    final SolrSearchResultSet srs = rp.getSearchResultSet(request, solrQuery);
    rp.writeResults(request, write, srs.getResultSetIterator());
    write.endArray();
}

From source file:org.sakaiproject.nakamura.meservice.LiteMeServlet.java

License:Apache License

/**
 * Writes a JSON Object that contains the number of contacts for a user split up in
 * PENDING, ACCEPTED.//from ww w.j  a  va  2  s .  c o  m
 *
 * @param writer
 * @param session
 * @param au
 * @throws JSONException
 * @throws SolrSearchException
 * @throws RepositoryException
 */
protected void writeContactCounts(ExtendedJSONWriter writer, Session session, Authorizable au,
        SlingHttpServletRequest request) throws JSONException, SolrSearchException {
    writer.object();

    // We don't do queries for anonymous users. (Possible ddos hole).
    String userID = au.getId();
    if (UserConstants.ANON_USERID.equals(userID)) {
        writer.endObject();
        return;
    }

    // Get the path to the store for this user.
    Map<String, Integer> contacts = new HashMap<String, Integer>();
    contacts.put(ACCEPTED.toString().toLowerCase(), 0);
    contacts.put(INVITED.toString().toLowerCase(), 0);
    contacts.put(PENDING.toString().toLowerCase(), 0);
    try {
        // This could just use ConnectionUtils.getConnectionPathBase, but that util class is
        // in the private package unfortunately.
        String store = LitePersonalUtils.getHomePath(userID) + "/" + ConnectionConstants.CONTACT_STORE_NAME;
        store = ISO9075.encodePath(store);
        String queryString = "path:" + ClientUtils.escapeQueryChars(store)
                + " AND resourceType:sakai/contact AND state:(ACCEPTED OR INVITED OR PENDING)";
        Query query = new Query(queryString);
        LOG.debug("Submitting Query {} ", query);
        SolrSearchResultSet resultSet = searchServiceFactory.getSearchResultSet(request, query, false);
        Iterator<Result> resultIterator = resultSet.getResultSetIterator();
        while (resultIterator.hasNext()) {
            Result contact = resultIterator.next();
            if (contact.getProperties().containsKey("state")) {
                String state = (String) contact.getProperties().get("state").iterator().next();
                int count = 0;
                if (contacts.containsKey(state)) {
                    count = contacts.get(state);
                }
                contacts.put(state, count + 1);
            }
        }
    } finally {
        for (Entry<String, Integer> entry : contacts.entrySet()) {
            writer.key(entry.getKey());
            writer.value(entry.getValue());
        }
    }
    writer.endObject();
}

From source file:org.sakaiproject.nakamura.meservice.LiteMeServlet.java

License:Apache License

/**
 * Writes a JSON Object that contains the unread messages for a user.
 *
 * @param writer/*from   ww w .j av a  2 s  .c  o  m*/
 *          The writer
 * @param session
 *          A JCR session to perform queries with. This session needs read access on the
 *          authorizable's message box.
 * @param au
 *          An authorizable to look up the messages for.
 * @throws JSONException
 * @throws RepositoryException
 * @throws MessagingException
 * @throws SolrSearchException
 */
protected void writeMessageCounts(ExtendedJSONWriter writer, Session session, Authorizable au,
        SlingHttpServletRequest request) throws JSONException, MessagingException, SolrSearchException {
    writer.object();
    writer.key("unread");

    // We don't do queries for anonymous users. (Possible ddos hole).
    String userID = au.getId();
    if (UserConstants.ANON_USERID.equals(userID)) {
        writer.value(0);
        writer.endObject();
        return;
    }

    long count = 0;
    try {
        String store = messagingService.getFullPathToStore(au.getId(), session);
        store = ISO9075.encodePath(store);
        store = store.substring(0, store.length() - 1);
        String queryString = "path:" + ClientUtils.escapeQueryChars(store)
                + " AND resourceType:sakai/message AND type:internal AND messagebox:inbox AND read:false";
        Query query = new Query(queryString);
        LOG.debug("Submitting Query {} ", query);
        SolrSearchResultSet resultSet = searchServiceFactory.getSearchResultSet(request, query, false);
        count = resultSet.getSize();
    } finally {
        writer.value(count);
    }
    writer.endObject();
}

From source file:org.sakaiproject.nakamura.message.LiteCountServlet.java

License:Apache License

@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {
    LOGGER.debug("In count servlet");

    Session session = StorageClientUtils
            .adaptToSession(request.getResourceResolver().adaptTo(javax.jcr.Session.class));

    try {/*  ww  w.j ava  2  s . c  om*/
        // Do the query
        // We do the query on the user his messageStore's path.
        String messageStorePath = ClientUtils
                .escapeQueryChars(messagingService.getFullPathToStore(request.getRemoteUser(), session));
        //path:a\:zach/contacts AND resourceType:sakai/contact AND state:("ACCEPTED" -NONE) (name:"*" OR firstName:"*" OR lastName:"*" OR email:"*")) AND readers:(zach OR everyone)&start=0&rows=25&sort=score desc
        StringBuilder queryString = new StringBuilder(
                "(path:" + messageStorePath + "* AND resourceType:sakai/message" + " AND type:internal");

        // Get the filters
        if (request.getRequestParameter("filters") != null && request.getRequestParameter("values") != null) {
            // The user wants to filter some things.
            String[] filters = request.getRequestParameter("filters").getString().split(",");
            String[] values = request.getRequestParameter("values").getString().split(",");
            if (filters.length != values.length) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "The amount of values doesn't match the amount of keys.");
            }

            for (int i = 0; i < filters.length; i++) {
                String filterName = filters[i].replaceFirst("sakai:", "");
                queryString.append(" AND " + filterName + ":\"" + values[i] + "\"");
            }
        }

        queryString.append(")");

        // The "groupedby" clause forces us to inspect every message. If not
        // specified, all we need is the count.
        final long itemCount;
        if (request.getRequestParameter("groupedby") == null) {
            itemCount = 0;
        } else {
            itemCount = MAX_RESULTS_COUNTED;
        }
        Map<String, Object> queryOptions = ImmutableMap.of(PARAMS_ITEMS_PER_PAGE,
                (Object) Long.toString(itemCount), CommonParams.START, "0", CommonParams.SORT, "_created desc");

        Query query = new Query(queryString.toString(), queryOptions);
        LOGGER.info("Submitting Query {} ", query);
        SolrSearchResultSet resultSet = searchServiceFactory.getSearchResultSet(request, query, false);
        Iterator<Result> resultIterator = resultSet.getResultSetIterator();

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        JSONWriter write = new JSONWriter(response.getWriter());

        if (request.getRequestParameter("groupedby") == null) {
            write.object();
            write.key("count");
            write.value(resultSet.getSize());
            write.endObject();
        } else {
            // The user want to group the count by a specified set.
            // We will have to traverse each node, get that property and count each
            // value for it.
            String groupedby = request.getRequestParameter("groupedby").getString();
            if (groupedby.startsWith("sakai:")) {
                groupedby = groupedby.substring(6);
            }

            long count = 0;
            Map<String, Integer> mapCount = new HashMap<String, Integer>();
            while (resultIterator.hasNext()) {
                Result n = resultIterator.next();

                if (count >= MAX_RESULTS_COUNTED) {
                    break;
                }
                count++;

                if (n.getProperties().containsKey(groupedby)) {
                    String key = (String) n.getFirstValue(groupedby);
                    int val = 1;
                    if (mapCount.containsKey(key)) {
                        val = mapCount.get(key) + 1;
                    }
                    mapCount.put(key, val);
                }
            }

            write.object();
            write.key("count");
            write.array();
            for (Entry<String, Integer> e : mapCount.entrySet()) {
                write.object();

                write.key("group");
                write.value(e.getKey());
                write.key("count");
                write.value(e.getValue());

                write.endObject();
            }
            write.endArray();
            write.endObject();

        }

    } catch (JSONException e) {
        LOGGER.error("JSON issue from query " + request.getQueryString(), e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getLocalizedMessage());
    } catch (Exception e) {
        LOGGER.error("Unexpected exception for query " + request.getQueryString(), e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getLocalizedMessage());
    }

}

From source file:org.sakaiproject.nakamura.message.search.MessageCountServiceImpl.java

License:Apache License

@Override
public long getUnreadMessageCount(SlingHttpServletRequest request) {
    final javax.jcr.Session jcrSession = request.getResourceResolver().adaptTo(javax.jcr.Session.class);
    final Session session = StorageClientUtils.adaptToSession(jcrSession);
    AuthorizableManager authzManager = null;
    Authorizable au = null;//from ww w. j  av a 2 s .  c  om
    try {
        authzManager = session.getAuthorizableManager();
        au = authzManager.findAuthorizable(request.getRemoteUser());
    } catch (Exception e) {
        LOGGER.error("error getting Authorizable for remote user", e);
    }

    if (au == null) {
        return 0;
    }

    // We don't do queries for anonymous users. (Possible ddos hole).
    String userID = au.getId();
    if (UserConstants.ANON_USERID.equals(userID)) {
        return 0;
    }

    String store = messagingService.getFullPathToStore(au.getId(), session);
    store = ISO9075.encodePath(store);
    String queryString = "messagestore:" + ClientUtils.escapeQueryChars(store)
            + " AND type:internal AND messagebox:inbox AND read:false";
    final Map<String, Object> queryOptions = ImmutableMap.of(PARAMS_ITEMS_PER_PAGE, (Object) "0",
            CommonParams.START, "0");
    Query query = new Query(queryString, queryOptions);
    LOGGER.debug("Submitting Query {} ", query);

    SolrSearchResultSet resultSet = null;
    try {
        resultSet = searchServiceFactory.getSearchResultSet(request, query, false);
    } catch (SolrSearchException e) {
        LOGGER.error("error executing query", e);
        return 0;
    }

    return resultSet.getSize();
}