Ejemplo n.º 1
0
  public void testFetchCommandsForClient() {
    String accountGUID = Utils.generateGuid();
    ArrayList<String> args = new ArrayList<String>();
    args.add("URI of Page");
    args.add("Sender GUID");
    args.add("Title of Page");
    String jsonArgs = JSONArray.toJSONString(args);

    Cursor cur = null;
    try {
      db.store(accountGUID, "displayURI", jsonArgs);

      // This row should ALSO show up in the fetch.
      args.add("Another arg.");
      db.store(accountGUID, "displayURI", JSONArray.toJSONString(args));

      // Test both stored items with the same GUID but different command are fetched.
      cur = db.fetchCommandsForClient(accountGUID);
      assertTrue(cur.moveToFirst());
      assertEquals(2, cur.getCount());
    } catch (NullCursorException e) {
      fail("Should not have NullCursorException");
    } finally {
      if (cur != null) {
        cur.close();
      }
    }
  }
Ejemplo n.º 2
0
  public void testDoubleArrayToString() throws IOException {
    assertEquals("null", JSONArray.toJSONString((double[]) null));
    assertEquals("[]", JSONArray.toJSONString(new double[0]));
    assertEquals("[12.8]", JSONArray.toJSONString(new double[] {12.8}));
    assertEquals(
        "[-7.1,22.234,86.7,-99.02]",
        JSONArray.toJSONString(new double[] {-7.1, 22.234, 86.7, -99.02}));

    StringWriter writer;

    writer = new StringWriter();
    JSONArray.writeJSONString((double[]) null, writer);
    assertEquals("null", writer.toString());

    writer = new StringWriter();
    JSONArray.writeJSONString(new double[0], writer);
    assertEquals("[]", writer.toString());

    writer = new StringWriter();
    JSONArray.writeJSONString(new double[] {12.8}, writer);
    assertEquals("[12.8]", writer.toString());

    writer = new StringWriter();
    JSONArray.writeJSONString(new double[] {-7.1, 22.234, 86.7, -99.02}, writer);
    assertEquals("[-7.1,22.234,86.7,-99.02]", writer.toString());
  }
Ejemplo n.º 3
0
  public void testObjectArrayToString() throws IOException {
    assertEquals("null", JSONArray.toJSONString((Object[]) null));
    assertEquals("[]", JSONArray.toJSONString(new Object[0]));
    assertEquals("[\"Hello\"]", JSONArray.toJSONString(new Object[] {"Hello"}));
    assertEquals(
        "[\"Hello\",12,[1,2,3]]",
        JSONArray.toJSONString(new Object[] {"Hello", new Integer(12), new int[] {1, 2, 3}}));

    StringWriter writer;

    writer = new StringWriter();
    JSONArray.writeJSONString((Object[]) null, writer);
    assertEquals("null", writer.toString());

    writer = new StringWriter();
    JSONArray.writeJSONString(new Object[0], writer);
    assertEquals("[]", writer.toString());

    writer = new StringWriter();
    JSONArray.writeJSONString(new Object[] {"Hello"}, writer);
    assertEquals("[\"Hello\"]", writer.toString());

    writer = new StringWriter();
    JSONArray.writeJSONString(new Object[] {"Hello", new Integer(12), new int[] {1, 2, 3}}, writer);
    assertEquals("[\"Hello\",12,[1,2,3]]", writer.toString());
  }
Ejemplo n.º 4
0
  public void testFloatArrayToString() throws IOException {
    assertEquals("null", JSONArray.toJSONString((float[]) null));
    assertEquals("[]", JSONArray.toJSONString(new float[0]));
    assertEquals("[12.8]", JSONArray.toJSONString(new float[] {12.8f}));
    assertEquals(
        "[-7.1,22.234,86.7,-99.02]",
        JSONArray.toJSONString(new float[] {-7.1f, 22.234f, 86.7f, -99.02f}));

    StringWriter writer;

    writer = new StringWriter();
    JSONArray.writeJSONString((float[]) null, writer);
    assertEquals("null", writer.toString());

    writer = new StringWriter();
    JSONArray.writeJSONString(new float[0], writer);
    assertEquals("[]", writer.toString());

    writer = new StringWriter();
    JSONArray.writeJSONString(new float[] {12.8f}, writer);
    assertEquals("[12.8]", writer.toString());

    writer = new StringWriter();
    JSONArray.writeJSONString(new float[] {-7.1f, 22.234f, 86.7f, -99.02f}, writer);
    assertEquals("[-7.1,22.234,86.7,-99.02]", writer.toString());
  }
Ejemplo n.º 5
0
  public void testLongArrayToString() throws IOException {
    assertEquals("null", JSONArray.toJSONString((long[]) null));
    assertEquals("[]", JSONArray.toJSONString(new long[0]));
    assertEquals("[12]", JSONArray.toJSONString(new long[] {12}));
    assertEquals(
        "[-7,22,9223372036854775807,-99]",
        JSONArray.toJSONString(new long[] {-7, 22, 9223372036854775807L, -99}));

    StringWriter writer;

    writer = new StringWriter();
    JSONArray.writeJSONString((long[]) null, writer);
    assertEquals("null", writer.toString());

    writer = new StringWriter();
    JSONArray.writeJSONString(new long[0], writer);
    assertEquals("[]", writer.toString());

    writer = new StringWriter();
    JSONArray.writeJSONString(new long[] {12}, writer);
    assertEquals("[12]", writer.toString());

    writer = new StringWriter();
    JSONArray.writeJSONString(new long[] {-7, 22, 86, -99}, writer);
    assertEquals("[-7,22,86,-99]", writer.toString());
  }
Ejemplo n.º 6
0
  public String toJSON() {
    JSONObject root = new JSONObject();

    JSONArray purchasesArray = new JSONArray();
    for (Map.Entry<Integer, Integer> entry : this.productId_quantity.entrySet()) {
      JSONObject purchases = new JSONObject();
      purchases.put("productId", entry.getKey());
      purchases.put("quantity", entry.getValue());
      purchasesArray.add(purchases);
    }

    HashMap classObj = new LinkedHashMap();
    classObj.put("customerId", this.getCustomerId());
    classObj.put("customerName", this.getCustomerName());
    classObj.put("timeReceived", this.getTimeReceived());
    classObj.put("timeProcessed", this.getTimeProcessed());
    classObj.put("timeFulfilled", this.getTimeFullFilled());
    classObj.put("purchases", purchasesArray);
    classObj.put("notes", this.getNotes());

    JSONArray orders = new JSONArray();
    orders.add(classObj);

    root.put("", orders);
    return orders.toJSONString();
  }
  @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);
    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");
  }
Ejemplo n.º 8
0
  /**
   * Convert an object to JSON text.
   *
   * <p>If this object is a Map or a List, and it's also a JSONAware, JSONAware will be considered
   * firstly.
   *
   * <p>DO NOT call this method from toJSONString() of a class that implements both JSONAware and
   * Map or List with "this" as the parameter, use JSONObject.toJSONString(Map) or
   * JSONArray.toJSONString(List) instead.
   *
   * @see org.json.simple.JSONObject#toJSONString(Map)
   * @see org.json.simple.JSONArray#toJSONString(List)
   * @param value
   * @return JSON text, or "null" if value is null or it's an NaN or an INF number.
   */
  public static String toJSONString(Object value) {
    if (value == null) return "null";

    if (value instanceof String) return "\"" + escape((String) value) + "\"";

    if (value instanceof Double) {
      if (((Double) value).isInfinite() || ((Double) value).isNaN()) return "null";
      else return value.toString();
    }

    if (value instanceof Float) {
      if (((Float) value).isInfinite() || ((Float) value).isNaN()) return "null";
      else return value.toString();
    }

    if (value instanceof Number) return value.toString();

    if (value instanceof Boolean) return value.toString();

    if ((value instanceof JSONAware)) return ((JSONAware) value).toJSONString();

    if (value instanceof Map) return JSONObject.toJSONString((Map) value);

    if (value instanceof List) return JSONArray.toJSONString((List) value);

    return value.toString();
  }
 public void acceptRepresentation(final Representation entity) throws ResourceException {
   final Form form = getRequest().getEntityAsForm();
   final String serviceUrl = form.getFirstValue("serviceTicketUrl");
   try {
     final Assertion authentication =
         this.centralAuthenticationService.validateServiceTicket(
             serviceTicketId, new SimpleWebApplicationServiceImpl(serviceUrl, this.httpClient));
     if (authentication.getChainedAuthentications().size() > 0) {
       // Iterate through each of the ChainedAuthentications and put them into the JSonArray
       JSONArray jsonResult = new JSONArray();
       for (Authentication auth : authentication.getChainedAuthentications()) {
         // Create the principle
         JSONObject principle = createJSONPrinciple(auth);
         JSONObject jsonAuth = new JSONObject();
         jsonAuth.put("authenticated_date", auth.getAuthenticatedDate());
         jsonAuth.put("attributes", principle);
         jsonResult.add(jsonAuth);
       }
       getResponse().setEntity(jsonResult.toJSONString(), MediaType.TEXT_PLAIN);
     } else {
       getResponse()
           .setEntity(
               java.lang.String.format("\"{\"authenticated\":\"false\"}\""), MediaType.TEXT_PLAIN);
     }
   } catch (final TicketException e) {
     log.error(e.getMessage(), e);
     getResponse()
         .setStatus(Status.CLIENT_ERROR_NOT_FOUND, "TicketGrantingTicket could not be found.");
   } catch (final Exception e) {
     log.error(e.getMessage(), e);
     getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST, e.getMessage());
   }
 }
Ejemplo n.º 10
0
  @RequestMapping(value = "/home")
  public String home(ModelMap modelMap) {
    HttpServletRequest request =
        ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    System.out.println("HomeController: passing through...");
    System.out.println("获取相关renren参数");
    String sessionKey = request.getParameter("xn_sig_session_key");
    String renrenUserId = request.getParameter("xn_sig_user");
    System.out.println("Session Key: " + sessionKey);
    System.out.println("renrenUserId: " + renrenUserId);
    if (sessionKey != null && renrenUserId != null) {
      RenrenApiClient apiClient = new RenrenApiClient(sessionKey);
      SessionKey sessionKeyReal = new SessionKey(sessionKey);
      // 获取用户信息
      JSONArray userInfo = apiClient.getUserService().getInfo(renrenUserId, sessionKeyReal);
      if (userInfo != null && userInfo.size() > 0) {
        JSONObject currentUser = (JSONObject) userInfo.get(0);
        if (currentUser != null) {
          String userName = (String) currentUser.get("name");
          String userHead = (String) currentUser.get("headurl");
          request.setAttribute("userName", userName);
          request.setAttribute("userHead", userHead);
        }
      }
      JSONArray friends = apiClient.getFriendsService().getFriends(2, 80, sessionKeyReal);
      String friendsStr = friends.toJSONString().replace("\"", "\'");
      request.setAttribute("friends", friendsStr);
    }

    // 测试commit

    modelMap.addAttribute("welcome", "Walter's APP");
    return "home";
  }
  @RequestMapping("api/admin/projectAdd.do")
  public @ResponseBody Map<String, Object> projectAdd(
      ProjectDTO fileDto, @RequestParam(value = "memberList") String memberList) {

    MultipartFile uploadFile = fileDto.getUploadFile();

    if (uploadFile != null) {

      String fileName = uploadFile.getOriginalFilename();

      Date date = new Date();
      int year = date.getYear() - 100;
      int month = date.getMonth() + 1;
      int day = date.getDate();
      int hour = date.getHours();
      int minute = date.getMinutes();
      int second = date.getSeconds();
      String time = year + "" + month + "" + day + "" + hour + "" + minute + "" + second;
      int comma = fileName.lastIndexOf(".");
      String pre = fileName.substring(0, comma);
      String end = fileName.substring(comma + 1, fileName.length());
      fileName = pre + time + "." + end;

      String projectDesc = fileDto.getProjectDesc();
      fileDto.setProjectDesc(projectDesc.replaceAll("\n", "<br>"));

      try {

        File file = new File(realPath + fileName);

        uploadFile.transferTo(file);

        fileDto.setProjectImg(fileName);

        System.out.println(memberList);
        JSONParser parser = new JSONParser();
        JSONArray ja = (JSONArray) parser.parse(memberList);
        System.out.println(ja.toJSONString());
        ArrayList list = new ArrayList();
        for (int i = 0; i < ja.size(); i++) {
          JSONObject jo = (JSONObject) ja.get(i);
          System.out.println(jo.get("userNo"));
          list.add(jo.get("userNo"));
        }

        projectDao.insertProject(fileDto);
        if (list != null) {
          Map<String, Object> param = new HashMap<String, Object>();
          param.put("list", list);
          projectMemberDao.projectMemberAdd(param);
        }

      } catch (Exception e) {
        e.printStackTrace();
      } // try - catch
    } // if

    return JsonUtil.putSuccessJsonContainer(null);
  }
Ejemplo n.º 12
0
  @Test
  public void testTaskResultByUnknownTag() throws Exception {
    HttpResponse response = sendRequest("jobs/" + jobId + "/tasks/tag/unknownTag/result");
    JSONArray jsonArray = toJsonArray(response);

    System.out.println(jsonArray.toJSONString());
    assertEquals(0, jsonArray.size());
  }
Ejemplo n.º 13
0
  @Test
  public void testJobTagsBadPrefix() throws Exception {
    HttpResponse response = sendRequest("jobs/" + jobId + "/tasks/tags/startsWith/blabla");
    JSONArray jsonArray = toJsonArray(response);

    System.out.println(jsonArray.toJSONString());

    assertEquals(0, jsonArray.size());
  }
Ejemplo n.º 14
0
  public void testJSONArrayCollection() {
    final ArrayList<String> testList = new ArrayList<String>();
    testList.add("First item");
    testList.add("Second item");

    final JSONArray jsonArray = new JSONArray(testList);

    assertEquals("[\"First item\",\"Second item\"]", jsonArray.toJSONString());
  }
Ejemplo n.º 15
0
  public String getTaskLogDateHistory(
      Long taskQueueId,
      List<TaskLog> taskLogList,
      String pybossaResult,
      JSONParser parser,
      ClientApp clientApp,
      ClientAppAnswer clientAppAnswer)
      throws Exception {
    // JSONObject aModified = new JSONObject();
    JSONArray outJson = new JSONArray();
    JSONObject dateJSON = new JSONObject();

    for (int i = 0; i < taskLogList.size(); i++) {
      TaskLog taskLog = taskLogList.get(i);
      switch (taskLog.getStatus()) {
        case 1:
          dateJSON.put("taskcreated", taskLog.getCreated().toString());
          dateJSON.put("taskpulled", taskLog.getCreated().toString());
          break;
      }
      dateJSON.put("taskpulled", DateTimeConverter.reformattedCurrentDate());
    }

    JSONArray array = (JSONArray) parser.parse(pybossaResult);

    if (array.size() > 0) {
      JSONObject oneFeatureJsonObj = (JSONObject) array.get(0);

      String taskPresented = (String) oneFeatureJsonObj.get("created");

      String taskCompleted = (String) oneFeatureJsonObj.get("finish_time");

      dateJSON.put("taskpresented", taskPresented);
      dateJSON.put("taskcompleted", taskCompleted);

      oneFeatureJsonObj.put("dateHistory", dateJSON);

      String finalAnswer =
          this.getAnswerResponse(clientApp, pybossaResult, parser, clientAppAnswer, taskQueueId);
      if (finalAnswer != null) {
        Long attributeID = clientApp.getNominalAttributeID();
        JSONObject infoJson =
            this.buildInfoJson(
                (JSONObject) oneFeatureJsonObj.get("info"), finalAnswer, attributeID);

        oneFeatureJsonObj.put("info", infoJson);

        outJson.add(oneFeatureJsonObj);

        return outJson.toJSONString();
      }
    }

    return null;
  }
Ejemplo n.º 16
0
 @SuppressWarnings("unchecked")
 @Override
 public String toJSONString() {
   JSONArray jsonArray = new JSONArray();
   for (String kw : keywords) {
     JSONObject data = new JSONObject();
     data.put("name", kw);
     data.put("value", kw);
     jsonArray.add(data);
   }
   return jsonArray.toJSONString();
 }
Ejemplo n.º 17
0
  @Test
  public void testJobTagsPrefix() throws Exception {
    HttpResponse response = sendRequest("jobs/" + jobId + "/tasks/tags/startsWith/LOOP");
    JSONArray jsonArray = toJsonArray(response);

    System.out.println(jsonArray.toJSONString());

    assertTrue(jsonArray.contains("LOOP-T2-1"));
    assertTrue(jsonArray.contains("LOOP-T2-2"));
    assertTrue(jsonArray.contains("LOOP-T2-3"));
    assertEquals(3, jsonArray.size());
  }
Ejemplo n.º 18
0
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {

      String su = request.getParameter("subid");

      int i = 1;

      Session s = NewHibernateUtil.getSessionFactory().openSession();
      Transaction t = s.beginTransaction();

      Criteria cr = s.createCriteria(Subject.class);
      cr.add(Restrictions.eq("idsubject", Integer.parseInt(su)));
      Subject sab = (Subject) cr.uniqueResult();
      Subject subt = (Subject) s.load(Subject.class, sab.getIdsubject());

      Criteria c = s.createCriteria(School.class);
      c.add(Restrictions.eq("subject", subt));

      JSONArray json = new JSONArray();
      Map m = new HashMap();

      List<School> list = c.list();

      for (School school : list) {
        m.put("schoolName", school.getSchoolName());
        m.put("grade11", school.getGrade11());
        m.put("grade10", school.getGrade10());
        m.put("grade9", school.getGrade9());
        m.put("subject", school.getSubject().getSubjectName());

        json.add(m);

        m = null;
        m = new HashMap();

        out.write(json.toJSONString());

        //                out.write("<tr>" + school.getSchoolName() + "</tr>");
        //                out.write("<tr>" + school.getGrade11() + "</tr>");
        //                out.write("<tr>" + school.getGrade10() + "</tr>");
        //                out.write("<tr>" + school.getGrade9() + "</tr>");
        //                out.write("<tr>" + school.getSubject().getSubjectName() + "</tr>");
      }

    } catch (Exception e) {
      throw new ServletException(e);
    }
  }
  /**
   * Return JSON response showing data groups available to this user
   *
   * @return String with JSON response
   */
  @GET
  @Authenticated
  @Path("/list")
  @Produces(MediaType.APPLICATION_JSON)
  public Response bcidList() {
    BcidMinter bcidMinter = new BcidMinter();
    String username = null;
    if (user != null) {
      username = user.getUsername();
    }
    JSONArray response = bcidMinter.bcidList(username);

    return Response.ok(response.toJSONString()).build();
  }
 /**
  * Gets the list activities from response.
  *
  * @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);
   }
 }
Ejemplo n.º 21
0
  @SuppressWarnings("unchecked")
  public ImportRecords(final Config c) {
    random = new SecureRandom();
    recordID = DigestUtils.sha1Hex(new BigInteger(16, random).toString(16)).substring(0, 16);

    record = new JSONObject();
    record.put("record_id", recordID);
    record.put("first_name", "First");
    record.put("last_name", "Last");
    record.put("address", "123 Cherry Lane\nNashville, TN 37015");
    record.put("telephone", "(615) 255-4000");
    record.put("email", "*****@*****.**");
    record.put("dob", "1972-08-10");
    record.put("age", "43");
    record.put("ethnicity", "1");
    record.put("race", "4");
    record.put("sex", "1");
    record.put("height", "180");
    record.put("weight", "105");
    record.put("bmi", "31.4");
    record.put("comments", "comments go here");
    record.put("redcap_event_name", "events_2_arm_1");
    record.put("basic_demography_form_complete", "2");

    data = new JSONArray();
    data.add(record);

    params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("token", c.API_TOKEN));
    params.add(new BasicNameValuePair("content", "record"));
    params.add(new BasicNameValuePair("format", "json"));
    params.add(new BasicNameValuePair("type", "flat"));
    params.add(new BasicNameValuePair("data", data.toJSONString()));

    post = new HttpPost(c.API_URL);
    post.setHeader("Content-Type", "application/x-www-form-urlencoded");

    try {
      post.setEntity(new UrlEncodedFormEntity(params));
    } catch (final Exception e) {
      e.printStackTrace();
    }

    result = new StringBuffer();
    client = HttpClientBuilder.create().build();
    respCode = -1;
    reader = null;
    line = null;
  }
Ejemplo n.º 22
0
  public void testBooleanArrayToString() throws IOException {
    assertEquals("null", JSONArray.toJSONString((boolean[]) null));
    assertEquals("[]", JSONArray.toJSONString(new boolean[0]));
    assertEquals("[true]", JSONArray.toJSONString(new boolean[] {true}));
    assertEquals("[true,false,true]", JSONArray.toJSONString(new boolean[] {true, false, true}));

    StringWriter writer;

    writer = new StringWriter();
    JSONArray.writeJSONString((boolean[]) null, writer);
    assertEquals("null", writer.toString());

    writer = new StringWriter();
    JSONArray.writeJSONString(new boolean[0], writer);
    assertEquals("[]", writer.toString());

    writer = new StringWriter();
    JSONArray.writeJSONString(new boolean[] {true}, writer);
    assertEquals("[true]", writer.toString());

    writer = new StringWriter();
    JSONArray.writeJSONString(new boolean[] {true, false, true}, writer);
    assertEquals("[true,false,true]", writer.toString());
  }
Ejemplo n.º 23
0
  public void testCharArrayToString() throws IOException {
    assertEquals("null", JSONArray.toJSONString((char[]) null));
    assertEquals("[]", JSONArray.toJSONString(new char[0]));
    assertEquals("[\"a\"]", JSONArray.toJSONString(new char[] {'a'}));
    assertEquals("[\"a\",\"b\",\"c\"]", JSONArray.toJSONString(new char[] {'a', 'b', 'c'}));

    StringWriter writer;

    writer = new StringWriter();
    JSONArray.writeJSONString((char[]) null, writer);
    assertEquals("null", writer.toString());

    writer = new StringWriter();
    JSONArray.writeJSONString(new char[0], writer);
    assertEquals("[]", writer.toString());

    writer = new StringWriter();
    JSONArray.writeJSONString(new char[] {'a'}, writer);
    assertEquals("[\"a\"]", writer.toString());

    writer = new StringWriter();
    JSONArray.writeJSONString(new char[] {'a', 'b', 'c'}, writer);
    assertEquals("[\"a\",\"b\",\"c\"]", writer.toString());
  }
Ejemplo n.º 24
0
  public void testToJSONStringCollection() throws ParseException {
    final HashSet<String> testSet = new HashSet<String>();
    testSet.add("First item");
    testSet.add("Second item");

    final JSONArray jsonArray = new JSONArray(testSet);

    final JSONParser parser = new JSONParser();
    String json = jsonArray.toJSONString();
    final JSONArray parsedArray = (JSONArray) parser.parse(json);

    assertTrue(parsedArray.containsAll(jsonArray));
    assertTrue(jsonArray.containsAll(parsedArray));
    assertEquals(2, jsonArray.size());
  }
Ejemplo n.º 25
0
  public String getOnlineUsers() {
    String query = "select * from Users where lastOnline >= NOW() - INTERVAL 1 MINUTE;";
    String[] values = new String[0];

    JSONArray output = null;
    try {
      output = this.dbc.query(query, values);
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      output = new JSONArray();
      e.printStackTrace();
    }

    return output.toJSONString();
  }
Ejemplo n.º 26
0
  public void testShortArrayToString() throws IOException {
    assertEquals("null", JSONArray.toJSONString((short[]) null));
    assertEquals("[]", JSONArray.toJSONString(new short[0]));
    assertEquals("[12]", JSONArray.toJSONString(new short[] {12}));
    assertEquals("[-7,22,86,-99]", JSONArray.toJSONString(new short[] {-7, 22, 86, -99}));

    StringWriter writer;

    writer = new StringWriter();
    JSONArray.writeJSONString((short[]) null, writer);
    assertEquals("null", writer.toString());

    writer = new StringWriter();
    JSONArray.writeJSONString(new short[0], writer);
    assertEquals("[]", writer.toString());

    writer = new StringWriter();
    JSONArray.writeJSONString(new short[] {12}, writer);
    assertEquals("[12]", writer.toString());

    writer = new StringWriter();
    JSONArray.writeJSONString(new short[] {-7, 22, 86, -99}, writer);
    assertEquals("[-7,22,86,-99]", writer.toString());
  }
Ejemplo n.º 27
0
  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append('[')
        .append(success ? "SUCCESS" : "FAIL")
        .append("] ")
        .append(status)
        .append('(')
        .append(status.getDescription())
        .append(')')
        .append(" : ")
        .append(data != null ? data.toJSONString() : "no data");

    return sb.toString();
  }
Ejemplo n.º 28
0
  public void testStoreAndFetchSpecificCommands() {
    String accountGUID = Utils.generateGuid();
    ArrayList<String> args = new ArrayList<String>();
    args.add("URI of Page");
    args.add("Sender GUID");
    args.add("Title of Page");
    String jsonArgs = JSONArray.toJSONString(args);

    Cursor cur = null;
    try {
      db.store(accountGUID, "displayURI", jsonArgs);

      // This row should not show up in the fetch.
      args.add("Another arg.");
      db.store(accountGUID, "displayURI", JSONArray.toJSONString(args));

      // Test stored item gets fetched correctly.
      cur = db.fetchSpecificCommand(accountGUID, "displayURI", jsonArgs);
      assertTrue(cur.moveToFirst());
      assertEquals(1, cur.getCount());

      String guid = RepoUtils.getStringFromCursor(cur, ClientsDatabase.COL_ACCOUNT_GUID);
      String commandType = RepoUtils.getStringFromCursor(cur, ClientsDatabase.COL_COMMAND);
      String fetchedArgs = RepoUtils.getStringFromCursor(cur, ClientsDatabase.COL_ARGS);

      assertEquals(accountGUID, guid);
      assertEquals("displayURI", commandType);
      assertEquals(jsonArgs, fetchedArgs);
    } catch (NullCursorException e) {
      fail("Should not have NullCursorException");
    } finally {
      if (cur != null) {
        cur.close();
      }
    }
  }
Ejemplo n.º 29
0
  public static String generateJajascriptJSON(int number) {
    Random random = new Random();
    JSONArray array = new JSONArray();
    for (int i = 0; i < number; i++) {
      int start = random.nextInt(23);
      int duration = 1 + random.nextInt(23 - start);
      JSONObject o = new JSONObject();
      o.put("VOL", String.valueOf(i + 1));
      o.put("DEPART", start);
      o.put("DUREE", duration);
      o.put("PRIX", random.nextInt(21) + 1);
      array.add(o);
    }

    return array.toJSONString();
  }
Ejemplo n.º 30
0
  @Override
  public void process(ProcessletInputs in, ProcessletOutputs out, ProcessletExecutionInfo info)
      throws ProcessletException {

    JSONArray args = parseRequestParams(in);

    try {
      String confOutputName = null;
      for (int i = 0; i < args.size(); i++) {
        JSONObject arg = (JSONObject) args.get(i);
        Object val = arg.get("OUTPUT_NAME");

        if (val != null) {
          confOutputName = val.toString();
          break;
        }
      }
      JSONObject conflationCommand = _createPostBody(args);
      JSONArray reviewArgs = new JSONArray();
      JSONObject param = new JSONObject();
      param.put("value", confOutputName);
      param.put("paramtype", String.class.getName());
      param.put("isprimitivetype", "false");
      reviewArgs.add(param);

      param = new JSONObject();
      param.put("value", false);
      param.put("paramtype", Boolean.class.getName());
      param.put("isprimitivetype", "true");
      reviewArgs.add(param);

      JSONObject prepareItemsForReviewCommand =
          _createReflectionJobReq(
              reviewArgs, "hoot.services.controllers.job.ReviewResource", "prepareItemsForReview");

      JSONArray jobArgs = new JSONArray();
      jobArgs.add(conflationCommand);
      jobArgs.add(prepareItemsForReviewCommand);

      postChainJobRquest(jobIdStr, jobArgs.toJSONString());

      ((LiteralOutput) out.getParameter("jobId")).setValue(jobIdStr);
    } catch (Exception e) {
      log.error(e.getMessage());
    }
  }