/**
   * Adds the date range values to the search template.
   *
   * <pre>{@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);
    }
  }
  /**
   * Load properties from the query node, request and property provider.<br>
   * Overwrite order: query node &lt; request &lt; property provider<br>
   * This ordering allows the query node to set defaults, the request to override those defaults but
   * the property provider to have the final say in what value is set.
   *
   * @param request
   * @param propertyProviderName
   * @return
   * @throws RepositoryException
   */
  private Map<String, String> loadProperties(
      SlingHttpServletRequest request, String propertyProviderName, Node node)
      throws RepositoryException {
    Map<String, String> propertiesMap = new HashMap<String, String>();

    // 0. load authorizable (user) information
    String userId = request.getRemoteUser();
    String userPrivatePath = ClientUtils.escapeQueryChars(LitePersonalUtils.getPrivatePath(userId));
    propertiesMap.put("_userPrivatePath", userPrivatePath);
    propertiesMap.put("_userId", ClientUtils.escapeQueryChars(userId));

    // 1. load in properties from the query template node so defaults can be set
    PropertyIterator props = node.getProperties();
    while (props.hasNext()) {
      javax.jcr.Property prop = props.nextProperty();
      if (!propertiesMap.containsKey(prop.getName()) && !prop.isMultiple()) {
        propertiesMap.put(prop.getName(), prop.getString());
      }
    }

    // 2. load in properties from the request
    RequestParameterMap params = request.getRequestParameterMap();
    for (Entry<String, RequestParameter[]> entry : params.entrySet()) {
      String key = entry.getKey();
      RequestParameter[] vals = entry.getValue();
      String requestValue = vals[0].getString();

      // blank values aren't cool
      if (StringUtils.isBlank(requestValue)) {
        continue;
      }

      // KERN-1601 Wildcard searches have to be manually lowercased for case insensitive
      // matching as Solr bypasses the analyzer when dealing with a wildcard or fuzzy
      // search.
      if (StringUtils.contains(requestValue, '*') || StringUtils.contains(requestValue, '~')) {
        requestValue = requestValue.toLowerCase();
      }
      // KERN-1703 Escape just :
      requestValue = StringUtils.replace(requestValue, ":", "\\:");
      propertiesMap.put(entry.getKey(), requestValue);
    }

    // 3. load properties from a property provider
    if (propertyProviderName != null) {
      LOGGER.debug("Trying Provider Name {} ", propertyProviderName);
      SolrSearchPropertyProvider provider = propertyProvider.get(propertyProviderName);
      if (provider != null) {
        LOGGER.debug("Trying Provider {} ", provider);
        provider.loadUserProperties(request, propertiesMap);
      } else {
        LOGGER.warn("No properties provider found for {} ", propertyProviderName);
      }
    } else {
      LOGGER.debug("No Provider ");
    }

    return propertiesMap;
  }
Beispiel #3
0
 private SolrQuery buildSolrQuery(HttpServletRequest req) {
   SolrQuery query = new SolrQuery();
   query.setParam(CommonParams.WT, "json"); // $NON-NLS-1$
   query.setParam(CommonParams.FL, FIELD_NAMES);
   String queryString = getEncodedParameter(req, CommonParams.Q);
   if (queryString == null) return null;
   if (queryString.length() > 0) {
     String processedQuery = ""; // $NON-NLS-1$
     // divide into search terms delimited by space or plus ('+') character
     List<String> terms =
         new ArrayList<String>(Arrays.asList(queryString.split("[\\s\\+]+"))); // $NON-NLS-1$
     while (!terms.isEmpty()) {
       String term = terms.remove(0);
       if (term.length() == 0) continue;
       if (isSearchField(term)) {
         if (term.startsWith("NameLower:")) { // $NON-NLS-1$
           // solr does not lowercase queries containing wildcards
           // https://issues.apache.org/jira/browse/SOLR-219
           processedQuery += "NameLower:" + term.substring(10).toLowerCase(); // $NON-NLS-1$
         } else if (term.startsWith("Location:")) { // $NON-NLS-1${
           // all other field searches are case sensitive
           processedQuery += "Location:" + term.substring(9 + req.getContextPath().length());
         } else {
           // all other field searches are case sensitive
           processedQuery += term;
         }
       } else {
         // decode the term string now
         try {
           term = URLDecoder.decode(term, "UTF-8");
         } catch (UnsupportedEncodingException e) {
           // try with encoded term
         }
         boolean isPhrase = term.charAt(0) == '"';
         // solr does not lowercase queries containing wildcards
         // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=359766
         String processedTerm = ClientUtils.escapeQueryChars(term.toLowerCase());
         // add leading and trailing wildcards to match word segments
         if (!isPhrase) {
           if (processedTerm.charAt(0) != '*') processedTerm = '*' + processedTerm;
           if (processedTerm.charAt(processedTerm.length() - 1) != '*') processedTerm += '*';
         }
         processedQuery += processedTerm;
       }
       processedQuery += " AND "; // $NON-NLS-1$
     }
     queryString = processedQuery;
   }
   queryString +=
       ProtocolConstants.KEY_USER_NAME + ':' + ClientUtils.escapeQueryChars(req.getRemoteUser());
   query.setQuery(queryString);
   // other common fields
   setField(req, query, CommonParams.ROWS);
   setField(req, query, CommonParams.START);
   setField(req, query, CommonParams.SORT);
   return query;
 }
  /**
   * Apply the 'search by role' filter to the lucene query string.
   *
   * @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);
    }
  }
  /**
   * Returns an array where the first value is the search string and the second is a display string.
   *
   * @param lsid
   * @return
   */
  public String[] getTaxonSearch(String lsid) {

    String[] result = new String[0];
    // use the name matching index
    try {
      if (nameIndex == null) {
        nameIndex = new ALANameSearcher(nameIndexLocation);
      }
      NameSearchResult nsr = nameIndex.searchForRecordByLsid(lsid);
      if (nsr != null) {
        String rank = nsr.getRank() != null ? nsr.getRank().toString() : "Unknown Rank";
        String scientificName =
            nsr.getRankClassification() != null
                ? nsr.getRankClassification().getScientificName()
                : null;
        StringBuffer dispSB = new StringBuffer(rank + ": " + scientificName);
        StringBuilder sb = new StringBuilder("lft:[");
        String lft = nsr.getLeft() != null ? nsr.getLeft() : "0";
        String rgt = nsr.getRight() != null ? nsr.getRight() : "0";
        sb.append(lft).append(" TO ").append(rgt).append("]");
        return new String[] {sb.toString(), dispSB.toString()};
      } else {
        return new String[] {
          "taxon_concept_lsid:" + ClientUtils.escapeQueryChars(lsid), "taxon_concept_lsid:" + lsid
        };
      }
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }

    return result;
  }
Beispiel #6
0
 @Override
 public SolrFilterResult buildSolrQuery() {
   String format =
       dateProvider.format(date).replace("Z", ".000Z"); // Tweak to set the milliseconds
   return new SolrFilterResult(
       "item.lastmodified:[" + ClientUtils.escapeQueryChars(format) + " TO *]");
 }
 /**
  * {@inheritDoc}
  *
  * @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) {
   LOGGER.debug("GetDelete for {} ", event);
   String path = (String) event.getProperty("path");
   boolean ignore = ignorePath(path);
   if (ignore) {
     return Collections.emptyList();
   } else {
     return ImmutableList.of(FIELD_ID + ":" + ClientUtils.escapeQueryChars(path));
   }
 }
 /**
  * {@inheritDoc}
  *
  * @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) {
   String user = request.getRemoteUser();
   String connectionPath =
       ClientUtils.escapeQueryChars(ConnectionUtils.getConnectionPathBase(user));
   if (connectionPath.startsWith("/")) {
     connectionPath = connectionPath.substring(1);
   }
   propertiesMap.put(SEARCH_PROP_CONNECTIONSTORE, connectionPath);
 }
 /**
  * {@inheritDoc}
  *
  * @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;
 }
  /**
   * {@inheritDoc}
   *
   * @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) {
    String user = request.getRemoteUser();
    Session session =
        StorageClientUtils.adaptToSession(
            request.getResourceResolver().adaptTo(javax.jcr.Session.class));
    propertiesMap.put(
        MessageConstants.SEARCH_PROP_MESSAGESTORE,
        ClientUtils.escapeQueryChars(messagingService.getFullPathToStore(user, session)) + "*");

    RequestParameter address = request.getRequestParameter("address");
    if (address != null && !address.getString().equals("")) {
      // resolve the address by finding the authorizables.
      String addressString = address.getString();
      String storePath = messagingService.getFullPathToStore(addressString, session);
      propertiesMap.put(
          MessageConstants.SEARCH_PROP_MESSAGESTORE, ClientUtils.escapeQueryChars(storePath) + "*");
    }

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

      StringBuilder solrQuery = new StringBuilder();

      // build solr query
      solrQuery.append("from:(");
      for (int i = 0; i < users.length; i++) {
        solrQuery.append('"').append(ClientUtils.escapeQueryChars(users[i])).append('"');

        if (i < users.length - 1) {
          solrQuery.append(" OR ");
        }
      }
      solrQuery.append(")");

      propertiesMap.put("_from", solrQuery.toString());
    }
  }
 /**
  * @param request
  * @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);
   }
 }
 private String expandHomeDirectory(String queryString) {
   Matcher homePathMatcher = homePathPattern.matcher(queryString);
   if (homePathMatcher.find()) {
     String username = homePathMatcher.group(3);
     String homePrefix = homePathMatcher.group(1);
     String userHome = LitePersonalUtils.getHomePath(username);
     userHome = ClientUtils.escapeQueryChars(userHome);
     String homePath = homePrefix + userHome + "/";
     String prefix = "";
     if (homePathMatcher.start() > 0) {
       prefix = queryString.substring(0, homePathMatcher.start());
     }
     String suffix = queryString.substring(homePathMatcher.end());
     queryString = prefix + homePath + suffix;
   }
   return queryString;
 }
  /**
   * @param request
   * @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);
    }
  }
 /**
  * {@inheritDoc}
  *
  * @see
  *     org.sakaiproject.nakamura.api.solr.IndexingHandler#getDeleteQueries(org.sakaiproject.nakamura.api.solr.RepositorySession,
  *     org.osgi.service.event.Event)
  */
 public Collection<String> getDeleteQueries(RepositorySession respositorySession, Event event) {
   logger.debug("GetDelete for {} ", event);
   String path = (String) event.getProperty(FIELD_PATH);
   return ImmutableList.of("id:" + ClientUtils.escapeQueryChars(path));
 }