@RequestMapping(value = "/link", method = RequestMethod.POST)
 public ResponseEntity<?> shortener(
     @RequestParam("url") String url,
     @RequestParam(value = "custom", required = false) String custom,
     @RequestParam(value = "expire", required = false) String expireDate,
     @RequestParam(value = "hasToken", required = false) String hasToken,
     @RequestParam(value = "emails[]", required = false) String[] emails,
     @RequestParam(value = "days", required = false) String days,
     HttpServletRequest request,
     Principal principal)
     throws Exception {
   JSONObject jn = getFreegeoip(request);
   String country = jn.getString("country_name");
   ShortURL su =
       createAndSaveIfValid(
           url, custom, hasToken, expireDate, extractIP(request), emails, principal, country);
   if (su != null) {
     /* If there is an expire date, it sets an alert */
     if (!expireDate.equals("")) {
       Date alertDate = processAlertDate(expireDate, days);
       logger.info("New alert date: " + alertDate);
       String mail = UrlShortenerControllerWithLogs.getOwnerMail();
       Alert alert = new Alert(mail, su.getHash(), alertDate);
       alertRepository.save(alert);
     }
     HttpHeaders h = new HttpHeaders();
     h.setLocation(su.getUri());
     return new ResponseEntity<>(su, h, HttpStatus.CREATED);
   } else {
     return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
   }
 }
  /**
   * Checks if is scope valid.
   *
   * @param scope the scope
   * @param response the response
   * @return true, if is scope valid
   */
  private boolean isScopeValid(String scope, String response) {
    boolean isValid = true;
    JSONObject obj;
    try {
      obj = new JSONObject(response);

      if (obj.toString().equals("{}")) {
        System.out.println("No claims have not null values in the scope : " + scope);
        return true;
      }

      Iterator keys = obj.keys();
      List xmlScopeList = scopes.get(scope).getClaims().getClaimValues();

      while (keys.hasNext()) {
        String key = (String) keys.next();
        if (!xmlScopeList.contains(key)) {
          log.info("Response contains a claim value that is not belongs to scope " + scope);
          isValid = false;
          break;
        }
      }
    } catch (JSONException e) {
      e.printStackTrace();
      return false;
    }
    return isValid;
  }
Example #3
0
 private void handleLinkFavicon(final JSONObject message) throws JSONException {
   if (mContentDelegate != null) {
     int id = message.getInt("tabID");
     mContentDelegate.onReceivedFavicon(
         GeckoView.this, new Browser(id), message.getString("href"), message.getInt("size"));
   }
 }
Example #4
0
  public void sendMessage(Message message) throws JSONException {
    JSONObject json = new JSONObject();
    json.put("text", message.getText());
    json.put("roomId", message.getRoomId());
    if (message.getFileAddress() != null && message.getFileAddress().length() > 0) {
      json.put("file", message.getFileAddress());
    } else {
      json.put("file", "");
    }
    NetworkManager.sendRequest(
        MethodsName.SEND_MESSAGE,
        json,
        new NetworkReceiver() {
          @Override
          public void onResponse(Object response) {
            // todo change message status to sent
            Log.wtf("SEND_MESSAGE", response.toString());
          }

          @Override
          public void onErrorResponse(BerimNetworkException error) {
            // todo show error for message.
            Log.wtf("SEND_MESSAGE", error.getMessage());
          }
        });
    addMessage(message);
  }
    @Override
    protected String doInBackground(String... params) {
      String response = null;

      try {

        ServerCommunicator serverCommunicator = new ServerCommunicator();

        String requestURL = Configuration.GET_CATEGORIES;

        System.out.println("the getting url is++" + requestURL);
        try {
          // 3. build jsonObject
          JSONObject jsonObject = new JSONObject();
          jsonObject.accumulate("category", "All");

          // 4. convert JSONObject to JSON to String
          reqParams = jsonObject.toString();
          Log.d("Login request params:", reqParams);

        } catch (JSONException e) {
          e.getLocalizedMessage();
        }
        response = serverCommunicator.postJSONData(reqParams, requestURL);
      } catch (Exception e) {
        e.printStackTrace();
      }
      System.out.println("responseresponse responseresponse--" + response);
      return response;
    }
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_stories_view, container, false);
    getActivity().setTitle(getResources().getString(R.string.title_activity_news_home_screen));

    swipeLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh_layout);
    swipeLayout.setOnRefreshListener(this);

    TextView noTopicsText = (TextView) rootView.findViewById(R.id.no_topics_textview);
    user = ValuesAndUtil.getInstance().loadUserData(getActivity().getApplicationContext());

    boolean hasTopics = false;
    try {
      hasTopics = user.has("topics") && user.getJSONArray("topics").length() > 0;
    } catch (JSONException e) {
      e.printStackTrace();
    }
    Log.d("SVF", "Has topics = " + hasTopics);
    if (!hasTopics) {
      noTopicsText.setText(getString(R.string.no_topics_available));
      swipeLayout.setVisibility(View.INVISIBLE);
    } else {
      Log.d("SVF", "Topics were not null");
      swipeLayout.setVisibility(View.VISIBLE);
      try {
        topics = user.getJSONArray("topics");
        setUpList(rootView, topics);
      } catch (JSONException e) {
        e.printStackTrace();
      }
    }

    return rootView;
  }
  public static HashMap<String, Integer> getAnimeSearchedMAL(
      String username, String password, String anime) {
    HashMap<String, Integer> map = new HashMap<String, Integer>();

    JSONObject xmlJSONObj;
    String json = "";
    String xml = "";
    try {
      xml = searchAnimeMAL(username, password, anime);
      xmlJSONObj = XML.toJSONObject(xml);
      json = xmlJSONObj.toString(4);
    } catch (Exception e) {
      MAMUtil.writeLog(e);
      e.printStackTrace();
    }
    JsonParser parser = new JsonParser();
    JsonObject root = parser.parse(json).getAsJsonObject();
    if (root.has("anime") && root.get("anime").getAsJsonObject().get("entry").isJsonArray()) {
      JsonArray searchedAnime = root.get("anime").getAsJsonObject().get("entry").getAsJsonArray();
      for (JsonElement obj : searchedAnime) {
        String name = obj.getAsJsonObject().get("title").getAsString();
        int id = obj.getAsJsonObject().get("id").getAsInt();
        map.put(name, id);
      }
    } else if (root.has("anime")) {
      JsonObject obj = root.get("anime").getAsJsonObject().get("entry").getAsJsonObject();
      int id = obj.getAsJsonObject().get("id").getAsInt();
      map.put(anime, id);
    }
    return map;
  }
  /**
   * Get the JSON data for the Case Study
   *
   * @return boolean indicates whether the case study data is loaded
   */
  private boolean cacheJSON() {
    if (this.getType().equals("LOCAL")) {
      try {
        JSONobj = (new JSONObject(this.loadJSONFromAsset(this.getLocation())));
        Iterator<String> iter = JSONobj.keys();
        this.id = iter.next();

        JSONobj = JSONobj.getJSONObject(this.id);
      } catch (JSONException e) {
        e.printStackTrace();
      }
      return true;
    } else if (this.getType().equals("DISK")) {
      try {
        JSONobj = (new JSONObject(this.loadJSONFromStorage(this.getLocation())));
        Iterator<String> iter = JSONobj.keys();
        this.id = iter.next();

        JSONobj = JSONobj.getJSONObject(this.id);
      } catch (JSONException e) {
        e.printStackTrace();
      }
      return true;
    } else {
      return false;
    }
  }
  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);
    }
  }
Example #10
0
 public static Bundle Json2Bundle(JSONObject json) {
   Bundle mBundle = new Bundle();
   @SuppressWarnings("unchecked")
   Iterator<String> iter = json.keys();
   Object value;
   while (iter.hasNext()) {
     String key = iter.next();
     try {
       value = json.get(key);
       if (Boolean.class.isInstance(value)) {
         mBundle.putBoolean(key, (Boolean) value);
       } else if (Double.class.isInstance(value)) {
         mBundle.putDouble(key, (Double) value);
       } else if (Integer.class.isInstance(value)) {
         mBundle.putInt(key, (Integer) value);
       } else if (Long.class.isInstance(value)) {
         mBundle.putLong(key, (Long) value);
       } else if (JSONObject.class.isInstance(value)) {
         mBundle.putBundle(key, Json2Bundle((JSONObject) value));
       } else {
         mBundle.putString(key, json.getString(key));
       }
     } catch (JSONException e) {
       e.printStackTrace();
     }
   }
   return mBundle;
 }
 private Payload doInBackgroundRegister(Payload data) {
   String username = (String) data.data[0];
   String password = (String) data.data[1];
   BasicHttpSyncer server = new RemoteServer(this, null);
   HttpResponse ret = server.register(username, password);
   String hostkey = null;
   boolean valid = false;
   data.returnType = ret.getStatusLine().getStatusCode();
   String status = null;
   if (data.returnType == 200) {
     try {
       JSONObject jo = (new JSONObject(server.stream2String(ret.getEntity().getContent())));
       status = jo.getString("status");
       if (status.equals("ok")) {
         hostkey = jo.getString("hkey");
         valid = (hostkey != null) && (hostkey.length() > 0);
       }
     } catch (JSONException e) {
     } catch (IllegalStateException e) {
       throw new RuntimeException(e);
     } catch (IOException e) {
       throw new RuntimeException(e);
     }
   }
   if (valid) {
     data.success = true;
     data.data = new String[] {username, hostkey};
   } else {
     data.success = false;
     if (status != null) {
       data.data = new String[] {status};
     }
   }
   return data;
 }
  /**
   * Create and show a simple notification containing the received GCM message.
   *
   * @param message GCM message received.
   */
  private void sendNotification(String message, String extra) {
    Intent intent = new Intent("com.ibm.bluebridge.pushnotification");
    try {
      JSONObject data = new JSONObject(extra);
      Iterator<String> itr = data.keys();
      while (itr.hasNext()) {
        String key = itr.next();
        intent.putExtra(key, data.getString(key));
      }
    } catch (JSONException e) {
      Log.e(TAG, "Cannot parse data, no extra set to Notification");
    }
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent =
        PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder =
        new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.logo)
            .setContentTitle("BlueBridge")
            .setContentText(message)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
  }
Example #13
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");
      }
    }
  protected void createAndSaveClick(String hash, HttpServletRequest request) {
    /* Gets the IP from the request, and looks in the db for its country */
    String dirIp = extractIP(request);
    BigInteger valueIp = getIpValue(dirIp);
    Ip subnet = ipRepository.findSubnet(valueIp);
    String country = (subnet != null) ? (subnet.getCountry()) : ("");

    request.getHeader(USER_AGENT);
    JSONObject jn = getFreegeoip(request);
    String city = jn.getString("city");
    Float latitude = new Float(jn.getDouble("latitude"));
    Float longitude = new Float(jn.getDouble("longitude"));
    Click cl =
        new Click(
            null,
            hash,
            new Date(System.currentTimeMillis()),
            request.getHeader(REFERER),
            request.getHeader(USER_AGENT),
            request.getHeader(USER_AGENT),
            dirIp,
            country,
            city,
            longitude,
            latitude);
    cl = clickRepository.save(cl);
    logger.info(
        cl != null
            ? "[" + hash + "] saved with id [" + cl.getId() + "]"
            : "[" + hash + "] was not saved");
  }
  public void refreshAllStories() {
    // get all topics
    if (!user.has("topics")) {
      swipeLayout.setRefreshing(false);
      return;
    }

    try {
      for (int i = 0; i < topics.length(); i++) {
        JSONObject topic = topics.getJSONObject(i);
        JSONArray topicWords = topic.getJSONObject("modifiedTopicWords").names();
        String urlParams = "";
        for (int j = 0; j < topicWords.length(); j++) {
          String curr = topicWords.getString(j);
          curr = curr.replaceAll("\\s+", "+");
          urlParams += ("words=" + curr + "&");
        }
        long timestamp = topic.getLong("lastTimeStamp");
        urlParams += ("timestamp=" + timestamp);
        String category = topic.getString("category");
        urlParams += ("&category=" + category);
        Log.d("SVF", "Would send: " + urlParams);
        new DownloadNextArticleData().execute(urlParams, Integer.toString(i));
      }
    } 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));
  }
 public void doAfterPostSuccess(String s, int articleId) {
   if (s.equals("IOException")) {
     Toast.makeText(
             getActivity().getApplicationContext(),
             "Server not available, please contact application owner",
             Toast.LENGTH_SHORT)
         .show();
     mAdapter.notifyDataSetChanged();
     swipeLayout.setRefreshing(false);
     return;
   }
   addNewArticleToUser(s, articleId);
   done++;
   Log.d("SVF", "Done " + done + " out of " + topics.length());
   if (done == topics.length()) {
     swipeLayout.setRefreshing(false);
     ValuesAndUtil.getInstance().saveUserData(user, getActivity().getApplicationContext());
     try {
       JSONArray sortedTopics =
           ValuesAndUtil.getInstance().sortTopicsArray(user.getJSONArray("topics"));
       user.put("topics", sortedTopics);
       ValuesAndUtil.getInstance().saveUserData(user, getActivity().getApplicationContext());
       mAdapter = new StoriesViewAdapter(sortedTopics);
       if (numUpdated == 0) {
         Toast.makeText(getActivity(), "No updates found for any stories", Toast.LENGTH_SHORT)
             .show();
       }
     } catch (JSONException e) {
       e.printStackTrace();
     }
     mRecyclerView.setAdapter(mAdapter);
     Log.d("SVF", "Finished updating all articles");
   }
 }
 private static JSONObject toJSONObject(NamedTagHead tag) throws JSONException {
   JSONObject retval = new JSONObject();
   retval.put("guid", MiscUtils.toString(tag.getTagGUID()));
   retval.put("type", MiscUtils.toString(tag.getTagType()));
   retval.put("name", tag.getName());
   return retval;
 }
Example #19
0
    @Override
    public Void doInBackground(String... params) {
      HttpsURLConnection connection = null;

      try {
        URL url = new URL(SEARCH_URL + params[0]);
        Log.d("****URL:", url.toString());
        connection = (HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Host", "api.twitter.com");
        connection.setRequestProperty("User-Agent", "JustDoIt");
        connection.setRequestProperty("Authorization", "Bearer " + BEARER_TOKEN);
        connection.setUseCaches(false);

        JSONObject obj = new JSONObject(ReadResponse.readResponse(connection));

        buildTweets(obj);

        Log.d("***GetTweets:", obj.toString());

      } catch (MalformedURLException e) {
        Log.e("***GetTweets", "Invalid endpoint URL specified.", e);

      } catch (IOException e) {
        Log.e("***GetTweets", "IOException: ", e);
      } catch (JSONException e) {
        e.printStackTrace();
      } finally {
        if (connection != null) {
          connection.disconnect();
        }
        lock.release();
      }
      return null;
    }
Example #20
0
    public void onComplete(Bundle values) {
      //  Handle a successful login

      String token = this.fba.facebook.getAccessToken();
      long token_expires = this.fba.facebook.getAccessExpires();
      SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.fba.ctx);
      prefs.edit().putLong("access_expires", token_expires).commit();
      prefs.edit().putString("access_token", token).commit();

      Log.d("FB", "authorized");
      Log.d("PhoneGapLog", values.toString());

      try {
        JSONObject o = new JSONObject(this.fba.facebook.request("/me"));
        this.fba.userId = o.getString("id");
        this.fba.success(getResponse(), this.fba.callbackId);
      } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
Example #21
0
  public void seenMessagesOnServer(final ArrayList<Message> messages, final boolean retry)
      throws JSONException {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("status", "seen");
    JSONArray messageIdArray = new JSONArray();
    for (Message message : messages) {
      if (message.getSender().getId() != mMe.getId()) {
        messageIdArray.put(message.getId());
      }
    }
    jsonObject.put("messages", messageIdArray);
    if (messageIdArray.length() == 0) {
      return;
    }
    NetworkManager.sendRequest(
        MethodsName.bULK_CHANGE_MESSAGE_STATUS_GOT,
        jsonObject,
        new NetworkReceiver() {
          @Override
          public void onResponse(Object response) {
            // message seen in server side
          }

          @Override
          public void onErrorResponse(BerimNetworkException error) {
            if (retry) {
              try {
                seenMessagesOnServer(messages, false);
              } catch (JSONException e) {

              }
            }
          }
        });
  }
    @Override
    protected void onPostExecute(String s) {
      super.onPostExecute(s);

      // Parse JSON
      try {
        JSONObject jsonObject = new JSONObject(s);
        String status = jsonObject.getString("result");
        if (status.equalsIgnoreCase("success")) {
          errorText.setText("Account Successfully Created!");

          // introduce a small delay to allow for user to know account is created
          Handler h = new Handler();
          h.postDelayed(
              new Runnable() {
                @Override
                public void run() {
                  myDialog.dismiss();
                }
              },
              1500);
        } else {
          String reason = jsonObject.getString("error");
          errorText.setText("Error: " + reason);
        }
      } catch (Exception e) {
        Log.d(TAG, "Parsing JSON Exception " + e.getMessage());
      }
    }
Example #23
0
  public void applySettingStatusReport(JSONObject js) {
    /**
     * This breaks the mold a bit.. but its more efficient. This gets called off the top of
     * ParseJson if it has an "SR" in it. Sr's are called so often that instead of walking the
     * normal parsing tree.. this skips to the end
     */
    try {
      Iterator ii = js.keySet().iterator();
      // This is a special multi single value response object
      while (ii.hasNext()) {
        String key = ii.next().toString();

        responseCommand rc =
            new responseCommand(MNEMONIC_GROUP_SYSTEM, key.toString(), js.get(key).toString());
        TinygDriver.getInstance().machine.applyJsonStatusReport(rc);
        //                _applySettings(rc.buildJsonObject(), rc.getSettingParent()); //we will
        // supply the parent object name for each key pair
      }
      setChanged();
      message[0] = "STATUS_REPORT";
      message[1] = null;
      notifyObservers(message);

    } catch (Exception ex) {
      logger.error("[!] Error in applySettingStatusReport(JsonOBject js) : " + ex.getMessage());
      logger.error("[!]js.tostring " + js.toString());
      setChanged();
      message[0] = "STATUS_REPORT";
      message[1] = null;
      notifyObservers(message);
    }
  }
Example #24
0
 public ToxicoViewModel(JSONObject json) {
   try {
     Fecha = Tools.JsonDateToDate(json.getString("Fecha"));
     ToxicosDescripcion = json.getString("ToxicosDescripcion");
   } catch (JSONException e) {
   }
 }
  /**
   * Gets the token.
   *
   * @param scope the scope
   * @return the token
   */
  private String getToken(String scope) {
    Process curlProc;
    String outputString;
    DataInputStream curlIn = null;
    String access_token = null;
    String command =
        "curl -X POST -H Content-Type:application/x-www-form-urlencoded "
            + adminUrl
            + "/oauth2/token --insecure --data"
            + " client_id="
            + client_id
            + "&"
            + "client_secret="
            + client_secret
            + "&grant_type=client_credentials&scope="
            + scope;
    try {
      curlProc = Runtime.getRuntime().exec(command);

      curlIn = new DataInputStream(curlProc.getInputStream());

      while ((outputString = curlIn.readLine()) != null) {
        JSONObject obj = new JSONObject(outputString);
        access_token = obj.getString("access_token");
      }
    } catch (IOException e1) {
      e1.printStackTrace();
    } catch (JSONException e) {
      e.printStackTrace();
    }
    return access_token;
  }
  // set in array cells that will contain total value
  private void setNewSummaryCell(IDataStore dataStore, Integer row, Integer column) {
    if (row == null) {
      // if row not specified means is referring to last row that will be store lenght + already
      // added summary rows length
      row =
          Long.valueOf(dataStore.getRecordsCount()).intValue()
              + summaryRecordsAddedCounter
              - 1; // row starts from 0
    }

    try {
      JSONObject obj = new JSONObject();
      obj.put("row", row);
      obj.put("column", column);
      summaryCellsArray.put(obj);
    } catch (JSONException e) {
      logger.error(
          "Error while tracing summary cell in row "
              + row
              + " and column "
              + column
              + ": "
              + e.getMessage());
    }
  }
  private JSONArray getResultsFromJson(String moviesJsonStr) throws JSONException {

    final String RESULTS = "results";
    JSONObject moviesJson = new JSONObject(moviesJsonStr);
    JSONArray moviePostersArray = moviesJson.getJSONArray(RESULTS);
    return moviePostersArray;
  }
Example #28
0
  private void uploadLink(
      @Nullable String title, @Nullable String description, @NonNull String url) {
    LogUtil.v(TAG, "Received URL to upload");
    ApiClient client = new ApiClient(Endpoints.UPLOAD.getUrl(), ApiClient.HttpRequest.POST);

    FormEncodingBuilder builder = new FormEncodingBuilder().add("image", url).add("type", "URL");

    if (!TextUtils.isEmpty(title)) {
      builder.add("title", title);
    }

    if (!TextUtils.isEmpty(description)) {
      builder.add("description", description);
    }

    RequestBody body = builder.build();

    try {
      if (mNotificationId <= 0) mNotificationId = url.hashCode();
      onUploadStarted();
      JSONObject json = client.doWork(body);
      int status = json.getInt(ApiClient.KEY_STATUS);

      if (status == ApiClient.STATUS_OK) {
        handleResponse(json.getJSONObject(ApiClient.KEY_DATA));
      } else {
        onUploadFailed(title, description, url, false);
      }
    } catch (IOException | JSONException e) {
      LogUtil.e(TAG, "Error uploading url", e);
      onUploadFailed(title, description, url, false);
    }
  }
  public static Bundle convertToBundle(JSONObject jsonObject) throws JSONException {
    Bundle bundle = new Bundle();
    @SuppressWarnings("unchecked")
    Iterator<String> jsonIterator = jsonObject.keys();
    while (jsonIterator.hasNext()) {
      String key = jsonIterator.next();
      Object value = jsonObject.get(key);
      if (value == null || value == JSONObject.NULL) {
        // Null is not supported.
        continue;
      }

      // Special case JSONObject as it's one way, on the return it would be Bundle.
      if (value instanceof JSONObject) {
        bundle.putBundle(key, convertToBundle((JSONObject) value));
        continue;
      }

      Setter setter = SETTERS.get(value.getClass());
      if (setter == null) {
        throw new IllegalArgumentException("Unsupported type: " + value.getClass());
      }
      setter.setOnBundle(bundle, key, value);
    }

    return bundle;
  }
  public void btnPostJson(View view) {

    // TODO 提交JSON

    JSONObject json = new JSONObject();

    try {
      json.put("name", "abc");
      json.put("pass", "123");
    } catch (JSONException e) {
      e.printStackTrace();
    }

    JsonObjectRequest request =
        new JsonObjectRequest(
            "http://10.0.175.103:8080/post",
            json,
            new Response.Listener<JSONObject>() {
              @Override
              public void onResponse(JSONObject response) {
                textView.setText("" + response.toString());
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                textView.setText("" + error.getMessage());
              }
            });

    RequestQueue requestQueue = NetworkSingleton.getInstance().getRequestQueue();

    requestQueue.add(request);
  }