private MonsterModel parseMonsterFromObject(final JSONObject cardResult) throws JSONException {
    MyLog.entry();

    // "cuid": 1, "exp": 15939, "lv": 16, "slv": 1, "mcnt": 11, "no": 3, "plus": [0, 0, 0, 0]
    final MonsterModel monster = new MonsterModel();
    monster.setExp(cardResult.getLong("exp"));
    monster.setLevel(cardResult.getInt("lv"));
    monster.setSkillLevel(cardResult.getInt("slv"));
    final int origId = cardResult.getInt("no");
    int idJp = -1;
    try {
      idJp = idConverter.getMonsterRefIdByCapturedId(origId);
    } catch (UnknownMonsterException e) {
      MyLog.warn(e.getMessage());
    }
    monster.setIdJp(idJp);
    final JSONArray plusResults = cardResult.getJSONArray("plus");
    monster.setPlusHp(plusResults.getInt(0));
    monster.setPlusAtk(plusResults.getInt(1));
    monster.setPlusRcv(plusResults.getInt(2));
    monster.setAwakenings(plusResults.getInt(3));
    // TODO set latent awakenings, but I don't know where this type of card data comes up

    MyLog.exit();
    return monster;
  }
예제 #2
0
  /**
   * Executes the request and returns PluginResult.
   *
   * @param action The action to execute.
   * @param args JSONArry of arguments for the plugin.
   * @param callbackId The callback id used when calling back into JavaScript.
   * @return A PluginResult object with a status and message.
   */
  public PluginResult execute(String action, JSONArray args, String callbackId) {
    PluginResult.Status status = PluginResult.Status.OK;
    String result = "";
    this.callbackId = callbackId;

    try {
      if (action.equals("takePicture")) {
        int destType = DATA_URL;
        if (args.length() > 1) {
          destType = args.getInt(1);
        }
        int srcType = CAMERA;
        if (args.length() > 2) {
          srcType = args.getInt(2);
        }
        if (srcType == CAMERA) {
          this.takePicture(args.getInt(0), destType);
        } else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
          this.getImage(srcType, destType);
        }
        PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
        r.setKeepCallback(true);
        return r;
      }
      return new PluginResult(status, result);
    } catch (JSONException e) {
      e.printStackTrace();
      return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
    }
  }
예제 #3
0
  public static void main2(String[] args) throws Exception {
    Map map = new LinkedHashMap();
    map.put("kind", 1);
    map.put("PreParams", 2);
    map.put("HAParams", 3);
    List l1 = new LinkedList();
    int[] k = {3, 1, 80};
    l1.add(k);
    int[] t = {8, -1, 20};
    l1.add(t);
    map.put("DataList", l1);
    map.put("ends", "ends");

    JSONObject jo = new JSONObject(map);
    JSONArray ja = new JSONArray();

    ja.put(map);
    ja.put(map);
    System.out.println(ja.toString());

    String s = jo.toString();
    System.out.println(s);

    String a = FilePlus.ReadTextFileToString("bin/conf.json");

    System.out.println(a);

    JSONObject jo2 = new JSONObject(a);
    //		Map map2 = (Map) jo2.get("value");
    ja = jo2.getJSONArray("DataLists");
    JSONArray ja2 = ja.getJSONArray(0);
    System.out.println(ja2.getInt(0));
    System.out.println(ja2.getInt(1));
    System.out.println(ja2.getInt(2));
  }
 @Override
 public boolean execute(String action, JSONArray args, CallbackContext callbackContext)
     throws JSONException {
   PluginResult.Status status = PluginResult.Status.OK;
   String result = "";
   this.callbackContext = callbackContext;
   try {
     if (action.equals("takePicture")) {
       this.targetHeight = 0;
       this.targetWidth = 0;
       this.mQuality = 80;
       this.targetHeight = args.getInt(4);
       this.targetWidth = args.getInt(3);
       this.mQuality = args.getInt(0);
       this.takePicture();
       PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
       r.setKeepCallback(true);
       callbackContext.sendPluginResult(r);
       return true;
     }
     return false;
   } catch (JSONException e) {
     e.printStackTrace();
     callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
     return true;
   }
 }
예제 #5
0
 public List<Object> parseJSONArray(JSONArray values, Table table) throws ParseException {
   List<Object> parsedValues = new ArrayList<>();
   for (int i = 0; i < table.getColumnsCount(); i++) {
     Class<?> type = table.getColumnType(i);
     Object val = values.get(i);
     if (val.equals(null)) {
       parsedValues.add(null);
     } else if (type == Integer.class && val.getClass() == Integer.class) {
       parsedValues.add(values.getInt(i));
     } else if (type == Long.class
         && (val.getClass() == Long.class || val.getClass() == Integer.class)) {
       parsedValues.add(values.getLong(i));
     } else if (type == Byte.class && val.getClass() == Integer.class) {
       Integer a = values.getInt(i);
       parsedValues.add(a.byteValue());
     } else if (type == Float.class && val.getClass() == Double.class) {
       Double a = values.getDouble(i);
       parsedValues.add(a.floatValue());
     } else if (type == Double.class && val.getClass() == Double.class) {
       parsedValues.add(values.getDouble(i));
     } else if (type == Boolean.class && val.getClass() == Boolean.class) {
       parsedValues.add(values.getBoolean(i));
     } else if (type == String.class && val.getClass() == String.class) {
       parsedValues.add(val);
     } else {
       throw new ParseException("types mismatch", 0);
     }
   }
   return parsedValues;
 }
  private PADCapturedFriendModel parseFriend(final JSONArray friendResult) throws JSONException {
    MyLog.entry();

    // [4, 333300602, "NeraudMule", 17, 1, "140829151957", 9, 29, 6, 1, 0, 0, 0, 0, 2, 15, 1, 0, 0,
    // 0, 0, 2, 15, 1, 0, 0, 0, 0]
    // New [5, 329993422, "HFR|Neraud", 292, 1, "150613152858", 48, 50, 6, 1, 0, 0, 0, 0, 0, 1422,
    // 99, 1, 13, 12, 9, 6, 0, 1217, 99, 6, 99, 99, 99, 6, 0]
    final PADCapturedFriendModel friend = new PADCapturedFriendModel();
    // index 0 could be the version number for the friend struct
    // version 7 added skill inheritance?
    friend.setId(friendResult.getLong(1));
    friend.setName(friendResult.getString(2));
    friend.setRank(friendResult.getInt(3));
    friend.setStartingColor(StartingColor.valueByCode(friendResult.getInt(4)));
    final String lastActivityDateString = friendResult.getString(5);
    try {
      final DateFormat parseFormat = new SimpleDateFormat("yyMMddHHmmss");
      parseFormat.setTimeZone(region.getTimeZone());
      final Date lastActivityDate = parseFormat.parse(lastActivityDateString);
      friend.setLastActivityDate(lastActivityDate);
    } catch (ParseException e) {
      MyLog.warn("error parsing lastActivityDate : " + e.getMessage());
    }

    final BaseMonsterStatsModel leader1 = extractFriendLeader(friendResult, 16);
    friend.setLeader1(leader1);

    final BaseMonsterStatsModel leader2 = extractFriendLeader(friendResult, 26);
    friend.setLeader2(leader2);

    MyLog.exit();
    return friend;
  }
예제 #7
0
 private void insertTable(JSONObject j) throws Exception {
   try {
     JSONArray jsonArray = j.getJSONArray("insert");
     for (int l = 0; l < jsonArray.length(); l++) {
       String table = j.getString("table"); // 新增至哪個資料表
       JSONArray columns = j.getJSONArray("columns"); // 欄位
       JSONArray values = jsonArray.getJSONArray(l); // 值
       if (columns.length() != values.length()) // 如果值跟欄位不相符 執行下一筆
       {
         continue;
       }
       // ===============是否重複================================================
       JSONObject temp = new JSONObject();
       temp.put(
           "sqlCommand",
           "select * from "
               + table
               + " where keyword='"
               + jsonArray.getJSONArray(l).get(0).toString()
               + "'");
       temp.put("keys", j.getJSONArray("columns"));
       JSONObject ifExist = SelectKeyword(temp);
       String insertdbSQL;
       if (ifExist != null) {
         System.out.println(ifExist);
         JSONArray oldV = ifExist.getJSONArray("values");
         insertdbSQL = "update ";
         insertdbSQL = insertdbSQL + table + " set ";
         int i;
         for (i = 1; i < columns.length() - 1; i++) {
           String v = String.valueOf(values.getInt(i) + oldV.getInt(i));
           insertdbSQL = insertdbSQL + columns.get(i).toString() + "=" + v + ",";
         }
         String v = String.valueOf(values.getInt(i) + oldV.getInt(i));
         insertdbSQL = insertdbSQL + columns.get(i).toString() + "=" + v + " where ";
         insertdbSQL = insertdbSQL + "seg_dic_id=" + ifExist.getString("seg_dic_id");
       } else {
         insertdbSQL = "insert into ";
         insertdbSQL = insertdbSQL + table + "(";
         int i;
         for (i = 0; i < columns.length() - 1; i++) {
           insertdbSQL = insertdbSQL + columns.get(i).toString() + ",";
         }
         insertdbSQL = insertdbSQL + columns.get(i).toString() + ") VALUES (";
         for (i = 0; i < values.length() - 1; i++) {
           insertdbSQL = insertdbSQL + "'" + values.get(i).toString() + "'" + ",";
         }
         insertdbSQL = insertdbSQL + "'" + values.get(i).toString() + "'" + ")";
       }
       System.out.println(insertdbSQL);
       pst = con.prepareStatement(insertdbSQL);
       pst.executeUpdate();
     }
   } catch (SQLException e) {
     System.out.println("InsertDB Exception :" + e.toString());
   } finally {
     Close();
   }
 }
예제 #8
0
  /**
   * Parses the supplied JSON string and adds the extracted ratings to the supplied {@link AppStats}
   * object
   *
   * @param json
   * @param stats
   * @throws JSONException
   */
  static void parseRatings(String json, AppStats stats) throws JSONException {
    // Extract just the array with the values
    JSONArray values = new JSONObject(json).getJSONArray("result").getJSONArray(1).getJSONArray(0);

    // Ratings are at index 2 - 6
    stats.setRating(
        values.getInt(2), values.getInt(3), values.getInt(4), values.getInt(5), values.getInt(6));
  }
  private void analyzeJsonLossValue(JSONObject lossValueJsonObject) {
    try {
      String messageString = lossValueJsonObject.getString("message");
      String errorString = lossValueJsonObject.getString("error_code");

      // 网络获取失败
      if (!errorString.equals(PROTOCOL_QUERYESUCCESS_FLAG)) {
        Message msg = new Message();

        Bundle bundle = new Bundle();
        bundle.putString("msg", messageString);
        msg.setData(bundle);

        msg.arg1 = GET_LOSSVALUE_ERROR;
      }
      // 网络获取成功,解析Json数据
      else {
        JSONArray lossValueArray = lossValueJsonObject.getJSONArray("result");
        int length = lossValueArray.length();

        for (int i = 0; i < length; i++) {
          JSONObject lossValueObject = (JSONObject) lossValueArray.get(i);

          int[] blues = new int[16];
          int[] reds = new int[33];
          String batchCode = null;

          JSONObject valueObject = lossValueObject.getJSONObject("value");

          JSONArray bluesArray = valueObject.getJSONArray("blue");
          int blueLength = bluesArray.length();
          blues = new int[blueLength];
          for (int l = 0; l < blueLength; l++) {
            blues[l] = bluesArray.getInt(l);
          }

          JSONArray redsArray = valueObject.getJSONArray("red");
          int redLength = redsArray.length();
          reds = new int[redLength];
          for (int k = 0; k < redLength; k++) {
            reds[k] = redsArray.getInt(k);
          }

          batchCode = lossValueObject.getString("batchCode");

          LossValue lossValue = new LossValue(reds, blues, batchCode);

          lossValuesList.add(lossValue);
        }

        msg.arg1 = GET_LOSSVALUE_SUCCESS;
      }

    } catch (JSONException e) {
      Log.i(TAG, e.toString());
    }
  }
  public DiffData readDiffData(String source) throws ReviewboardException {

    try {
      JSONObject jsonDiffData = checkedGetJSonRootObject(source).getJSONObject("diff_data");

      DiffData diffData = new DiffData();
      diffData.setBinary(jsonDiffData.getBoolean("binary"));
      diffData.setNewFile(jsonDiffData.getBoolean("new_file"));
      diffData.setNumChanges(jsonDiffData.getInt("num_changes"));

      JSONArray changedChunkIndexes = jsonDiffData.getJSONArray("changed_chunk_indexes");
      for (int i = 0; i < changedChunkIndexes.length(); i++)
        diffData.getChangedChunkIndexes().add(changedChunkIndexes.getInt(i));

      JSONArray chunks = jsonDiffData.getJSONArray("chunks");
      for (int i = 0; i < chunks.length(); i++) {

        JSONObject jsonChunk = chunks.getJSONObject(i);

        Chunk chunk = new Chunk();
        chunk.setChange(Type.fromString(jsonChunk.getString("change")));
        chunk.setCollapsable(jsonChunk.getBoolean("collapsable"));
        chunk.setIndex(jsonChunk.getInt("index"));
        chunk.setNumLines(jsonChunk.getInt("numlines"));

        JSONArray lines = jsonChunk.getJSONArray("lines");
        for (int j = 0; j < lines.length(); j++) {

          JSONArray lineArray = lines.getJSONArray(j);

          Line line = new Line();
          line.setDiffRowNumber(lineArray.getInt(0));
          line.setLeftFileRowNumber(getPossiblyEmptyInt(lineArray, 1));
          line.setLeftLineText(lineArray.getString(2));

          line.setRightFileRowNumber(getPossiblyEmptyInt(lineArray, 4));
          line.setRightLineText(lineArray.getString(5));

          line.setWhitespaceOnly(lineArray.getBoolean(7));

          chunk.getLines().add(line);
        }

        diffData.getChunks().add(chunk);
      }

      return diffData;
    } catch (JSONException e) {
      throw new ReviewboardException(e.getMessage(), e);
    }
  }
예제 #11
0
  private static List<?> getList(JSONArray jsonArray, Class<?> childrenType)
      throws JSONException, IllegalAccessException, InstantiationException {

    List<Object> list = new Vector<Object>(jsonArray.length());

    for (int i = 0; i < jsonArray.length(); i++) {

      Object child = null;

      if (childrenType == List.class) {
        child = getList(jsonArray.getJSONArray(i), childrenType);

      } else if (childrenType == String.class) {
        child = jsonArray.getString(i);

      } else if (childrenType == boolean.class || childrenType == Boolean.class) {
        child = jsonArray.getBoolean(i);

      } else if (childrenType == int.class || childrenType == Integer.class) {
        child = jsonArray.getInt(i);

      } else if (childrenType == double.class || childrenType == Double.class) {
        child = jsonArray.getDouble(i);

      } else {
        child = childrenType.newInstance();
        reflectJsonObject(child, jsonArray.getJSONObject(i));
      }

      list.add(child);
    }

    return list;
  }
예제 #12
0
  private void doJson() {
    try {
      Log.i("json", detail);
      JSONArray arr = new JSONArray(detail);
      JSONArray main = arr.getJSONArray(0);

      tvSender.setText(main.getString(4));
      tvSendTime.setText(HttpConstant.convertTime(main.getLong(7)));
      tvMsg.setText(main.getString(1));
      tvLoc.setText(main.getString(6));
      alert_id = main.getInt(2);
      Picasso.with(this).load(HttpConstant.BAIDUFACE + main.getString(5)).into(ivFace);

      for (int i = 1; i < arr.length(); i++) {
        LostBean lb = new LostBean();
        JSONArray lost = arr.getJSONArray(i);
        lb.title = lost.optString(0);
        lb.description = lost.optString(1);
        lb.alert_id = lost.optString(2);
        lb.from_user_id = lost.optString(3);
        lb.uname = lost.optString(4);
        lb.uface = lost.optString(5);
        lb.position = lost.optString(6);
        lb.time = lost.optLong(7);
        lostList.add(lb);
      }
      adapter.notifyDataSetChanged();
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }
 private void parseData(String data) {
   try {
     JSONObject boardArrayData = new JSONObject(data);
     currentTurn = boardArrayData.getInt("turn");
     players = new LinkedList<>();
     JSONArray playersList = new JSONArray(boardArrayData.get("players_list").toString());
     for (int i = 0; i < playersList.length(); i++) {
       JSONObject obj = playersList.optJSONObject(i);
       players.add(
           new Player(
               PlayerType.values()[obj.getInt("type")],
               obj.getString("name"),
               obj.getInt("image")));
     }
     JSONArray rowArray = new JSONArray(boardArrayData.get("double_array").toString());
     JSONArray coloumArray = new JSONArray(rowArray.get(0).toString());
     int rowLength = rowArray.length();
     int coloumLength = coloumArray.length();
     arrayOfBoard = new Integer[rowLength][coloumLength];
     for (int i = 0; i < rowLength; i++) {
       coloumArray = new JSONArray(rowArray.get(i).toString());
       for (int j = 0; j < coloumArray.length(); j++) {
         arrayOfBoard[i][j] = coloumArray.getInt(j);
       }
     }
   } catch (JSONException e) {
     e.printStackTrace();
   }
 }
예제 #14
0
  Session(JSONObject o) {
    this.sessionId = o.optInt("id");
    this.dayId = o.optInt("day");
    this.type = Type.TYPES.get(o.optInt("session_type"));
    this.roomId = o.optInt("room");
    this.streamId = o.optInt("stream");
    this.sessionGroupId = o.optInt("session_group");
    this.name = JSON.getString(o, "name");
    this.startDateTime =
        JSON.getLocalDateTime(
            o, "start_datetime", DateIntepretation.SECONDS_SINCE_1970, DateTimeZone.UTC);
    this.endDateTime =
        JSON.getLocalDateTime(
            o, "end_datetime", DateIntepretation.SECONDS_SINCE_1970, DateTimeZone.UTC);
    this.text = JSON.getString(o, "description");

    try {
      JSONArray a = o.getJSONArray("speakers");
      for (int x = 0; x < a.length(); x++) {
        speakerIds.add(a.getInt(x));
      }
    } catch (JSONException e) {
      // ignore
    }
  }
예제 #15
0
  /**
   * Opens a socket connection.
   *
   * @param args
   * @param callbackContext
   */
  private void connect(JSONArray args, CallbackContext callbackContext) {
    String key;
    String host;
    int port;
    Connection socket;

    // validating parameters
    if (args.length() < 2) {
      callbackContext.error("Missing arguments when calling 'connect' action.");
    } else {

      // opening connection and adding into pool
      try {

        // preparing parameters
        host = args.getString(0);
        port = args.getInt(1);
        key = this.buildKey(host, port);

        // creating connection
        if (this.pool.get(key) == null) {
          socket = new Connection(this, host, port);
          socket.start();
          this.pool.put(key, socket);
        }

        // adding to pool
        callbackContext.success(key);

      } catch (JSONException e) {
        callbackContext.error("Invalid parameters for 'connect' action: " + e.getMessage());
      }
    }
  }
  private boolean invokeBlinkup(
      final Activity activity, final BlinkupController controller, JSONArray data) {
    int timeoutMs;
    try {
      mApiKey = data.getString(BLINKUP_ARG_API_KEY);
      mDeveloperPlanId = data.getString(BLINKUP_ARG_DEVELOPER_PLAN_ID);
      timeoutMs = data.getInt(BLINKUP_ARG_TIMEOUT_MS);
      mGeneratePlanId = data.getBoolean(BLINKUP_ARG_GENERATE_PLAN_ID);
    } catch (JSONException exc) {
      BlinkUpPluginResult.sendPluginErrorToCallback(ERROR_INVALID_ARGUMENTS);
      return false;
    }

    // if api key not valid, send error message and quit
    if (!apiKeyFormatValid()) {
      BlinkUpPluginResult.sendPluginErrorToCallback(ERROR_INVALID_API_KEY);
      return false;
    }

    Intent blinkupCompleteIntent = new Intent(activity, BlinkUpCompleteActivity.class);
    blinkupCompleteIntent.putExtra(Extras.EXTRA_DEVELOPER_PLAN_ID, mDeveloperPlanId);
    blinkupCompleteIntent.putExtra(Extras.EXTRA_TIMEOUT_MS, timeoutMs);
    controller.intentBlinkupComplete = blinkupCompleteIntent;

    // default is to run on WebCore thread, we have UI so need UI thread
    activity.runOnUiThread(
        new Runnable() {
          @Override
          public void run() {
            presentBlinkUp(activity, controller);
          }
        });
    return true;
  }
예제 #17
0
 private void ripVideos() throws IOException {
   String oid = getGID(this.url).replace("videos", "");
   String u = "http://vk.com/al_video.php";
   Map<String, String> postData = new HashMap<String, String>();
   postData.put("al", "1");
   postData.put("act", "load_videos_silent");
   postData.put("offset", "0");
   postData.put("oid", oid);
   Document doc = Http.url(u).referrer(this.url).ignoreContentType().data(postData).post();
   String[] jsonStrings = doc.toString().split("<!>");
   JSONObject json = new JSONObject(jsonStrings[jsonStrings.length - 1]);
   JSONArray videos = json.getJSONArray("all");
   logger.info("Found " + videos.length() + " videos");
   for (int i = 0; i < videos.length(); i++) {
     JSONArray jsonVideo = videos.getJSONArray(i);
     int vidid = jsonVideo.getInt(1);
     String videoURL =
         com.rarchives.ripme.ripper.rippers.video.VkRipper.getVideoURLAtPage(
             "http://vk.com/video" + oid + "_" + vidid);
     String prefix = "";
     if (Utils.getConfigBoolean("download.save_order", true)) {
       prefix = String.format("%03d_", i + 1);
     }
     addURLToDownload(new URL(videoURL), prefix);
     try {
       Thread.sleep(500);
     } catch (InterruptedException e) {
       logger.error("Interrupted while waiting to fetch next video URL", e);
       break;
     }
   }
   waitForThreads();
 }
  @Override
  public List<MerchantBean> fetchHotMerchantBeans(int userId, double longitude, double latitude)
      throws JSONException {
    // TODO Auto-generated method stub
    JSONObject root = new JSONObject();
    root.put("method", RecommenderUtils.getHotPredictMethod());
    JSONObject params = new JSONObject();
    params.put("longitude", longitude);
    params.put("latitude", latitude);
    root.put("params", params);
    BaseHttpClient httpClient = new BaseHttpClient(RecommenderUtils.getRecommenderUrl());
    JSONObject response = httpClient.post(root);

    List<MerchantBean> merchantPredictList = new ArrayList<MerchantBean>();
    if (response.has("result") && response.getString("result").equals("success")) {
      JSONArray hotList = response.getJSONArray("hotList");
      for (int i = 0; i < hotList.length(); i++) {
        JSONArray hotItem = hotList.getJSONArray(i);
        Integer merchantId = Integer.valueOf(hotItem.getString(0));
        MerchantBean merchantBean = fetchMerchantBean(merchantId, userId, longitude, latitude);
        if (merchantBean != null) {
          merchantBean.setCollectionCount(hotItem.getInt(1));
          merchantPredictList.add(merchantBean);
        }
      }
    }
    return merchantPredictList;
  }
 private String a(JSONObject jSONObject) {
   StringBuilder stringBuilder = new StringBuilder();
   try {
     stringBuilder.append("FREQ=").append(jSONObject.getString("frequency")).append(";");
   } catch (JSONException e) {
     MMLog.b(d, "Unable to get calendar event recurrence frequency");
   }
   try {
     stringBuilder
         .append("UNTIL=")
         .append(f.format(DateUtils.parseDate(jSONObject.getString("expires"), e)))
         .append(";");
   } catch (DateParseException e2) {
     MMLog.e(d, "Error parsing calendar event recurrence expiration date");
   } catch (JSONException e3) {
     MMLog.b(d, "Unable to get calendar event recurrence expiration date");
   }
   try {
     JSONArray jSONArray = jSONObject.getJSONArray("daysInWeek");
     CharSequence stringBuilder2 = new StringBuilder();
     int i = 0;
     while (i < jSONArray.length()) {
       stringBuilder2.append(a(jSONArray.getInt(i))).append(",");
       i++;
     }
     stringBuilder.append("BYDAY=").append(stringBuilder2).append(";");
   } catch (JSONException e4) {
     MMLog.b(d, "Unable to get days in week");
   }
   try {
     stringBuilder
         .append("BYMONTHDAY=")
         .append(
             jSONObject
                 .getString("daysInMonth")
                 .replaceAll("\\[", AdTrackerConstants.BLANK)
                 .replaceAll("\\]", AdTrackerConstants.BLANK))
         .append(";");
   } catch (JSONException e5) {
     MMLog.b(d, "Unable to get days in month");
   }
   try {
     stringBuilder
         .append("BYMONTH=")
         .append(
             jSONObject
                 .getString("monthsInYear:")
                 .replaceAll("\\[", AdTrackerConstants.BLANK)
                 .replaceAll("\\]", AdTrackerConstants.BLANK))
         .append(";");
   } catch (JSONException e6) {
     MMLog.b(d, "Unable to get months in year:");
   }
   try {
     stringBuilder.append("BYYEARDAY=").append(jSONObject.getString("daysInYear")).append(";");
   } catch (JSONException e7) {
     MMLog.b(d, "Unable to get days in year");
   }
   return stringBuilder.toString().toUpperCase();
 }
예제 #20
0
 /**
  * 从jsonarray中获取产品列表信息
  *
  * @param jsonArray
  * @throws Exception
  */
 private void getProductList(JSONArray jsonArray) throws Exception {
   for (int i = 0; i < jsonArray.length(); i++) {
     Products products = new Products();
     JSONObject o = (JSONObject) jsonArray.get(i);
     JSONArray cidArrayJson = o.getJSONArray("cids");
     JSONArray cidArrayProImg = o.getJSONArray("proImages");
     JSONArray playableArray = o.getJSONArray("playables");
     products.count = o.getInt("count");
     products.findTime = o.getString("findtime");
     products.showTime = o.getString("showtime");
     for (int k = 0; k < cidArrayJson.length(); k++) {
       String cid = cidArrayJson.getString(k);
       LogPrint.Print("lybjson", "cid =" + cid); //
       products.arrcid.add(cid);
     }
     for (int k = 0; k < cidArrayProImg.length(); k++) {
       String proImg = cidArrayProImg.getString(k);
       LogPrint.Print("lybjson", "proImg = " + proImg); //
       products.arrProImg.add(proImg);
     }
     for (int k = 0; k < playableArray.length(); k++) {
       int playable = playableArray.getInt(k);
       products.arrPlayable.add(playable);
     }
     LogPrint.Print("lyb", "arrCommodity size = " + products.arrProImg.size());
     productItem.arrProducts.add(products);
   }
 }
  public void testStreamArray() throws IOException, JSONException {
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);
    ProtocolMessageWriter writer = new JsonMessageWriter(printWriter);
    Display display = new Display();
    Shell shell = new Shell(display);
    writer.appendPayload(
        WidgetUtil.getId(shell),
        IProtocolConstants.PAYLOAD_CONSTRUCT,
        "key",
        new Integer[] {new Integer(1), new Integer(2)});
    writer.appendPayload(
        WidgetUtil.getId(shell), IProtocolConstants.PAYLOAD_CONSTRUCT, "key2", new Boolean(true));

    writer.finish();
    String actual = stringWriter.getBuffer().toString();
    JSONObject message = new JSONObject(actual);
    JSONArray widgetArray = message.getJSONArray(IProtocolConstants.MESSAGE_WIDGETS);
    JSONObject widgetObject = widgetArray.getJSONObject(0);
    JSONObject payload = widgetObject.getJSONObject(IProtocolConstants.WIDGETS_PAYLOAD);
    JSONArray array = payload.getJSONArray("key");
    assertEquals(1, array.getInt(0));
    assertEquals(2, array.getInt(1));
    assertTrue(payload.getBoolean("key2"));
  }
  @Override
  public PluginResult execute(String action, JSONArray args, String callbackId) {
    // Log.d("MindSetPlugin", "Plugin Called");
    PluginResult result = null;
    PluginResult.Status status = PluginResult.Status.OK;

    try {
      if (START_ACTION.equals(action)) {
        // Log.d("MindSetPlugin", "Start passed");
        String o =
            start(
                args.getString(0),
                args.getBoolean(1),
                args.getInt(2),
                args.getInt(3),
                args.getString(4));
        result = new PluginResult(status, o);

      } else if (STOP_ACTION.equals(action)) {
        // Log.d("MindSetPlugin", "Stop passed");
        stop(args.getString(0));
        result = new PluginResult(status, "");

      } else {
        result = new PluginResult(Status.INVALID_ACTION);
        // Log
        //		.d("MindSetPlugin", "Invalid action : " + action
        //				+ " passed");
      }
    } catch (JSONException ex) {
    }
    return result;
  }
  public Integer getFoldersAndArticlesCount(long groupId, long userId, long folderId, int status)
      throws Exception {
    JSONObject _command = new JSONObject();

    try {
      JSONObject _params = new JSONObject();

      _params.put("groupId", groupId);
      _params.put("userId", userId);
      _params.put("folderId", folderId);
      _params.put("status", status);

      _command.put("/journal.journalfolder/get-folders-and-articles-count", _params);
    } catch (JSONException _je) {
      throw new Exception(_je);
    }

    JSONArray _result = session.invoke(_command);

    if (_result == null) {
      return null;
    }

    return _result.getInt(0);
  }
예제 #24
0
  public MediaEntityJSONImpl(final JSONObject json) throws TwitterException {
    try {
      final JSONArray indicesArray = json.getJSONArray("indices");
      start = indicesArray.getInt(0);
      end = indicesArray.getInt(1);
      id = getLong("id", json);

      try {
        url = new URL(json.getString("url"));
      } catch (final MalformedURLException ignore) {
      }

      if (!json.isNull("expanded_url")) {
        try {
          expandedURL = new URL(json.getString("expanded_url"));
        } catch (final MalformedURLException ignore) {
        }
      }
      if (!json.isNull("media_url")) {
        try {
          mediaURL = new URL(json.getString("media_url"));
        } catch (final MalformedURLException ignore) {
        }
      }
      if (!json.isNull("media_url_https")) {
        try {
          mediaURLHttps = new URL(json.getString("media_url_https"));
        } catch (final MalformedURLException ignore) {
        }
      }
      if (!json.isNull("display_url")) {
        displayURL = json.getString("display_url");
      }
      final JSONObject sizes = json.getJSONObject("sizes");
      this.sizes = new HashMap<Integer, MediaEntity.Size>(4);
      // thumbworkarounding API side issue
      addMediaEntitySizeIfNotNull(this.sizes, sizes, MediaEntity.Size.LARGE, "large");
      addMediaEntitySizeIfNotNull(this.sizes, sizes, MediaEntity.Size.MEDIUM, "medium");
      addMediaEntitySizeIfNotNull(this.sizes, sizes, MediaEntity.Size.SMALL, "small");
      addMediaEntitySizeIfNotNull(this.sizes, sizes, MediaEntity.Size.THUMB, "thumb");
      if (!json.isNull("type")) {
        type = json.getString("type");
      }
    } catch (final JSONException jsone) {
      throw new TwitterException(jsone);
    }
  }
 @Override
 public void call(JSONArray args) throws JSONException {
   if (argsLengthValid(3, args)) {
     Crashlytics.log(args.getInt(0), args.getString(1), args.getString(2));
   } else {
     Crashlytics.log(args.getString(0));
   }
 }
예제 #26
0
  @Override
  public void parseData(Object jsonResponse) throws JSONException {
    JSONArray response = (JSONArray) jsonResponse;

    int id = response.getInt(0);
    String name = response.getString(1);
    String pos = response.getString(2);
    int freqCnt = response.getInt(3);
    String inflections = response.getString(4);

    mWord = new Word(id, name, pos);

    mWord.setFreqCnt(freqCnt);
    mWord.setInflections(inflections);

    mExpirationMillis = response.getLong(5) * 1000;
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_worker_availability);

    settings = PreferenceManager.getDefaultSharedPreferences(this);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowTitleEnabled(false);
    result =
        new DrawerBuilder()
            .withActivity(this)
            .withToolbar(toolbar)
            .withSavedInstance(savedInstanceState)
            .build();
    result.getActionBarDrawerToggle().setDrawerIndicatorEnabled(false);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    toolbar.setNavigationOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            finish();
          }
        });
    data = (HashMap<Integer, String>) getIntent().getSerializableExtra("data");
    days = new ArrayList<>();
    mon = (CheckBox) findViewById(R.id.chkMon);
    tues = (CheckBox) findViewById(R.id.chkTues);
    wed = (CheckBox) findViewById(R.id.chkWed);
    thurs = (CheckBox) findViewById(R.id.chkThurs);
    fri = (CheckBox) findViewById(R.id.chkFri);
    sat = (CheckBox) findViewById(R.id.chkSat);
    sun = (CheckBox) findViewById(R.id.chkSun);
    days.add(mon);
    days.add(tues);
    days.add(wed);
    days.add(thurs);
    days.add(fri);
    days.add(sat);
    days.add(sun);

    availability = "\"availability\":[";

    try {
      action = getIntent().getAction();
      profileData = getIntent().getStringExtra("availability");
      jsonArray = new JSONArray(profileData);
      for (int i = 0; i < jsonArray.length(); i++) {
        days.get(jsonArray.getInt(i) - 1).setChecked(true);
      }
    } catch (Exception e) {
      action = "";
      profileData = "";
    }

    progress = new ProgressDialog(this);
    progress.setMessage("Updating profile");
  }
  private MonsterModel parseMonsterFromArray(final JSONArray cardResult) throws JSONException {
    MyLog.entry();

    // [8,190542,30,1,0,1655,0,0,0,0,0]
    final MonsterModel monster = new MonsterModel();
    monster.setCardId(cardResult.getLong(0));
    monster.setExp(cardResult.getLong(1));
    monster.setLevel(cardResult.getInt(2));
    monster.setSkillLevel(cardResult.getInt(3));
    final int origId = cardResult.getInt(5);
    int idJp = -1;
    try {
      idJp = idConverter.getMonsterRefIdByCapturedId(origId);
    } catch (UnknownMonsterException e) {
      MyLog.warn(e.getMessage());
    }
    monster.setIdJp(idJp);
    monster.setPlusHp(cardResult.getInt(6));
    monster.setPlusAtk(cardResult.getInt(7));
    monster.setPlusRcv(cardResult.getInt(8));
    monster.setAwakenings(cardResult.getInt(9));
    monster.setLatentAwakeningsFromPackedInt(cardResult.getInt(10));

    MyLog.exit();
    return monster;
  }
  private BaseMonsterStatsModel extractFriendLeader(final JSONArray friendResult, int startPosition)
      throws JSONException {
    final BaseMonsterStatsModel leader = new BaseMonsterStatsModel();

    // 2, 15, 1, 0, 0, 0, 0
    final int origId1 = friendResult.getInt(startPosition++);
    int idJp1 = -1;
    try {
      idJp1 = idConverter.getMonsterRefIdByCapturedId(origId1);
    } catch (UnknownMonsterException e) {
      MyLog.warn("leader : " + e.getMessage());
    }

    leader.setIdJp(idJp1);
    leader.setLevel(friendResult.getInt(startPosition++));
    leader.setSkillLevel(friendResult.getInt(startPosition++));
    leader.setPlusHp(friendResult.getInt(startPosition++));
    leader.setPlusAtk(friendResult.getInt(startPosition++));
    leader.setPlusRcv(friendResult.getInt(startPosition++));
    leader.setAwakenings(friendResult.getInt(startPosition++));
    leader.setLatentAwakeningsFromPackedInt(friendResult.getInt(startPosition++));
    // inherited skill id?
    // inherited skill level?
    return leader;
  }
예제 #30
0
 @Override
 public void paser(JSONObject json) throws Exception {
   mListTeams = new LinkedList<Integer>();
   JSONArray arr = json.getJSONArray(KEY_RESULT);
   int size = arr.length();
   for (int i = 0; i < size; i++) {
     mListTeams.add(arr.getInt(i));
   }
 }