Example usage for org.json.simple JSONArray toJSONString

List of usage examples for org.json.simple JSONArray toJSONString

Introduction

In this page you can find the example usage for org.json.simple JSONArray toJSONString.

Prototype

public String toJSONString() 

Source Link

Usage

From source file:org.exoplatform.social.client.core.model.ActivityImplTest.java

@Test
public void shouldJsonActivityStreamArrayParser1() throws Exception {

    String jsonActivity1 = "{" + "\"activities\":[" + "{" + "\"id\":\"1a2b3c4d5e6f7g8h9j\","
            + "\"title\":\"Hello World!!!\"," + "\"appId\":\"\"," + "\"type\":\"DEFAULT_ACTIVITY\","
            + "\"postedTime\":123456789," + "\"createdAt\":\"Fri Jun 17 06:42:26 +0000 2011\","
            + "\"priority\":0.5," + "\"templateParams\":{" + "}," + "\"titleId\":\"\","
            + "\"identityId\":\"123456789abcdefghi\"," + "\"liked\":true," + "\"likedByIdentities\":[" + "{"
            + "\"id\":\"123456313efghi\"," + "\"providerId\":\"organization\"," + "\"remoteId\":\"demo\","
            + "\"profile\":{" + "\"fullName\":\"Demo GTN\","
            + "\"avatarUrl\":\"http://localhost:8080/profile/u/demo/avatar.jpg?u=12345\"" + "}" + "}" + "],"
            + "\"totalNumberOfLikes\":20," + "\"posterIdentity\":{" + "\"id\":\"123456313efghi\","
            + "\"providerId\":\"organization\"," + "\"remoteId\":\"demo\"," + "\"profile\":{"
            + "\"fullName\":\"Demo GTN\","
            + "\"avatarUrl\":\"http://localhost:8080/profile/u/demo/avatar.jpg?u=12345\"" + "}" + "},"
            + "\"comments\":[" + "{" + "}" + "]," + "\"totalNumberOfComments\":1234," + "\"activityStream\":{"
            + "\"type\":\"user\"," + "\"prettyId\":\"root\","
            + "\"faviconUrl\":\"http://demo3.exoplatform.org/favicons/exo-default.jpg\","
            + "\"title\":\"Activity Stream of Root Root\","
            + "\"permaLink\":\"http://localhost:8080/profile/root\"" + "}" + "}," + "{"
            + "\"id\":\"1a210983123f7g8h9j\"," + "\"title\":\"Hello World 1!!!\"," + "\"appId\":\"\","
            + "\"type\":\"DEFAULT_ACTIVITY\"," + "\"postedTime\":123456789,"
            + "\"createdAt\":\"Fri Jun 19 06:42:26 +0000 2011\"," + "\"priority\":0.5," + "\"templateParams\":{"
            + "}," + "\"titleId\":\"\"," + "\"identityId\":\"123456789abcdefghi\"," + "\"liked\":true,"
            + "\"likedByIdentities\":[" + "{" + "\"id\":\"123456313efghi\","
            + "\"providerId\":\"organization\"," + "\"remoteId\":\"demo\"," + "\"profile\":{"
            + "\"fullName\":\"Demo GTN\","
            + "\"avatarUrl\":\"http://localhost:8080/profile/u/demo/avatar.jpg?u=12345\"" + "}" + "}" + "],"
            + "\"totalNumberOfLikes\":20," + "\"posterIdentity\":{" + "\"id\":\"123456313efghi\","
            + "\"providerId\":\"organization\"," + "\"remoteId\":\"demo\"," + "\"profile\":{"
            + "\"fullName\":\"Demo GTN\","
            + "\"avatarUrl\":\"http://localhost:8080/profile/u/demo/avatar.jpg?u=12345\"" + "}" + "},"
            + "\"comments\":[" + "{" + "}" + "]," + "\"totalNumberOfComments\":1234," + "\"activityStream\":{"
            + "\"type\":\"user\"," + "\"fullName\":\"Root Root\"," + "\"prettyId\":\"root\","
            + "\"faviconUrl\":\"http://demo3.exoplatform.org/favicons/exo-default.jpg\","
            + "\"title\":\"Activity Stream of Root Root\","
            + "\"permaLink\":\"http://localhost:8080/profile/root\"" + "}" + "}" + "]" + "}";

    JSONObject jsonObject = (JSONObject) JSONValue.parse(jsonActivity1);
    JSONArray jsonArray = (JSONArray) jsonObject.get("activities");
    List<RestActivity> activities = SocialJSONDecodingSupport.JSONArrayObjectParser(RestActivity.class,
            jsonArray.toJSONString());
    assertEquals(activities.size(), 2);/*  w w w . j  ava  2  s .c o m*/

    for (RestActivity e : activities) {
        assertThat("PosterIdentity must not be null.", e.getPosterIdentity(), notNullValue());
        assertThat("ActivityStream must not be null.", e.getActivityStream(), notNullValue());
        assertThat("LikedByIdentity must not be null.", e.getAvailableLikes(), notNullValue());

        RestIdentity identity = e.getAvailableLikes().get(0);
        assertThat("RestProfile must not be null.", identity.getProfile(), notNullValue());

        RestProfile profile = identity.getProfile();
        assertThat(profile.getFullName(), equalTo("Demo GTN"));
        assertThat(profile.getAvatarUrl(), equalTo("http://localhost:8080/profile/u/demo/avatar.jpg?u=12345"));
    }
}

From source file:org.exoplatform.social.client.core.service.ActivitiesRealtimeListAccessV1Alpha1.java

/**
 * Gets the list activities from response.
 * /* w  w w  .j  a v a  2 s  .c om*/
 * @param response
 * @return
 */
private List<RestActivity> getListActivitiesFromResponse(HttpResponse response) {
    try {
        JSONObject jsonObject = (JSONObject) JSONValue.parse(getContent(response));
        JSONArray jsonArray = (JSONArray) jsonObject.get("activities");
        List<RestActivity> activities = SocialJSONDecodingSupport.JSONArrayObjectParser(RestActivity.class,
                jsonArray.toJSONString());
        List<RestActivity> copyRestActivities = new ArrayList(activities);
        Collections.copy(copyRestActivities, activities);
        return copyRestActivities;
    } catch (Exception e) {
        throw new ServiceException(ActivityService.class, "invalid response", null);
    }
}

From source file:org.exoplatform.social.client.core.util.SocialJSONDecodingSupportTest.java

@Test
public void testJsonArrayParser() throws Exception {
    String jsonActivity = "["
            + "{\"numberOfComments\":1,\"identityId\":\"d5039b437f0001010011fd153a4fcbd8\",\"liked\":true,},"
            + "{\"numberOfComments\":2,\"identityId\":\"d5039b437f0001010011fd153a4fcba8\",\"liked\":false,}"
            + "]";
    RestActivity model1 = SocialJSONDecodingSupport.JSONArrayObjectParser(RestActivity.class, jsonActivity)
            .get(0);//from w w w.ja  va 2  s.  c  o  m
    RestActivity model2 = SocialJSONDecodingSupport.JSONArrayObjectParser(RestActivity.class, jsonActivity)
            .get(1);
    assertEquals(model1.getIdentityId(), "d5039b437f0001010011fd153a4fcbd8");
    assertEquals(model2.getIdentityId(), "d5039b437f0001010011fd153a4fcba8");

    String jsonActivity1 = "{\"activities\":[" + "{"
            + "\"appId\":null,\"identityId\":\"f845f6ed7f000101003ed4d98a09beb3\","
            + "\"totalNumberOfComments\":0,\"liked\":false,\"templateParams\":{},"
            + "\"postedTime\":1309839511830,\"type\":\"DEFAULT_ACTIVITY\","
            + "\"posterIdentity\":null,\"activityStream\":null,"
            + "\"id\":\"f884d11a7f000101000230e5c0e8a602\"," + "\"title\":\"hello\",\"priority\":null,"
            + "\"createdAt\":\"Tue Jul 5 11:18:31 +0700 2011\","
            + "\"likedByIdentities\":null,\"titleId\":null,\"comments\":null}" + "]}";

    JSONObject jsonObject = (JSONObject) JSONValue.parse(jsonActivity1);
    JSONArray jsonArray = (JSONArray) jsonObject.get("activities");
    RestActivity model3 = SocialJSONDecodingSupport
            .JSONArrayObjectParser(RestActivity.class, jsonArray.toJSONString()).get(0);
    assertEquals(model3.getIdentityId(), "f845f6ed7f000101003ed4d98a09beb3");
}

From source file:org.fao.fenix.wds.core.utils.Wrapper.java

@SuppressWarnings("unchecked")
public static StringBuilder wrapAsJSON(List<List<String>> table) throws WDSException {
    try {/*from  w  ww .ja v  a  2  s .c  o  m*/
        JSONArray json = new JSONArray();
        for (List<String> l : table) {
            JSONArray row = new JSONArray();
            row.addAll(l);
            json.add(row);
        }
        return new StringBuilder(json.toJSONString());
    } catch (Exception e) {
        throw new WDSException(e.getMessage());
    }
}

From source file:org.iipg.hurricane.jmx.client.JMXRequestHandler.java

/**
 * Get an HTTP Request for requesting multiples requests at once
 *
 * @param pRequests requests to put into a HTTP request
 * @return HTTP request to send to the server
 *//*  w ww  .j ava 2  s .c o  m*/
public <T extends JMXRequest> HttpUriRequest getHttpRequest(List<T> pRequests,
        Map<JMXQueryParameter, String> pProcessingOptions)
        throws UnsupportedEncodingException, URISyntaxException {
    JSONArray bulkRequest = new JSONArray();
    String queryParams = prepareQueryParameters(pProcessingOptions);
    HttpPost postReq = new HttpPost(createRequestURI(serverUrl.getPath(), queryParams));
    for (T request : pRequests) {
        JSONObject requestContent = getJsonRequestContent(request);
        bulkRequest.add(requestContent);
    }
    postReq.setEntity(new StringEntity(bulkRequest.toJSONString(), "utf-8"));
    return postReq;
}

From source file:org.javascool.polyfilewriter.Gateway.java

/**
 * List files into a directory.//from  w  w w .  j a  v  a 2 s .  co  m
 *
 * @param location The directory to list
 * @return A string with a structure as this
 *         [
 *         {"name":"toto.java","isFile":true,"isHidden":false,"path":"/home/user/toto.java"},
 *         ]
 */
public String listDirectory(final String location) throws Exception {
    assertSafeUsage();
    try {
        final File[] list = AccessController.doPrivileged(new PrivilegedAction<File[]>() {
            public File[] run() {
                return new File(location).listFiles();
            }
        });
        final JSONArray files = new JSONArray();
        for (int i = 0; i < list.length; i++) {
            final int c = i;
            files.add(AccessController.doPrivileged(new PrivilegedAction<JSONObject>() {
                public JSONObject run() {
                    JSONObject obj = new JSONObject();
                    obj.put("name", list[c].getName());
                    obj.put("path", list[c].getAbsolutePath());
                    obj.put("isHidden", list[c].isHidden());
                    obj.put("isFile", list[c].isFile());
                    return obj;
                }
            }));
        }
        return files.toJSONString();
    } catch (Exception e) {
        popException(e);
        throw e;
    }
}

From source file:org.jitsi.jicofo.log.EventFactory.java

/**
 * Parses <tt>statsStr</tt> as JSON in the format used by Jitsi Meet, and
 * returns an Object[][] containing the values to be used in an
 * <tt>Event</tt> for the given JSON.
 * @param conferenceId the value to use for the conference_id field.
 * @param endpointId the value to use for the endpoint_id field.
 * @param statsStr the PeerConnection JSON string.
 * @return an Object[][] containing the values to be used in an
 * <tt>Event</tt> for the given JSON.
 * @throws Exception if parsing fails for any reason.
 */// w  w  w  .j a v  a  2  s  . c o m
private static Object[] parsePeerConnectionStats(String conferenceId, String endpointId, String statsStr)
        throws Exception {
    // An example JSON in the format that we expect:
    // {
    //   "timestamps": [1, 2, 3],
    //   "stats": {
    //      "group1": {
    //          "type": "some string",
    //          "stat1": ["some", "values", ""]
    //          "stat2": ["some", "more", "values"]
    //      },
    //      "bweforvideo": {
    //          "type":"VideoBwe",
    //          "googActualEncBitrate": ["12","34","56"],
    //          "googAvailableSendBandwidth": ["78", "90", "12"]
    //      }
    //   }
    // }

    // time: 1
    // conference_id: blabla
    // endpoint_id: blabla
    // value: [
    //     ["group1", "some string", {"stat1": "some", "stat2": "some"}],
    //     ["bweforvideo", "VideoBwe", {"googActualEncBitrate": "12", "googAvailableSendBandwidth": "78"}]
    // ]

    JSONParser parser = new JSONParser();
    JSONObject jsonObject = (JSONObject) parser.parse(statsStr);

    List<Object[]> values = new LinkedList<Object[]>();
    JSONArray timestamps = (JSONArray) jsonObject.get("timestamps");
    JSONObject stats = (JSONObject) jsonObject.get("stats");

    for (int i = 0; i < timestamps.size(); i++) {
        long timestamp = (Long) timestamps.get(i);

        JSONArray value = new JSONArray();
        for (Object groupName : stats.keySet()) {
            JSONArray groupValue = new JSONArray();
            JSONObject group = ((JSONObject) stats.get(groupName));
            Object type = group.get("type");

            groupValue.add(groupName);
            groupValue.add(type);

            JSONObject s = new JSONObject();
            for (Object statName : group.keySet()) {
                if ("type".equals(statName))
                    continue;

                JSONArray statValues = (JSONArray) group.get(statName);
                s.put(statName, statValues.get(i));
            }
            groupValue.add(s);

            value.add(groupValue);
        }
        Object[] point = new Object[LoggingHandler.PEER_CONNECTION_STATS_COLUMNS.length];

        point[0] = timestamp;
        point[1] = conferenceId;
        point[2] = endpointId;
        point[3] = value.toJSONString();

        values.add(point);
    }

    return values.toArray();
}

From source file:org.jitsi.sphinx4http.server.RequestHandler.java

/**
 * When a request has been verified and accepted, this method will manage
 * the actual transcription work. This method will transcribe the whole file
 * and sent the result when the transcription is completely done
 * @param baseRequest the baseRequest//from www. ja v a 2  s .c  o m
 * @param response the response of the server
 * @param session the session belonging to the request
 * @param audioFile the audio file which is going to get transcribed
 * @throws IOException when writing the response goes wrong
 */
@SuppressWarnings("unchecked") //for JSONObject.put()
private void transcribeRequestChunked(Request baseRequest, HttpServletResponse response, Session session,
        File audioFile) throws IOException {
    //start by sending 200 OK and the meta data JSON object
    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("application/json");

    JSONObject object = new JSONObject();
    object.put(JSON_SESSION_ID, session.getId());

    //and send the initial object
    response.getWriter().write("{\"objects\":[" + object.toJSONString());
    response.getWriter().flush();

    //start the transcription, which will send
    //JSON objects constantly
    JSONArray result;
    try {
        logger.info("Started audio transcription for id: {}", session.getId());
        result = session.chunkedTranscribe(audioFile, response.getWriter());
    } catch (IOException e) {
        logger.warn("chunked transcription with id {} failed due to " + "IO error", e);
        sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Failed to execute request due to" + "an error in transcribing the audio file", baseRequest,
                response);
        return;
    }

    //the request is handled
    response.getWriter().write("]}");
    response.getWriter().flush();
    baseRequest.setHandled(true);

    //log result
    logger.info("Successfully handled request with id: {}", session.getId());
    logger.debug("Result of chunked request with id {}:\n{}", session.getId(), result.toJSONString());
}

From source file:org.jitsi.videobridge.influxdb.LoggingHandler.java

/**
 * Logs an <tt>InfluxDBEvent</tt> to an <tt>InfluxDB</tt> database. This
 * method returns without blocking, the blocking operations are performed
 * by a thread from {@link #executor}./*from   w  w w.  j ava 2  s  .  c om*/
 *
 * @param e the <tt>Event</tt> to log.
 */
@SuppressWarnings("unchecked")
protected void logEvent(InfluxDBEvent e) {
    // The following is a sample JSON message in the format used by InfluxDB
    //  [
    //    {
    //     "name": "series_name",
    //     "columns": ["column1", "column2"],
    //     "points": [
    //           ["value1", 1234],
    //           ["value2", 5678]
    //          ]
    //    }
    //  ]

    boolean useLocalTime = e.useLocalTime();
    long now = System.currentTimeMillis();
    boolean multipoint = false;
    int pointCount = 1;
    JSONArray columns = new JSONArray();
    JSONArray points = new JSONArray();
    Object[] values = e.getValues();

    if (useLocalTime)
        columns.add("time");
    Collections.addAll(columns, e.getColumns());

    if (values[0] instanceof Object[]) {
        multipoint = true;
        pointCount = values.length;
    }

    if (multipoint) {
        for (int i = 0; i < pointCount; i++) {
            if (!(values[i] instanceof Object[]))
                continue;

            JSONArray point = new JSONArray();
            if (useLocalTime)
                point.add(now);
            Collections.addAll(point, (Object[]) values[i]);
            points.add(point);
        }
    } else {
        JSONArray point = new JSONArray();
        if (useLocalTime)
            point.add(now);
        Collections.addAll(point, values);
        points.add(point);
    }

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("name", e.getName());
    jsonObject.put("columns", columns);
    jsonObject.put("points", points);

    JSONArray jsonArray = new JSONArray();
    jsonArray.add(jsonObject);

    // TODO: this is probably a good place to optimize by grouping multiple
    // events in a single POST message and/or multiple points for events
    // of the same type together).
    final String jsonString = jsonArray.toJSONString();
    executor.execute(new Runnable() {
        @Override
        public void run() {
            sendPost(jsonString);
        }
    });
}

From source file:org.jolokia.client.request.J4pRequestHandler.java

/**
 * Get an HTTP Request for requesting multiples requests at once
 *
 * @param pRequests requests to put into a HTTP request
 * @return HTTP request to send to the server
 *//* w  ww.ja v a 2 s.c  o m*/
public <T extends J4pRequest> HttpUriRequest getHttpRequest(List<T> pRequests,
        Map<J4pQueryParameter, String> pProcessingOptions)
        throws UnsupportedEncodingException, URISyntaxException {
    JSONArray bulkRequest = new JSONArray();
    String queryParams = prepareQueryParameters(pProcessingOptions);
    HttpPost postReq = new HttpPost(createRequestURI(j4pServerUrl.getPath(), queryParams));
    for (T request : pRequests) {
        JSONObject requestContent = getJsonRequestContent(request);
        bulkRequest.add(requestContent);
    }
    postReq.setEntity(new StringEntity(bulkRequest.toJSONString(), "utf-8"));
    return postReq;
}