public static void extractTranslation(final JSONWriter writer, final Resource translationResource)
      throws JSONException, IOException {

    final Iterable<Resource> translations = translationResource.getChildren();
    final ValueMap props = translationResource.adaptTo(ValueMap.class);
    String languageLabel = (String) props.get("language");
    if (null == languageLabel) {
      languageLabel = (String) props.get("mtlanguage");
      if (null == languageLabel) {
        return;
      }
    }
    writer.key(ContentTypeDefinitions.LABEL_TRANSLATION);
    writer.object();
    writer.key("mtlanguage");
    if (languageLabel.equals("nb")) {
      // SPECIAL CASE FOR LEGACY EXPORTER ONLY:
      // the label for norwegian changed between 6.0 and 6.1
      // (i.e. this section must be removed for 6.1 exporter)
      languageLabel = "no";
    }

    writer.value(languageLabel);
    writer.key("jcr:created");
    writer.value(props.get("jcr:created", Long.class));
    writer.key("jcr:createdBy");
    writer.value(props.get("jcr:createdBy"));
    if (translations.iterator().hasNext()) {
      writer.key(ContentTypeDefinitions.LABEL_TRANSLATIONS);
      final JSONWriter translationObjects = writer.object();
      UGCExportHelper.extractTranslations(translationObjects, translations);
      writer.endObject();
    }
    writer.endObject();
  }
  public static void extractTally(
      final JSONWriter responseArray, final Resource rootNode, final String tallyType)
      throws JSONException, UnsupportedEncodingException {

    final Map<String, Map<Long, ResponseValue>> responses = getTallyResponses(rootNode);
    if (null != responses) {
      for (final String userIdentifier : responses.keySet()) {
        for (final Map.Entry<Long, ResponseValue> entry :
            responses.get(userIdentifier).entrySet()) {
          final JSONWriter voteObject = responseArray.object();
          final String response = entry.getValue().getResponseValue();
          voteObject.key("timestamp");
          voteObject.value(entry.getKey());
          voteObject.key("response");
          voteObject.value(URLEncoder.encode(response, "UTF-8"));
          voteObject.key("userIdentifier");
          voteObject.value(URLEncoder.encode(userIdentifier, "UTF-8"));
          if (tallyType != null) {
            // for the purposes of this export, tallyType is fixed
            voteObject.key("tallyType");
            voteObject.value(tallyType);
          }
          voteObject.endObject();
        }
      }
    }
  }
Esempio n. 3
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. 4
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. 5
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();
  }
  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. 7
0
 private void writeResponse(
     JSONWriter write, ResponseWrapper responseWrapper, RequestInfo requestData)
     throws JSONException {
   try {
     String body = responseWrapper.getDataAsString();
     write.object();
     write.key("url");
     write.value(requestData.getUrl());
     write.key("success");
     write.value(true);
     write.key("body");
     write.value(body);
     write.key("status");
     write.value(responseWrapper.getResponseStatus());
     write.key("headers");
     write.object();
     Dictionary<String, String> headers = responseWrapper.getResponseHeaders();
     Enumeration<String> keys = headers.keys();
     while (keys.hasMoreElements()) {
       String k = keys.nextElement();
       write.key(k);
       write.value(headers.get(k));
     }
     write.endObject();
     write.endObject();
   } catch (UnsupportedEncodingException e) {
     writeFailedRequest(write, requestData);
   }
 }
Esempio n. 8
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();
  }
 public static void extractSubNode(JSONWriter object, final Resource node) throws JSONException {
   final ValueMap childVm = node.adaptTo(ValueMap.class);
   extractProperties(object, childVm);
   final Iterable<Resource> childNodes = node.getChildren();
   if (childNodes != null) {
     object.key(ContentTypeDefinitions.LABEL_SUBNODES);
     object.object();
     for (final Resource subNode : childNodes) {
       object.key(subNode.getName());
       JSONWriter subObject = object.object();
       extractSubNode(subObject, subNode);
       object.endObject();
     }
     object.endObject();
   }
 }
Esempio n. 10
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. 11
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();
    }
  }
 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. 13
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();
 }
Esempio n. 14
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();
 }
  public static void extractTranslations(
      final JSONWriter writer, final Iterable<Resource> translations)
      throws JSONException, IOException {
    for (final Resource translation : translations) {
      final JSONArray timestampFields = new JSONArray();
      final ValueMap vm = translation.adaptTo(ValueMap.class);
      if (!vm.containsKey("jcr:description")) {
        continue; // if there's no translation, we're done here
      }
      String languageLabel = translation.getName();
      if (languageLabel.equals("nb")) {
        // SPECIAL CASE FOR LEGACY EXPORTER ONLY:
        // the label for norwegian changed between 6.0 and 6.1
        // (i.e. this section must be removed for 6.1 exporter)
        languageLabel = "no";
      }
      writer.key(languageLabel);

      JSONWriter translationObject = writer.object();
      translationObject.key("jcr:description");
      translationObject.value(URLEncoder.encode((String) vm.get("jcr:description"), "UTF-8"));
      if (vm.containsKey("jcr:createdBy")) {
        translationObject.key("jcr:createdBy");
        translationObject.value(URLEncoder.encode((String) vm.get("jcr:createdBy"), "UTF-8"));
      }
      if (vm.containsKey("jcr:title")) {
        translationObject.key("jcr:title");
        translationObject.value(URLEncoder.encode((String) vm.get("jcr:title"), "UTF-8"));
      }
      if (vm.containsKey("postEdited")) {
        translationObject.key("postEdited");
        translationObject.value(vm.get("postEdited"));
      }
      if (vm.containsKey("translationDate")) {
        translationObject.key("translationDate");
        translationObject.value(((Calendar) vm.get("translationDate")).getTimeInMillis());
        timestampFields.put("translationDate");
      }
      if (vm.containsKey("jcr:created")) {
        translationObject.key("jcr:created");
        translationObject.value(((Calendar) vm.get("jcr:created")).getTimeInMillis());
        timestampFields.put("jcr:created");
      }
      if (timestampFields.length() > 0) {
        translationObject.key(ContentTypeDefinitions.LABEL_TIMESTAMP_FIELDS);
        translationObject.value(timestampFields);
      }
      translationObject.endObject();
    }
  }
  /**
   * 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();
  }
  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);
      }
    }
  }
 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();
 }
  /**
   * {@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;
 }
Esempio n. 21
0
  /**
   * Takes the original request and starts the batching.
   *
   * @param request
   * @param response
   * @throws IOException
   */
  protected void batchRequest(
      SlingHttpServletRequest request, SlingHttpServletResponse response, boolean allowModify)
      throws IOException {
    // Grab the JSON block out of it and convert it to RequestData objects we can use.
    String json = request.getParameter(REQUESTS_PARAMETER);
    List<RequestInfo> batchedRequests = new ArrayList<RequestInfo>();
    try {
      JSONArray arr = new JSONArray(json);
      for (int i = 0; i < arr.length(); i++) {
        JSONObject obj = arr.getJSONObject(i);
        RequestInfo r = new RequestInfo(obj);
        if (allowModify || r.isSafe()) {
          batchedRequests.add(r);
        }
      }
    } catch (JSONException e) {
      response.sendError(
          HttpServletResponse.SC_BAD_REQUEST,
          "Failed to parse the " + REQUESTS_PARAMETER + " parameter");
      LOGGER.warn("Failed to parse the " + REQUESTS_PARAMETER + " parameter");
      return;
    }

    // Loop over the requests and handle each one.
    try {
      StringWriter sw = new StringWriter();
      JSONWriter write = new JSONWriter(sw);
      write.object();
      write.key("results");
      write.array();

      for (RequestInfo r : batchedRequests) {
        doRequest(request, response, r, write);
      }
      write.endArray();
      write.endObject();
      response.setContentType("application/json");
      response.setCharacterEncoding("UTF-8");
      response.getWriter().write(sw.getBuffer().toString());
    } catch (JSONException e) {
      LOGGER.warn("Failed to create a JSON response");
      response.sendError(
          HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to write JSON response");
    }
  }
 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();
 }
Esempio n. 23
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();
   }
 }
Esempio n. 24
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();
  }
  /**
   * 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();
    }
  }
Esempio n. 26
0
 public void write(JSONWriter writer) throws JSONException {
   writer.object();
   writer.key("xtype").value("tbseparator");
   writer.endObject();
 }
Esempio n. 27
0
 public void write(JSONWriter writer) throws JSONException {
   writer.object();
   writer.key("xtype").value("tbtext");
   writer.key("text").value(text);
   writer.endObject();
 }
  /**
   * {@inheritDoc}
   *
   * @see
   *     org.apache.sling.api.servlets.SlingAllMethodsServlet#doPost(org.apache.sling.api.SlingHttpServletRequest,
   *     org.apache.sling.api.SlingHttpServletResponse)
   */
  @Override
  protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {

    // Check if the current user is logged in.
    if (request.getRemoteUser().equals("anonymous")) {
      response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Anonymous user cannot crop images.");
      return;
    }

    RequestParameter imgParam = request.getRequestParameter("img");
    RequestParameter saveParam = request.getRequestParameter("save");
    RequestParameter xParam = request.getRequestParameter("x");
    RequestParameter yParam = request.getRequestParameter("y");
    RequestParameter widthParam = request.getRequestParameter("width");
    RequestParameter heightParam = request.getRequestParameter("height");
    RequestParameter dimensionsParam = request.getRequestParameter("dimensions");

    if (imgParam == null
        || saveParam == null
        || xParam == null
        || yParam == null
        || widthParam == null
        || heightParam == null
        || dimensionsParam == null) {
      response.sendError(
          HttpServletResponse.SC_BAD_REQUEST,
          "The following parameters are required: img, save, x, y, width, height, dimensions");
      return;
    }

    try {
      // Grab the session
      ResourceResolver resourceResolver = request.getResourceResolver();
      Session session = resourceResolver.adaptTo(Session.class);

      String img = imgParam.getString();
      String save = saveParam.getString();
      int x = Integer.parseInt(xParam.getString());
      int y = Integer.parseInt(yParam.getString());
      int width = Integer.parseInt(widthParam.getString());
      int height = Integer.parseInt(heightParam.getString());
      String[] dimensionsList = StringUtils.split(dimensionsParam.getString(), ';');
      List<Dimension> dimensions = new ArrayList<Dimension>();
      for (String s : dimensionsList) {
        Dimension d = new Dimension();
        String[] size = StringUtils.split(s, 'x');
        int diWidth = Integer.parseInt(size[0]);
        int diHeight = Integer.parseInt(size[1]);

        diWidth = checkIntBiggerThanZero(diWidth, 0);
        diHeight = checkIntBiggerThanZero(diHeight, 0);

        d.setSize(diWidth, diHeight);
        dimensions.add(d);
      }

      x = checkIntBiggerThanZero(x, 0);
      y = checkIntBiggerThanZero(y, 0);
      width = checkIntBiggerThanZero(width, 0);
      height = checkIntBiggerThanZero(height, 0);

      // Make sure the save path is correct.
      save = PathUtils.normalizePath(save) + "/";

      String[] crop = CropItProcessor.crop(session, x, y, width, height, dimensions, img, save);

      JSONWriter output = new JSONWriter(response.getWriter());
      output.object();
      output.key("files");
      output.array();
      for (String url : crop) {
        output.value(url);
      }
      output.endArray();
      output.endObject();

    } catch (ArrayIndexOutOfBoundsException e) {
      response.sendError(
          HttpServletResponse.SC_BAD_REQUEST,
          "The dimensions have to be specified in a widthxheight;widthxheight fashion.");
      return;
    } catch (NumberFormatException e) {
      response.sendError(
          HttpServletResponse.SC_BAD_REQUEST,
          "The following parameters have to be integers: x, y, width, height. (Dimensions has to be of the form widthxheight;widthxheight");
      return;
    } catch (ImageException e) {
      // Something went wrong..
      logger.warn("ImageException e: " + e.getMessage());
      response.sendError(e.getCode(), e.getMessage());
    } catch (JSONException e) {
      response.sendError(500, "Unable to output JSON.");
    }
  }
Esempio n. 29
0
  protected void dump(Node node, JSONWriter w, int currentRecursionLevel, int maxRecursionLevels)
      throws RepositoryException, JSONException {

    // check for array
    boolean isArray = true;
    NodeIterator children = node.getNodes();
    if (!children.hasNext()) { // has no children
      isArray = false;
    }
    while (children.hasNext()) {
      final Node n = children.nextNode();
      if (!n.getName().matches("\\d+")) {
        isArray = false;
        break;
      }
    }
    PropertyIterator props = node.getProperties();
    if (isArray && props.hasNext()) {
      // array should not have properties
      while (props.hasNext()) {
        Property prop = props.nextProperty();
        // ignore any jcr:* properties
        if (!prop.getName().matches("jcr:.+")) {
          isArray = false;
          break;
        }
      }
    }

    if (isArray) {
      w.array();
      // the child nodes
      if (recursionLevelActive(currentRecursionLevel, maxRecursionLevels)) {
        children = node.getNodes();
        while (children.hasNext()) {
          final Node n = children.nextNode();
          dump(n, w, currentRecursionLevel + 1, maxRecursionLevels);
        }
      }
      w.endArray();
    } else {
      w.object();
      props = node.getProperties();
      // the node's actual properties
      while (props.hasNext()) {
        Property prop = props.nextProperty();
        if (prop.getName().matches("jcr:.+")) { // ignore any jcr:* properties
          continue;
        }
        if (prop.getName().matches("cq:.+")) { // ignore any cq:* properties
          continue;
        }
        writeProperty(w, prop);
      }

      // the child nodes
      if (recursionLevelActive(currentRecursionLevel, maxRecursionLevels)) {
        children = node.getNodes();
        while (children.hasNext()) {
          final Node n = children.nextNode();
          dumpSingleNode(n, w, currentRecursionLevel, maxRecursionLevels);
        }
      }
      w.endObject();
    }
  }
    /**
     * Write the given resource list as JSON array to the output.
     *
     * @param out writer
     * @param list list of resources
     * @param orderable whether the list of resources is orderable.
     * @param numChildrenCheck the maximum number of children to check whether it matches the
     *     predicate.
     * @throws JSONException if a JSON error occurs
     */
    private void write(JSONWriter out, List<Resource> list, boolean orderable, int numChildrenCheck)
        throws JSONException {
      out.array();
      List<Resource> oList = orderable ? list : orderList(list);
      for (Resource resource : oList) {
        out.object();

        LabeledResource lr = resource.adaptTo(LabeledResource.class);
        String name = Text.getName(resource.getPath());
        out.key("name").value(name);
        String text;

        if (lr == null) {
          text = name;
        } else {
          text = (lr.getTitle() == null) ? name : lr.getTitle();
          if (lr.getDescription() != null) {
            out.key("description").value(lr.getDescription());
          }
        }
        if (text != null) {
          text = text.replaceAll("<", "&lt;");
        }
        out.key("text").value(text);

        out.key("type").value(resource.getResourceType());
        int children = countChildren(resource, numChildrenCheck);
        boolean hasChildren = children > 0;

        // write CSS class information according to presence of children.
        // this should probably be done via the 'type' attribute above in
        // the widget itself
        out.key("cls").value(hasChildren ? "folder" : "file");

        if (!hasChildren) {
          out.key("leaf").value(true);
        } else {
          out.key("sub").value(children);
        }

        try {
          Node node = resource.adaptTo(Node.class);
          String dpsType = DPSUtil.getDPSResourceType(node);
          out.key(DPSConstants.PN_DPS_RESOURCE_TYPE).value(dpsType);
          if (dpsType != null) {
            out.key("uiProvider").value("publishingNodeUI");
            out.key("dpsType").value(dpsType);
            DPSArticle article = resource.adaptTo(DPSArticle.class);
            if (article != null) {
              out.key("ad").value(article.isAdvertisement());
            }
          }
        } catch (RepositoryException ex) {
          log.error("could not query child for DPSResourceType", ex);
        }

        // if a user wants to delete an item from the tree, we must check if it is replicated
        // thus, adding replication state information to the JSON result
        try {
          writeReplicationState(out, resource);
        } catch (Exception e) {
          throw new JSONException("Unable to append replication state", e);
        }

        out.endObject();
      }
      out.endArray();
    }