/** parse an acknowledge to a token sent, analyze for permissions, disconnect on error */
  protected void parseVideoTokenResponse(JSONArray arg) {
    // TODO dk: parse all the other things that come with the response? TURN
    // Server, etc?
    boolean success = false;
    String message = "";
    try {
      success = "success".equalsIgnoreCase(arg.getString(0));
      if (success) {
        JSONObject obj = arg.getJSONObject(1);
        boolean subscribe = false;
        boolean publish = false;
        if (obj.has("permissions")) {
          JSONObject permissions = obj.getJSONObject("permissions");
          subscribe = permissions.has("subscribe") && permissions.getBoolean("subscribe");
          publish = permissions.has("publish") && permissions.getBoolean("publish");
        }
        mPermissionSubscribe = subscribe;
        mPermissionPublish = publish;
      } else {
        message = arg.get(1).toString();
      }
    } catch (JSONException e) {
      log(e.getMessage());
    }

    if (!success) {
      log("Token failed: " + message);
      disconnect();
    }
  }
Example #2
0
  /**
   * Description: Logs a user in.
   *
   * @param user -The user's username.
   * @param password -The user's password.
   * @throws RPCException when a Pandora RPC error occurs.
   * @throws SubscriberTypeException when a Pandora user is identified as not being the expected
   *     subscriber type.
   * @throws IOException when Pandora's servers can't be reached.
   * @throws HttpResponseException when an unexpected HTTP response occurs.
   * @throws Exception when an improper call to connect has been made.
   */
  public void connect(String user, String password)
      throws RPCException, SubscriberTypeException, IOException, HttpResponseException, Exception {
    if (!this.isPartnerAuthorized()) {
      throw new Exception("Improper call to connect(), " + "the application is not authorized.");
    }

    Map<String, Object> request_args = new HashMap<String, Object>();
    request_args.put("loginType", "user");
    request_args.put("username", user);
    request_args.put("password", password);
    request_args.put("partnerAuthToken", this.partner_auth_token);

    JSONObject result = this.doCall("auth.userLogin", request_args, true, true, null);

    // There are a few ways of handling these, but this way seems most
    // appropriate.
    // If this is a PandoraOne subscriber and the credentials aren't correct
    if (!result.getBoolean("hasAudioAds") && !isPandoraOneCredentials()) {
      throw new SubscriberTypeException(
          true, "The subscriber is Pandora One and default device credentials were given.");
      //			this.runPartnerLogin(true);
    }
    // If this is a non-PandoraOne subscriber and the credentials aren't correct
    else if (result.getBoolean("hasAudioAds") && isPandoraOneCredentials()) {
      throw new SubscriberTypeException(
          false, "The subscriber is standard and Pandora One device credentials were given.");
      //			this.runPartnerLogin(false);
    } else {
      this.user_auth_token = result.getString("userAuthToken");
      this.standard_url_params.put("auth_token", user_auth_token);
      this.standard_url_params.put("user_id", result.getString("userId"));
      // return user_auth_token != null;
    }
  }
  @Override
  protected void setLocalOptions(JSONObject o) throws JSONException {
    super.setLocalOptions(o);

    if (o.has("value")) {
      this.value = o.getString("value");
    }
    if (o.has("color")) {
      this.color = o.getString("color");
    }
    if (o.has("backgroundColor")) {
      this.backgroundColor = o.getString("backgroundColor");
    }
    if (o.has("enableReturnKey")) {
      this.enableReturnKey = o.getBoolean("enableReturnKey");
    }
    if (o.has("fontSize")) {
      this.fontSize = o.getString("fontSize");
    }
    if (o.has("fontWeight")) {
      this.fontWeight = o.getString("fontWeight");
    }
    if (o.has("showCancel")) {
      this.showCancel = o.getBoolean("showCancel");
    }
    if (o.has("barColor")) {
      this.barColor = o.getString("barColor");
    }
  }
 /**
  * Constructor
  *
  * @param jsonObject
  * @throws JSONException
  */
 public UserinfoData(JSONObject jsonObject) throws JSONException {
   if (jsonObject != null) {
     this.sub = jsonObject.has("sub") ? jsonObject.getString("sub") : null;
     this.name = jsonObject.has("name") ? jsonObject.getString("name") : null;
     this.given_name = jsonObject.has("given_name") ? jsonObject.getString("given_name") : null;
     this.family_name = jsonObject.has("family_name") ? jsonObject.getString("family_name") : null;
     this.middle_name = jsonObject.has("middle_name") ? jsonObject.getString("middle_name") : null;
     this.nickname = jsonObject.has("nickname") ? jsonObject.getString("nickname") : null;
     this.preferred_username =
         jsonObject.has("preferred_username") ? jsonObject.getString("preferred_username") : null;
     this.profile = jsonObject.has("profile") ? jsonObject.getString("profile") : null;
     this.picture = jsonObject.has("picture") ? jsonObject.getString("picture") : null;
     this.website = jsonObject.has("website") ? jsonObject.getString("website") : null;
     this.email = jsonObject.has("email") ? jsonObject.getString("email") : null;
     this.email_verified =
         jsonObject.has("email_verified") ? jsonObject.getBoolean("email_verified") : false;
     this.gender = jsonObject.has("gender") ? jsonObject.getString("gender") : null;
     this.birthdate = jsonObject.has("birthdate") ? jsonObject.getString("birthdate") : null;
     this.zoneinfo = jsonObject.has("zoneinfo") ? jsonObject.getString("zoneinfo") : null;
     this.locale = jsonObject.has("locale") ? jsonObject.getString("locale") : null;
     this.phone_number =
         jsonObject.has("phone_number") ? jsonObject.getString("phone_number") : null;
     this.phone_number_verfied =
         jsonObject.has("phone_number_verfied")
             ? jsonObject.getBoolean("phone_number_verfied")
             : false;
     if (jsonObject.has("address")) {
       JSONObject jsonAddress = jsonObject.getJSONObject("address");
       this.address = new UserinfoAddress(jsonAddress);
     } else this.address = null;
     this.updated_at = jsonObject.has("updated_at") ? (Number) jsonObject.get("updated_at") : null;
   }
 }
  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;
  }
Example #6
0
  private UserModel user(JSONObject jsonObject, int type, String account) throws JSONException {
    // TODO Auto-generated method stub
    // JSON包含id name screen_name location gender birthday description profile_image_url
    // profile_image_url_large
    // url protected followers_count friends_count favourites_count  statuses_count following
    // notifications
    // created_at utc_offset  profile_background_color profile_text_color profile_link_color
    // profile_sidebar_fill_color
    // profile_sidebar_border_color profile_background_image_url profile_background_tile
    UserModel model = new UserModel();
    model.setId(jsonObject.getString("id"));
    model.setAccount(this.account); // 全局
    model.setOwner(account); // 本地

    model.setType(type);
    model.setFlag(0);

    model.setRawid(0);
    model.setTime(FanFouParser.date(jsonObject.getString("created_at")).getTime());

    model.setName(jsonObject.getString("name"));
    model.setScreenName(jsonObject.getString("screen_name"));
    model.setLocation(jsonObject.getString("location"));
    model.setGender(jsonObject.getString("gender"));
    model.setBirthday(jsonObject.getString("birthday"));
    model.setDescription(jsonObject.getString("description"));

    model.setProfileImageUrl(jsonObject.getString("profile_image_url"));
    model.setProfileImageUrlLarge(jsonObject.getString("profile_image_url_large"));
    model.setUrl(jsonObject.getString("url"));

    if (jsonObject.has("status")) {
      JSONObject so = jsonObject.getJSONObject("status");
      model.setStatus(so.getString("text"));
    }

    model.setFollowersCount(jsonObject.getInt("followers_count"));
    model.setFriendsCount(jsonObject.getInt("friends_count"));
    model.setFavouritesCount(jsonObject.getInt("favourites_count"));
    model.setStatusesCount(jsonObject.getInt("statuses_count"));

    model.setFollowing(jsonObject.getBoolean("following"));
    model.setProtect(jsonObject.getBoolean("protected"));
    model.setNotifications(jsonObject.getBoolean("notifications"));
    model.setVerified(false);
    model.setFollowMe(false);

    LogUtil.d(
        TAG,
        "user() id="
            + model.getId()
            + " type="
            + model.getType()
            + " owner="
            + model.getOwner()
            + " account="
            + model.getAccount());

    return model;
  }
Example #7
0
  private static void setAuthentication(Site site, JSONObject jAuth) throws JSONException {
    site.mStandardAuth = jAuth.has("standard") && jAuth.getBoolean("standard");

    site.mSsoUrl = jAuth.has("sso") ? jAuth.getString("sso") : null;

    site.mPublicRegistration = jAuth.getBoolean("public-registration");
  }
 public void testMessageWithListen() 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);
   Button button = new Button(shell, SWT.PUSH);
   Map listeners = new HashMap();
   listeners.put("selection", new Boolean(false));
   listeners.put("focus", new Boolean(true));
   listeners.put("fake", new Boolean(true));
   writer.addListenPayload(WidgetUtil.getId(button), listeners);
   String widgetId = WidgetUtil.getId(button);
   String actual = stringWriter.getBuffer().toString();
   JSONObject message = new JSONObject(actual + "]}");
   JSONArray widgetArray = message.getJSONArray(IProtocolConstants.MESSAGE_WIDGETS);
   JSONObject widgetObject = widgetArray.getJSONObject(0);
   String actualId = widgetObject.getString(IProtocolConstants.WIDGETS_ID);
   assertEquals(widgetId, actualId);
   String type = widgetObject.getString(IProtocolConstants.WIDGETS_TYPE);
   assertEquals(IProtocolConstants.PAYLOAD_LISTEN, type);
   JSONObject payload = widgetObject.getJSONObject(IProtocolConstants.WIDGETS_PAYLOAD);
   assertFalse(payload.getBoolean("selection"));
   assertTrue(payload.getBoolean("focus"));
   assertTrue(payload.getBoolean("fake"));
 }
  public static THotelData fromJSON(JSONObject jsonObj) throws Exception {

    THotelData hotel = new THotelData();
    hotel.avgRating = jsonObj.getDouble("avgRating");
    hotel.distance = jsonObj.getDouble("distance");
    hotel.address = jsonObj.getString("address");
    hotel.lat = jsonObj.getDouble("lat");
    hotel.lng = jsonObj.getDouble("lng");
    hotel.name = jsonObj.getString("name");
    hotel.stars = jsonObj.getInt("stars");
    hotel.votes = jsonObj.getInt("votes");
    hotel.dataLink = jsonObj.getString("dataLink");
    JSONArray hRooms = jsonObj.getJSONArray("rooms");
    if (hRooms.length() > 0) {
      hotel.rooms = new ArrayList<TRoomData>();
      for (int n = 0; n < hRooms.length(); n++) {
        TRoomData room = TRoomData.fromJSON(hotel, (JSONObject) hRooms.get(n));
        hotel.rooms.add(room);
      }
    }

    hotel.cancelable = jsonObj.getBoolean("cancelable");
    hotel.withBreakfast = jsonObj.getBoolean("withBreakfast");
    hotel.ranking = jsonObj.getInt("ranking");
    hotel.avgDayPrice = jsonObj.getDouble("avgDayPrice");
    hotel.avgPrice = jsonObj.getDouble("avgPrice");
    hotel.avgCalculatedPrice = jsonObj.getDouble("avgCalculatedPrice");

    return hotel;
  }
 public boolean preloadProducts() {
   try {
     logger.log(Level.INFO, "Preloading products");
     ServerLoader loader = new ServerLoader();
     ServerLoader.Response r = loader.read("ProductsAPI", "getAll");
     if (r.getStatus().equals(ServerLoader.Response.STATUS_OK)) {
       JSONArray a = r.getArrayContent();
       List<ProductInfoExt> products = new ArrayList<ProductInfoExt>();
       for (int i = 0; i < a.length(); i++) {
         JSONObject o = a.getJSONObject(i);
         if (!o.getBoolean("visible")) {
           // Don't add products not sold
           continue;
         }
         ProductInfoExt prd = new ProductInfoExt(o);
         products.add(prd);
         try {
           if (o.getBoolean("hasImage")) {
             byte[] img = this.loadImage(TYPE_PRD, prd.getID());
             CatalogCache.storeProductImage(prd.getID(), img);
           }
         } catch (BasicException e) {
           logger.log(Level.WARNING, "Unable to get product image for " + prd.getID(), e);
         }
       }
       CatalogCache.refreshProducts(products);
       return true;
     } else {
       return false;
     }
   } catch (Exception e) {
     e.printStackTrace();
     return false;
   }
 }
Example #11
0
  public void recursiveRoute(
      final String currentPath, final String url, final JSONArray currentArray) {
    try {
      String res = this.get(url, new HashMap<String, String>());
      JSONObject responseObj = new JSONObject(res);

      if (responseObj.getBoolean("is_dir")) {
        JSONArray sub = responseObj.getJSONArray("contents");
        for (int i = 0; i < sub.length(); ++i) {
          JSONObject file = sub.getJSONObject(i);
          JSONObject fileToAdd = new JSONObject();
          String nxtPath = file.getString("path");
          fileToAdd.put("path", nxtPath.substring(1));
          if (file.getBoolean("is_dir")) {
            recursiveRoute(
                nxtPath,
                "https://api.dropboxapi.com/1/metadata/auto"
                    + nxtPath
                    + "?access_token="
                    + this.m_token,
                currentArray);
          }
          currentArray.put(fileToAdd);
        }
      }
    } catch (Exception e) {
      e.getMessage();
    }
  }
Example #12
0
 public static NotificationVo getStringToObj(String jArr, NotificationVo nv) {
   NotificationVo result = nv;
   try {
     LogUtil.d(TAG, "json :---------" + jArr.toString());
     JSONObject objJson = new JSONObject(jArr);
     String msgType = objJson.getString("msg_type");
     String msgId = objJson.getString("msgId");
     String msgClassName = objJson.getString("msgClassName");
     String msgFromClassName = objJson.getString("mfcName");
     boolean isPing = objJson.getBoolean("isPing");
     boolean isShock = objJson.getBoolean("isShock");
     String msgc = objJson.getString("msg_c");
     if ("2".equals(msgType)) {
       String msgToType = objJson.getString("msgToType");
       String strData = objJson.getString("strData");
       result.setStrData(strData);
       result.setMsgToType(msgToType);
     } else {
       String openUrl = objJson.getString("open_url");
       nv.setOpenUrl(openUrl);
     }
     result.setMsgId(msgId);
     result.setMsgClassName(msgClassName);
     result.setMsgFromClassName(msgFromClassName);
     result.setMsgType(msgType);
     result.setPing(isPing);
     result.setShock(isShock);
     result.setMsgC(msgc);
   } catch (Exception e) {
     e.printStackTrace();
   }
   return result;
 }
  /** Optionally expects boolean params 'deleted' and 'privilegeInheritanceBlocked' */
  @Override
  public <T extends FsSecureBusinessObject> Object putRepresentation(
      T sbo, Object params, FsAccessToken token) {
    JSONObject data = (JSONObject) params;

    try {
      boolean deleted = data.getBoolean("deleted");

      if (sbo.isDeleted() != deleted) {
        sbo.setDeleted(deleted);
      }
    } catch (JSONException e) {
      // do nothing, because we do not force a client to always send this information back to the
      // server
    }

    try {
      boolean privInheritanceBlocked = data.getBoolean("privilegeInheritanceBlocked");

      if (sbo.isPrivilegeInheritanceBlocked() != privInheritanceBlocked) {
        sbo.setPrivilegeInheritanceBlocked(privInheritanceBlocked);
      }
    } catch (JSONException e) {
      // do nothing, because we do not force a client to always send this information back to the
      // server
    }

    return getRepresentation(sbo, params, token);
  }
 public WorkTime(JSONObject json) throws JSONException {
   id = json.getLong(JSON_ID);
   clockInTime = new Date(json.getLong(JSON_CLOCK_IN));
   clockOutTime = new Date(json.getLong(JSON_CLOCK_OUT));
   active = json.getBoolean(JSON_ACTIVE);
   working = json.getBoolean(JSON_WORKING);
   breakTime = json.getLong(JSON_BREAK_TIME);
   breakTimeStart = json.getLong(JSON_LAST_SAVED_BREAK_TIME);
   initOtherVars();
 }
  private void freightUI(JSONObject jsonObject) throws JSONException {

    ls_data.clear();

    JSONArray array = jsonObject.getJSONArray("data");

    int size = array.length();
    if (size == 0) {
      CodeUtil.toast(COBaseFragment.this.getActivity(), "没有订单");
      if (ls_data.size() == 0) {
        setReloadAvailable();
      } else {
        setReloadGone();
      }
      adapter.notifyDataSetChanged();
      return;
    }

    for (int i = 0; i < size; i++) {

      JSONObject object = array.getJSONObject(i);
      OrderBaseAdapter.OrderInfo info = new OrderBaseAdapter.OrderInfo();
      CodeUtil.doOrderCommonDo(object, info);

      info.isValid = object.getBoolean("isvalid");
      info.isPayOnline = object.getBoolean("isPayOln");

      // 是否有效
      if (!info.isValid) {
        info.cause = object.getString("cause");

        // 是否在线付款了
        if (info.isPayOnline) {
          info.refundStatus = object.getInt("status");
        }

      } else {

        if (object.opt("category") == null) {
          info.status = 5;
          info.out_time = DateUtil.getHourAndMinute(object.getString("sendtime"));

        } else {
          info.status = object.optInt("category");
          if (info.status == 5) {
            info.out_time = DateUtil.getHourAndMinute(object.getString("sendtime"));
          }
        }
      }
      ls_data.add(info);
    }

    setReloadGone();
    adapter.notifyDataSetChanged();
  }
  @Override
  protected void onPostExecute(String result) {

    ArrayList<MimicData> mimicdata = new ArrayList<MimicData>();

    if (result.length() == 0) {}

    try {
      JSONObject x = new JSONObject(result);
      JSONArray respobj = x.getJSONArray("results");
      for (int i = 0; i < respobj.length(); i++) {
        JSONObject post = respobj.getJSONObject(i);
        JSONObject user = post.getJSONObject("user");
        String username = user.getString("username");
        String dpurl = user.getString("profilepictureurl");
        String profileurl = user.getString("url");
        String url = post.getString("url");
        boolean owner = post.getBoolean("own");
        String posturl = post.getString("posturls");
        String description = post.getString("description");
        if (description == "null") {
          description = " ";
        }
        int comments = post.getInt("commentscount");
        int likes = post.getInt("likescount");
        int postid = post.getInt("id");
        Boolean likesbool = post.getBoolean("favourites");
        String timestamp = post.getString("time");

        mimicdata.add(
            new MimicData(
                username,
                dpurl,
                url,
                postid,
                likes,
                comments,
                posturl,
                description,
                likesbool,
                timestamp,
                profileurl,
                true,
                owner));
      }

    } catch (JSONException e) {

      e.printStackTrace();
    }
    this.activity.setMimics(mimicdata);
    prog.dismiss();
  }
  private Review getReview(JSONObject jsonReview) throws JSONException {

    Review review = new Review();
    review.setId(jsonReview.getInt("id"));
    review.setBodyTop(jsonReview.getString("body_top"));
    review.setBodyBottom(jsonReview.getString("body_bottom"));
    review.setUser(jsonReview.getJSONObject("links").getJSONObject("user").getString("title"));
    review.setPublicReview(jsonReview.getBoolean("public"));
    review.setShipIt(jsonReview.getBoolean("ship_it"));
    review.setTimestamp(ReviewboardUtil.marshallDate(jsonReview.getString("timestamp")));
    return review;
  }
  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);
    }
  }
 public OutputLogItemContainer(JSONObject newLogItems) throws JSONException {
   JSONArray arrayOfItems = new JSONArray();
   JSONObject object = new JSONObject();
   logItems = new ArrayList<OutputLogItem>();
   arrayOfItems = newLogItems.getJSONArray(logItems_JSON);
   for (int i = 0; i < arrayOfItems.length(); i++) {
     object = arrayOfItems.getJSONObject(i);
     logItems.add(new OutputLogItem(object));
   }
   alreadySetPoopAward = newLogItems.getBoolean(poopAward_JSON);
   alreadySetPeeAward = newLogItems.getBoolean(peeAward_JSON);
   didPoop = newLogItems.getBoolean(didPoop_JSON);
   hadPeeAccident = newLogItems.getBoolean(peeAccident_JSON);
   dateCreated = new Date(newLogItems.getLong(dateCreated_JSON));
 }
Example #20
0
  public static Tweet fromJson(JSONObject jsonObj) {
    Tweet tweet = new Tweet();
    try {
      tweet.body = jsonObj.getString("text");
      tweet.id = jsonObj.getLong("id");
      tweet.createdAt = jsonObj.getString("created_at");
      try {
        tweet.numFavorites = jsonObj.getLong("favorite_count");
      } catch (JSONException j) {
        tweet.numFavorites = 0l;
      }
      try {
        tweet.numReTweets = jsonObj.getLong("retweet_count");
      } catch (JSONException j) {
        tweet.numReTweets = 0l;
      }
      tweet.user = User.fromJson(jsonObj.getJSONObject("user"));

      try {
        tweet.favorited = jsonObj.getBoolean("favorited");
      } catch (JSONException j) {
        tweet.favorited = false;
      }

      try {
        tweet.retweeted = jsonObj.getBoolean("retweeted");
      } catch (JSONException j) {
        tweet.retweeted = false;
      }

      tweet.mediaUrl = "";
      try {
        JSONArray ja = jsonObj.getJSONObject("entities").getJSONArray("media");
        for (int i = 0; i < ja.length(); i += 1) {
          if ("photo".equals(ja.getJSONObject(i).getString("type"))) {
            tweet.mediaUrl = ja.getJSONObject(i).getString("media_url");
            break;
          }
        }
      } catch (JSONException j) {
        tweet.mediaUrl = "";
      }
    } catch (JSONException je) {
      je.printStackTrace();
      return null;
    }
    return tweet;
  }
 public void addNewArticleToUser(String data, int articleId) {
   Log.d("SVF", "Modifying topic " + articleId);
   try {
     JSONObject article = new JSONObject(data);
     boolean found = article.getBoolean("found");
     if (found) {
       // update topic with new article; don't do anything if not found
       if (!ValuesAndUtil.getInstance().articleAlreadyExists(article, topics, articleId)) {
         article.remove("found");
         article.put("thumbsUp", false);
         article.put("thumbsDown", false);
         JSONObject topic = topics.getJSONObject(articleId);
         JSONArray timeline = topic.getJSONArray("timeline");
         timeline = ValuesAndUtil.getInstance().addToExistingJSON(timeline, 0, article);
         topic.put("timeline", timeline);
         topic.put("lastTimeStamp", article.getLong("date"));
         topic.put("lastSignature", article.getString("signature"));
         topic.put("lastUpdated", System.currentTimeMillis());
         Log.d("SVF", topic.toString(2));
         topics.put(articleId, topic);
         user.put("topics", topics);
         ValuesAndUtil.getInstance().saveUserData(user, getActivity().getApplicationContext());
         mAdapter.notifyItemChanged(articleId);
         numUpdated++;
       }
     }
   } catch (JSONException e) {
     e.printStackTrace();
   }
 }
  @Test
  public void testMultipart() throws IOException, JSONException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://localhost:" + PORT + "/");

    File image = new File("resources/test/base.png");
    FileBody imagePart = new FileBody(image);
    StringBody messagePart = new StringBody("some message");

    MultipartEntity req = new MultipartEntity();
    req.addPart("image", imagePart);
    req.addPart("message", messagePart);
    httppost.setEntity(req);

    ImageEchoServer server = new ImageEchoServer(PORT);
    HttpResponse response = httpclient.execute(httppost);
    server.stop();

    HttpEntity resp = response.getEntity();
    assertThat(resp.getContentType().getValue(), is("application/json"));

    // sweet one-liner to convert an inputstream to a string from stackoverflow:
    // http://stackoverflow.com/questions/309424/in-java-how-do-i-read-convert-an-inputstream-to-a-string
    String out = new Scanner(resp.getContent()).useDelimiter("\\A").next();

    JSONObject json = new JSONObject(out);

    String base64 = Base64.encodeFromFile("resources/test/base.png");

    assertThat(json.getString("screenshot"), is(base64));
    assertThat(json.getBoolean("imageEcho"), is(true));
  }
Example #23
0
    @Override
    protected void onPostExecute(String response) {
      super.onPostExecute(response);
      Log.d(TAG, "Response : " + response);
      if (response != null) {

        try {
          JSONObject jsonObject = new JSONObject(response);
          boolean isSuccess = jsonObject.getBoolean(Keys.KEY_SUCCESS);

          if (isSuccess) {

            Log.d(TAG, "Profile information Updated");
            Snackbar.make(profileImgView, "Profile information Updated", Snackbar.LENGTH_LONG)
                .setAction("Action", null)
                .show();

          } else {
            Snackbar.make(profileImgView, "Profile information not Updated", Snackbar.LENGTH_LONG)
                .setAction("Action", null)
                .show();
            Log.d(TAG, "Profile information not Updated");
          }
        } catch (JSONException e) {
          e.printStackTrace();
        }
      } else {
        Log.d(TAG, "Update response is NULL");
      }
    }
 /**
  * バッテリー全属性取得テストを行う.
  *
  * <pre>
  * 【HTTP通信】
  * Method: GET
  * Path: /battery?deviceid=xxxx
  * </pre>
  *
  * <pre>
  * 【期待する動作】
  * ・resultに0が返ってくること。
  * ・chargingがfalseで返ってくること。
  * ・chargingtimeが50000で返ってくること。
  * ・dischargingtimeが10000で返ってくること。
  * ・levelが0.5で返ってくること。
  * </pre>
  */
 public void testGetBattery() {
   URIBuilder builder = TestURIBuilder.createURIBuilder();
   builder.setProfile(BatteryProfileConstants.PROFILE_NAME);
   builder.addParameter(DConnectProfileConstants.PARAM_DEVICE_ID, getDeviceId());
   builder.addParameter(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN, getAccessToken());
   try {
     HttpUriRequest request = new HttpGet(builder.toString());
     JSONObject root = sendRequest(request);
     assertResultOK(root);
     assertEquals(
         "charging is not equals.",
         TestBatteryProfileConstants.CHARGING,
         root.getBoolean(BatteryProfileConstants.ATTRIBUTE_CHARGING));
     assertEquals(
         "chargingtime is not equals.",
         TestBatteryProfileConstants.CHARGING_TIME,
         root.getDouble(BatteryProfileConstants.ATTRIBUTE_CHARGING_TIME));
     assertEquals(
         "dischargingtime is not equals.",
         TestBatteryProfileConstants.DISCHARGING_TIME,
         root.getDouble(BatteryProfileConstants.ATTRIBUTE_DISCHARGING_TIME));
     assertEquals(
         "level is not equals.",
         TestBatteryProfileConstants.LEVEL,
         root.getDouble(BatteryProfileConstants.ATTRIBUTE_LEVEL));
   } catch (JSONException e) {
     fail("Exception in JSONObject." + e.getMessage());
   }
 }
Example #25
0
  @Test
  public void testReadDirectoryChildren()
      throws CoreException, IOException, SAXException, JSONException {
    String dirName = "path" + System.currentTimeMillis();
    String directoryPath = "sample/directory/" + dirName;
    createDirectory(directoryPath);

    String subDirectory = "subdirectory";
    createDirectory(directoryPath + "/" + subDirectory);

    String subFile = "subfile.txt";
    createFile(directoryPath + "/" + subFile, "Sample file");

    WebRequest request = getGetFilesRequest(directoryPath + "?depth=1");
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    List<JSONObject> children = getDirectoryChildren(new JSONObject(response.getText()));

    assertEquals("Wrong number of directory children", 2, children.size());

    for (JSONObject child : children) {
      if (child.getBoolean("Directory")) {
        checkDirectoryMetadata(child, subDirectory, null, null, null, null, null);
      } else {
        checkFileMetadata(child, subFile, null, null, null, null, null, null, null);
      }
    }
  }
  public static List<User> getAllUsers() {

    List<User> users = new ArrayList<User>();

    NoJsonHttpRequest getRequest = new NoJsonHttpRequest(serverUrl, usersPath, "GET");
    getRequest.addHeaderParameter(authorizationHeaderName, Util.base64Header);

    int statusCode = getRequest.execute();

    if (statusCode >= 300) {
      return users;
    }

    String response = getRequest.getResponse();

    try {
      JSONArray ja = new JSONArray(response);
      for (int i = 0; i < ja.length(); i++) {
        JSONObject jo = ja.getJSONObject(i);
        users.add(
            new User(
                jo.getInt("id"),
                jo.getString("name"),
                jo.getString("surname"),
                jo.getBoolean("isManager"),
                jo.getString("username")));
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }

    return users;
  }
Example #27
0
  public CommentSet findCommentsForIssue(String issueId, int page, int pageSize)
      throws ServiceException {
    try {
      StringBuilder url = new StringBuilder();
      url.append(rootURL).append("/issue/").append(issueId).append("/comments");
      if (page > 0) url.append("?page=").append(page).append("&pageSize=").append(pageSize);

      HttpGet get = new HttpGet(url.toString());
      HttpResponse response = execute(get);
      int code = response.getStatusLine().getStatusCode();
      if (HttpStatus.SC_NOT_FOUND == code) {
        if (Config.LOGD) Log.d(TAG, "No comments for issue '" + issueId + "'.");
        List<Comment> comments = Collections.emptyList();
        return new CommentSet(comments, false);
      } else if (HttpStatus.SC_OK == code) {
        JSONObject obj = readJSON(response);
        if (Config.LOGV) Log.v(TAG, "Comments JSON:  " + obj.toString(4));
        List<Comment> issues = loadComments(obj);
        boolean more = obj.getBoolean("more");
        if (Config.LOGD) Log.d(TAG, "Searched returned " + issues.size() + " results.");
        return new CommentSet(issues, more);
      } else throw new ServiceException(MSG_REMOTE_ERROR + code);
    } catch (JSONException e) {
      throw new ServiceException(MSG_PARSE_ERROR, e);
    } catch (IOException e) {
      throw new ServiceException(MSG_CONNECT_ERROR, e);
    }
  }
Example #28
0
  private void Login(String login, String password) {
    HttpClient httpclient = new DefaultHttpClient();
    // Prepare a request object
    StringBuilder url = new StringBuilder(getResources().getString(R.string.AUTHENTIFICATION_URL));
    url.append("?tag=login&login=");
    url.append(login);
    url.append("&password=");
    url.append(password);
    HttpGet httpget = new HttpGet(url.toString());

    // Execute the request
    HttpResponse response;
    try {
      response = httpclient.execute(httpget);
      // Examine the response status
      Log.i("connection prete", response.getStatusLine().toString());

      // Get hold of the response entity

      if (response.getEntity() != null) {

        InputStream inputStream = response.getEntity().getContent();

        // Lecture du retour au format JSON
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder stringBuilder = new StringBuilder();

        String ligneLue = bufferedReader.readLine();
        while (ligneLue != null) {
          stringBuilder.append(ligneLue + " \n");
          ligneLue = bufferedReader.readLine();
        }
        bufferedReader.close();

        // Get hold of the response entity
        JSONObject jsonObject = new JSONObject(stringBuilder.toString());

        Log.i("Chaine JSON", stringBuilder.toString());

        //	             JSONObject jsonResultSet = jsonObject.getJSONObject("nb");
        jsonObject.getJSONObject("utilisateurs").getString("mail");
        jsonObject.get("id");

        if (jsonObject.getBoolean("error") == false) {
          Intent i = new Intent(getApplicationContext(), LoggedActivity.class);
          startActivity(i);
        } else {
          Toast.makeText(getApplicationContext(), "Erreur d'identification", Toast.LENGTH_LONG)
              .show();
        }

        // If the response does not enclose an entity, there is no need
        // to worry about connection release

      }
    } catch (Exception e) {

      e.printStackTrace();
    }
  }
  /** Getting product details in background thread */
  protected Integer doInBackground(User... args) {
    User user = args[0];

    // Check for success tag
    boolean success = false;
    try {
      // Building Parameters
      List<NameValuePair> params = new ArrayList<NameValuePair>();
      params.add(new BasicNameValuePair(User.NAME_TAG, user.getName()));
      params.add(new BasicNameValuePair(User.PASSWORD_TAG, user.getPassword()));

      // getting product details by making HTTP request
      // Note that product details url will use GET request
      JSONObject json = jsonParser.makeHttpRequest(RestConstants.URL_VALIDATE_USER, "GET", params);

      // check your log for json response
      // Log.d("Single Product Details", json.toString());

      // json success tag
      success = json.getBoolean(RestConstants.TAG_SUCCESS);
      if (success) {

        int userId = json.getInt(RestConstants.TAG_RESULT);

        return userId;
      } else {
        return -1;
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }

    return -1;
  }
Example #30
0
    @Override
    protected Boolean doInBackground(Void... params) {
      try {
        // Simulate network access.
        Thread.sleep(0);
      } catch (InterruptedException e) {
        return false;
      }

      String jsonString =
          ServerUtils.submitRequest(
              "userLogin", "action=login", "password=" + mPassword, "email=" + mEmail);
      JSONObject jso;
      try {
        jso = new JSONObject(jsonString);
        if (jso.getBoolean("result")) {
          mUserJson = jso.getJSONObject("user");
          return true;
        }
      } catch (JSONException e) {
        e.printStackTrace();
      }

      return false;
    }