Esempio n. 1
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. 2
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. 3
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();
  }
Esempio n. 4
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();
    }
  }
  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. 7
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. 8
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. 9
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 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. 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();
    }
  }
  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 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. 14
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());
    }
  }
  public static void writeNodeContentsToWriter(JSONWriter write, Node node)
      throws RepositoryException, JSONException {
    // Since removal of bigstore we add in jcr:path and jcr:name
    write.key("jcr:path");
    write.value(PathUtils.translateAuthorizablePath(node.getPath()));
    write.key("jcr:name");
    write.value(node.getName());

    PropertyIterator properties = node.getProperties();
    while (properties.hasNext()) {
      Property prop = properties.nextProperty();
      String name = prop.getName();
      write.key(name);
      PropertyDefinition propertyDefinition = prop.getDefinition();
      int propertyType = prop.getType();
      if (PropertyType.BINARY == propertyType) {
        if (propertyDefinition.isMultiple()) {
          write.array();
          for (long l : prop.getLengths()) {
            write.value("binary-length:" + String.valueOf(l));
          }
          write.endArray();
        } else {
          write.value("binary-length:" + String.valueOf(prop.getLength()));
        }
      } else {
        if (propertyDefinition.isMultiple()) {
          Value[] values = prop.getValues();
          write.array();
          for (Value value : values) {
            Object ovalue = stringValue(value);
            if (isUserPath(name, ovalue)) {
              write.value(PathUtils.translateAuthorizablePath(ovalue));
            } else {
              write.value(ovalue);
            }
          }
          write.endArray();
        } else {
          Object value = stringValue(prop.getValue());
          if (isUserPath(name, value)) {
            write.value(PathUtils.translateAuthorizablePath(value));
          } else {
            write.value(value);
          }
        }
      }
    }
  }
 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);
 }
  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();
    }
  }
  /**
   * {@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();
  }
Esempio n. 19
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. 21
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. 22
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 {
      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);
    }
  }
Esempio n. 24
0
 public void write(JSONWriter writer) throws JSONException {
   writer.value(this);
 }
  /**
   * {@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.");
    }
  }
  public static void extractTopic(
      final JSONWriter writer,
      final Post post,
      final ResourceResolver resolver,
      final String resourceType,
      final String childResourceType,
      final Writer responseWriter)
      throws JSONException, IOException {

    final ValueMap vm = post.getProperties();
    final JSONArray timestampFields = new JSONArray();
    for (final Map.Entry<String, Object> prop : vm.entrySet()) {
      final Object value = prop.getValue();
      if (value instanceof String[]) {
        final JSONArray list = new JSONArray();
        for (String v : (String[]) value) {
          list.put(v);
        }
        writer.key(prop.getKey());
        writer.value(list);
      } else if (value instanceof GregorianCalendar) {
        timestampFields.put(prop.getKey());
        writer.key(prop.getKey());
        writer.value(((Calendar) value).getTimeInMillis());
      } else if (prop.getKey().equals("sling:resourceType")) {
        writer.key(prop.getKey());
        writer.value(resourceType);
      } else if (prop.getKey().equals("sentiment")) {
        writer.key(prop.getKey());
        // 1 = 1, 2 = 3, 3 = 5, 4 = 8, 5 = 10
        short shortValue = Short.parseShort(value.toString());
        switch (shortValue) {
          case 1:
            writer.value(1);
            break;
          case 2:
            writer.value(3);
            break;
          case 3:
            writer.value(5);
            break;
          case 4:
            writer.value(8);
            break;
          case 5:
            writer.value(10);
            break;
          default:
            writer.value(value);
        }
      } else {
        writer.key(prop.getKey());
        try {
          writer.value(URLEncoder.encode(prop.getValue().toString(), "UTF-8"));
        } catch (final UnsupportedEncodingException e) {
          throw new JSONException(
              "Unsupported encoding (UTF-8) for resource at " + post.getPath(), e);
        }
      }
    }
    if (timestampFields.length() > 0) {
      writer.key(ContentTypeDefinitions.LABEL_TIMESTAMP_FIELDS);
      writer.value(timestampFields);
    }
    final Resource thisResource = resolver.getResource(post.getPath());
    final Resource attachments = thisResource.getChild("attachments");
    if (attachments != null) {
      writer.key(ContentTypeDefinitions.LABEL_ATTACHMENTS);
      final JSONWriter attachmentsWriter = writer.array();
      for (final Resource attachment : attachments.getChildren()) {
        UGCExportHelper.extractAttachment(responseWriter, attachmentsWriter.object(), attachment);
        attachmentsWriter.endObject();
      }
      writer.endArray();
    }
    final Iterable<Resource> children = thisResource.getChildren();
    for (final Resource child : children) {
      if (child.isResourceType("social/tally/components/hbs/voting")
          || child.isResourceType("social/tally/components/voting")) {
        writer.key(ContentTypeDefinitions.LABEL_TALLY);
        final JSONWriter voteObjects = writer.array();
        UGCExportHelper.extractTally(voteObjects, child, "Voting");
        writer.endArray();
      } else if (child.getName().equals("translation")) {
        extractTranslation(writer, child);
      }
    }
    final Iterator<Post> posts = post.getPosts();
    if (posts.hasNext()) {
      writer.key(ContentTypeDefinitions.LABEL_REPLIES);
      final JSONWriter replyWriter = writer.object();
      while (posts.hasNext()) {
        Post childPost = posts.next();
        replyWriter.key(childPost.getId());
        extractTopic(
            replyWriter.object(),
            childPost,
            resolver,
            childResourceType,
            childResourceType,
            responseWriter);
        replyWriter.endObject();
      }
      writer.endObject();
    }
  }
 public static void extractJournalEntry(
     final JSONWriter entryObject, final JournalEntry entry, final Writer rawWriter)
     throws JSONException, IOException {
   final Resource thisResource = entry.getTextComment().getResource();
   final ValueMap vm = thisResource.adaptTo(ValueMap.class);
   final JSONArray timestampFields = new JSONArray();
   // make sure we only migrate the fields we want
   final Map<String, Boolean> fieldsToMigrate = new HashMap<String, Boolean>();
   fieldsToMigrate.put("userIdentifier", true);
   fieldsToMigrate.put("authorizableId", true);
   fieldsToMigrate.put("published", true);
   fieldsToMigrate.put("jcr:description", true);
   fieldsToMigrate.put("jcr:title", true);
   fieldsToMigrate.put("negative", true);
   fieldsToMigrate.put("positive", true);
   fieldsToMigrate.put("sentiment", true);
   for (final Map.Entry<String, Object> prop : vm.entrySet()) {
     if (!fieldsToMigrate.containsKey(prop.getKey())) {
       continue;
     }
     final Object value = prop.getValue();
     if (prop.getKey().equals("published") && value instanceof GregorianCalendar) {
       timestampFields.put("added");
       entryObject.key("added");
       entryObject.value(((Calendar) value).getTimeInMillis());
     } else {
       entryObject.key(prop.getKey());
       try {
         entryObject.value(URLEncoder.encode(prop.getValue().toString(), "UTF-8"));
       } catch (final UnsupportedEncodingException e) {
         throw new JSONException(
             "Unsupported encoding (UTF-8) for resource at " + thisResource.getPath(), e);
       }
     }
   }
   // resource type has changed, so ignore the current one and force the new one
   entryObject.key("sling:resourceType");
   entryObject.value("social/journal/components/hbs/entry_topic");
   if (timestampFields.length() > 0) {
     entryObject.key(ContentTypeDefinitions.LABEL_TIMESTAMP_FIELDS);
     entryObject.value(timestampFields);
   }
   final Resource translationResource = thisResource.getChild("translation");
   if (null != translationResource) {
     extractTranslation(entryObject, translationResource);
   }
   if (entry.hasAttachments()) {
     entryObject.key(ContentTypeDefinitions.LABEL_ATTACHMENTS);
     JSONWriter attachmentsArray = entryObject.array();
     List<Resource> attachmentList = entry.getAttachments();
     for (final Resource attachment : attachmentList) {
       extractAttachment(rawWriter, attachmentsArray.object(), attachment);
       attachmentsArray.endObject();
     }
     entryObject.endArray();
   }
   if (entry.hasComments()) {
     final Iterator<Comment> posts = entry.getComments();
     entryObject.key(ContentTypeDefinitions.LABEL_REPLIES);
     final JSONWriter replyWriter = entryObject.object();
     while (posts.hasNext()) {
       final Comment childPost = posts.next();
       replyWriter.key(childPost.getId());
       extractComment(
           replyWriter.object(), childPost, entry.getResource().getResourceResolver(), rawWriter);
       replyWriter.endObject();
     }
     entryObject.endObject();
   }
 }
 public static void extractProperties(
     final JSONWriter object,
     final Map<String, Object> properties,
     final Map<String, String> renamedProperties,
     final String resourceType)
     throws JSONException {
   final JSONArray timestampFields = new JSONArray();
   boolean setResourceType = false;
   for (Map.Entry<String, Object> prop : properties.entrySet()) {
     Object value = prop.getValue();
     String key;
     if (null != renamedProperties && renamedProperties.containsKey(prop.getKey())) {
       key = renamedProperties.get(prop.getKey());
       if (null == key) {
         continue; // we're excluding this property from the export
       }
     } else {
       key = prop.getKey();
     }
     if (null != resourceType && key.equals(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY)) {
       value = resourceType;
       setResourceType = true;
     }
     if (value instanceof String[]) {
       final JSONArray list = new JSONArray();
       for (String v : (String[]) value) {
         try {
           list.put(URLEncoder.encode(v, "UTF-8"));
         } catch (final UnsupportedEncodingException e) {
           throw new JSONException(
               "String value cannot be encoded as UTF-8 for JSON transmission", e);
         }
       }
       object.key(key);
       object.value(list);
     } else if (value instanceof GregorianCalendar) {
       timestampFields.put(key);
       object.key(key);
       object.value(((Calendar) value).getTimeInMillis());
     } else if (value instanceof InputStream) {
       object.key(ContentTypeDefinitions.LABEL_ENCODED_DATA_FIELDNAME);
       object.value(key);
       object.key(ContentTypeDefinitions.LABEL_ENCODED_DATA);
       try {
         final InputStream data = (InputStream) value;
         byte[] byteData = new byte[DATA_ENCODING_CHUNK_SIZE];
         int read = 0;
         final StringBuilder stringBuilder = new StringBuilder();
         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);
             stringBuilder.append(new String(encodedBytes));
           } else if (read == DATA_ENCODING_CHUNK_SIZE) {
             byte[] encodedBytes = Base64.encodeBase64(byteData);
             stringBuilder.append(new String(encodedBytes));
           }
         }
         object.value(stringBuilder.toString());
       } catch (IOException e) {
         object.value(
             ""); // if we error out on the first read attempt, we need a placeholder value still
         object.key(ContentTypeDefinitions.LABEL_ERROR);
         object.value("IOException while getting attachment: " + e.getMessage());
       }
     } else {
       object.key(key);
       try {
         object.value(URLEncoder.encode(value.toString(), "UTF-8"));
       } catch (final UnsupportedEncodingException e) {
         throw new JSONException(
             "String value cannot be encoded as UTF-8 for JSON transmission", e);
       }
     }
   }
   if (null != resourceType
       && !setResourceType) { // make sure this gets included if it's been specified
     object.key(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY);
     object.value(resourceType);
   }
   if (timestampFields.length() > 0) {
     object.key(ContentTypeDefinitions.LABEL_TIMESTAMP_FIELDS);
     object.value(timestampFields);
   }
 }