public JSONObject loadTestAndAllQuestions(JSONRPC2Request req, HttpServletRequest request)
      throws Exception {
    JSONObject jsonResult = new JSONObject();
    JSONArray jsonAllQuestions = new JSONArray();
    JSONObject jsonTest = new JSONObject();

    // retrievers
    Map<String, Object> params = req.getNamedParams();
    NamedParamsRetriever np = new NamedParamsRetriever(params);
    Map<String, Object> tParams = np.getMap("test");
    NamedParamsRetriever testNp = new NamedParamsRetriever(tParams);
    int tid = testNp.getInt("id");

    // get data from DB
    MySQLDAO dao = new MySQLDAO();
    Test t = dao.loadTest(tid);
    QuestionsList allQuestions = QuestionController.loadAllQuestions();

    // set result
    jsonTest = t.toJSONObject();
    jsonAllQuestions = allQuestions.toJSONArray();
    jsonResult.put("test", jsonTest);
    jsonResult.put("questions", jsonAllQuestions);

    return jsonResult;
  }
 @Override
 public JSONObject toJSON(Online o) {
   JSONObject c = new JSONObject();
   c.put("id", getJSONId());
   c.put("node", JSONs.elementToJSON(o.getInvolvedNodes().iterator().next()));
   return c;
 }
 /**
  * userList
  *
  * @return HttpResponse
  */
 @GET
 @Path("/")
 @Produces(MediaType.APPLICATION_JSON)
 @Consumes(MediaType.TEXT_PLAIN)
 @ApiResponses(
     value = {
       @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "intErrorResponse"),
       @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "userResponse")
     })
 @ApiOperation(value = "userList", notes = "")
 public HttpResponse userList() {
   // intErrorResponse
   boolean intErrorResponse_condition = true;
   if (intErrorResponse_condition) {
     String intError = "Some String";
     HttpResponse intErrorResponse =
         new HttpResponse(intError, HttpURLConnection.HTTP_INTERNAL_ERROR);
     return intErrorResponse;
   }
   // userResponse
   boolean userResponse_condition = true;
   if (userResponse_condition) {
     JSONObject userList = new JSONObject();
     HttpResponse userResponse =
         new HttpResponse(userList.toJSONString(), HttpURLConnection.HTTP_OK);
     return userResponse;
   }
   return null;
 }
  @ResponseBody
  @RequestMapping(value = "modify", method = RequestMethod.POST)
  public String modify(HttpServletRequest request, HttpServletResponse response) {
    JSONObject json = FormRequestUtil.parseData(request);

    Object _id = json.get("id");
    if (_id == null) {
      response.setStatus(HttpStatus.BAD_REQUEST.value());
      return "媒体Id不能为空";
    }

    int id = Integer.parseInt(_id.toString());
    Media media = service.getById(id);
    if (media != null) {
      String desc = (String) json.get("desc");
      String logourl = (String) json.get("logourl");
      String siteurl = (String) json.get("siteurl");
      if (StringUtils.isNotBlank(desc)) {
        media.setDesc(desc);
      }
      if (StringUtils.isNotBlank(logourl)) {
        media.setLogourl(logourl);
      }
      if (StringUtils.isNotBlank(siteurl)) {
        media.setSiteurl(siteurl);
      }

      return media.toJson().toJSONString();
    } else {
      response.setStatus(HttpStatus.NOT_FOUND.value());
      return "媒体[id=" + _id + "]不存在";
    }
  }
  public static Manifest manifestFromJSonObject(JSONObject parsedObject) {
    String versionStr = "";
    String guid = "";
    String urlRoot = "";

    Object tmp = parsedObject.get(ManifestConstants.VERSION);
    if (null != tmp) {
      versionStr = tmp.toString();
    }

    tmp = parsedObject.get(ManifestConstants.GUID);
    if (null != tmp) {
      guid = tmp.toString();
    }
    tmp = parsedObject.get(ManifestConstants.URLROOT);
    if (null != tmp) {
      urlRoot = tmp.toString();
    }

    Manifest toReturn = new Manifest(Util.intFromStringWithoutThrow(versionStr), guid, urlRoot);

    tmp = parsedObject.get(ManifestConstants.ENTRIES);
    if (tmp instanceof JSONArray) {
      JSONArray entries = (JSONArray) tmp;
      for (Object tmpEntry : entries) {
        if (tmpEntry instanceof JSONObject) {
          Entry e = entryFromJsonObject((JSONObject) tmpEntry);
          if (null != e) {
            toReturn.addEntry(e);
          }
        }
      }
    }
    return toReturn;
  }
Beispiel #6
0
  @Test
  public void DecodingJsonText() throws ParseException {
    System.out.println("=======decode=======");

    String s = "[0,{'1':{'2':{'3':{'4':[5,{'6':7}]}}}}]";
    Object obj = JSONValue.parse(s);
    JSONArray array = (JSONArray) obj;
    System.out.println("======the 2nd element of array======");
    System.out.println(array.get(1));
    System.out.println();

    JSONObject obj2 = (JSONObject) array.get(1);
    System.out.println("======field \"1\"==========");
    System.out.println(obj2.get("1"));

    s = "{}";
    obj = JSONValue.parse(s);
    System.out.println(obj);

    s = "{\"key\":\"Value\"}";
    // JSONValue.parseStrict()
    // can be use to be sure that the input is wellformed
    obj = JSONValue.parseStrict(s);
    JSONObject obj3 = (JSONObject) obj;
    System.out.println("====== Object content ======");
    System.out.println(obj3.get("key"));
    System.out.println();
  }
  public JSONObject updateQuestion(JSONRPC2Request req, HttpServletRequest request)
      throws JSONRPC2Error, Exception {
    JSONObject jsonUpdateQuestion = new JSONObject();

    // get question
    Map<String, Object> params = req.getNamedParams();
    NamedParamsRetriever np = new NamedParamsRetriever(params);
    Map<String, Object> qParams = np.getMap("question");
    NamedParamsRetriever questionNp = new NamedParamsRetriever(qParams);
    int questionId = questionNp.getInt("id");
    String questionBody = questionNp.getString("body");
    String questionAnswer = questionNp.getString("answer");

    int qOwnerId = questionNp.getInt("ownerId");

    User u = getCurrentUser(request);

    // check if this is the owner of the question
    if (u.getId() == qOwnerId) {
      // update question in database
      Question qUpdated =
          QuestionController.updateQuestion(questionId, questionBody, questionAnswer);

      // return result
      jsonUpdateQuestion.put("question", qUpdated.toJSONObject());
      return jsonUpdateQuestion;
    } else {
      throw new Exception("no privileges");
    }
  }
  /**
   * @param queryString is a simple query of 4 types (assault, murder, robbery, rape) e.g.
   *     assault>300&&rape<10
   * @return List<CityCrime> of CityCrime objects
   */
  public List<CityCrime> filterByViolentType(String queryString) {
    Configuration config = Configuration.builder().options(Option.AS_PATH_LIST).build();
    String formatted = formatQueryString("totals.violent", queryString);
    List<String> foundPaths =
        JsonPath.using(config).parse(rawData).read("$[*].data[?(" + formatted + ")]");
    List<CityCrime> resultList = new ArrayList<CityCrime>();

    // Regex:::create matcher object to get the parent
    for (String path : foundPaths) {
      String pattern = "\\$\\[\\d+\\]"; // root

      // Create a Pattern object
      Pattern r = Pattern.compile(pattern);
      CityCrime cityCrime = new CityCrime();

      Matcher m = r.matcher(path);
      if (m.find()) {
        JSONObject rawObj = JsonPath.read(rawData, m.group(0));
        cityCrime.setDepartment((String) rawObj.get("department"));
        cityCrime.setState((String) rawObj.get("state"));

        JSONObject reportObj = JsonPath.read(rawData, path);
        List<Report> reports = new ArrayList<Report>();
        reports.add(new Report(reportObj));
        cityCrime.setReport(reports);
      }
      resultList.add(cityCrime);
    }
    return resultList;
  }
  public JSONObject addQuestion(JSONRPC2Request req, HttpServletRequest request)
      throws JSONRPC2Error {
    // json object for the result
    JSONObject jsonAddQuestion = new JSONObject();

    // get question
    System.out.println(req.toString());
    Map<String, Object> params = req.getNamedParams();
    NamedParamsRetriever np = new NamedParamsRetriever(params);
    Map<String, Object> qParams = np.getMap("question");
    NamedParamsRetriever questionNp = new NamedParamsRetriever(qParams);
    String body = questionNp.getString("body");
    String answer = questionNp.getString("answer");

    // get user
    User u = getCurrentUser(request);
    int userID = (int) u.getId();
    System.out.println("current user id" + userID);

    // return ID of Question if added successfully
    Question q = QuestionController.addQuestion(body, answer, userID);

    jsonAddQuestion.put("question", q.toJSONObject());

    return jsonAddQuestion;
  }
  public JSONObject updateTest(JSONRPC2Request req, HttpServletRequest request)
      throws JSONRPC2Error, Exception {
    JSONObject jsonUpdateTest = new JSONObject();

    // get question
    Map<String, Object> params = req.getNamedParams();
    NamedParamsRetriever np = new NamedParamsRetriever(params);
    Map<String, Object> tParams = np.getMap("test");
    NamedParamsRetriever testNp = new NamedParamsRetriever(tParams);
    int testId = testNp.getInt("id");
    String testName = testNp.getString("name");
    int tOwnerId = testNp.getInt("ownerId");

    User u = getCurrentUser(request);

    // check for privileges
    if (u.getId() == tOwnerId) {
      // update question in database
      Test testUpdated = TestController.updateTest(testId, testName);

      // return result
      jsonUpdateTest.put("updatedTest", testUpdated.toJSONObject());

      return jsonUpdateTest;
    } else {
      throw new Exception("no privileges");
    }
  }
  protected void onMessage(String message) {
    logger.debug("New message: " + message);

    String channel = JsonPath.compile("$.channel").read(message);

    String primary = null;
    try {
      primary = JsonPath.compile("$.trade.primary").read(message);
    } catch (Exception ex) {
      // ignore
    }

    if (MTGOX_TRADES_CHANNEL.equals(channel) && "Y".equals(primary)) {

      JSONObject trade = JsonPath.compile("$.trade").read(message);
      this.broadcaster.broadcast(trade.toString());

      // Example message:
      // {"channel":"dbf1dee9-4f2e-4a08-8cb7-748919a71b21","op":"private","origin":"broadcast","private":"trade","trade":{"amount":0.01,"amount_int":"1000000","date":1342989115,"item":"BTC","price":8.50097,"price_currency":"USD","price_int":"850097","primary":"Y","properties":"limit","tid":"1342989115044532","trade_type":"bid","type":"trade"}}
      logger.debug("Published trade: " + trade);
    } else {
      // ignore any non-trade messages that might slip in before our
      // op:unsubscribes sent above have been handled; also ignore any
      // 'non-primary' trades. see
      // https://en.bitcoin.it/wiki/MtGox/API/HTTP/v1#Multi_currency_trades
      logger.debug("Message ignored");
    }
  }
  public JSONObject removeTestQuestion(JSONRPC2Request req, HttpServletRequest request)
      throws Exception, SQLException {
    JSONObject jsonResult = new JSONObject();

    // set retrievers
    Map<String, Object> params = req.getNamedParams();
    NamedParamsRetriever np = new NamedParamsRetriever(params);
    Map<String, Object> tParams = np.getMap("test");
    NamedParamsRetriever testNp = new NamedParamsRetriever(tParams);
    Map<String, Object> qParams = np.getMap("question");
    NamedParamsRetriever questNp = new NamedParamsRetriever(qParams);

    MySQLDAO dao = new MySQLDAO();
    Test t = dao.loadTest(testNp.getInt(("id")));
    dao = new MySQLDAO();
    Question q = dao.loadQuestion(questNp.getInt("id"));

    User u = getCurrentUser(request);

    if (u.getId() == t.getOwnerId()) {
      dao = new MySQLDAO();
      t = dao.deleteTestQuestion(t, q);
    } else {
      throw new Exception("no privileges : you do not own this test");
    }

    JSONObject jsonTest = t.toJSONObject();
    JSONObject jsonQuestion = q.toJSONObject();

    jsonResult.put("test", jsonTest);
    jsonResult.put("question", jsonQuestion);

    return jsonResult;
  }
  public JSONObject checkTest(JSONRPC2Request req, HttpServletRequest request)
      throws JSONRPC2Error, Exception {
    JSONObject jsonResult = new JSONObject();
    JSONArray jsonWrongQuestions = new JSONArray();
    QuestionsList wrongQuestions = new QuestionsList();

    // retrievers
    Map<String, Object> params = req.getNamedParams();
    NamedParamsRetriever np = new NamedParamsRetriever(params);
    Map<String, Object> tParams = np.getMap("test");
    NamedParamsRetriever testNp = new NamedParamsRetriever(tParams);

    // get guessed questions values
    QuestionsList guessQuestions = new QuestionsList();
    List<Object> questions = testNp.getList("questions");
    for (Object q : questions) {
      // set new retriever for each question
      NamedParamsRetriever questNp = new NamedParamsRetriever((Map<String, Object>) q);
      // retrieve values
      String answer = questNp.getString("answer");
      String body = questNp.getString("body");
      int id = questNp.getInt("id");
      // create question with the values and add it to the guessed questions
      Question quest = new Question();
      quest.setId(id);
      quest.setBody(body);
      quest.setAnswer(answer);
      guessQuestions.add(quest);
    }

    // get test
    int tid = testNp.getInt("id");
    MySQLDAO dao = new MySQLDAO();
    Test t = dao.loadTest(tid);

    // get true questions
    MySQLDAO questionsDao = new MySQLDAO();
    QuestionsList trueQuestions = questionsDao.loadQuestionsByTest(tid);

    // cycle through questions and find these with same id
    for (Question tq : trueQuestions) {
      for (Question gq : guessQuestions) {
        if (tq.getId() == gq.getId()) {
          // if answers are different, than there is mistake
          System.out.println("id match!");
          if (!tq.getAnswer().equals(gq.getAnswer())) {
            System.out.println("Wrong question!");
            wrongQuestions.add(gq);
          }
        }
      }
    }

    jsonWrongQuestions = wrongQuestions.toJSONArray();
    jsonResult.put("test", t);
    jsonResult.put("wrongQuestions", jsonWrongQuestions);

    return jsonResult;
  }
Beispiel #14
0
 private String getStreamJsonPrefix(Stream stream) throws JsonProcessingException {
   ObjectMapper mapper = new ObjectMapper();
   AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
   mapper.setAnnotationIntrospector(introspector);
   JSONObject json = (JSONObject) JSONValue.parse(mapper.writeValueAsString(stream));
   String strJson = json.toString();
   return strJson.substring(0, strJson.length() - 1) + ",\"tuples\":[";
 }
Beispiel #15
0
 private int query(String query) throws IOException {
   URL url = new URL("http://api.qubole.com/api/v1.2/commands");
   JSONObject queryJson = new JSONObject();
   queryJson.put("query", query);
   String body = queryJson.toString();
   Map response = makeRequest(url, body);
   return (Integer) response.get("id");
 }
 private static JSONObject jsonObjectFromEntry(Entry entry) {
   JSONObject objToReturn = new JSONObject();
   objToReturn.put(ManifestConstants.FILE, entry.getRelativeFile());
   objToReturn.put(ManifestConstants.HASH, entry.getHash());
   objToReturn.put(ManifestConstants.TIME, entry.getTime());
   objToReturn.put(ManifestConstants.SIZE, entry.getSize());
   objToReturn.put(ManifestConstants.TYPE, entry.getStatus().toString());
   return objToReturn;
 }
 /**
  * createUser
  *
  * @param user a JSONObject
  * @return HttpResponse
  */
 @POST
 @Path("/")
 @Produces(MediaType.APPLICATION_JSON)
 @Consumes(MediaType.APPLICATION_JSON)
 @ApiResponses(
     value = {
       @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "userResponse"),
       @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "BadRequestResponse"),
       @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "unauthorizedResponse"),
       @ApiResponse(code = HttpURLConnection.HTTP_CONFLICT, message = "userConflictResponse"),
       @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "intErrorResponse")
     })
 @ApiOperation(value = "createUser", notes = "")
 public HttpResponse createUser(@ContentParam String user) {
   JSONObject user_JSON = (JSONObject) JSONValue.parse(user);
   // userResponse
   boolean userResponse_condition = true;
   if (userResponse_condition) {
     JSONObject user = new JSONObject();
     HttpResponse userResponse =
         new HttpResponse(user.toJSONString(), HttpURLConnection.HTTP_CREATED);
     return userResponse;
   }
   // BadRequestResponse
   boolean BadRequestResponse_condition = true;
   if (BadRequestResponse_condition) {
     JSONObject BadRequest = new JSONObject();
     HttpResponse BadRequestResponse =
         new HttpResponse(BadRequest.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
     return BadRequestResponse;
   }
   // unauthorizedResponse
   boolean unauthorizedResponse_condition = true;
   if (unauthorizedResponse_condition) {
     JSONObject unauthorized = new JSONObject();
     HttpResponse unauthorizedResponse =
         new HttpResponse(unauthorized.toJSONString(), HttpURLConnection.HTTP_UNAUTHORIZED);
     return unauthorizedResponse;
   }
   // userConflictResponse
   boolean userConflictResponse_condition = true;
   if (userConflictResponse_condition) {
     String userConflict = "Some String";
     HttpResponse userConflictResponse =
         new HttpResponse(userConflict, HttpURLConnection.HTTP_CONFLICT);
     return userConflictResponse;
   }
   // intErrorResponse
   boolean intErrorResponse_condition = true;
   if (intErrorResponse_condition) {
     String intError = "Some String";
     HttpResponse intErrorResponse =
         new HttpResponse(intError, HttpURLConnection.HTTP_INTERNAL_ERROR);
     return intErrorResponse;
   }
   return null;
 }
Beispiel #18
0
 private Double getKelvinsTemp(String cityId) throws Exception, ParseException {
   String url = baseUrl.replaceFirst("CITY_ID", cityId);
   String json = URLConnectionReader.getText(url);
   JSONParser p = new JSONParser(JSONParser.MODE_PERMISSIVE);
   JSONObject o1 = (JSONObject) p.parse(json);
   o1 = (JSONObject) o1.get("main");
   Number kelvins = (Number) o1.get("temp");
   return kelvins.doubleValue();
 }
Beispiel #19
0
  private Pair<String, Class<? extends Tablespace>> extractStorage(Map.Entry<String, Object> entry)
      throws ClassNotFoundException {

    String storageType = entry.getKey();
    JSONObject storageDesc = (JSONObject) entry.getValue();
    String handlerClass = (String) storageDesc.get(KEY_STORAGE_HANDLER);

    return new Pair<String, Class<? extends Tablespace>>(
        storageType, (Class<? extends Tablespace>) Class.forName(handlerClass));
  }
 @Override
 public JSONObject toJSON(Overbook o) {
   JSONObject c = new JSONObject();
   c.put("id", getJSONId());
   c.put("node", toJSON(o.getInvolvedNodes().iterator().next()));
   c.put("rc", o.getResource());
   c.put("ratio", o.getRatio());
   c.put("continuous", o.isContinuous());
   return c;
 }
Beispiel #21
0
 public static void loadSections() {
   if (Utils.configSections == null) {
     JSONObject resultsJSONObject = Utils.getJSON();
     if (resultsJSONObject == null) {
       Synapse.currentEnvironmentState = Synapse.environmentState.JSON_FAILURE;
       return;
     }
     Utils.configSections = (JSONArray) resultsJSONObject.get("sections");
   }
 }
Beispiel #22
0
  public SGeneric(
      JSONObject element, LinearLayout layout, MainActivity.TabSectionFragment fragment) {
    super(element, layout, fragment);

    if (element.containsKey("action")) this.command = (String) element.get("action");
    else throw new IllegalArgumentException("SCheckBox has no action defined");

    if (this.element.containsKey("label")) this.label = Utils.localise(element.get("label"));

    if (element.containsKey("default")) this.original = element.get("default");

    if (element.containsKey("inputType")) this.inputType = (String) element.get("inputType");

    /** Add a description element inside our own with the same JSON object */
    if (element.containsKey("description"))
      descriptionObj = new SDescription(element, layout, fragment);

    if (element.containsKey("title")) titleObj = new STitleBar(element, layout, fragment);

    resumeTask =
        new Runnable() {
          @Override
          public void run() {
            try {
              refreshValue();
            } catch (ElementFailureException e) {
              Utils.createElementErrorView(e);
            }
          }
        };

    ActionValueNotifierHandler.register(this);
  }
  public JSONObject getJSONObject() {
    JSONObject obj = new JSONObject();
    try {
      obj.put("uniqueID", this.uniqueID);
      obj.put("creatorId", Long.toString(this.creatorId));
      obj.put("time", "0");
      obj.put("message", this.message);
    } catch (Exception e) {

    }
    return obj;
  }
Beispiel #24
0
  public static JSONObject getJsonTablespace(Map<String, String> connProperties)
      throws IOException {
    JSONObject configElements = new JSONObject();
    configElements.put(JdbcTablespace.CONFIG_KEY_MAPPED_DATABASE, PgSQLTestServer.DATABASE_NAME);

    JSONObject connPropertiesJson = new JSONObject();
    for (Map.Entry<String, String> entry : connProperties.entrySet()) {
      connPropertiesJson.put(entry.getKey(), entry.getValue());
    }
    configElements.put(JdbcTablespace.CONFIG_KEY_CONN_PROPERTIES, connPropertiesJson);

    return configElements;
  }
Beispiel #25
0
  public SLiveLabel(
      JSONObject element, LinearLayout layout, MainActivity.TabSectionFragment fragment) {
    super(element, layout, fragment);

    if (element.containsKey("action")) this.command = (String) element.get("action");
    else throw new IllegalArgumentException("SSeekBar has no action defined");

    if (element.containsKey("refresh")) {
      refreshInterval = (Integer) element.get("refresh");
      if (refreshInterval != 0 && refreshInterval < 50) refreshInterval = 50;
    }

    if (element.containsKey("style")) style = (String) element.get("style");

    resumeTask =
        new Runnable() {
          @Override
          public void run() {
            try {
              liveLabel.setText(Utils.runCommand(command).replace("@n", "\n"));
              if (refreshInterval > 0) Synapse.handler.postDelayed(this, refreshInterval);
            } catch (Exception e) {
              liveLabel.setText(e.getMessage());
            }
          }
        };

    /** Add a description element inside our own with the same JSON object */
    if (element.containsKey("description"))
      descriptionObj = new SDescription(element, layout, fragment);

    if (element.containsKey("title")) titleObj = new STitleBar(element, layout, fragment);
  }
 private static Entry entryFromJsonObject(JSONObject object) {
   String file = object.get(ManifestConstants.FILE).toString();
   String hash = object.get(ManifestConstants.HASH).toString();
   String time = object.get(ManifestConstants.TIME).toString();
   String size = object.get(ManifestConstants.SIZE).toString();
   String type = object.get(ManifestConstants.TYPE).toString();
   EntryStatus statType = EntryStatus.valueOf(type);
   return new Entry(
       file,
       hash,
       Util.longFromStringWithoutThrow(time),
       Util.longFromStringWithoutThrow(size),
       statType);
 }
Beispiel #27
0
  @Test
  public void Merge2JsonObject() throws ParseException {
    String json1 = "{'car':{'color':'blue'}}";
    String json2 = "{'car':{'size':'3.5m'}}";

    @SuppressWarnings("deprecation")
    JSONParser p = new JSONParser();
    JSONObject o1 = (JSONObject) p.parse(json1);
    JSONObject o2 = (JSONObject) p.parse(json2);

    o1.merge(o2);

    System.out.println(o1);
  }
 public static JSONObject jsonObjectFromManifest(Manifest manifest) {
   JSONObject rootObject = new JSONObject();
   rootObject.put(ManifestConstants.TIME, manifest.getTimestamp());
   rootObject.put(
       ManifestConstants.GUID, manifest.getGuid()); // unique identifier for this manifest.
   rootObject.put(ManifestConstants.URLROOT, manifest.getUrlRoot());
   rootObject.put(ManifestConstants.VERSION, manifest.getVersion());
   // let's get that array
   JSONArray array = new JSONArray();
   for (Entry entry : manifest.getEntries()) {
     array.add(jsonObjectFromEntry(entry));
   }
   rootObject.put(ManifestConstants.ENTRIES, array);
   return rootObject;
 }
  public JSONObject addTestQuestion(JSONRPC2Request req, HttpServletRequest request)
      throws Exception, SQLException {
    JSONObject jsonResult = new JSONObject();

    // set retrievers
    Map<String, Object> params = req.getNamedParams();
    NamedParamsRetriever np = new NamedParamsRetriever(params);
    Map<String, Object> tParams = np.getMap("test");
    NamedParamsRetriever testNp = new NamedParamsRetriever(tParams);
    Map<String, Object> qParams = np.getMap("question");
    NamedParamsRetriever questNp = new NamedParamsRetriever(qParams);
    int tid = testNp.getInt(("id"));
    int qid = questNp.getInt(("id"));

    // load test and question
    MySQLDAO dao = new MySQLDAO();
    Test t = dao.loadTest(tid);
    dao = new MySQLDAO();
    Question q = dao.loadQuestion(qid);

    // load current user
    User u = getCurrentUser(request);

    if (u.getId() == t.getOwnerId()) {
      // check for duplicates
      boolean duplicate = false;
      for (Question quest : t.getQuestions()) {
        if (quest.getId() == qid) {
          duplicate = true;
        }
      }
      if (!duplicate) {
        dao = new MySQLDAO();
        t = dao.saveTestQuestion(t, q);
      }
    } else {
      throw new Exception("no privileges : you do not own this test!");
    }

    // set result
    JSONObject jsonTest = t.toJSONObject();
    JSONObject jsonQuestion = q.toJSONObject();

    jsonResult.put("test", jsonTest);
    jsonResult.put("question", jsonQuestion);

    return jsonResult;
  }
Beispiel #30
0
  @Test
  public void responseCanBeSerialized() {
    // Arrange:
    final JsonSerializer serializer = new JsonSerializer();
    final ErrorResponse response = new ErrorResponse(new TimeInstant(18), "badness", 500);

    // Act:
    response.serialize(serializer);
    final JSONObject jsonObject = serializer.getObject();

    // Assert:
    Assert.assertThat(jsonObject.get("timeStamp"), IsEqual.equalTo(18));
    Assert.assertThat(jsonObject.get("error"), IsEqual.equalTo("Internal Server Error"));
    Assert.assertThat(jsonObject.get("message"), IsEqual.equalTo("badness"));
    Assert.assertThat(jsonObject.get("status"), IsEqual.equalTo(500));
  }