示例#1
0
  /**
   * Write the contents of the JSONArray as JSON text to a writer. For compactness, no whitespace is
   * added.
   *
   * <p>Warning: This method assumes that the data structure is acyclical.
   *
   * @param indentFactor The number of spaces to add to each level of indentation.
   * @param indent The indention of the top level.
   * @return The writer.
   * @throws JSONException
   */
  Writer write(Writer writer, int indentFactor, int indent) throws JSONException {
    try {
      boolean commanate = false;
      int length = this.length();
      writer.write('[');

      if (length == 1) {
        JSONObject.writeValue(writer, this.myArrayList.get(0), indentFactor, indent);
      } else if (length != 0) {
        final int newindent = indent + indentFactor;

        for (int i = 0; i < length; i += 1) {
          if (commanate) {
            writer.write(',');
          }
          if (indentFactor > 0) {
            writer.write('\n');
          }
          JSONObject.indent(writer, newindent);
          JSONObject.writeValue(writer, this.myArrayList.get(i), indentFactor, newindent);
          commanate = true;
        }
        if (indentFactor > 0) {
          writer.write('\n');
        }
        JSONObject.indent(writer, indent);
      }
      writer.write(']');
      return writer;
    } catch (IOException e) {
      throw new JSONException(e);
    }
  }
示例#2
0
  private JSONObject castEventToJSONObj(Event event) {
    JSONObject jsonObj = new JSONObject();

    DateFormat dfDeadline = new SimpleDateFormat("yyyy-M-dd");
    Date deadLine = null;

    try {
      deadLine = dfDeadline.parse("1970-01-01");
    } catch (ParseException e) {
      e.printStackTrace();
    }

    try {
      jsonObj.put("name", event.getName());
      jsonObj.put("description", event.getDescription());
      jsonObj.put("category", event.getCategory());
      jsonObj.put("status", event.getStatus());
      jsonObj.put("location", event.getLocation());

      if (event.getCategory().equals(GenericEvent.Category.DEADLINE)) {
        jsonObj.put("startTime", deadLine);
        jsonObj.put("endTime", event.getEndTime());
      } else {
        jsonObj.put("startTime", event.getStartTime());
        jsonObj.put("endTime", event.getEndTime());
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }

    return jsonObj;
  }
示例#3
0
  private Event castJSONObjToEvent(JSONObject jsonObj) {
    Event event = new Event();
    DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH);

    try {
      String startTime = jsonObj.get("startTime").toString();
      String endTime = jsonObj.get("endTime").toString();

      event.setName(jsonObj.getString("name"));
      event.setDescription(jsonObj.getString("description"));
      event.setCategory(getCategory(jsonObj));
      event.setStatus(getStatus(jsonObj));
      event.setLocation(jsonObj.getString("location"));

      if (event.getCategory().equals(GenericEvent.Category.FLOATING)) {
        // doesn't set start time and end time
      } else {
        event.setStartTime(df.parse(startTime));
        event.setEndTime(df.parse(endTime));
      }

    } catch (JSONException e2) {
      e2.printStackTrace();
    } catch (ParseException e1) {
      e1.printStackTrace();
    }

    return event;
  }
示例#4
0
 public static String getJSONValue(JSONObject json, String key) {
   try {
     if (json.has(key)) return (json.getString(key));
     else return "NULL";
   } catch (JSONException e) {
     return "NULL";
   }
 }
示例#5
0
 Resolution(JSONObject res) {
   try {
     width = res.getInt("width");
     height = res.getInt("height");
   } catch (JSONException ex) {
     Logger.getLogger(DisplayParameters.class.getName()).log(Level.SEVERE, null, ex);
   }
 }
示例#6
0
 private GenericEvent.Category getCategory(JSONObject jsonObj) throws JSONException {
   if (jsonObj.get("category").equals(Constant.CATEGORY_DEADLINE)) {
     return GenericEvent.Category.DEADLINE;
   } else if (jsonObj.get("category").equals(Constant.CATEGORY_EVENT)) {
     return GenericEvent.Category.EVENT;
   } else {
     return GenericEvent.Category.FLOATING;
   }
 }
示例#7
0
 Eye(JSONObject eye) {
   try {
     center_proj_x = (float) eye.getDouble("center_proj_x");
     center_proj_y = (float) eye.getDouble("center_proj_y");
     rotate_180 = eye.getInt("rotate_180");
   } catch (JSONException ex) {
     Logger.getLogger(DisplayParameters.class.getName()).log(Level.SEVERE, null, ex);
   }
 }
 public void update_get_open_orders() {
   try {
     JSONObject jo =
         new JSONObject(query("getInfo", new HashMap<String, String>())).getJSONObject("return");
     currentOpenOrders = jo.getInt("open_orders");
   } catch (JSONException e) {
     utils.logger.log(true, e.getMessage());
     currentOpenOrders = 0;
   }
 }
 public void UpdateUSDFunds() {
   try {
     JSONObject jo =
         new JSONObject(query("getInfo", new HashMap<String, String>())).getJSONObject("return");
     USDFunds = new BigDecimal(jo.getJSONObject("funds").getDouble("usd"));
   } catch (JSONException e) {
     utils.logger.log(true, e.getMessage());
     USDFunds = new BigDecimal(0);
   }
 }
示例#10
0
 /**
  * Produce a JSONObject by combining a JSONArray of names with the values of this JSONArray.
  *
  * @param names A JSONArray containing a list of key strings. These will be paired with the
  *     values.
  * @return A JSONObject, or null if there are no names or if this JSONArray has no values.
  * @throws JSONException If any of the names are null.
  */
 public JSONObject toJSONObject(JSONArray names) throws JSONException {
   if (names == null || names.length() == 0 || this.length() == 0) {
     return null;
   }
   JSONObject jo = new JSONObject();
   for (int i = 0; i < names.length(); i += 1) {
     jo.put(names.getString(i), this.opt(i));
   }
   return jo;
 }
示例#11
0
 /**
  * Converts a property file object into a JSONObject. The property file object is a table of name
  * value pairs.
  *
  * @param properties java.util.Properties
  * @return JSONObject
  * @throws JSONException
  */
 public static JSONObject toJSONObject(Properties properties) throws JSONException {
   JSONObject jo = new JSONObject();
   if (properties != null && !properties.isEmpty()) {
     Enumeration<?> enumProperties = properties.propertyNames();
     while (enumProperties.hasMoreElements()) {
       String name = (String) enumProperties.nextElement();
       jo.put(name, properties.getProperty(name));
     }
   }
   return jo;
 }
示例#12
0
 /**
  * Converts the JSONObject into a property file object.
  *
  * @param jo JSONObject
  * @return java.util.Properties
  * @throws JSONException
  */
 public static Properties toProperties(JSONObject jo) throws JSONException {
   Properties properties = new Properties();
   if (jo != null) {
     Iterator<String> keys = jo.keys();
     while (keys.hasNext()) {
       String name = keys.next();
       properties.put(name, jo.getString(name));
     }
   }
   return properties;
 }
示例#13
0
 private GenericEvent.Status getStatus(JSONObject jsonObj) throws JSONException {
   if (jsonObj.get("status").equals("COMPLETE")) {
     return GenericEvent.Status.COMPLETE;
   } else if (jsonObj.get("status").equals("INCOMPLETE")) {
     return GenericEvent.Status.INCOMPLETE;
   } else if (jsonObj.get("status").equals("UNDETERMINED")) {
     return GenericEvent.Status.UNDETERMINED;
   } else {
     return GenericEvent.Status.NULL;
   }
 }
示例#14
0
 public void parse(String displayParameters) throws JSONException {
   jsonObject = new JSONObject(displayParameters).getJSONObject("hmd");
   JSONArray jsonEyes = (JSONArray) jsonObject.get("eyes");
   eyes = new Eye[jsonEyes.length()];
   for (int i = 0; i < jsonEyes.length(); i++) {
     eyes[i] = new Eye(jsonEyes.getJSONObject(i));
   }
   JSONArray jsonRes = (JSONArray) jsonObject.get("resolutions");
   resolutions = new Resolution[jsonRes.length()];
   for (int i = 0; i < jsonRes.length(); i++) {
     resolutions[i] = new Resolution(jsonRes.getJSONObject(i));
   }
 }
 @Override
 public void doHook() throws Exception {
   JSONObject obj = new JSONObject();
   try {
     obj.put("opCanName", opCanName);
     obj.put("opName", opName);
     obj.put("jobID", jobID);
     obj.put("ipAddress", ipAddress);
   } catch (JSONException e) {
     e.printStackTrace();
   }
   HttpPostJSON(serviceURL, obj);
 }
示例#16
0
  public State readStorage(String fileName) {
    String line = null;
    State state = new State();
    String jsonData = "";

    try {
      FileReader fr = new FileReader(fileName);
      BufferedReader br = new BufferedReader(fr);

      while ((line = br.readLine()) != null) {
        jsonData += line + "\n";
      }

      if (jsonData.contains("{")) {
        JSONObject object = new JSONObject(jsonData);

        JSONArray arrCompleted = object.getJSONArray("completed");
        JSONArray arrIncompleted = object.getJSONArray("incompleted");
        JSONArray arrUndetermined = object.getJSONArray("undetermined");
        JSONArray arrReserved = object.getJSONArray("reserved");

        for (int i = 0; i < arrCompleted.length(); i++) {
          Event e = castJSONObjToEvent(arrCompleted.getJSONObject(i));
          state.completedEvents.add(e);
        }
        for (int i = 0; i < arrIncompleted.length(); i++) {
          Event e = castJSONObjToEvent(arrIncompleted.getJSONObject(i));
          state.incompletedEvents.add(e);
        }
        for (int i = 0; i < arrUndetermined.length(); i++) {
          ReservedEvent e = castJSONObjToFloatingEvent(arrUndetermined.getJSONObject(i));
          state.undeterminedEvents.add(e);
        }
        for (int i = 0; i < arrReserved.length(); i++) {
          ReservedEvent e = castJSONObjToReservedEvent(arrReserved.getJSONObject(i));
          state.reservedEvents.add(e);
        }
      }
    } catch (FileNotFoundException ex) {
      System.out.println("Unable to open file '" + fileName + "'");
    } catch (IOException ex) {
      ex.printStackTrace();
    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    updatedDisplayedEvents(state);

    return state;
  }
示例#17
0
  /**
   * Convert an HTTP header string into a JSONObject. It can be a request header or a response
   * header. A request header will contain
   *
   * <pre>{
   *    Method: "POST" (for example),
   *    "Request-URI": "/" (for example),
   *    "HTTP-Version": "HTTP/1.1" (for example)
   * }</pre>
   *
   * A response header will contain
   *
   * <pre>{
   *    "HTTP-Version": "HTTP/1.1" (for example),
   *    "Status-Code": "200" (for example),
   *    "Reason-Phrase": "OK" (for example)
   * }</pre>
   *
   * In addition, the other parameters in the header will be captured, using the HTTP field names as
   * JSON names, so that
   *
   * <pre>
   *    Date: Sun, 26 May 2002 18:06:04 GMT
   *    Cookie: Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s
   *    Cache-Control: no-cache</pre>
   *
   * become
   *
   * <pre>{...
   *    Date: "Sun, 26 May 2002 18:06:04 GMT",
   *    Cookie: "Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s",
   *    "Cache-Control": "no-cache",
   * ...}</pre>
   *
   * It does no further checking or conversion. It does not parse dates. It does not do '%'
   * transforms on URLs.
   *
   * @param string An HTTP header string.
   * @return A JSONObject containing the elements and attributes of the XML string.
   * @throws JSONException
   */
  public static JSONObject toJSONObject(String string) throws JSONException {
    JSONObject jo = new JSONObject();
    HTTPTokener x = new HTTPTokener(string);
    String token;

    token = x.nextToken();
    if (token.toUpperCase().startsWith("HTTP")) {

      // Response

      jo.put("HTTP-Version", token);
      jo.put("Status-Code", x.nextToken());
      jo.put("Reason-Phrase", x.nextTo('\0'));
      x.next();

    } else {

      // Request

      jo.put("Method", token);
      jo.put("Request-URI", x.nextToken());
      jo.put("HTTP-Version", x.nextToken());
    }

    // Fields

    while (x.more()) {
      String name = x.nextTo(':');
      x.next(':');
      jo.put(name, x.nextTo('\0'));
      x.next();
    }
    return jo;
  }
示例#18
0
  public void recognizeFromFileExplicit() throws Exception {
    File pcmFile = new File(testFileName);
    HttpURLConnection conn = (HttpURLConnection) new URL(serverURL).openConnection();

    // construct params
    JSONObject params = new JSONObject();
    params.put("format", "wav");
    params.put("rate", 16000);
    params.put("channel", "1");
    params.put("token", token);
    params.put("cuid", cuid);
    params.put("len", pcmFile.length());
    params.put("speech", DatatypeConverter.printBase64Binary(loadFile(pcmFile)));

    // add request header
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");

    conn.setDoInput(true);
    conn.setDoOutput(true);

    // send request
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(params.toString());
    wr.flush();
    wr.close();

    printResponse(conn);
  }
示例#19
0
  /**
   * Creating Visitor object with collected data.
   *
   * @param json JSONObject with visitor's data.
   */
  public Visitor(JSONObject json) {
    /** This string is made of all information about visitor. */
    String userDataStringForMD5 = "";

    String userAgent = json.getString("userAgent");
    userDataStringForMD5 += userAgent;
    this.userAgent = userAgent;

    JSONArray headers = json.getJSONArray("headers");
    JSONArray headersArray = new JSONArray();
    for (int i = 0; i < headers.length(); i++) {
      String head = headers.getString(i).replace("\"", "").replace("{", "").replace("}", "");
      String[] splitLine = head.split(":");
      userDataStringForMD5 += splitLine[1];
      headersArray.put(splitLine[1]);
    }
    this.headers = headers;

    JSONArray screen = json.getJSONArray("screen");
    JSONArray screenArray = new JSONArray();
    for (int i = 0; i < screen.length(); i++) {
      String scr = screen.getString(i).replace("\"", "").replace("{", "").replace("}", "");
      String[] splitLine = scr.split(":");
      userDataStringForMD5 += splitLine[1];
      screenArray.put(splitLine[1]);
    }
    this.screen = screen;

    int timezone = json.getInt("timezone");
    userDataStringForMD5 += timezone;
    this.timezone = timezone;

    boolean enabledCookies = json.getBoolean("enabledCookies");
    userDataStringForMD5 += enabledCookies;
    this.enabledCookies = enabledCookies;

    JSONArray plugins = json.getJSONArray("plugins");
    JSONArray pluginsArray = new JSONArray();
    for (int i = 0; i < plugins.length(); i++) {
      String plugin = plugins.getString(i).replace("\"", "").replace("{", "").replace("}", "");
      String[] splitLine = plugin.split(":");
      userDataStringForMD5 += splitLine[1];
      pluginsArray.put(splitLine[1]);
    }
    this.plugins = plugins;

    JSONArray fonts = json.getJSONArray("fonts");
    JSONArray fontsArray = new JSONArray();
    for (int i = 0; i < fonts.length(); i++) {
      String font = fonts.getString(i).replace("\"", "").replace("{", "").replace("}", "");
      String[] splitLine = font.split(":");
      userDataStringForMD5 += splitLine[1];
      fontsArray.put(splitLine[1]);
    }
    this.fonts = fonts;

    this.md5Id = json.getString("cookiesId");

    this.md5Data = createMD5(userDataStringForMD5);
  }
示例#20
0
  private ReservedEvent castJSONObjToFloatingEvent(JSONObject jsonObj) {
    ReservedEvent event = new ReservedEvent();
    try {
      event.setName(jsonObj.getString("name"));
      event.setDescription(jsonObj.getString("description"));
      event.setCategory(getCategory(jsonObj));
      event.setStatus(getStatus(jsonObj));
      event.setLocation(jsonObj.getString("location"));

    } catch (JSONException e2) {
      e2.printStackTrace();
    }

    return event;
  }
示例#21
0
 /**
  * Get the enum value associated with an index.
  *
  * @param clazz The type of enum to retrieve.
  * @param index The index must be between 0 and length() - 1.
  * @return The enum value at the index location
  * @throws JSONException if the key is not found or if the value cannot be converted to an enum.
  */
 public <E extends Enum<E>> E getEnum(Class<E> clazz, int index) throws JSONException {
   E val = optEnum(clazz, index);
   if (val == null) {
     // JSONException should really take a throwable argument.
     // If it did, I would re-implement this with the Enum.valueOf
     // method and place any thrown exception in the JSONException
     throw new JSONException(
         "JSONObject["
             + JSONObject.quote(Integer.toString(index))
             + "] is not an enum of type "
             + JSONObject.quote(clazz.getSimpleName())
             + ".");
   }
   return val;
 }
示例#22
0
 /**
  * Construct a JSONArray from a Collection.
  *
  * @param collection A Collection.
  */
 public JSONArray(Collection<Object> collection) {
   this.myArrayList = new ArrayList<Object>();
   if (collection != null) {
     Iterator<Object> iter = collection.iterator();
     while (iter.hasNext()) {
       this.myArrayList.add(JSONObject.wrap(iter.next()));
     }
   }
 }
示例#23
0
 /**
  * Construct a JSONArray from an array
  *
  * @throws JSONException If not an array.
  */
 public JSONArray(Object array) throws JSONException {
   this();
   if (array.getClass().isArray()) {
     int length = Array.getLength(array);
     for (int i = 0; i < length; i += 1) {
       this.put(JSONObject.wrap(Array.get(array, i)));
     }
   } else {
     throw new JSONException("JSONArray initial value should be a string or collection or array.");
   }
 }
示例#24
0
  /**
   * Make a string from the contents of this JSONArray. The <code>separator</code> string is
   * inserted between each element. Warning: This method assumes that the data structure is
   * acyclical.
   *
   * @param separator A string that will be inserted between the elements.
   * @return a string.
   * @throws JSONException If the array contains an invalid number.
   */
  public String join(String separator) throws JSONException {
    int len = this.length();
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < len; i += 1) {
      if (i > 0) {
        sb.append(separator);
      }
      sb.append(JSONObject.valueToString(this.myArrayList.get(i)));
    }
    return sb.toString();
  }
示例#25
0
 public void update() {
   MarketModel btce = new MarketModel();
   URL url;
   try {
     url = new URL(tickerurl);
     HttpURLConnection connection = (HttpURLConnection) url.openConnection();
     connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; Java Test client)");
     JSONObject jo =
         new JSONObject(new JSONTokener(connection.getInputStream())).getJSONObject("ticker");
     btce.setHigh(jo.getDouble("high"));
     btce.setLow(jo.getDouble("low"));
     btce.setAvg(jo.getDouble("avg"));
     btce.setLast(jo.getDouble("last"));
     btce.setBuy(jo.getDouble("buy"));
     btce.setSell(jo.getDouble("sell"));
   } catch (MalformedURLException e) {
     utils.logger.log(true, e.getMessage());
     currentMarketModel = null;
     return;
   } catch (JSONException e) {
     utils.logger.log(true, e.getMessage());
     currentMarketModel = null;
     return;
   } catch (IOException e) {
     utils.logger.log(true, e.getMessage());
     currentMarketModel = null;
     return;
   }
   currentMarketModel = btce;
 }
示例#26
0
 public void submit_order(String type, String amount, String price) {
   super.submit_order(type, amount, price);
   HashMap<String, String> args = new HashMap<String, String>();
   args.put("pair", "btc_usd");
   if (type.equals("bid")) {
     args.put("type", "buy");
   } else if (type.equals("ask")) {
     args.put("type", "sell");
   }
   args.put("rate", price);
   args.put("amount", amount);
   JSONObject reponse;
   try {
     reponse = new JSONObject(query("Trade", args));
     if (reponse.has("success") && reponse.getInt("success") == 1) {
       settings.lasttrade.setOrderid(
           Integer.toString(reponse.getJSONObject("return").getInt("order_id")));
     }
   } catch (JSONException e) {
     reponse = new JSONObject();
   }
   utils.logger.log(false, reponse.toString());
   needsToUpdateBlances = true;
 }
示例#27
0
 /**
  * Put or replace an object value in the JSONArray. If the index is greater than the length of the
  * JSONArray, then null elements will be added as necessary to pad it out.
  *
  * @param index The subscript.
  * @param value The value to put into the array. The value should be a Boolean, Double, Integer,
  *     JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object.
  * @return this.
  * @throws JSONException If the index is negative or if the the value is an invalid number.
  */
 public JSONArray put(int index, Object value) throws JSONException {
   JSONObject.testValidity(value);
   if (index < 0) {
     throw new JSONException("JSONArray[" + index + "] not found.");
   }
   if (index < this.length()) {
     this.myArrayList.set(index, value);
   } else {
     while (index != this.length()) {
       this.put(JSONObject.NULL);
     }
     this.put(value);
   }
   return this;
 }
示例#28
0
  private JSONObject castFloatingEventToJSONObj(ReservedEvent event) {
    JSONObject jsonObj = new JSONObject();

    try {
      jsonObj.put("name", event.getName());
      jsonObj.put("description", event.getDescription());
      jsonObj.put("category", event.getCategory());
      jsonObj.put("status", event.getStatus());
      jsonObj.put("location", event.getLocation());
      jsonObj.put("startTime", "");
      jsonObj.put("endTime", "");
    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return jsonObj;
  }
  public void HttpPostJSON(String url, JSONObject js) throws IOException {
    String content = js.toString();

    URLConnection conn = new URL(url).openConnection();
    conn.setUseCaches(false);
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setRequestProperty("Content-Length", "" + content.length());
    conn.setRequestProperty("Content-Type", "application/json");

    OutputStream out = conn.getOutputStream();
    out.write(content.getBytes());
    out.close();

    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String response = br.readLine();
    br.close();
    if (!response.equals(success))
      throw new IOException("Error when posting update to .NET service");
  }
示例#30
0
  public void stateToStorage(State completeState, String fileName) {
    clearFile(fileName);

    JSONArray arrCompleted = new JSONArray();
    JSONArray arrIncompleted = new JSONArray();
    JSONArray arrUndetermined = new JSONArray();
    JSONArray arrReserved = new JSONArray();

    for (Event e : completeState.completedEvents) {
      JSONObject object = new JSONObject();
      object = castEventToJSONObj(e);
      arrCompleted.put(object);
    }
    for (Event e : completeState.incompletedEvents) {
      JSONObject object = new JSONObject();
      object = castEventToJSONObj(e);
      arrIncompleted.put(object);
    }
    for (ReservedEvent e : completeState.undeterminedEvents) {
      JSONObject object = new JSONObject();
      object = castFloatingEventToJSONObj(e);
      arrUndetermined.put(object);
    }
    for (ReservedEvent e : completeState.reservedEvents) {
      JSONObject object = new JSONObject();
      object = castReservedEventToJSONObj(e);
      arrReserved.put(object);
    }

    JSONObject o = new JSONObject();
    try {
      o.put("completed", arrCompleted);
      o.put("incompleted", arrIncompleted);
      o.put("undetermined", arrUndetermined);
      o.put("reserved", arrReserved);
    } catch (JSONException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }

    try {
      FileWriter fw = new FileWriter(fileName, true);
      PrintWriter pw = new PrintWriter(fw);
      pw.println(o.toString());
      pw.close();
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }