예제 #1
0
  /**
   * 打印支持JSONP格式的结果
   *
   * @param response
   * @param restRequest
   * @param restResponse
   * @throws java.io.IOException
   */
  public static void printJsonForJsonp(
      HttpServletResponse response, RestRequest restRequest, RestResponse restResponse)
      throws IOException {

    PrintWriter out = response.getWriter();
    String jsonString = JSON.toJSONString(restResponse);
    response.setContentType("text/javascript; charset=UTF-8");
    out.print(restRequest.getCallback() + "(" + jsonString + ")");
  }
 @Override
 public ArrayList<RemoteObject> deserializeArray(String queryScope, String input) {
   String bodyFormat = getDeserializationBodyFormat();
   if (XML.equals(bodyFormat)) {
     return deserializeArrayAsXml(queryScope, input);
   } else if (JSON.equals(bodyFormat)) {
     return deserializeArrayAsJson(queryScope, input);
   } else {
     return deserializeArrayAsJson(queryScope, input);
   }
 }
예제 #3
0
  /**
   * gets the path given in database.json and stores it on the Database class
   *
   * @param mainJSON The main json tokener
   */
  public static void initialise(JSONTokener mainJSON) {
    // main.json
    JSONObject mainObj = (new JSONObject(mainJSON)).getJSONObject("main");
    JSONObject settingsObj = mainObj.getJSONObject("settings");
    String databasePath = settingsObj.getString("database");

    // database.json
    JSONObject databaseObj =
        (new JSONObject(JSON.getJSONTokener(databasePath))).getJSONObject("database");

    dbPath = databaseObj.getString("path");

    Debug.println("Database -> " + dbPath);
  }
  @Override
  public RemoteObject deserialize(String queryScope, String input) {
    String bodyFormat = getDeserializationBodyFormat();
    // TODO parse role if auth object
    Parser parser = null;
    if (XML.equals(bodyFormat)) {
      parser = createXmlParser(queryScope, input);
    } else if (JSON.equals(bodyFormat)) {
      parser = createJsonParser(queryScope, input);
    } else {
      parser = createJsonParser(queryScope, input);
    }

    return deserialize(queryScope, parser);
  }
  /**
   * Process HTTP request.
   *
   * @param act Action.
   * @param req Http request.
   * @param res Http response.
   */
  private void processRequest(String act, HttpServletRequest req, HttpServletResponse res) {
    res.setContentType("application/json");
    res.setCharacterEncoding("UTF-8");

    GridRestCommand cmd = command(req);

    if (cmd == null) {
      res.setStatus(HttpServletResponse.SC_BAD_REQUEST);

      return;
    }

    if (!authChecker.apply(req.getHeader("X-Signature"))) {
      res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

      return;
    }

    GridRestResponse cmdRes;

    Map<String, Object> params = parameters(req);

    try {
      GridRestRequest cmdReq = createRequest(cmd, params, req);

      if (log.isDebugEnabled()) log.debug("Initialized command request: " + cmdReq);

      cmdRes = hnd.handle(cmdReq);

      if (cmdRes == null)
        throw new IllegalStateException("Received null result from handler: " + hnd);

      byte[] sesTok = cmdRes.sessionTokenBytes();

      if (sesTok != null) cmdRes.setSessionToken(U.byteArray2HexString(sesTok));

      res.setStatus(HttpServletResponse.SC_OK);
    } catch (Exception e) {
      res.setStatus(HttpServletResponse.SC_OK);

      U.error(log, "Failed to process HTTP request [action=" + act + ", req=" + req + ']', e);

      cmdRes = new GridRestResponse(STATUS_FAILED, e.getMessage());
    } catch (Throwable e) {
      U.error(log, "Failed to process HTTP request [action=" + act + ", req=" + req + ']', e);

      throw e;
    }

    JsonConfig cfg = new GridJettyJsonConfig();

    // Workaround for not needed transformation of string into JSON object.
    if (cmdRes.getResponse() instanceof String)
      cfg.registerJsonValueProcessor(cmdRes.getClass(), "response", SKIP_STR_VAL_PROC);

    if (cmdRes.getResponse() instanceof GridClientTaskResultBean
        && ((GridClientTaskResultBean) cmdRes.getResponse()).getResult() instanceof String)
      cfg.registerJsonValueProcessor(cmdRes.getResponse().getClass(), "result", SKIP_STR_VAL_PROC);

    JSON json;

    try {
      json = JSONSerializer.toJSON(cmdRes, cfg);
    } catch (JSONException e) {
      U.error(log, "Failed to convert response to JSON: " + cmdRes, e);

      json = JSONSerializer.toJSON(new GridRestResponse(STATUS_FAILED, e.getMessage()), cfg);
    }

    try {
      if (log.isDebugEnabled())
        log.debug("Parsed command response into JSON object: " + json.toString(2));

      res.getWriter().write(json.toString());

      if (log.isDebugEnabled())
        log.debug(
            "Processed HTTP request [action=" + act + ", jsonRes=" + cmdRes + ", req=" + req + ']');
    } catch (IOException e) {
      U.error(log, "Failed to send HTTP response: " + json.toString(2), e);
    }
  }
예제 #6
0
  public static String toJsonString(Object obj) {

    return JSON.toJSONString(obj, SerializerFeature.WriteDateUseDateFormat);
  }
예제 #7
0
 public BPRankObj getBPRankList(String aid) {
   String json = HttpUtils.getHttpsCommonContent(BiliUtils.getBpList(aid));
   BPRankObj obj = JSON.parseObject(json, BPRankObj.class);
   return obj;
 }
  @Override
  public String serialize() {
    String bodyFormat = getSerializationBodyFormat();
    SerializerBuilder builder = null;

    String recordSelector = HttpAdapter.createResponseWrangling(this).getRecordSelector();
    if (XML.equals(bodyFormat)) {
      builder = new XmlSerializer.XmlSerializerBuilder(recordSelector);
    } else if (JSON.equals(bodyFormat)) {
      builder = new JsonSerializer.JsonSerializerBuilder(recordSelector);
    } else if (FORM_ENCODED.equals(bodyFormat)) {
      builder = new FormEncodedSerializer.FormEncodedSerializerBuilder(recordSelector);
    }

    final RouterAdapter routerAdapter = RemoteRailsConfig.getRouterAdapterByClass(this.getClass());
    if (builder != null && routerAdapter != null) {

      builder.addFieldMapping(
          ((HttpAdapter) routerAdapter)
              .getConfigurationsAsConfiguration("POST")
              .getResponseRemoteFieldName("id"),
          "id");

      builder.addFieldMapping(
          ((HttpAdapter) routerAdapter)
              .getConfigurationsAsConfiguration("POST")
              .getResponseRemoteFieldName("comments"),
          "comments");

      builder.addFieldMapping(
          ((HttpAdapter) routerAdapter)
              .getConfigurationsAsConfiguration("POST")
              .getResponseRemoteFieldName("currency"),
          "currency");

      builder.addFieldMapping(
          ((HttpAdapter) routerAdapter)
              .getConfigurationsAsConfiguration("POST")
              .getResponseRemoteFieldName("last_price"),
          "last_price");

      builder.addFieldMapping(
          ((HttpAdapter) routerAdapter)
              .getConfigurationsAsConfiguration("POST")
              .getResponseRemoteFieldName("last_qty"),
          "last_qty");

      builder.addFieldMapping(
          ((HttpAdapter) routerAdapter)
              .getConfigurationsAsConfiguration("POST")
              .getResponseRemoteFieldName("price"),
          "price");

      builder.addFieldMapping(
          ((HttpAdapter) routerAdapter)
              .getConfigurationsAsConfiguration("POST")
              .getResponseRemoteFieldName("quantity"),
          "quantity");

      builder.addFieldMapping(
          ((HttpAdapter) routerAdapter)
              .getConfigurationsAsConfiguration("POST")
              .getResponseRemoteFieldName("side"),
          "side");

      builder.addFieldMapping(
          ((HttpAdapter) routerAdapter)
              .getConfigurationsAsConfiguration("POST")
              .getResponseRemoteFieldName("status"),
          "status");

      builder.addFieldMapping(
          ((HttpAdapter) routerAdapter)
              .getConfigurationsAsConfiguration("POST")
              .getResponseRemoteFieldName("symbol"),
          "symbol");

      builder.addFieldMapping(
          ((HttpAdapter) routerAdapter)
              .getConfigurationsAsConfiguration("POST")
              .getResponseRemoteFieldName("transact_time"),
          "transact_time");

      return builder.create().serialize(this);
    } else {
      return super.serialize();
    }
  }