public void writeResults(
      SlingHttpServletRequest request, JSONWriter write, Iterator<Result> results)
      throws JSONException {
    ExtendedJSONWriter exWriter = (ExtendedJSONWriter) write;
    Session session =
        StorageClientUtils.adaptToSession(
            request.getResourceResolver().adaptTo(javax.jcr.Session.class));

    String currUser = request.getRemoteUser();
    try {
      // write out the profile information for each result
      while (results.hasNext()) {
        Result result = results.next();
        // start the object here so we can decorate with contact details
        write.object();
        super.writeResult(request, write, result, true);

        // add contact information if appropriate
        String otherUser = String.valueOf(result.getFirstValue("path"));
        connMgr.writeConnectionInfo(exWriter, session, currUser, otherUser);

        write.endObject();
      }
    } catch (StorageClientException e) {
      LOGGER.error(e.getMessage(), e);
    } catch (AccessDeniedException e) {
      LOGGER.error(e.getMessage(), e);
    }
  }
 public void writeResult(SlingHttpServletRequest request, JSONWriter write, Result result)
     throws JSONException {
   String contentPath = result.getPath();
   Session session =
       StorageClientUtils.adaptToSession(
           request.getResourceResolver().adaptTo(javax.jcr.Session.class));
   try {
     Content contentResult = session.getContentManager().get(contentPath);
     if (contentResult != null) {
       write.object();
       writeCanManageProperty(request, write, session, contentResult);
       writeCommentCountProperty(write, session, contentResult);
       int depth = SolrSearchUtil.getTraversalDepth(request);
       ExtendedJSONWriter.writeContentTreeToWriter(write, contentResult, true, depth);
       write.endObject();
     }
   } catch (AccessDeniedException ade) {
     // if access is denied we simply won't
     // write anything for this result
     // this implies content was private
     LOGGER.info("Denied {} access to {}", request.getRemoteUser(), contentPath);
     return;
   } catch (Exception e) {
     throw new JSONException(e);
   }
 }
  @Test
  public void oneGroup() {
    Result result1 = mock(Result.class);
    Map<String, Collection<Object>> props1 = Maps.newHashMap();
    props1.put("id", Sets.newHashSet((Object) "prop1-id"));

    List<Result> results = Lists.newArrayList(result1);
    when(result1.getProperties()).thenReturn(props1);
    when(rs.getResultSetIterator()).thenReturn(results.iterator());

    Map<String, String> propertiesMap = Maps.newHashMap();

    provider.loadUserProperties(request, propertiesMap);

    assertEquals(
        " AND id:(\"prop1\\-id\"^1) AND -readers:\"user1\"", propertiesMap.get("_groupQuery"));
  }
 /**
  * Same as writeResults logic, but counts number of results iterated over.
  *
  * @param request
  * @param write
  * @param iterator
  * @return Set containing all unique paths processed.
  * @throws JSONException
  */
 public Set<String> writeResultsInternal(
     SlingHttpServletRequest request, JSONWriter write, Iterator<Result> iterator)
     throws JSONException {
   final Set<String> uniquePaths = new HashSet<String>();
   final Integer iDepth = (Integer) request.getAttribute("depth");
   int depth = 0;
   if (iDepth != null) {
     depth = iDepth.intValue();
   }
   try {
     javax.jcr.Session jcrSession = request.getResourceResolver().adaptTo(javax.jcr.Session.class);
     final Session session = StorageClientUtils.adaptToSession(jcrSession);
     while (iterator.hasNext()) {
       final Result result = iterator.next();
       uniquePaths.add(result.getPath());
       try {
         if ("authorizable".equals(result.getFirstValue("resourceType"))) {
           AuthorizableManager authManager = session.getAuthorizableManager();
           Authorizable auth = authManager.findAuthorizable((String) result.getFirstValue("id"));
           if (auth != null) {
             write.object();
             ValueMap map = profileService.getProfileMap(auth, jcrSession);
             ExtendedJSONWriter.writeValueMapInternals(write, map);
             write.endObject();
           }
         } else {
           String contentPath = result.getPath();
           final Content content = session.getContentManager().get(contentPath);
           if (content != null) {
             handleContent(content, session, write, depth);
           } else {
             LOGGER.debug("Found null content item while writing results [{}]", contentPath);
           }
         }
       } catch (AccessDeniedException e) {
         // do nothing
       } catch (RepositoryException e) {
         throw new JSONException(e);
       }
     }
   } catch (StorageClientException e) {
     throw new JSONException(e);
   }
   return uniquePaths;
 }
  @Test
  public void threeGroups() {

    Result result1 = mock(Result.class);
    Map<String, Collection<Object>> props1 = Maps.newHashMap();
    props1.put("id", Sets.newHashSet((Object) "prop1"));
    when(result1.getProperties()).thenReturn(props1);

    Result result2 = mock(Result.class);
    Map<String, Collection<Object>> props2 = Maps.newHashMap();
    props2.put("id", Sets.newHashSet((Object) "prop2"));
    when(result2.getProperties()).thenReturn(props2);

    Result result3 = mock(Result.class);
    Map<String, Collection<Object>> props3 = Maps.newHashMap();
    props3.put("id", Sets.newHashSet((Object) "prop3"));
    when(result3.getProperties()).thenReturn(props3);

    List<Result> results = Lists.newArrayList(result1, result2, result3);

    when(rs.getSize()).thenReturn((long) 3);
    when(rs.getResultSetIterator()).thenReturn(results.iterator());

    Map<String, String> propertiesMap = Maps.newHashMap();

    provider.loadUserProperties(request, propertiesMap);

    System.out.println("GOT: " + propertiesMap.get("_groupQuery"));

    assertEquals(
        " AND id:(\"prop1\"^4 OR \"prop2\"^3 OR \"prop3\"^2) AND -readers:\"user1\"",
        propertiesMap.get("_groupQuery"));
  }
 public void writeResult(SlingHttpServletRequest request, JSONWriter write, Result result)
     throws JSONException {
   String contentPath = (String) result.getFirstValue("path");
   Session session =
       StorageClientUtils.adaptToSession(
           request.getResourceResolver().adaptTo(javax.jcr.Session.class));
   try {
     Content contentResult = session.getContentManager().get(contentPath);
     if (contentResult != null) {
       ExtendedJSONWriter.writeContentTreeToWriter(write, contentResult, -1);
     } else {
       write.object().endObject();
     }
   } catch (Exception e) {
     throw new JSONException(e);
   }
 }
  /**
   * {@inheritDoc}
   *
   * @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(
      SlingHttpServletRequest request, JSONWriter writer, Iterator<Result> iterator)
      throws JSONException {

    try {
      Session session =
          StorageClientUtils.adaptToSession(
              request.getResourceResolver().adaptTo(javax.jcr.Session.class));
      ContentManager cm = session.getContentManager();
      List<String> basePosts = new ArrayList<String>();
      Map<String, List<Post>> postChildren = new HashMap<String, List<Post>>();
      Map<String, Post> allPosts = new HashMap<String, Post>();
      while (iterator.hasNext()) {
        Result result = iterator.next();
        Content content = cm.get(result.getPath());
        if (content == null) {
          continue;
        }
        Post p = new Post(content, session);
        allPosts.put((String) content.getProperty(MessageConstants.PROP_SAKAI_ID), p);

        if (content.hasProperty(DiscussionConstants.PROP_REPLY_ON)) {
          // This post is a reply on another post.
          String replyon = (String) content.getProperty(DiscussionConstants.PROP_REPLY_ON);
          if (!postChildren.containsKey(replyon)) {
            postChildren.put(replyon, new ArrayList<Post>());
          }

          postChildren.get(replyon).add(p);

        } else {
          // This post is not a reply to another post, thus it is a basepost.
          basePosts.add(p.getPostId());
        }
      }

      // Now that we have all the base posts, we can sort the replies properly
      for (Entry<String, List<Post>> postChild : postChildren.entrySet()) {
        Post parentPost = allPosts.get(postChild.getKey());
        if (parentPost != null) {
          List<Post> childrenList = parentPost.getChildren();
          List<Post> childrenActual = postChild.getValue();
          childrenList.addAll(childrenActual);
        }
      }

      // The posts are sorted, now return them as json.
      for (String basePostId : basePosts) {
        allPosts
            .get(basePostId)
            .outputPostAsJSON(
                (ExtendedJSONWriter) writer, presenceService, basicUserInfoService, session);
      }
    } catch (StorageClientException e) {
      throw new RuntimeException(e.getMessage(), e);
    } catch (AccessDeniedException e) {
      throw new RuntimeException(e.getMessage(), e);
    } catch (RepositoryException e) {
      throw new RuntimeException(e.getMessage(), e);
    }
  }