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);
    }
  }
Esempio n. 2
0
 /** Dump given property in JSON */
 public void dump(Property p, Writer w)
     throws JSONException, ValueFormatException, RepositoryException {
   final JSONWriter jw = new JSONWriter(w);
   jw.object();
   writeProperty(jw, p);
   jw.endObject();
 }
Esempio n. 3
0
  /** Dump given node in JSON, optionally recursing into its child nodes */
  protected void dump(Node node, JSONWriter w, int currentRecursionLevel, int maxRecursionLevels)
      throws RepositoryException, JSONException {

    w.object();
    PropertyIterator props = node.getProperties();

    // the node's actual properties
    while (props.hasNext()) {
      Property prop = props.nextProperty();

      if (propertyNamesToIgnore != null && propertyNamesToIgnore.contains(prop.getName())) {
        continue;
      }

      writeProperty(w, prop);
    }

    // the child nodes
    if (recursionLevelActive(currentRecursionLevel, maxRecursionLevels)) {
      final NodeIterator children = node.getNodes();
      while (children.hasNext()) {
        final Node n = children.nextNode();
        dumpSingleNode(n, w, currentRecursionLevel, maxRecursionLevels);
      }
    }

    w.endObject();
  }
  @Override
  public void write(Hit hit, JSONWriter jsonWriter, Query query)
      throws RepositoryException, JSONException {

    // Get the Node that represents a Query "hit"
    Node node = hit.getNode();

    // Write simple values like the node's path to the JSON result object
    jsonWriter.key("path").value(node.getPath());

    // Write node properties from the hit result node (or relative nodes) to the JSON result object
    final String property1 = "jcr:content/jcr:title";
    if (node.hasProperty(property1)) {
      final Property property = node.getProperty(property1);
      // You have full control over the names/values of the JSON key/value pairs returned.
      // These do not have to match node names
      jsonWriter
          .key("key-to-use-in-json")
          .value(property.getString() + "(pulled from jcr:content node)");
    }

    // Custom logic can be used to transform and/or retrieve data to be added to the resulting JSON
    // object
    // Note: Keep this logic as light as possible. Complex logic can introduce performance issues
    // that are
    // less visible (Will not appear in Slow Query logs as this logic executes after the actual
    // Query returns).
    String complexValue = sampleComplexLogic(node);
    jsonWriter.key("complex").value(complexValue);
  }
 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);
   }
 }
Esempio n. 6
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();
    }
  }
Esempio n. 7
0
 /**
  * Dump all Nodes of given NodeIterator in JSON
  *
  * @throws JSONException
  */
 public void dump(NodeIterator it, Writer out) throws RepositoryException, JSONException {
   final JSONWriter w = new JSONWriter(out);
   w.array();
   while (it.hasNext()) {
     dump(it.nextNode(), w, 1, 1);
   }
   w.endArray();
 }
Esempio n. 8
0
 public void write(JSONWriter writer, String key) throws JSONException {
   if (key != null) {
     writer.key(key);
   }
   writer.array();
   for (Item item : items) {
     item.write(writer);
   }
   writer.endArray();
 }
Esempio n. 9
0
  private static void writePermissions(
      Content content, org.sakaiproject.nakamura.api.lite.Session session, JSONWriter writer)
      throws StorageClientException, JSONException {
    if (content == null) {
      log.warn("Can't output permissions of null content.");
      return;
    }

    AccessControlManager acm = session.getAccessControlManager();
    String path = content.getPath();

    writer.key("permissions");
    writer.object();
    writer.key("set_property");
    // TODO does CAN_WRITE == set_property -CFH : yes, ieb
    // TODO: make this a bit more efficient, checking permissions one by one is going to rely on
    //       caching to make it efficient. It would be better to get the permissions bitmap and then
    //       check it to see what has been set. That might require a niew methods in the
    // AccessControl
    //       manager API.
    writer.value(hasPermission(acm, path, Permissions.CAN_WRITE));
    writer.key("read");
    writer.value(hasPermission(acm, path, Permissions.CAN_READ));
    writer.key("remove");
    writer.value(hasPermission(acm, path, Permissions.CAN_DELETE));
    writer.endObject();
  }
 private void writeCommentCountProperty(JSONWriter write, Session session, Content contentResult)
     throws StorageClientException, JSONException, AccessDeniedException {
   ContentManager contentManager = session.getContentManager();
   Content comments = contentManager.get(contentResult.getPath() + "/" + "comments");
   long commentCount = 0;
   if (comments != null) {
     for (@SuppressWarnings("unused") Content comment : comments.listChildren()) {
       commentCount++;
     }
   }
   write.key("commentCount");
   write.value(commentCount);
 }
Esempio n. 11
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();
  }
Esempio n. 12
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();
    }
  }
Esempio n. 13
0
  /** Write a single property */
  protected void writeProperty(JSONWriter w, Property p)
      throws ValueFormatException, RepositoryException, JSONException {
    // special handling for binaries: we dump the length and not the length
    if (p.getType() == PropertyType.BINARY) {
      // TODO for now we mark binary properties with an initial colon in
      // their name
      // (colon is not allowed as a JCR property name)
      // in the name, and the value should be the size of the binary data
      w.key(":" + p.getName());
      if (!p.getDefinition().isMultiple()) {
        w.value(p.getLength());
      } else {
        final long[] sizes = p.getLengths();
        w.array();
        for (int i = 0; i < sizes.length; i++) {
          w.value(sizes[i]);
        }
        w.endArray();
      }
      return;
    }
    w.key(p.getName());

    if (!p.getDefinition().isMultiple()) {
      dumpValue(w, p.getValue());
    } else {
      w.array();
      for (Value v : p.getValues()) {
        dumpValue(w, v);
      }
      w.endArray();
    }
  }
  /**
   * Give a JSON representation of the content.
   *
   * @param content
   * @param session
   * @param write The {@link JSONWriter} to output to.
   * @param depth
   * @throws JSONException
   * @throws StorageClientException
   */
  protected void handleContent(
      final Content content, final Session session, final JSONWriter write, final int depth)
      throws JSONException, StorageClientException {

    write.object();
    final String type = (String) content.getProperty(SLING_RESOURCE_TYPE_PROPERTY);
    if (FilesConstants.RT_SAKAI_LINK.equals(type)) {
      FileUtils.writeLinkNode(content, session, write, true);
    } else {
      FileUtils.writeFileNode(content, session, write, depth, true);
    }
    FileUtils.writeComments(content, session, write);
    FileUtils.writeCommentCountProperty(content, session, write, repository);
    write.endObject();
  }
  public static void extractAttachment(
      final Writer ioWriter, final JSONWriter writer, final Resource node)
      throws JSONException, UnsupportedEncodingException {
    Resource contentNode = node.getChild("jcr:content");
    if (contentNode == null) {
      writer.key(ContentTypeDefinitions.LABEL_ERROR);
      writer.value(
          "provided resource was not an attachment - no content node beneath " + node.getPath());
      return;
    }
    ValueMap content = contentNode.adaptTo(ValueMap.class);
    if (!content.containsKey("jcr:mimeType") || !content.containsKey("jcr:data")) {
      writer.key(ContentTypeDefinitions.LABEL_ERROR);
      writer.value(
          "provided resource was not an attachment - content node contained no attachment data under "
              + node.getPath());
      return;
    }
    writer.key("filename");
    writer.value(URLEncoder.encode(node.getName(), "UTF-8"));
    writer.key("jcr:mimeType");
    writer.value(content.get("jcr:mimeType"));

    try {
      ioWriter.write(",\"jcr:data\":\"");
      final InputStream data = (InputStream) content.get("jcr:data");
      byte[] byteData = new byte[DATA_ENCODING_CHUNK_SIZE];
      int read = 0;
      while (read != -1) {
        read = data.read(byteData);
        if (read > 0 && read < DATA_ENCODING_CHUNK_SIZE) {
          // make a right-size container for the byte data actually read
          byte[] byteArray = new byte[read];
          System.arraycopy(byteData, 0, byteArray, 0, read);
          byte[] encodedBytes = Base64.encodeBase64(byteArray);
          ioWriter.write(new String(encodedBytes));
        } else if (read == DATA_ENCODING_CHUNK_SIZE) {
          byte[] encodedBytes = Base64.encodeBase64(byteData);
          ioWriter.write(new String(encodedBytes));
        }
      }
      ioWriter.write("\"");
    } catch (IOException e) {
      writer.key(ContentTypeDefinitions.LABEL_ERROR);
      writer.value(
          "IOException while getting attachment at " + node.getPath() + ": " + e.getMessage());
    }
  }
Esempio n. 16
0
 /**
  * Gives the permissions for this user.
  *
  * @param node
  * @param session
  * @param write
  * @throws RepositoryException
  * @throws JSONException
  */
 private static void writePermissions(Node node, Session session, JSONWriter write)
     throws RepositoryException, JSONException {
   String path = node.getPath();
   write.key("permissions");
   write.object();
   write.key("set_property");
   write.value(hasPermission(session, path, "set_property"));
   write.key("read");
   write.value(hasPermission(session, path, "read"));
   write.key("remove");
   write.value(hasPermission(session, path, "remove"));
   write.endObject();
 }
  /**
   * {@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();
  }
 private void writeReplicationState(JSONWriter out, Resource resource) throws Exception {
   out.key("replication").object();
   ReplicationStatus replicationStatus = resource.adaptTo(ReplicationStatus.class);
   if (replicationStatus != null) {
     Calendar published = replicationStatus.getLastPublished();
     if (published != null) {
       out.key("published").value(published.getTimeInMillis());
     }
     if (replicationStatus.getLastReplicationAction() != null) {
       String action = replicationStatus.getLastReplicationAction().name();
       if (action != null && action.length() > 0) {
         out.key("action").value(action);
       }
     }
   }
   out.endObject();
 }
Esempio n. 19
0
 /** Dump a single node */
 protected void dumpSingleNode(
     Node n, JSONWriter w, int currentRecursionLevel, int maxRecursionLevels)
     throws RepositoryException, JSONException {
   if (recursionLevelActive(currentRecursionLevel, maxRecursionLevels)) {
     w.key(n.getName());
     dump(n, w, currentRecursionLevel + 1, maxRecursionLevels);
   }
 }
  private void writeNode(
      SlingHttpServletRequest request, JSONWriter write, Aggregator aggregator, Row row)
      throws JSONException, RepositoryException {
    Session session = request.getResourceResolver().adaptTo(Session.class);
    Node node = RowUtils.getNode(row, session);

    Node siteNode = node;
    boolean foundSite = false;
    while (!siteNode.getPath().equals("/")) {

      if (siteService.isSite(siteNode)) {
        foundSite = true;
        break;
      }
      siteNode = siteNode.getParent();
    }
    if (foundSite) {
      if (node.hasProperty(SLING_RESOURCE_TYPE_PROPERTY)) {
        String type = node.getProperty(SLING_RESOURCE_TYPE_PROPERTY).getString();

        // From looking at the type we determine how we should represent this node.
        SearchResultProcessor processor = tracker.getSearchResultProcessorByType(type);
        if (processor != null) {
          write.object();
          write.key("path");
          write.value(node.getPath());
          write.key("site");
          siteSearchResultProcessor.writeNode(write, siteNode);
          write.key("type");
          write.value(node.getProperty(SLING_RESOURCE_TYPE_PROPERTY).getString());
          write.key("excerpt");
          write.value(RowUtils.getDefaultExcerpt(row));
          write.key("data");
          processor.writeNode(request, write, aggregator, row);
          write.endObject();
        } else {
          // No processor found, just dump the properties
          writeDefaultNode(write, aggregator, row, siteNode, session);
        }

      } else {
        // No type, just dump the properties
        writeDefaultNode(write, aggregator, row, siteNode, session);
      }
    }
  }
 /**
  * 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;
 }
Esempio n. 22
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();
   }
 }
 private void writeCanManageProperty(
     SlingHttpServletRequest request, JSONWriter write, Session session, Content contentResult)
     throws StorageClientException, JSONException, AccessDeniedException {
   write.key("sakai:canmanage");
   Authorizable thisUser =
       session.getAuthorizableManager().findAuthorizable(request.getRemoteUser());
   Collection<String> principals = new ArrayList<String>();
   principals.addAll(Arrays.asList(thisUser.getPrincipals()));
   principals.add(request.getRemoteUser());
   boolean canManage = false;
   for (String principal : principals) {
     if (Arrays.asList(
             StorageClientUtils.nonNullStringArray(
                 (String[]) contentResult.getProperty("sakai:pooled-content-manager")))
         .contains(principal)) {
       canManage = true;
     }
   }
   write.value(canManage);
 }
Esempio n. 24
0
  /**
   * Writes commentCount of content
   *
   * @param node
   * @param session
   * @param write
   * @throws RepositoryException
   * @throws JSONException
   */
  public static void writeCommentCountProperty(
      Content content,
      org.sakaiproject.nakamura.api.lite.Session session,
      JSONWriter writer,
      Repository repository)
      throws StorageClientException, JSONException {

    int commentCount = 0;
    String COMMENTCOUNT = "commentCount";

    if (content.hasProperty(COMMENTCOUNT)) {
      commentCount = (Integer) content.getProperty(COMMENTCOUNT);
    } else {
      // no commentCount property on Content, then evaluate count and add property
      Content comments = null;
      org.sakaiproject.nakamura.api.lite.Session adminSession = null;
      try {
        comments = session.getContentManager().get(content.getPath() + "/comments");
        if (comments != null) {
          commentCount = Iterables.size(comments.listChildPaths());
        }
        content.setProperty(COMMENTCOUNT, commentCount);
        // save property
        adminSession = repository.loginAdministrative();
        ContentManager adminContentManager = adminSession.getContentManager();
        adminContentManager.update(content);
      } catch (org.sakaiproject.nakamura.api.lite.accesscontrol.AccessDeniedException e) {
        log.error(e.getMessage(), e);
      } finally {
        if (adminSession != null) {
          try {
            adminSession.logout();
          } catch (Exception e) {
            log.error("Could not logout administrative session.");
          }
        }
      }
    }
    writer.key(COMMENTCOUNT);
    writer.value(commentCount);
  }
Esempio n. 25
0
  /**
   * Writes the given value to the JSON writer. currently the following conversions are done:
   *
   * <table>
   * <tr>
   * <th>JSR Property Type</th>
   * <th>JSON Value Type</th>
   * </tr>
   * <tr>
   * <td>BINARY</td>
   * <td>always 0 as long</td>
   * </tr>
   * <tr>
   * <td>DATE</td>
   * <td>converted date string as defined by ECMA</td>
   * </tr>
   * <tr>
   * <td>BOOLEAN</td>
   * <td>boolean</td>
   * </tr>
   * <tr>
   * <td>LONG</td>
   * <td>long</td>
   * </tr>
   * <tr>
   * <td>DOUBLE</td>
   * <td>double</td>
   * </tr>
   * <tr>
   * <td><i>all other</li>
   * </td>
   * <td>string</td>
   * </tr>
   * </table>
   *
   * <sup>1</sup> Currently not implemented and uses 0 as default.
   *
   * @param w json writer
   * @param v value to dump
   */
  protected void dumpValue(JSONWriter w, Value v)
      throws ValueFormatException, IllegalStateException, RepositoryException, JSONException {

    switch (v.getType()) {
      case PropertyType.BINARY:
        w.value(0);
        break;

      case PropertyType.DATE:
        w.value(format(v.getDate()));
        break;

      case PropertyType.BOOLEAN:
        w.value(v.getBoolean());
        break;

      case PropertyType.LONG:
        w.value(v.getLong());
        break;

      case PropertyType.DOUBLE:
        w.value(v.getDouble());

        break;
      default:
        w.value(v.getString());
    }
  }
Esempio n. 26
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();
  }
Esempio n. 27
0
 private void writeFailedRequest(JSONWriter write, RequestInfo requestData) throws JSONException {
   write.object();
   write.key("url");
   write.value(requestData.getUrl());
   write.key("success");
   write.value(false);
   write.endObject();
 }
  protected void simpleResultCountCheck(SearchResultProcessor processor)
      throws RepositoryException, JSONException {
    int itemCount = 12;
    QueryResult queryResult = createMock(QueryResult.class);
    RowIterator results = createMock(RowIterator.class);
    expect(queryResult.getRows()).andReturn(results);
    expect(results.getSize()).andReturn(500L).anyTimes();
    Row dummyRow = createMock(Row.class);
    Value val = createMock(Value.class);
    expect(val.getString()).andReturn("").times(itemCount);
    expect(dummyRow.getValue("jcr:path")).andReturn(val).times(itemCount);
    expect(results.hasNext()).andReturn(true).anyTimes();
    expect(results.nextRow()).andReturn(dummyRow).times(itemCount);
    SlingHttpServletRequest request = createMock(SlingHttpServletRequest.class);
    ResourceResolver resourceResolver = createMock(ResourceResolver.class);
    Session session = createMock(Session.class);
    Node resultNode = createMock(Node.class);
    expect(resultNode.getPath()).andReturn("/path/to/node").anyTimes();
    expect(resultNode.getName()).andReturn("node").anyTimes();
    expect(request.getResourceResolver()).andReturn(resourceResolver).times(itemCount);
    expect(resourceResolver.adaptTo(Session.class)).andReturn(session).times(itemCount);
    expect(session.getItem("")).andReturn(resultNode).times(itemCount);
    PropertyIterator propIterator = createMock(PropertyIterator.class);
    expect(propIterator.hasNext()).andReturn(false).anyTimes();
    expect(resultNode.getProperties()).andReturn(propIterator).anyTimes();

    replay();
    JSONWriter write = new JSONWriter(new PrintWriter(new ByteArrayOutputStream()));
    write.array();
    RowIterator iterator = queryResult.getRows();
    int i = 0;
    while (iterator.hasNext() && i < itemCount) {
      processor.writeNode(request, write, null, iterator.nextRow());
      i++;
    }
    write.endArray();
    verify();
  }
  /**
   * Represent an entire JCR tree in JSON format.
   *
   * @param write The {@link JSONWriter writer} to send the data to.
   * @param node The node and it's subtree to output. Note: The properties of this node will be
   *     outputted as well.
   * @param objectInProgress use true if you don't want the method to enclose the output in fresh
   *     object braces
   * @param maxDepth Maximum depth of subnodes to traverse. The properties on {@link node} are
   *     processed before this is taken into account.
   * @param currentLevel Internal parameter to track the current processing level.
   * @throws RepositoryException
   * @throws JSONException
   */
  protected static void writeNodeTreeToWriter(
      JSONWriter write, Node node, boolean objectInProgress, int maxDepth, int currentLevel)
      throws RepositoryException, JSONException {
    // Write this node's properties.
    if (!objectInProgress) {
      write.object();
    }
    writeNodeContentsToWriter(write, node);

    if (maxDepth == -1 || currentLevel < maxDepth) {
      // Write all the child nodes.
      NodeIterator iterator = node.getNodes();
      while (iterator.hasNext()) {
        Node childNode = iterator.nextNode();
        write.key(childNode.getName());
        writeNodeTreeToWriter(write, childNode, false, maxDepth, currentLevel + 1);
      }
    }

    if (!objectInProgress) {
      write.endObject();
    }
  }
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {

    try {
      final ResourceResolver resolver = request.getResourceResolver();
      final String vanityPath = request.getParameter("vanityPath");
      final String pagePath = request.getParameter("pagePath");
      log.debug(
          "vanity path parameter passed is {}; page path parameter passed is {}",
          vanityPath,
          pagePath);

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

      JSONWriter jsonWriter = new JSONWriter(response.getWriter());
      jsonWriter.array();

      if (StringUtils.isNotBlank(vanityPath)) {
        String xpath =
            "//element(*)[" + NameConstants.PN_SLING_VANITY_PATH + "='" + vanityPath + "']";
        @SuppressWarnings("deprecation")
        Iterator<Resource> resources = resolver.findResources(xpath, Query.XPATH);
        while (resources.hasNext()) {
          Resource resource = resources.next();
          String path = resource.getPath();
          if (path.startsWith("/content") && !path.equals(pagePath)) {
            jsonWriter.value(path);
          }
        }
      }
      jsonWriter.endArray();
    } catch (JSONException e) {
      throw new ServletException("Unable to generate JSON result", e);
    }
  }