Beispiel #1
0
  public static Tweet parseTweet(JSONObject input) {
    // Example of a tweet in JSON format:
    // https://dev.twitter.com/docs/api/1/get/search
    // logger.info("parsing as twitter doc");
    try {
      Tweet t = new Tweet();

      JSONObject user;
      user = input.getJSONObject("user");
      t.userID = user.getLong("id");
      t.text = input.getString("text");
      t.isRetweet = !input.isNull("retweeted_status");
      t.setDoctype(DocumentType.TWIITER_DOC);
      if (input.has("coordinates") && !input.isNull("coordinates")) {
        JSONObject geo = (JSONObject) input.getJSONObject("coordinates");
        if (geo.getString("type") == "Point") {
          JSONArray coords = geo.getJSONArray("coordinates");
          GeoLabel.LonLatPair geotag = new GeoLabel.LonLatPair();
          geotag.setLongitude(coords.getDouble(0));
          geotag.setLatitude(coords.getDouble(1));
        }
      }
      return t;
    } catch (JSONException e) {
      logger.error("Json exception in parsing tweet: " + input);
      logger.error(elog.toStringException(e));
      throw new RuntimeException(e);
    }
  }
  private GenomicRegionSearchInfo parseRegionRequest() throws Exception {
    String input = "";
    if ("application/x-www-form-urlencoded".equals(request.getContentType())
        || "GET".equalsIgnoreCase(request.getMethod())) {
      input = request.getParameter("query");
    } else {
      input = IOUtils.toString(request.getInputStream());
    }
    JSONObject jsonRequest = new JSONObject(input);
    GenomicRegionSearchInfo parsed = new GenomicRegionSearchInfo();
    parsed.setOrganism(jsonRequest.getString("organism"));
    if (!jsonRequest.isNull("isInterbase")) {
      parsed.setInterbase(jsonRequest.getBoolean("isInterbase"));
    }
    if (!jsonRequest.isNull("extension")) {
      parsed.setExtension(jsonRequest.optInt("extension", 0));
    }
    JSONArray fts = jsonRequest.getJSONArray("featureTypes");
    int noOfTypes = fts.length();
    List<String> featureTypes = new ArrayList<String>();
    for (int i = 0; i < noOfTypes; i++) {
      featureTypes.add(fts.getString(i));
    }
    parsed.setFeatureTypes(featureTypes);

    JSONArray regs = jsonRequest.getJSONArray("regions");
    int noOfRegs = regs.length();
    List<String> regions = new ArrayList<String>();
    for (int i = 0; i < noOfRegs; i++) {
      regions.add(regs.getString(i));
    }
    parsed.setRegions(regions);
    return parsed;
  }
  public sp_GetMessage_Items(JSONObject obj) {
    super(obj);
    try {

      if (bsuccess) {
        JSONObject data = obj.getJSONObject("data");
        if (data != null) //
        {
          // 새 매시지
          if (!data.isNull("newmessages")) {
            JSONArray array = data.getJSONArray("newmessages");
            if (array != null) {
              for (int i = 0; i < array.length(); i++) {
                newmessages.add(new sp_GetMessage_Result(array.getJSONObject(i)));
              }
            }
          }

          // 상대방이 읽은 마지막 메시지
          if (!data.isNull("readmessage"))
            readmessage = new sp_GetLatestReadMessage_Result(data.getJSONObject("readmessage"));

        } else Logger.Instance().Write("sp_GetMessage_Items 파싱중 data가 null임");
      } else // 실패시는 errorcode입력
      {
        resultCode = ResultCode.valueOf(obj.getString("data"));
      }

    } catch (JSONException e) {
      Logger.Instance().Write(e);
    }
  }
Beispiel #4
0
  private int getCmsId(String orderBy) {

    Map<String, String> params = new LinkedHashMap<String, String>();

    params.put("pn", "1");
    params.put("pl", "2");
    params.put("fd", "title desc cmsurl thumburl publishtime");
    params.put("ob", orderBy);
    params.put("cl", "search_result");

    JSONObject resource = NovaMiddleResource.search("cms", "cms", "", params);

    if (resource == null || resource.isNull("results")) {
      for (int i = 0; i < 5; i++) {
        resource = NovaMiddleResource.search("cms", "cms", "", params);
        if (resource != null && !resource.isNull("results")) {
          break;
        }
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }

    JSONArray showArray = resource.optJSONArray("results");
    if (!JSONUtil.isEmpty(showArray)) {
      return showArray.optJSONObject(0).optInt("cmsid");
    }
    return 0;
  }
Beispiel #5
0
 /** method to update data in caching layer object from JSON * */
 public boolean updateFromJSON(JSONObject jsonObj) {
   try {
     JSONArray hasArcsArray = jsonObj.optJSONArray("hasArcs");
     if (hasArcsArray != null) {
       ArrayList<Arc> aListOfHasArcs = new ArrayList<Arc>(hasArcsArray.length());
       for (int i = 0; i < hasArcsArray.length(); i++) {
         int id = hasArcsArray.optInt(i);
         if (ArcManager.getInstance().get(id) != null) {
           aListOfHasArcs.add(ArcManager.getInstance().get(id));
         }
       }
       setHasArcs(aListOfHasArcs);
     }
     if (!jsonObj.isNull("hasPropertySet")) {
       int hasPropertySetId = jsonObj.optInt("hasPropertySet");
       PropertySet value = PropertySetManager.getInstance().get(hasPropertySetId);
       if (value != null) {
         setHasPropertySet(value);
       }
     }
     if (!jsonObj.isNull("hasDomainNodes")) {
       int hasDomainNodesId = jsonObj.optInt("hasDomainNodes");
       NodeList value = NodeListManager.getInstance().get(hasDomainNodesId);
       if (value != null) {
         setHasDomainNodes(value);
       }
     }
   } catch (Exception e) {
     logWriter.error("Failure updating from JSON", e);
     return false;
   }
   return true;
 }
Beispiel #6
0
 public static Weibo fromJson(JSONObject weiboJsonObj) throws JSONException {
   Weibo weibo = new Weibo();
   weibo.setMid(weiboJsonObj.getLong("mid"));
   weibo.setSource(weiboJsonObj.getString("source"));
   weibo.setCreateTime(weiboJsonObj.getString("created_at"));
   weibo.setText(weiboJsonObj.getString("text"));
   weibo.setReportsNum(weiboJsonObj.getInt("reposts_count"));
   weibo.setCommentsNum(weiboJsonObj.getInt("comments_count"));
   weibo.setAttitudeStatus(weiboJsonObj.getInt("attitudes_status"));
   weibo.setLikeCount(weiboJsonObj.getInt("like_count"));
   weibo.setBid(weiboJsonObj.getString("bid"));
   weibo.setAttitudesNum(weiboJsonObj.getInt("attitudes_count"));
   if (!weiboJsonObj.isNull("pics")) {
     JSONArray picsJsonArray = weiboJsonObj.getJSONArray("pics");
     for (int i = 0; i < picsJsonArray.length(); i++) {
       JSONObject picsJsonObj = picsJsonArray.getJSONObject(i);
       weibo.getPics().add(picsJsonObj.getString("url"));
     }
   }
   if (!weiboJsonObj.isNull("user")) {
     weibo.setUser(User.fromJson(weiboJsonObj.getJSONObject("user")));
   }
   if (!weiboJsonObj.isNull("retweeted_status")) {
     weibo.setSrcWeibo(Weibo.fromJson(weiboJsonObj.getJSONObject("retweeted_status")));
   }
   return weibo;
 }
Beispiel #7
0
  public static QSource getQSource(JSONObject json) {
    QSource mQsource = new QSource();
    if (!json.isNull("source")) {
      JSONObject source;
      try {
        source = json.getJSONObject("source");
        if (!source.isNull("image")) {
          JSONArray images = source.getJSONArray("image");
          if (images != null && images.length() > 0) {
            mQsource.setSource_image(images.optString(0) + "/120");
            mQsource.setSource_medium_image(images.optString(0) + "/460");
            // Log.v(TAG, "source_image_url:  " + source_image);
          }
        }
        if (!source.isNull("nick")) {
          mQsource.setSource_nick(source.getString("nick"));
          // Log.v(TAG, "source_nick:  " + source_nick);

          if (!source.isNull("origtext")) {
            mQsource.setSource_text(
                mQsource.getSource_nick() + ":  " + source.getString("origtext"));
            // Log.v(TAG, "source_origtext:  " + source_text);
          }
        }
      } catch (JSONException e) {
        e.printStackTrace();
        return null;
      }
      // Log.v(TAG, "sourcel:  " + source);

      return mQsource;
    } else return null;
  }
  private void getOrderData(JSONObject response) throws JSONException {
    ArrayList<ImageItem> mImageItems = new ArrayList<AlbumHelper.ImageItem>();
    if (!response.isNull("traceInfo")) {

      String traceid = null, actmemo = null, actmemoinner = null;
      JSONObject jsonObject = response.getJSONObject("traceInfo");
      Log.e(TAG, mNewOrder.toString());
      if (!jsonObject.isNull("traceid")) traceid = jsonObject.getString("traceid");
      // mNewOrder.setActidx(traceid);
      if (!jsonObject.isNull("actmemo")) actmemo = jsonObject.getString("actmemo");
      mNewOrder.setActmemo(actmemo);
      if (!jsonObject.isNull("actmemoinner")) actmemoinner = jsonObject.getString("actmemoinner");
      mNewOrder.setActmemoinner(actmemoinner);
      Log.e(TAG, "" + traceid + "<" + actmemo + "<" + actmemoinner);
      if (jsonObject.isNull("pics")) return;
      JSONArray jsonArray = jsonObject.getJSONArray("pics");
      for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject object = jsonArray.getJSONObject(i);
        ImageItem imageItem = new ImageItem();
        String picid = object.getString("picid");
        String smallimg = object.getString("smallimg");
        String bigimg = object.getString("bigimg");
        imageItem.thumbnailPath = smallimg;
        imageItem.imagePath = bigimg;
        mImageItems.add(imageItem);
      }
      mNewOrder.setImageItems(mImageItems);
    }
    Log.e(TAG, mNewOrder.toString());
    startOrderExecute();
  }
Beispiel #9
0
  private void parseJsonFeed(JSONObject response) {
    try {
      JSONArray feedArray = response.getJSONArray("feed");

      for (int i = 0; i < feedArray.length(); i++) {
        JSONObject feedObj = (JSONObject) feedArray.get(i);

        FeedItem item = new FeedItem();
        item.setId(feedObj.getInt("id"));
        item.setName(feedObj.getString("name"));

        // Image might be null sometimes
        String image = feedObj.isNull("image") ? null : feedObj.getString("image");
        item.setImge(image);
        item.setStatus(feedObj.getString("status"));
        item.setProfilePic(feedObj.getString("profilePic"));
        item.setTimeStamp(feedObj.getString("timeStamp"));

        // url might be null sometimes
        String feedUrl = feedObj.isNull("url") ? null : feedObj.getString("url");
        item.setUrl(feedUrl);

        item.setCountLiked((int) (Math.random() * 100));
        item.setIsLiked(false);

        feedItems.add(item);
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }
  public sp_GetProvidesByArea_Result(JSONObject obj) {
    try {

      if (!obj.isNull("id")) id = obj.getString("id");

      if (!obj.isNull("photo")) photo = obj.getString("photo");

      if (!obj.isNull("lat")) lat = obj.getDouble("lat");

      if (!obj.isNull("lon")) lon = obj.getDouble("lon");

      if (!obj.isNull("bidding_id")) bidding_id = obj.getString("bidding_id");

      if (!obj.isNull("title")) title = obj.getString("title");

      if (!obj.isNull("name")) name = obj.getString("name");

      if (!obj.isNull("min_price")) min_price = obj.getInt("min_price");

      if (!obj.isNull("description")) description = obj.getString("description");

      if (!obj.isNull("user_id")) user_id = obj.getString("user_id");

    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Beispiel #11
0
 private void onJson(String str) {
   if (TextUtils.isEmpty(str)) return;
   this.setJsonStr(str);
   try {
     JSONObject object = new JSONObject(str);
     this.setType(object.optString("type"));
     this.setGid(object.optLong("gid"));
     if (!object.isNull("gift_record_id")) {
       this.setGift_record_id(object.optLong("gift_record_id"));
     }
     this.setF_uid(object.optLong("f_uid"));
     this.setT_uid(object.optLong("t_uid"));
     this.setGift_name(object.optString("gift_name"));
     this.setGift_info(object.optString("gift_info"));
     this.setGift_img(object.optString("gift_img"));
     if (!object.isNull("gift_res")) {
       this.setGift_res(object.optString("gift_res"));
     }
     this.setF_nickname(object.optString("f_nickname"));
     this.setT_nickname(object.optString("t_nickname"));
     this.setCost(object.optInt("cost"));
     this.setTime(setStrTime(object.optString("tm")));
   } catch (JSONException e) {
     e.printStackTrace();
   }
 }
  public List<AccountName> getList(JSONArray jsonArray) {
    List<AccountName> listName = new ArrayList<AccountName>();

    for (int i = 0; i < jsonArray.length(); i++) {
      AccountName bankName = new AccountName();
      try {
        JSONObject json = jsonArray.getJSONObject(i);
        bankName.setBankName(json.getString("bankname"));
        // Log.e("json.isNull===",""+json.isNull("creditCard"));
        if (!json.isNull("creditCard")) { // 信用卡
          AccountType bankType = new AccountType();
          bankType.setName("信用卡");
          setAccountType(json.getString("creditCard"), bankType);
          bankName.getBankType().add(bankType);
        }
        if (!json.isNull("debitCard")) { // 借记卡
          AccountType bankType = new AccountType();
          bankType.setName("借记卡");
          setAccountType(json.getString("debitCard"), bankType);
          bankName.getBankType().add(bankType);
        }
      } catch (JSONException e) {
        e.printStackTrace();
      }
      listName.add(bankName);
    }

    return listName;
  }
Beispiel #13
0
  public static ArrayList<FeedItem> parseJsonFeed(JSONObject response) {
    ArrayList<FeedItem> mFeedItems = new ArrayList<FeedItem>();
    Log.d("response", String.valueOf(response));

    try {
      JSONArray feedArray = response.getJSONArray("feed");

      for (int i = 0; i < feedArray.length(); i++) {
        JSONObject feedObj = (JSONObject) feedArray.get(i);

        FeedItem item = new FeedItem();
        item.setId(feedObj.getInt("id"));
        item.setName(feedObj.getString("name"));

        // Image might be null sometimes
        String image = feedObj.isNull("image") ? null : feedObj.getString("image");
        item.setImage(image);
        item.setStatus(feedObj.getString("status"));
        item.setProfilePic(feedObj.getString("profilePic"));
        item.setTimeStamp(feedObj.getString("timeStamp"));

        // url might be null sometimes
        String feedUrl = feedObj.isNull("url") ? null : feedObj.getString("url");
        item.setUrl(feedUrl);

        mFeedItems.add(item);
      }

    } catch (JSONException e) {
      e.printStackTrace();
    }
    return mFeedItems;
  }
  private Reminder createReminderFromJson(JSONObject reminderJson) throws JSONException {
    int id = reminderJson.getInt("id");
    String message = reminderJson.getString("message");
    String startTime = reminderJson.getString("startTime");
    String endTime = reminderJson.getString("endTime");
    int eventId = reminderJson.getInt("actionId");
    String ssid = reminderJson.isNull("ssid") ? null : reminderJson.getString("ssid");
    String latLong = reminderJson.isNull("latLong") ? null : reminderJson.getString("latLong");
    String days = reminderJson.getString("days");
    boolean enabled = reminderJson.getBoolean("enabled");
    boolean repeat = reminderJson.getBoolean("repeat");
    boolean postActivity = reminderJson.getBoolean("postActivity");

    Reminder reminder = new Reminder();

    reminder.id = id;
    reminder.notificationText = message;
    reminder.startTime = startTime;
    reminder.endTime = endTime;
    reminder.action = Action.values()[eventId];
    reminder.ssid = ssid;
    reminder.latLong = latLong;
    reminder.days = new ArrayList<Integer>();
    reminder.enabled = enabled;
    reminder.repeat = repeat;
    reminder.postActivity = postActivity;

    for (char day : days.toCharArray()) {
      reminder.days.add(Character.getNumericValue(day));
    }

    return reminder;
  }
Beispiel #15
0
  // SET_VOLUME messages have a |level| and |muted| properties. One of them is
  // |null| and the other one isn't. |muted| is expected to be a boolean while
  // |level| is a float from 0.0 to 1.0.
  // Example:
  // {
  //   "volume" {
  //     "level": 0.9,
  //     "muted": null
  //   }
  // }
  @Override
  public HandleVolumeMessageResult handleVolumeMessage(
      JSONObject volume, final String clientId, final int sequenceNumber) throws JSONException {
    if (volume == null) return new HandleVolumeMessageResult(false, false);

    if (isApiClientInvalid()) return new HandleVolumeMessageResult(false, false);

    boolean waitForVolumeChange = false;
    try {
      if (!volume.isNull("muted")) {
        boolean newMuted = volume.getBoolean("muted");
        if (Cast.CastApi.isMute(mApiClient) != newMuted) {
          Cast.CastApi.setMute(mApiClient, newMuted);
          waitForVolumeChange = true;
        }
      }
      if (!volume.isNull("level")) {
        double newLevel = volume.getDouble("level");
        double currentLevel = Cast.CastApi.getVolume(mApiClient);
        if (!Double.isNaN(currentLevel)
            && Math.abs(currentLevel - newLevel) > MIN_VOLUME_LEVEL_DELTA) {
          Cast.CastApi.setVolume(mApiClient, newLevel);
          waitForVolumeChange = true;
        }
      }
    } catch (IOException e) {
      Log.e(TAG, "Failed to send volume command: " + e);
      return new HandleVolumeMessageResult(false, false);
    }

    return new HandleVolumeMessageResult(true, waitForVolumeChange);
  }
Beispiel #16
0
  private void parseStep(JSONObject step) {
    try {
      travelMode = step.getString("travel_mode");

      if (!step.isNull("start_location")) {
        JSONObject pos = step.getJSONObject("start_location");
        start = new LatLng(pos.getDouble("lat"), pos.getDouble("lng"));
      }

      if (!step.isNull("end_location")) {
        JSONObject pos = step.getJSONObject("end_location");
        end = new LatLng(pos.getDouble("lat"), pos.getDouble("lng"));
      }

      if (!step.isNull("duration")) {
        JSONObject pos = step.getJSONObject("duration");
        duration = pos.getString("text");
      }

      if (!step.isNull("distance")) {
        JSONObject pos = step.getJSONObject("distance");
        distance = pos.getString("text");
      }

      if (!step.isNull("polyline")) {
        JSONObject pos = step.getJSONObject("polyline");
        decodePoly(pos.getString("points"));
        //				Log.d("Step count", String.valueOf(stepLine.size()));
      }

      instructions = step.getString("html_instructions");
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }
  private OfflineStoreRequest loadRequestJson(JSONObject jsonObject, String bucket)
      throws CloudException, JSONException {
    String jobId = jsonObject.getString("JobId");
    String actionDescription = jsonObject.getString("Action");

    String archiveId = null;
    if (jsonObject.has("ArchiveId") && !jsonObject.isNull("ArchiveId")) {
      archiveId = jsonObject.getString("ArchiveId");
    }

    OfflineStoreRequestAction action = OfflineStoreRequestAction.UNKNOWN;
    String sizeKey = null;
    if (actionDescription == null) {
      throw new CloudException("invalid glacier job action");
    } else if (actionDescription.equalsIgnoreCase(ACTION_ARCHIVE_RETRIEVAL)) {
      action = OfflineStoreRequestAction.DOWNLOAD;
      sizeKey = "ArchiveSizeInBytes";
    } else if (actionDescription.equalsIgnoreCase(ACTION_INVENTORY_RETRIEVAL)) {
      action = OfflineStoreRequestAction.LIST;
      sizeKey = "InventorySizeInBytes";
    }
    long bytes = -1;
    if (jsonObject.has(sizeKey) && !jsonObject.isNull(sizeKey)) {
      bytes = jsonObject.getLong(sizeKey);
    }

    String jobDescription = jsonObject.getString("JobDescription");
    if (jobDescription == null) {
      jobDescription = "";
    }

    String statusCode = jsonObject.getString("StatusCode");
    String statusDescription = jsonObject.getString("StatusMessage");
    if (statusDescription == null) {
      statusDescription = "";
    }

    long creationTs = parseTimestamp(jsonObject.getString("CreationDate"));
    long completionTs =
        jsonObject.isNull("CompletionDate")
            ? -1L
            : parseTimestamp(jsonObject.getString("CompletionDate"));

    Storage<Byte> storage = bytes != -1 ? new Storage<Byte>(bytes, Storage.BYTE) : null;
    OfflineStoreRequestStatus requestStatus = parseRequestStatus(statusCode);

    return new OfflineStoreRequest(
        jobId,
        bucket,
        archiveId,
        action,
        actionDescription,
        storage,
        jobDescription,
        requestStatus,
        statusDescription,
        creationTs,
        completionTs);
  }
Beispiel #18
0
  @Override
  protected void parseSelf(JSONObject jObject) throws JSONException {

    coreStatus = jObject.isNull("core_status") ? -1 : jObject.getInt("core_status");

    msg = jObject.isNull("msg") ? "" : jObject.getString("msg");

    token = jObject.isNull("token") ? "" : jObject.getString("token");
  }
  /** Upgrading device firmware over the air (OTA). */
  public void upgradeFirmware(boolean isStatusCheck) {
    Log.i(TAG, "An upgrade has been requested");
    Context context = this.getApplicationContext();
    Preference.putBoolean(
        context,
        context.getResources().getString(R.string.firmware_status_check_in_progress),
        isStatusCheck);
    Preference.putString(
        context,
        context.getResources().getString(R.string.firmware_download_progress),
        String.valueOf(DEFAULT_STATE_INFO_CODE));
    Preference.putInt(
        context, context.getResources().getString(R.string.operation_id), operationId);

    String schedule = null;
    String server;
    if (command != null && !command.trim().isEmpty()) {
      try {
        JSONObject upgradeData = new JSONObject(command);
        if (!upgradeData.isNull(context.getResources().getString(R.string.alarm_schedule))) {
          schedule =
              (String) upgradeData.get(context.getResources().getString(R.string.alarm_schedule));
        }

        if (!upgradeData.isNull(context.getResources().getString(R.string.firmware_server))) {
          server =
              (String) upgradeData.get(context.getResources().getString(R.string.firmware_server));
          if (URLUtil.isValidUrl(server)) {
            Preference.putString(
                context, context.getResources().getString(R.string.firmware_server), server);
          }
        }
      } catch (JSONException e) {
        Log.e(TAG, "Firmware upgrade payload parsing failed." + e);
      }
    }
    if (schedule != null && !schedule.trim().isEmpty()) {
      Log.i(TAG, "Upgrade has been scheduled to " + schedule);
      Preference.putString(
          context, context.getResources().getString(R.string.alarm_schedule), schedule);
      try {
        AlarmUtils.setOneTimeAlarm(context, schedule, Constants.Operation.UPGRADE_FIRMWARE, null);
      } catch (ParseException e) {
        Log.e(TAG, "One time alarm time string parsing failed." + e);
      }
    } else {
      if (isStatusCheck) {
        Log.i(TAG, "Firmware status check is initiated by admin.");
      } else {
        Log.i(TAG, "Upgrade request initiated by admin.");
      }
      // Prepare for upgrade
      OTADownload otaDownload = new OTADownload(context);
      otaDownload.startOTA();
    }
  }
  public sp_GetMyActiveProvides_Result(JSONObject obj) {
    try {

      if (!obj.isNull("provide_id")) provide_id = obj.getString("provide_id");

      if (!obj.isNull("min_price")) min_price = obj.getInt("min_price");

      if (!obj.isNull("lat")) lat = obj.getDouble("lat");

      if (!obj.isNull("lon")) lon = obj.getDouble("lon");

      if (!obj.isNull("status")) status = obj.getInt("status");

      if (!obj.isNull("bidding_count")) bidding_count = obj.getInt("bidding_count");

      if (!obj.isNull("title")) title = obj.getString("title");

      if (!obj.isNull("matching_count")) matching_count = obj.getInt("matching_count");

      if (!obj.isNull("description")) description = obj.getString("description");

    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    ReadingDBInterface db;
    ConfigManager cm = new ConfigManager(this); // this object gets the database connections values

    response.setContentType("application/json");
    PrintWriter out = response.getWriter();
    String callback = request.getParameter("callback");

    StringBuilder sb = new StringBuilder();
    BufferedReader reader = request.getReader();
    try {
      String line;
      while ((line = reader.readLine()) != null) {
        sb.append(line).append('\n');
      }
    } finally {
      reader.close();
    }

    try {
      JSONObject json = new JSONObject(sb.toString());
      String usr = (!json.isNull("usr") ? json.getString("usr") : "");
      String questionId = (!json.isNull("questionid") ? json.getString("questionid") : "");
      double score = (!json.isNull("score") ? json.getDouble("score") : 0.0);

      String answers =
          (!json.isNull("answerchoices") ? json.getJSONArray("answerchoices").toString() : "");
      answers =
          answers
              .replaceAll("\\[", "")
              .replaceAll("\\]", "")
              .replaceAll(",", ";")
              .replaceAll("\"", "");

      db = new ReadingDBInterface(cm.dbstring, cm.dbuser, cm.dbpass);
      db.openConnection();

      // System.out.println(answers);
      long id = db.insertAnswer(questionId, usr, score, answers);
      db.closeConnection();

      // System.out.println(ranges.toString());
      Common.writeOutput(out, callback, "{\"res\":1,\"msg\":\"ok\",\"answerid\":\"" + id + "\"}");

    } catch (Exception e) {
      e.printStackTrace();
      Common.writeOutput(out, callback, "{\"error\":\"problem on parsing the json\"}");
    }
  }
 private Drawable a(JSONObject paramJSONObject, List<String> paramList)
 {
   int i = 0;
   try
   {
     if (paramJSONObject.isNull("url")) {
       throw new uf("Can't construct a BitmapDrawable with a null url");
     }
   }
   catch (JSONException paramJSONObject)
   {
     throw new uf("Couldn't read drawable description", paramJSONObject);
   }
   String str = paramJSONObject.getString("url");
   boolean bool = paramJSONObject.isNull("dimensions");
   int j;
   int k;
   int m;
   if (bool)
   {
     j = 0;
     k = 0;
     m = 0;
   }
   for (int n = 0;; n = 1)
   {
     try
     {
       paramJSONObject = b.a(str);
       paramList.add(str);
       paramJSONObject = new BitmapDrawable(Resources.getSystem(), paramJSONObject);
       if (n == 0) {
         break;
       }
       paramJSONObject.setBounds(m, j, k, i);
       return paramJSONObject;
     }
     catch (uv paramJSONObject)
     {
       throw new ug(paramJSONObject.getMessage(), paramJSONObject.getCause());
     }
     paramJSONObject = paramJSONObject.getJSONObject("dimensions");
     m = paramJSONObject.getInt("left");
     k = paramJSONObject.getInt("right");
     j = paramJSONObject.getInt("top");
     i = paramJSONObject.getInt("bottom");
   }
   return paramJSONObject;
 }
Beispiel #23
0
 public CompareMatch(JSONObject json) throws JSONException {
   home = json.get("home").toString();
   away = json.get("away").toString();
   home_flag = json.get("home_flag").toString();
   away_flag = json.get("away_flag").toString();
   if (!json.isNull("final_score")) {
     final_score = new Score(json.getJSONObject("final_score"));
   }
   if (!json.isNull("mine")) {
     mine = new Bet(json.getJSONObject("mine"));
   }
   if (!json.isNull("other")) {
     other = new Bet(json.getJSONObject("other"));
   }
 }
  public void LoadSeedData(String strColl, String metadatafile) throws Exception {
    try {
      InputStream is = this.getClass().getResourceAsStream(metadatafile);
      String xml;
      xml = IOUtils.toString(is);
      JSONObject rwSeed = XML.toJSONObject(xml);

      if (!rwSeed.isNull("ReferralWireSeedData")) {
        JSONObject json = rwSeed.getJSONObject("ReferralWireSeedData");
        DBCollection dbcoll = store.getColl(strColl);

        Object coll = (Object) json.get(strColl);
        if (coll instanceof JSONArray) {
          JSONArray defs = (JSONArray) coll;
          for (int i = 0; i < defs.length(); i++) {
            Object obj = (JSONObject) defs.get(i);
            dbcoll.insert((DBObject) com.mongodb.util.JSON.parse(obj.toString()));
          }
        } else {
          dbcoll.insert((DBObject) com.mongodb.util.JSON.parse(coll.toString()));
        }
      }
    } catch (IOException e) {
      // TODO Auto-generated catch block
      log.debug("API Error: ", e);
    }
  }
  private Blob loadVaultJson(JSONObject jsonObject, String regionId, String baseUrl)
      throws JSONException {
    String vaultName = jsonObject.getString("VaultName");
    String url;
    if (baseUrl.endsWith(vaultName)) {
      url = baseUrl;
    } else {
      url = baseUrl + "/" + vaultName;
    }

    String creationDate = jsonObject.getString("CreationDate");

    long creationTs = parseTimestamp(creationDate);

    if (jsonObject.has("SizeInBytes") && !jsonObject.isNull("SizeInBytes")) {
      Storage<Byte> storage = new Storage<Byte>(jsonObject.getLong("SizeInBytes"), Storage.BYTE);

      // somewhat dangerous: we want to specify a size for the vault, but currently
      // dasein-core only allows this specified on the Blob.getInstance() intended for
      // objects. It has a @Nonnull decorator for objectName, but we pass a null value
      // here. Currently in the implementation it does not matter.

      //noinspection ConstantConditions
      return Blob.getInstance(regionId, url, vaultName, null, creationTs, storage);
    }
    return Blob.getInstance(regionId, url, vaultName, creationTs);
  }
  private Place buildPlace(JSONObject json) {

    Place place = new Place();
    place.setAddressString(json.getJSONObject("address_obj").getString("address_string"));

    Coordinates coord = new Coordinates(json.getDouble("latitude"), json.getDouble("longitude"));

    if (coord.getLat() != 0 || coord.getLon() != 0) {

      place.setCoord(coord);
    }

    place.setId(json.getString("location_id"));
    place.setName(json.getString("name"));

    Rating rating = new Rating();
    rating.setRating(json.getDouble("rating"));
    rating.setRevisions(json.getInt("num_reviews"));

    place.setRating(rating);

    if (json.has("price_level") && !json.isNull("price_level")) {

      place.setPriceLevel(json.getString("price_level").length());
    } else {

      place.setPriceLevel(-1);
    }

    place.setPhotoId(place.getId());
    place.setProvider(providerId);

    return place;
  }
  @TargetApi(Build.VERSION_CODES.LOLLIPOP)
  @Override
  public void setProfileName(Operation operation) throws AndroidAgentException {
    // sets the name of the user since the agent is the device owner.
    String profileName = null;
    try {
      JSONObject setProfileNameData = new JSONObject(operation.getPayLoad().toString());
      if (!setProfileNameData.isNull(
          getContextResources().getString(R.string.intent_extra_profile_name))) {
        profileName =
            (String)
                setProfileNameData.get(
                    getContextResources().getString(R.string.intent_extra_profile_name));
      }

      operation.setStatus(getContextResources().getString(R.string.operation_value_completed));
      getResultBuilder().build(operation);

      if (profileName != null && !profileName.isEmpty()) {
        getDevicePolicyManager().setProfileName(getCdmDeviceAdmin(), profileName);
      }

      if (Constants.DEBUG_MODE_ENABLED) {
        Log.d(TAG, "Profile Name is set");
      }
    } catch (JSONException e) {
      operation.setStatus(getContextResources().getString(R.string.operation_value_error));
      getResultBuilder().build(operation);
      throw new AndroidAgentException("Invalid JSON format.", e);
    }
  }
  @TargetApi(Build.VERSION_CODES.LOLLIPOP)
  @Override
  public void blockUninstallByPackageName(Operation operation) throws AndroidAgentException {
    String packageName = null;
    try {
      JSONObject hideAppData = new JSONObject(operation.getPayLoad().toString());
      if (!hideAppData.isNull(getContextResources().getString(R.string.intent_extra_package))) {
        packageName =
            (String)
                hideAppData.get(getContextResources().getString(R.string.intent_extra_package));
      }

      operation.setStatus(getContextResources().getString(R.string.operation_value_completed));
      getResultBuilder().build(operation);

      if (packageName != null && !packageName.isEmpty()) {
        getDevicePolicyManager().setUninstallBlocked(getCdmDeviceAdmin(), packageName, true);
      }

      if (Constants.DEBUG_MODE_ENABLED) {
        Log.d(TAG, "App-Uninstall-Block successful.");
      }
    } catch (JSONException e) {
      operation.setStatus(getContextResources().getString(R.string.operation_value_error));
      getResultBuilder().build(operation);
      throw new AndroidAgentException("Invalid JSON format.", e);
    }
  }
  @Override
  public void changeLockCode(Operation operation) throws AndroidAgentException {
    getDevicePolicyManager()
        .setPasswordMinimumLength(getCdmDeviceAdmin(), getDefaultPasswordMinLength());
    String password = null;

    try {
      JSONObject lockData = new JSONObject(operation.getPayLoad().toString());
      if (!lockData.isNull(getContextResources().getString(R.string.intent_extra_lock_code))) {
        password =
            (String) lockData.get(getContextResources().getString(R.string.intent_extra_lock_code));
      }

      operation.setStatus(getContextResources().getString(R.string.operation_value_completed));
      getResultBuilder().build(operation);

      if (password != null && !password.isEmpty()) {
        getDevicePolicyManager()
            .resetPassword(password, DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY);
        getDevicePolicyManager().lockNow();
      }

      if (Constants.DEBUG_MODE_ENABLED) {
        Log.d(TAG, "Lock code changed");
      }
    } catch (JSONException e) {
      operation.setStatus(getContextResources().getString(R.string.operation_value_error));
      getResultBuilder().build(operation);
      throw new AndroidAgentException("Invalid JSON format.", e);
    }
  }
Beispiel #30
0
  @Override
  public Response handle(HttpRequest request) throws JSONException {
    SelendroidLogger.log("execute script command");
    JSONObject payload = getPayload(request);
    String script = payload.getString("script");
    JSONArray args = payload.optJSONArray("args");
    Object value = null;
    try {
      if (args.length() > 0) {
        value = getSelendroidDriver(request).executeScript(script, args);
      } else {
        value = getSelendroidDriver(request).executeScript(script);
      }
    } catch (UnsupportedOperationException e) {
      return new SelendroidResponse(getSessionId(request), 13, e);
    }
    if (value instanceof String) {
      String result = (String) value;
      if (result.contains("value")) {
        JSONObject json = new JSONObject(result);
        int status = json.optInt("status");
        if (0 != status) {
          return new SelendroidResponse(
              getSessionId(request), status, new SelendroidException(json.optString("value")));
        }
        if (json.isNull("value")) {
          return new SelendroidResponse(getSessionId(request), null);
        } else {
          return new SelendroidResponse(getSessionId(request), json.get("value"));
        }
      }
    }

    return new SelendroidResponse(getSessionId(request), value);
  }