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.pool.PooledContentNodeSearchPropertyProvider.java

License:Apache License

/**
 * @see org.sakaiproject.nakamura.api.search.SearchPropertyProvider#loadUserProperties(org.apache.sling.api.SlingHttpServletRequest, java.util.Map)
 */// w ww  . ja v a 2 s.  c om
public void loadUserProperties(SlingHttpServletRequest request, Map<String, String> propertiesMap) {
    RequestParameter rp = request.getRequestParameter(POOLED_CONTENT_PROPERTY);
    if (rp != null) {
        String resourcePath = rp.getString();
        ResourceResolver resourceResolver = request.getResourceResolver();
        Resource pooledResource = resourceResolver.getResource(resourcePath);
        if (pooledResource != null) {
            Content pooledContent = pooledResource.adaptTo(Content.class);
            String safePath = ClientUtils.escapeQueryChars(pooledContent.getPath());
            propertiesMap.put(POOLED_CONTENT_NODE_PATH_PROPERTY, safePath);
        }
    }
}

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

License:Apache License

/**
 * Apply the 'search by role' filter to the lucene query string.
 * /*from www  . j  a  v a 2 s.  c o m*/
 * @param parametersMap
 * @param filters
 */
protected void buildSearchByRoleQuery(Map<String, String> parametersMap, List<String> filters) {
    SearchableRole role = SearchableRole
            .valueOf(getSearchParam(parametersMap, REQUEST_PARAMETERS.role.toString()));
    String userid = getSearchParam(parametersMap, REQUEST_PARAMETERS.userid.toString());
    AuthorizableManager authorizableManager = null;
    Session adminSession = null;
    try {
        adminSession = repository.loginAdministrative();
        authorizableManager = adminSession.getAuthorizableManager();
        Authorizable au = authorizableManager.findAuthorizable(userid);
        List<Authorizable> groups = AuthorizableUtil.getUserFacingGroups(au, authorizableManager);
        groups.add(au);

        List<String> groupStrs = new ArrayList<String>(groups.size());
        for (Authorizable memberAuthz : groups) {
            groupStrs.add(ClientUtils.escapeQueryChars(memberAuthz.getId()));
        }

        filters.add(String.format(ROLE_TEMPLATE, role.toString(), JOINER_OR.join(groupStrs)));
        adminSession.logout();
    } catch (ClientPoolException e) {
        throw new RuntimeException(e);
    } catch (StorageClientException e) {
        throw new RuntimeException(e);
    } catch (AccessDeniedException e) {
        throw new RuntimeException(e);
    } finally {
        SparseUtils.logoutQuietly(adminSession);
    }
}

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

License:Apache License

/**
 * {@inheritDoc}/*from w w w.  j a va 2 s  .co m*/
 */
public void loadUserProperties(final SlingHttpServletRequest request, final Map<String, String> propertiesMap) {

    try {
        String user = request.getRemoteUser();

        RequestParameter contentPathParam = request.getRequestParameter("contentPath");

        String suggestedIds = null;

        if (contentPathParam != null) {
            String contentPath = contentPathParam.getString();
            String contentId = contentPath.substring(contentPath.lastIndexOf("/") + 1);

            LOGGER.debug("Suggesting content similar to '{}'", contentId);

            suggestedIds = SolrSearchUtil.getMoreLikeThis(request, searchServiceFactory,
                    String.format("id:\"%s\"", ClientUtils.escapeQueryChars(contentId)), "fl", "*,score",
                    "rows", "10", "mlt", "true", "mlt.fl", "resourceType,manager,viewer,title,name,tagname",
                    "mlt.count", "10", "mlt.maxntp", "0", "mlt.mintf", "1", "mlt.mindf", "1", "mlt.boost",
                    "true", "mlt.qf", "resourceType^100 manager^4 viewer^3 name^2 tagname^1 title^1");

        }

        if (suggestedIds != null) {
            propertiesMap.put("_contentQuery", String.format(" AND %s", suggestedIds));
        } else {
            propertiesMap.put("_contentQuery", "");
        }

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

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

License:Apache License

public void loadUserProperties(SlingHttpServletRequest request, Map<String, String> propertiesMap) {

    String user = request.getRemoteUser();

    // Set the userid.
    propertiesMap.put("_me", ClientUtils.escapeQueryChars(user));

    // Set the public space.
    propertiesMap.put("_mySpace", ClientUtils.escapeQueryChars(LitePersonalUtils.getPublicPath(user)));

    // Set the contacts.
    propertiesMap.put("_mycontacts", getMyContacts(request, user));

    // Filter by links.
    String usedinClause = doUsedIn(request);
    String tags = doTags(request);
    String tagsAndUsedIn = "";
    if (tags.length() > 0) {
        propertiesMap.put("_usedin", " AND (" + tags + ")");
        tagsAndUsedIn = tags;//from  ww w  . jav  a2 s . c o m
    }

    if (usedinClause.length() > 0) {
        propertiesMap.put("_usedin", " AND (" + usedinClause + ")");
        tagsAndUsedIn = "(" + tagsAndUsedIn + ") AND (" + usedinClause + ")";

    }
    propertiesMap.put("_tags_and_usedin", tagsAndUsedIn);

}

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

License:Apache License

/**
 * Gets a clause for a query by looking at the sakai:tags request parameter.
 *
 * @param request/*from  w  w w .  j  ava2s. c om*/
 * @return
 */
protected String doTags(SlingHttpServletRequest request) {
    String[] tags = request.getParameterValues(FilesConstants.SAKAI_TAGS);
    StringBuilder tag = new StringBuilder();

    if (tags != null) {
        tag.append("(tag:(");
        StringBuilder ngram = new StringBuilder("ngram:(");
        StringBuilder edgeNgram = new StringBuilder("edgengram:(");

        for (int i = 0; i < tags.length; i++) {
            String term = ClientUtils.escapeQueryChars(tags[i]);
            tag.append("\"").append(term).append("\"");
            ngram.append("\"").append(term).append("\"");
            edgeNgram.append("\"").append(term).append("\"");

            if (i < tags.length - 1) {
                tag.append(" AND ");
                ngram.append(" AND ");
                edgeNgram.append(" AND ");
            }
        }
        tag.append(") OR ").append(ngram).append(") OR ").append(edgeNgram).append("))");
    }
    return tag.toString();
}

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

License:Apache License

/**
 * Get a string of all the connected users.
 * @param request // w  ww .  j  a  v  a 2  s  .  co  m
 *
 * @param user
 *          The user to get the contacts for.
 * @return "AND (createdBy:(\"simon\" OR \"ieb\")"
 */
@SuppressWarnings(justification = "connectionManager is OSGi managed", value = { "NP_UNWRITTEN_FIELD",
        "UWF_UNWRITTEN_FIELD" })
protected String getMyContacts(SlingHttpServletRequest request, String user) {
    List<String> connectedUsers = connectionManager.getConnectedUsers(request, user, ConnectionState.ACCEPTED);
    StringBuilder sb = new StringBuilder();

    if (connectedUsers.size() > 0) {
        sb.append("AND _createdBy:(");
        Iterator<String> users = connectedUsers.iterator();
        while (users.hasNext()) {
            String u = users.next();
            sb.append("\"").append(ClientUtils.escapeQueryChars(u)).append("\"");

            if (users.hasNext()) {
                sb.append(" OR ");
            }
        }
        sb.append(")");
    }

    return sb.toString();
}

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

License:Apache License

/**
 * {@inheritDoc}/*  www  .  ja  v  a 2  s  .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) {
    String group = request.getParameter("group");

    if (!StringUtils.isBlank(group)) {
        String groupReader = " AND readers:" + ClientUtils.escapeQueryChars(group);
        propertiesMap.put("_groupReaderAnd", groupReader);
    }
}

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

License:Apache License

/**
 * @param session//from w  w  w.j  a  v  a 2 s. com
 * @param authorizable
 * @return An empty list if the user cannot be found. Values will be solr query escaped.
 */
protected static Set<String> getPrincipals(final Session session, final String authorizable, int levels) {
    // put a limit on recursion
    if (levels > MAX_DEPTH) {
        levels = MAX_DEPTH;
    }
    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.PoolContentResourceTypeHandler.java

License:Apache License

/**
 * {@inheritDoc}/*from  w w w .  j  a  v a  2  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);
    boolean ignore = ignorePath(path);
    if (!ignore) {
        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.search.PoolContentResourceTypeHandlerTest.java

License:Apache License

@Test
public void testDeleteQueries() throws Exception {
    Map<String, Object> props = buildStandardPooledContentProperties();
    Content content = new Content(PATH_TO_FILE, props);

    when(repositorySession.adaptTo(Session.class)).thenReturn(session);
    when(session.getContentManager()).thenReturn(contentManager);
    when(contentManager.get(PATH_TO_FILE)).thenReturn(content);

    PoolContentResourceTypeHandler handler = new PoolContentResourceTypeHandler();

    Map<String, Object> eventProps = buildEventProperties();
    eventProps.put("resourceType", RESOURCE_TYPE);
    Event event = new Event("test", eventProps);

    Collection<String> queries = handler.getDeleteQueries(repositorySession, event);
    assertTrue(queries.contains("id:" + ClientUtils.escapeQueryChars((String) event.getProperty("path"))));
}