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();
    }
  }
  @Override
  protected final void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {

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

    final JSONArray jsonArray = new JSONArray();
    try {

      for (Map.Entry<String, TagDataConverter> entry : this.tagDataConverters.entrySet()) {
        final JSONObject jsonObject = new JSONObject();

        jsonObject.put("label", entry.getValue().getLabel());
        jsonObject.put("value", entry.getKey());

        jsonArray.put(jsonObject);
      }

      response.getWriter().print(jsonArray.toString());

    } catch (JSONException e) {
      response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
  }
示例#3
0
文件: CDL.java 项目: JEBailey/sling
 /**
  * Produce a JSONArray of JSONObjects from a comma delimited text string using a supplied
  * JSONArray as the source of element names.
  *
  * @param names A JSONArray of strings.
  * @param x A JSONTokener of the source text.
  * @return A JSONArray of JSONObjects.
  * @throws JSONException
  */
 public static JSONArray toJSONArray(JSONArray names, JSONTokener x) throws JSONException {
   if (names == null || names.length() == 0) {
     return null;
   }
   JSONArray ja = new JSONArray();
   for (; ; ) {
     JSONObject jo = rowToJSONObject(names, x);
     if (jo == null) {
       break;
     }
     ja.put(jo);
   }
   if (ja.length() == 0) {
     return null;
   }
   return ja;
 }
示例#4
0
文件: CDL.java 项目: JEBailey/sling
 /**
  * Produce a JSONArray of strings from a row of comma delimited values.
  *
  * @param x A JSONTokener of the source text.
  * @return A JSONArray of strings.
  * @throws JSONException
  */
 public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException {
   JSONArray ja = new JSONArray();
   for (; ; ) {
     String value = getValue(x);
     if (value == null) {
       return null;
     }
     ja.put(value);
     for (; ; ) {
       char c = x.next();
       if (c == ',') {
         break;
       }
       if (c != ' ') {
         if (c == '\n' || c == '\r' || c == 0) {
           return ja;
         }
         throw x.syntaxError("Bad character '" + c + "' (" + (int) c + ").");
       }
     }
   }
 }
 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);
   }
 }
 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 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();
    }
  }