private void writeProfileMap(
     javax.jcr.Session jcrSession,
     AuthorizableManager um,
     ExtendedJSONWriter writer,
     String user,
     boolean detailed)
     throws JSONException, AccessDeniedException, StorageClientException, RepositoryException {
   Authorizable au = um.findAuthorizable(user);
   if (au != null) {
     ValueMap profileMap;
     if (detailed) {
       profileMap = profileService.getProfileMap(au, jcrSession);
     } else {
       profileMap = new ValueMapDecorator(basicUserInfoService.getProperties(au));
     }
     if (profileMap != null) {
       writer.valueMap(profileMap);
     }
   } else {
     writer.object();
     writer.key("userid");
     writer.value(user);
     writer.endObject();
   }
 }
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {
    // get current user
    String user = request.getRemoteUser();
    if (user == null) {
      response.sendError(
          HttpServletResponse.SC_UNAUTHORIZED, "User must be logged in to check their status");
    }
    LOGGER.info("GET to PresenceContactsServlet (" + user + ")");

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

    try {
      Writer writer = response.getWriter();
      ExtendedJSONWriter output = new ExtendedJSONWriter(writer);
      // start JSON object
      output.object();
      PresenceUtils.makePresenceJSON(output, user, presenceService, true);
      // add in the list of contacts info
      Session session = request.getResourceResolver().adaptTo(Session.class);
      List<String> userIds = connectionManager.getConnectedUsers(user, ConnectionState.ACCEPTED);
      output.key("contacts");
      output.array();
      for (String userId : userIds) {
        output.object();
        // put in the basics
        PresenceUtils.makePresenceJSON(output, userId, presenceService, true);
        // add in the profile
        output.key("profile");
        Authorizable au = PersonalUtils.getAuthorizable(session, userId);
        Node profileNode = (Node) session.getItem(PersonalUtils.getProfilePath(au));
        ExtendedJSONWriter.writeNodeToWriter(output, profileNode);
        output.endObject();
      }
      output.endArray();
      // finish it
      output.endObject();
    } catch (JSONException e) {
      LOGGER.error(e.getMessage(), e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (RepositoryException e) {
      LOGGER.error(e.getMessage(), e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }

    return;
  }
 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);
   }
 }
Beispiel #4
0
  public static void writeLinkNode(
      Content content,
      org.sakaiproject.nakamura.api.lite.Session session,
      JSONWriter writer,
      boolean objectInProgress)
      throws StorageClientException, JSONException {

    if (!objectInProgress) {
      writer.object();
    }
    ContentManager contentManager = session.getContentManager();

    // Write all the properties.
    ExtendedJSONWriter.writeNodeContentsToWriter(writer, content);

    // permissions
    writePermissions(content, session, writer);

    // Write the actual file.
    if (content.hasProperty(SAKAI_LINK)) {
      String linkPath = (String) content.getProperty(SAKAI_LINK);
      writer.key("file");
      try {
        Content fileNode = contentManager.get(linkPath);
        writeFileNode(fileNode, session, writer);
      } catch (org.sakaiproject.nakamura.api.lite.accesscontrol.AccessDeniedException e) {
        writer.value(false);
      }
    }
    if (!objectInProgress) {
      writer.endObject();
    }
  }
Beispiel #5
0
  public static void writeFileNode(
      Content content,
      org.sakaiproject.nakamura.api.lite.Session session,
      JSONWriter write,
      int maxDepth,
      boolean objectInProgress)
      throws JSONException, StorageClientException {
    if (content == null) {
      log.warn("Can't output null content.");
      return;
    }

    if (!objectInProgress) {
      write.object();
    }
    // dump all the properties.
    ExtendedJSONWriter.writeContentTreeToWriter(write, content, true, maxDepth);
    // The permissions for this session.
    writePermissions(content, session, write);

    write.key(JcrConstants.JCR_LASTMODIFIED);
    Calendar cal = new GregorianCalendar();
    cal.setTimeInMillis(StorageClientUtils.toLong(content.getProperty(Content.LASTMODIFIED_FIELD)));
    write.value(DateUtils.iso8601(cal));
    write.key(JcrConstants.JCR_MIMETYPE);
    write.value(content.getProperty(Content.MIMETYPE_FIELD));
    write.key(JcrConstants.JCR_DATA);
    write.value(StorageClientUtils.toLong(content.getProperty(Content.LENGTH_FIELD)));
    if (!objectInProgress) {
      write.endObject();
    }
  }
  public void writeNodes(
      SlingHttpServletRequest request,
      JSONWriter write,
      Aggregator aggregator,
      RowIterator iterator)
      throws JSONException, RepositoryException {

    Session session = request.getResourceResolver().adaptTo(Session.class);

    // TODO Get size from somewhere else.
    long total = iterator.getSize();
    long start = SearchUtil.getPaging(request, total);

    iterator.skip(start);

    for (long i = 0; i < start && iterator.hasNext(); i++) {
      Row row = iterator.nextRow();
      String path = row.getValue("jcr:path").getString();
      Node node = (Node) session.getItem(path);
      if (aggregator != null) {
        aggregator.add(node);
      }
      ExtendedJSONWriter.writeNodeToWriter(write, node);
    }
  }
Beispiel #7
0
  /**
   * Writes all the properties of a sakai/file node. Also checks what the permissions are for a
   * session and where the links are.
   *
   * @param node
   * @param write
   * @param objectInProgress Whether object creation is in progress. If false, object is started and
   *     ended in this method call.
   * @throws JSONException
   * @throws RepositoryException
   */
  public static void writeFileNode(Node node, Session session, JSONWriter write, int maxDepth)
      throws JSONException, RepositoryException {

    write.object();

    // dump all the properties.
    ExtendedJSONWriter.writeNodeTreeToWriter(write, node, true, maxDepth);
    // The permissions for this session.
    writePermissions(node, session, write);

    if (node.hasNode(JcrConstants.JCR_CONTENT)) {
      Node contentNode = node.getNode(JcrConstants.JCR_CONTENT);
      write.key(JcrConstants.JCR_LASTMODIFIED);
      Calendar cal = contentNode.getProperty(JcrConstants.JCR_LASTMODIFIED).getDate();
      write.value(DateUtils.iso8601(cal));
      write.key(JcrConstants.JCR_MIMETYPE);
      write.value(contentNode.getProperty(JcrConstants.JCR_MIMETYPE).getString());

      if (contentNode.hasProperty(JcrConstants.JCR_DATA)) {
        write.key(JcrConstants.JCR_DATA);
        write.value(contentNode.getProperty(JcrConstants.JCR_DATA).getLength());
      }
    }

    write.endObject();
  }
  /** {@inheritDoc} */
  public void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {
    try {
      Resource resource = request.getResource();
      Node node = resource.adaptTo(Node.class);
      if (node == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
      }
      Version version = versionService.saveNode(node, request.getRemoteUser());

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

      ExtendedJSONWriter write = new ExtendedJSONWriter(response.getWriter());
      write.object();
      write.key("versionName");
      write.value(version.getName());
      ExtendedJSONWriter.writeNodeContentsToWriter(write, version);
      write.endObject();
    } catch (RepositoryException e) {
      LOGGER.info("Failed to save version ", e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
      return;
    } catch (JSONException e) {
      LOGGER.info("Failed to save version ", e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
      return;
    }
  }
 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.SearchResultProcessor#writeNode(org.apache.sling.api.SlingHttpServletRequest,
   *     org.apache.sling.commons.json.io.JSONWriter,
   *     org.sakaiproject.nakamura.api.search.Aggregator, javax.jcr.query.Row)
   */
  public void writeNode(
      SlingHttpServletRequest request, JSONWriter write, Aggregator aggregator, Row row)
      throws JSONException, RepositoryException {

    write.object();
    Node node = row.getNode();
    write.key("jcr:created");
    write.value(node.getProperty("jcr:created").getString());
    String userID = node.getName();
    UserManager um = AccessControlUtil.getUserManager(node.getSession());
    Authorizable au = um.getAuthorizable(userID);
    if (au != null) {
      ValueMap map = profileService.getCompactProfileMap(au, node.getSession());
      ((ExtendedJSONWriter) write).valueMapInternals(map);
    }
    write.endObject();
  }
 /**
  * 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;
 }
 private void writeDefaultNode(
     JSONWriter write, Aggregator aggregator, Row row, Node siteNode, Session session)
     throws JSONException, RepositoryException {
   Node node = RowUtils.getNode(row, session);
   if (aggregator != null) {
     aggregator.add(node);
   }
   write.object();
   write.key("path");
   write.value(node.getPath());
   write.key("site");
   siteSearchResultProcessor.writeNode(write, siteNode);
   write.key("excerpt");
   write.value(RowUtils.getDefaultExcerpt(row));
   write.key("data");
   ExtendedJSONWriter.writeNodeToWriter(write, node);
   write.endObject();
 }
Beispiel #13
0
 /**
  * Writes comments of content
  *
  * @param node
  * @param session
  * @param write
  * @throws RepositoryException
  * @throws JSONException
  */
 public static void writeComments(
     Content content, org.sakaiproject.nakamura.api.lite.Session session, JSONWriter writer)
     throws StorageClientException, JSONException {
   if (content == null) {
     log.warn("Can't output comments of null content.");
     return;
   }
   writer.key("comments");
   writer.object();
   Content commentContent = null;
   try {
     commentContent = session.getContentManager().get(content.getPath() + "/comments");
     ExtendedJSONWriter.writeContentTreeToWriter(writer, commentContent, true, 2);
   } catch (org.sakaiproject.nakamura.api.lite.accesscontrol.AccessDeniedException e) {
     writer.value(false);
   } finally {
     writer.endObject();
   }
 }
Beispiel #14
0
  /**
   * Writes all the properties for a linked node.
   *
   * @param node
   * @param write
   * @throws JSONException
   * @throws RepositoryException
   */
  public static void writeLinkNode(Node node, Session session, JSONWriter write)
      throws JSONException, RepositoryException {
    write.object();
    // Write all the properties.
    ExtendedJSONWriter.writeNodeContentsToWriter(write, node);
    // permissions
    writePermissions(node, session, write);

    // Write the actual file.
    if (node.hasProperty(SAKAI_LINK)) {
      String uuid = node.getProperty(SAKAI_LINK).getString();
      write.key("file");
      try {
        Node fileNode = session.getNodeByIdentifier(uuid);
        writeFileNode(fileNode, session, write);
      } catch (ItemNotFoundException e) {
        write.value(false);
      }
    }

    write.endObject();
  }
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {
    try {
      Resource resource = request.getResource();
      if (!resource.getPath().startsWith(SEARCH_PATH_PREFIX)) {
        response.sendError(
            HttpServletResponse.SC_FORBIDDEN,
            "Search templates can only be executed if they are located under "
                + SEARCH_PATH_PREFIX);
        return;
      }

      Node node = resource.adaptTo(Node.class);
      if (node != null && node.hasProperty(SAKAI_QUERY_TEMPLATE)) {
        // TODO: we might want to use this ?
        @SuppressWarnings("unused")
        boolean limitResults = true;
        if (node.hasProperty(SAKAI_LIMIT_RESULTS)) {
          limitResults = node.getProperty(SAKAI_LIMIT_RESULTS).getBoolean();
        }

        // KERN-1147 Respond better when all parameters haven't been provided for a query
        Query query = null;
        try {
          query = processQuery(request, node);
        } catch (MissingParameterException e) {
          response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
          return;
        }

        long nitems =
            SolrSearchUtil.longRequestParameter(
                request, PARAMS_ITEMS_PER_PAGE, DEFAULT_PAGED_ITEMS);
        long page = SolrSearchUtil.longRequestParameter(request, PARAMS_PAGE, 0);

        // allow number of items to be specified in sakai:query-template-options
        if (query.getOptions().containsKey(PARAMS_ITEMS_PER_PAGE)) {
          nitems = Long.valueOf(query.getOptions().get(PARAMS_ITEMS_PER_PAGE));
        } else {
          // add this to the options so that all queries are constrained to a limited
          // number of returns per page.
          query.getOptions().put(PARAMS_ITEMS_PER_PAGE, Long.toString(nitems));
        }

        if (query.getOptions().containsKey(PARAMS_PAGE)) {
          page = Long.valueOf(query.getOptions().get(PARAMS_PAGE));
        } else {
          // add this to the options so that all queries are constrained to a limited
          // number of returns per page.
          query.getOptions().put(PARAMS_PAGE, Long.toString(page));
        }

        boolean useBatch = false;
        // Get the
        SolrSearchBatchResultProcessor searchBatchProcessor = defaultSearchBatchProcessor;
        if (node.hasProperty(SAKAI_BATCHRESULTPROCESSOR)) {
          searchBatchProcessor =
              batchProcessors.get(node.getProperty(SAKAI_BATCHRESULTPROCESSOR).getString());
          useBatch = true;
          if (searchBatchProcessor == null) {
            searchBatchProcessor = defaultSearchBatchProcessor;
          }
        }

        SolrSearchResultProcessor searchProcessor = defaultSearchProcessor;
        if (node.hasProperty(SAKAI_RESULTPROCESSOR)) {
          searchProcessor = processors.get(node.getProperty(SAKAI_RESULTPROCESSOR).getString());
          if (searchProcessor == null) {
            searchProcessor = defaultSearchProcessor;
          }
        }

        SolrSearchResultSet rs = null;
        try {
          // Prepare the result set.
          // This allows a processor to do other queries and manipulate the results.
          if (useBatch) {
            rs = searchBatchProcessor.getSearchResultSet(request, query);
          } else {
            rs = searchProcessor.getSearchResultSet(request, query);
          }
        } catch (SolrSearchException e) {
          response.sendError(e.getCode(), e.getMessage());
          return;
        }

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

        ExtendedJSONWriter write = new ExtendedJSONWriter(response.getWriter());
        write.setTidy(isTidy(request));

        write.object();
        write.key(PARAMS_ITEMS_PER_PAGE);
        write.value(nitems);
        write.key(JSON_RESULTS);

        write.array();

        Iterator<Result> iterator = rs.getResultSetIterator();
        if (useBatch) {
          LOGGER.info("Using batch processor for results");
          searchBatchProcessor.writeResults(request, write, iterator);
        } else {
          LOGGER.info("Using regular processor for results");
          // We don't skip any rows ourselves here.
          // We expect a rowIterator coming from a resultset to be at the right place.
          for (long i = 0; i < nitems && iterator.hasNext(); i++) {
            // Get the next row.
            Result result = iterator.next();

            // Write the result for this row.
            searchProcessor.writeResult(request, write, result);
          }
        }
        write.endArray();

        // write the total out after processing the list to give the underlying iterator
        // a chance to walk the results then report how many there were.
        write.key(TOTAL);
        write.value(rs.getSize());

        write.endObject();
      }
    } catch (RepositoryException e) {
      LOGGER.error(e.getMessage(), e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (JSONException e) {
      LOGGER.error(e.getMessage(), e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
  }
  /**
   * {@inheritDoc}
   *
   * @see
   *     org.apache.sling.api.servlets.SlingSafeMethodsServlet#doGet(org.apache.sling.api.SlingHttpServletRequest,
   *     org.apache.sling.api.SlingHttpServletResponse)
   */
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {
    try {
      // Grab the search node.
      Node node = request.getResource().adaptTo(Node.class);

      // Grab the node that holds the repository information.
      Node proxyNode = DocProxyUtils.getProxyNode(node);

      // Grab the correct processor
      String type = proxyNode.getProperty(REPOSITORY_PROCESSOR).getString();
      ExternalRepositoryProcessor processor = tracker.getProcessorByType(type);
      if (processor == null) {
        LOGGER.warn("No processor found for type - {}", type);
        response.sendError(
            HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not handle this repository type.");
        return;
      }

      // Handle properties.
      Map<String, Object> searchProperties = new HashMap<String, Object>();
      handleProperties(searchProperties, node, request);

      // Process search
      Iterator<ExternalDocumentResult> results = processor.search(proxyNode, searchProperties);

      // Do the default search paging.
      long toSkip = SearchUtil.getPaging(request, -1);
      while (toSkip > 0) {
        if (results.hasNext()) {
          results.next();
          toSkip--;
        } else {
          throw new NoSuchElementException();
        }
      }

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

      ExtendedJSONWriter write = new ExtendedJSONWriter(response.getWriter());
      write.array();
      long nitems =
          SearchUtil.longRequestParameter(
              request, SearchConstants.PARAMS_ITEMS_PER_PAGE, SearchConstants.DEFAULT_PAGED_ITEMS);
      for (long i = 0; i < nitems && results.hasNext(); i++) {
        ExternalDocumentResult result = results.next();
        DocProxyUtils.writeMetaData(write, result);
      }
      write.endArray();

    } catch (RepositoryException e) {
      LOGGER.error("Got a repository exception when trying to grab search node information.", e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to perform search.");
    } catch (JSONException e) {
      LOGGER.error("Got a JSON exception when trying to grab search node information.", e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to perform search.");
    } catch (DocProxyException e) {
      LOGGER.error("Got a DocProxy exception when trying to grab search node information.", e);
      response.sendError(e.getCode(), e.getMessage());
    }
  }
Beispiel #17
0
  /**
   * {@inheritDoc}
   *
   * @see
   *     org.apache.sling.api.servlets.SlingSafeMethodsServlet#doGet(org.apache.sling.api.SlingHttpServletRequest,
   *     org.apache.sling.api.SlingHttpServletResponse)
   */
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {
    try {
      List<Content> contentList = null;
      RequestParameter rp = request.getRequestParameter("path");
      ResourceResolver resourceResolver = request.getResourceResolver();
      if (rp != null) {
        String contentPath = rp.getString("UTF-8");
        if (contentPath.startsWith("/_groupa:")) {
          contentPath = contentPath.replaceFirst("/_groupa:", "/~");
        }
        if (contentPath.endsWith("/")) {
          contentPath = contentPath.substring(0, contentPath.length() - 1);
        }

        Resource pagesResource = resourceResolver.getResource(contentPath);
        if (pagesResource != null) {
          contentList = getPageTree(pagesResource.adaptTo(Content.class));
          ;
        }
      }

      response.setContentType("application/json");
      response.setCharacterEncoding("UTF-8");
      PrintWriter w = response.getWriter();
      ExtendedJSONWriter writer = new ExtendedJSONWriter(w);
      writer.object();
      // pages info
      int messageCount = 0;
      writer.key("items");
      writer.value(255);

      writer.key("results");
      writer.array();
      if (contentList != null) {
        for (int i = 0; i < contentList.size(); i++) {
          Content page = contentList.get(i);

          writer.object();
          writer.key("jcr:path");
          writer.value(
              page.getPath()
                  .replaceFirst(
                      LitePersonalUtils.PATH_AUTHORIZABLE,
                      LitePersonalUtils.PATH_RESOURCE_AUTHORIZABLE));
          for (String messagePropKey : page.getProperties().keySet()) {
            writer.key(messagePropKey);
            writer.value(massageValue(messagePropKey, page.getProperty(messagePropKey)));
          }
          writer.endObject();
          messageCount++;
        }
      }
      writer.endArray();
      writer.key("total");
      writer.value(messageCount);

      writer.endObject();
    } catch (JSONException e) {
      LOG.error("Failed to create proper JSON response in /var/search/page", e);
      response.sendError(
          HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to create proper JSON response.");
    }
  }
  /**
   * Retrieves the list of members.
   *
   * <p>{@inheritDoc}
   *
   * @see
   *     org.apache.sling.api.servlets.SlingSafeMethodsServlet#doGet(org.apache.sling.api.SlingHttpServletRequest,
   *     org.apache.sling.api.SlingHttpServletResponse)
   */
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {
    try {
      // Get hold of the actual file.
      Resource resource = request.getResource();
      javax.jcr.Session jcrSession = request.getResourceResolver().adaptTo(javax.jcr.Session.class);
      Session session = resource.adaptTo(Session.class);

      AuthorizableManager am = session.getAuthorizableManager();
      AccessControlManager acm = session.getAccessControlManager();
      Content node = resource.adaptTo(Content.class);
      Authorizable thisUser = am.findAuthorizable(session.getUserId());

      if (!acm.can(thisUser, Security.ZONE_CONTENT, resource.getPath(), Permissions.CAN_READ)) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
      }

      Map<String, Object> properties = node.getProperties();
      String[] managers = (String[]) properties.get(POOLED_CONTENT_USER_MANAGER);
      String[] editors = (String[]) properties.get(POOLED_CONTENT_USER_EDITOR);
      String[] viewers = (String[]) properties.get(POOLED_CONTENT_USER_VIEWER);

      boolean detailed = false;
      boolean tidy = false;
      for (String selector : request.getRequestPathInfo().getSelectors()) {
        if ("detailed".equals(selector)) {
          detailed = true;
        } else if ("tidy".equals(selector)) {
          tidy = true;
        }
      }

      // Loop over the sets and output it.
      ExtendedJSONWriter writer = new ExtendedJSONWriter(response.getWriter());
      writer.setTidy(tidy);
      writer.object();
      writer.key("managers");
      writer.array();
      for (String manager : StorageClientUtils.nonNullStringArray(managers)) {
        try {
          writeProfileMap(jcrSession, am, writer, manager, detailed);
        } catch (AccessDeniedException e) {
          LOGGER.debug("Skipping private manager [{}]", manager);
        }
      }
      writer.endArray();
      writer.key("editors");
      writer.array();
      for (String editor : StorageClientUtils.nonNullStringArray(editors)) {
        try {
          writeProfileMap(jcrSession, am, writer, editor, detailed);
        } catch (AccessDeniedException e) {
          LOGGER.debug("Skipping private editor [{}]", editor);
        }
      }
      writer.endArray();
      writer.key("viewers");
      writer.array();
      for (String viewer : StorageClientUtils.nonNullStringArray(viewers)) {
        try {
          writeProfileMap(jcrSession, am, writer, viewer, detailed);
        } catch (AccessDeniedException e) {
          LOGGER.debug("Skipping private viewer [{}]", viewer);
        }
      }
      writer.endArray();
      writer.endObject();
    } catch (JSONException e) {
      response.sendError(SC_INTERNAL_SERVER_ERROR, "Failed to generate proper JSON.");
      LOGGER.error(e.getMessage(), e);
    } catch (StorageClientException e) {
      response.sendError(SC_INTERNAL_SERVER_ERROR, "Failed to generate proper JSON.");
      LOGGER.error(e.getMessage(), e);
    } catch (AccessDeniedException e) {
      response.sendError(SC_INTERNAL_SERVER_ERROR, "Failed to generate proper JSON.");
      LOGGER.error(e.getMessage(), e);
    } catch (RepositoryException e) {
      response.sendError(SC_INTERNAL_SERVER_ERROR, "Failed to generate proper JSON.");
      LOGGER.error(e.getMessage(), e);
    }
  }
 public void node(Node node) throws JSONException, RepositoryException {
   ExtendedJSONWriter.writeNodeToWriter(this, node);
 }
  /**
   * {@inheritDoc}
   *
   * @see
   *     org.apache.sling.api.servlets.SlingSafeMethodsServlet#doGet(org.apache.sling.api.SlingHttpServletRequest,
   *     org.apache.sling.api.SlingHttpServletResponse)
   */
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {
    Authorizable authorizable = null;
    Resource resource = request.getResource();
    if (resource != null) {
      authorizable = resource.adaptTo(Authorizable.class);
    }

    if (authorizable == null || !authorizable.isGroup()) {
      response.sendError(HttpServletResponse.SC_NO_CONTENT, "Couldn't find group");
      return;
    }

    Group group = (Group) authorizable;

    List<String> selectors = Arrays.asList(request.getRequestPathInfo().getSelectors());
    ExtendedJSONWriter writer = new ExtendedJSONWriter(response.getWriter());
    writer.setTidy(selectors.contains("tidy"));

    // Get the sorting order, default is ascending or the natural sorting order (which is
    // null for a TreeMap.)
    Comparator<String> comparator = null;
    String order = "ascending";
    if (request.getRequestParameter("sortOrder") != null) {
      order = request.getRequestParameter("sortOrder").getString();
      if (order.equals("descending")) {
        comparator = Collections.reverseOrder();
      }
    }

    try {
      response.setContentType("application/json");
      TreeMap<String, Authorizable> map = null;
      if (selectors.contains("managers")) {
        map = getManagers(request, group, comparator);
      } else {
        // Members is the default.
        map = getMembers(request, group, comparator);
      }

      // Do some paging.
      long items =
          (request.getParameter(ITEMS) != null) ? Long.parseLong(request.getParameter(ITEMS)) : 25;
      long page =
          (request.getParameter(PAGE) != null) ? Long.parseLong(request.getParameter(PAGE)) : 0;
      if (page < 0) {
        page = 0;
      }
      if (items < 0) {
        items = 25;
      }
      Iterator<Entry<String, Authorizable>> iterator =
          getInPlaceIterator(request, map, items, page);

      // Write the whole lot out.
      Session session = request.getResourceResolver().adaptTo(Session.class);
      writer.array();
      int i = 0;
      while (iterator.hasNext() && i < items) {
        Entry<String, Authorizable> entry = iterator.next();
        Authorizable au = entry.getValue();
        ValueMap profile;
        if (selectors.contains("detailed")) {
          profile = profileService.getProfileMap(au, session);
        } else {
          profile = profileService.getCompactProfileMap(au, session);
        }
        if (profile != null) {
          writer.valueMap(profile);
          i++;
        } else {
          // profile wasn't found.  safe to ignore and not include the group
          logger.info("Profile not found for " + au.getID());
        }
      }
      writer.endArray();

    } catch (RepositoryException e) {
      response.sendError(
          HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to retrieve members/managers.");
      return;
    } catch (JSONException e) {
      response.sendError(
          HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to build a proper JSON output.");
      return;
    }
  }