Java Code Examples for org.json.JSONException#printStackTrace()

The following examples show how to use org.json.JSONException#printStackTrace() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: m2x-android   File: Collection.java    License: MIT License 6 votes vote down vote up
@Override
public JSONObject toJsonObject() {
    JSONObject jsonObject = new JSONObject();
    try {
        if (id != null) jsonObject.put("id", id);
        if (parent != null) jsonObject.put("parent", parent);
        if (name != null) jsonObject.put("name", name);
        if (description != null) jsonObject.put("description", description);
        if (devices != null) jsonObject.put("devices", devices);
        if (collections != null) jsonObject.put("collections", collections);
        if (tags != null) jsonObject.put("tags", ArrayUtils.listToJsonStringArray(tags));
        if (metadata != null) jsonObject.put("metadata", ArrayUtils.mapToJsonObject(metadata));
        if (key != null) jsonObject.put("key", key);
        if (created != null) jsonObject.put("created", DateUtils.dateTimeToString(created));
        if (updated != null) jsonObject.put("updated", DateUtils.dateTimeToString(updated));
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return jsonObject;
}
 
Example 2
Source Project: JSON   File: JSON.java    License: MIT License 6 votes vote down vote up
public static JSONObject dic(Object... values) {

        JSONObject mainDic = new JSONObject();
        for (int i = 0; i < values.length; i += 2) {

            try {

                Object valueObject = values[i + 1];

                if (JSON.class.isInstance(valueObject)) {

                    if (((JSON) valueObject).getJsonArray() != null)
                        valueObject = ((JSON) valueObject).getJsonArray();

                    else if (((JSON) valueObject).getJsonObject() != null)
                        valueObject = ((JSON) valueObject).getJsonObject();
                }

                mainDic.put((String) values[i], valueObject == null ? JSONObject.NULL:valueObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return mainDic;
    }
 
Example 3
Source Project: letv   File: JavaScriptinterface.java    License: Apache License 2.0 6 votes vote down vote up
@JavascriptInterface
public void fun_openImage(String jsonString) {
    JSInBean jsInBean = JSBridgeUtil.getInstance().parseJsonArray(jsonString);
    try {
        int options = (int) (new JSONObject(jsInBean.getName()).getDouble("scale") * 100.0d);
        if (this.activityHandler != null) {
            Message message = new Message();
            message.what = 3;
            message.obj = Integer.valueOf(options);
            Bundle bundle = new Bundle();
            bundle.putString(a.c, jsInBean.getCallback());
            bundle.putString("callback_id", jsInBean.getCallback_id());
            message.setData(bundle);
            this.activityHandler.sendMessage(message);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    android.content.Intent intent = new android.content.Intent("android.intent.action.PICK");
    intent.setType("image/*");
    this.mActivity.startActivityForResult(intent, 10002);
}
 
Example 4
Source Project: sealrtc-android   File: CallActivity.java    License: MIT License 6 votes vote down vote up
private void selectAdmin() {
    if (!TextUtils.equals(myUserId, adminUserId) || mMembersMap.size() <= 1) return;
    UserInfo userInfo = mMembersMap.get(mMembers.get(1).userId);
    if (userInfo == null) return;
    RoomInfoMessage roomInfoMessage = new RoomInfoMessage(
        userInfo.userId, userInfo.userName, userInfo.joinMode, userInfo.timestamp, true);
    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.put("userId", userInfo.userId);
        jsonObject.put("userName", userInfo.userName);
        jsonObject.put("joinMode", userInfo.joinMode);
        jsonObject.put("joinTime", userInfo.timestamp);
        jsonObject.put("master", 1);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    room.setRoomAttributeValue(jsonObject.toString(), userInfo.userId, roomInfoMessage, null);
}
 
Example 5
Source Project: YourWeather   File: Utility.java    License: Apache License 2.0 6 votes vote down vote up
/**
 *解析和处理返回的市级数据
 */
public static boolean handleCityResponse(String response,int provinceId){
    if (!TextUtils.isEmpty(response)){
        try {
            JSONArray allCity = new JSONArray(response);
            for (int i=0;i<allCity.length();i++){
                JSONObject cityObject = allCity.getJSONObject(i);
                City city = new City();
                city.setCityName(cityObject.getString("name"));
                city.setCityCode(cityObject.getInt("id"));
                city.setProvinceId(provinceId);
                city.save();
            }
            return true;
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return false;
}
 
Example 6
Source Project: SI   File: AE.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public JSONObject setForCreate() {

    	JSONObject body_wrap = new JSONObject();
    	JSONObject body = new JSONObject();
    	JSONArray lbl = new JSONArray();
    	
        try {
        	if( getLbl() != null ){
	            for(String label : getLbl()) {
	                lbl.put(label);
	            }
	            body.put("lbl", lbl);
        	}

            body.put("rn", getRn());
            body.put("apn", getApn());
            body.put("api", getApi());
            body.put("rr", isRr());
            body.put("et", getEt());

            body_wrap.put(getNameSpace(this),body);

        } catch(JSONException jsone) {
            jsone.printStackTrace();
        } catch(Exception e) {
            e.printStackTrace();
        }
        
        return body_wrap;
    }
 
Example 7
@Override
public JSONObject asJSON() {
    JSONObject json = super.asJSON();

    try {
        JSONObject data = new JSONObject();
        data.put("calories",calories);
        json.put("Calories",data);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return json;
}
 
Example 8
@Parameters({"clientInfoPath"})
@Test
public void requestClientInfoInvalidToken(final String clientInfoPath) throws Exception {
    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + clientInfoPath).request();

    request.header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);

    ClientInfoRequest clientInfoRequest = new ClientInfoRequest("INVALID-TOKEN");
    clientInfoRequest.setAuthorizationMethod(AuthorizationMethod.FORM_ENCODED_BODY_PARAMETER);

    Response response = request
            .post(Entity.form(new MultivaluedHashMap<String, String>(clientInfoRequest.getParameters())));
    String entity = response.readEntity(String.class);

    showResponse("requestClientInfoInvalidToken", response, entity);

    assertEquals(response.getStatus(), 400, "Unexpected response code.");
    assertNotNull(entity, "Unexpected result: " + entity);
    try {
        JSONObject jsonObj = new JSONObject(entity);
        assertTrue(jsonObj.has("error"), "The error type is null");
        assertTrue(jsonObj.has("error_description"), "The error description is null");
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    }
}
 
Example 9
Source Project: tinkerpatch-sdk   File: BaseReport.java    License: MIT License 5 votes vote down vote up
public String toJson() {
    try {
        return toJsonObject().toString();
    } catch (JSONException e) {
        e.printStackTrace();
        return "";
    }
}
 
Example 10
@Parameters({"tokenPath"})
@Test(dependsOnMethods = {"dynamicClientRegistration", "revokeTokensStep2n3"})
public void revokeTokensStep4(final String tokenPath) throws Exception {
    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + tokenPath).request();

    TokenRequest tokenRequest = new TokenRequest(GrantType.REFRESH_TOKEN);
    tokenRequest.setRefreshToken(refreshToken1);
    tokenRequest.setScope("email read_stream manage_pages");
    tokenRequest.setAuthUsername(clientId);
    tokenRequest.setAuthPassword(clientSecret);

    request.header("Authorization", "Basic " + tokenRequest.getEncodedCredentials());

    Response response = request
            .post(Entity.form(new MultivaluedHashMap<String, String>(tokenRequest.getParameters())));
    String entity = response.readEntity(String.class);

    showResponse("revokeTokensStep4", response, entity);

    assertEquals(response.getStatus(), 400, "Unexpected response code.");
    assertNotNull(entity, "Unexpected result: " + entity);
    try {
        JSONObject jsonObj = new JSONObject(entity);
        assertTrue(jsonObj.has("error"), "The error type is null");
        assertTrue(jsonObj.has("error_description"), "The error description is null");
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    }
}
 
Example 11
Source Project: KinoCast   File: TheMovieDb.java    License: MIT License 5 votes vote down vote up
public JSONObject get(String url, boolean fetchIfNeeded) {
    JSONObject json;
    //String url = request.getUrl();

    // Check for image in memory
    json = getFromMemory(url);

    // Check for image on disk cache
    if(json == null) {
        json = getFromDisk(url);

        // Write bitmap back into memory cache
        if(json != null) {
            cacheToMemory(url, json);
        }
    }
    if(json == null || fetchIfNeeded) {
        try {
            // Get IMDB-ID from page
            ViewModel item = Parser.getInstance().loadDetail(url);
            String param = url.substring(url.indexOf("#") + 1);
            // tt1646971?api_key=f9dc7e5d12b2640bf4ef1cf20835a1cc&language=de&external_source=imdb_id
            JSONObject data = Utils.readJson("http://api.themoviedb.org/3/find/" + item.getImdbId() + "?api_key=" + API_KEY + "&external_source=imdb_id&" + param);
            if(data == null) return null;
            if(data.getJSONArray("movie_results").length() > 0) {
                json = data.getJSONArray("movie_results").getJSONObject(0);
            }else if(data.getJSONArray("tv_results").length() > 0) {
                json = data.getJSONArray("tv_results").getJSONObject(0);
            }
            if(json != null) {
                put(url, json);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    return json;
}
 
Example 12
private void sendCrossDeviceTransCommand(MethodCall call, final Result result) {
  HashMap<String, Object> map = call.arguments();
  try {
    JSONObject params = new JSONObject(map);
    String message = params.getString("message");
    String type = params.getString("platform");

    PlatformType platformType = PlatformType.all;
    if (type.equals("android")) {
      platformType = PlatformType.android;
    }else if (type.equals("ios")) {
      platformType = PlatformType.ios;
    }else if (type.equals("windows")) {
      platformType = PlatformType.windows;
    }else if (type.equals("web")) {
      platformType = PlatformType.web;
    }else {//all
      platformType = PlatformType.all;
    }

    JMessageClient.sendCrossDeviceTransCommand(platformType, message, new BasicCallback() {
      @Override
      public void gotResult(int status, String desc) {
        handleResult(status, desc, result);
      }
    });

  } catch (JSONException e) {
    e.printStackTrace();
    handleResult(ERR_CODE_PARAMETER, ERR_MSG_PARAMETER, result);
    return;
  }
}
 
Example 13
@Override
public String toString() {
    try {
        return toJSON().toString();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return super.toString();
}
 
Example 14
Source Project: odo   File: Client.java    License: Apache License 2.0 5 votes vote down vote up
protected ServerRedirect getServerRedirectFromJSON(JSONObject jsonServer) {
    ServerRedirect redirect = new ServerRedirect();
    if (jsonServer == null) {
        return null;
    }

    try {
        if (!jsonServer.isNull("id")) {
            redirect.setId(jsonServer.getInt("id"));
        }
        if (!jsonServer.isNull("srcUrl")) {
            redirect.setSourceHost(jsonServer.getString("srcUrl"));
        }
        if (!jsonServer.isNull("destUrl")) {
            redirect.setDestinationHost(jsonServer.getString("destUrl"));
        }
        if (!jsonServer.isNull("hostHeader")) {
            redirect.setHostHeader(jsonServer.getString("hostHeader"));
        }
        if (!jsonServer.isNull("profileId")) {
            redirect.setProfileId(jsonServer.getInt("profileId"));
        }
    } catch (JSONException e) {
        e.printStackTrace();
        return null;
    }

    return redirect;
}
 
Example 15
private Headers getHeaders(JSONObject httpJson){
    Headers result = null;
    
    try{
        JSONObject httpHeadersJson = httpJson.getJSONObject("headers");
        Hashtable<String, Object> httpHeadersHash = JsonRPCMarshaller.deserializeJSONObject(httpHeadersJson);
        result = new Headers(httpHeadersHash);
    }catch(JSONException e){
        Log.e("OnSystemRequest", "\"headers\" key doesn't exist in bulk data.");
        e.printStackTrace();
    }
    
    return result;
}
 
Example 16
Source Project: ALLGO   File: EventPageLogicImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void getEventDetails(int eid) {


	NetUtil netUtil = new NetUtil("event/details", refresh, context, new NetCallBack(){
		@Override
		public void getResult(JSONObject jsonObject) {
			try {
				 if(jsonObject.getString("response").equals("details")){
					followers_count = Integer.parseInt(jsonObject.getString("followers_count"));
					comments_count = Integer.parseInt(jsonObject.getString("comments_count"));
					refresh.refresh(followers_count+"人", 6);
					refresh.refresh(comments_count+"", 7);
					refresh.refresh(JSON.parseArray(jsonObject.getString("followers") , EventFollowerVo.class),10);
					refresh.refresh(JSON.parseArray(jsonObject.getString("adds") , EventAddVo.class),1);
					refresh.refresh(JSON.parseArray(jsonObject.getString("comments"),EventCommentVo.class),2);

				 }else if(jsonObject.getString("response").equals("event_destroy")){
					 refresh.refresh(null,9);
				 }else{
        	        	refresh.refresh("更新出错", -1);
        	        }
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		
	});
	netUtil.add("eid" , eid+"");
	netUtil.get();

}
 
Example 17
public void parse(JSONObject jsonObject) {
    try {
        date = jsonObject.getString("date");
        weather = jsonObject.getString("weather");
        wind = jsonObject.getString("wind");
        temperature = jsonObject.getString("temperature");
    } catch (JSONException e) {
        e.printStackTrace();
    }

}
 
Example 18
Source Project: hellosign-java-sdk   File: AbstractResource.java    License: MIT License 5 votes vote down vote up
protected Boolean getBoolean(String key) {
    if (dataObj.has(key) && !dataObj.isNull(key)) {
        try {
            return dataObj.getBoolean(key);
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }
    return null;
}
 
Example 19
Source Project: Moticons   File: IabHelper.java    License: GNU General Public License v3.0 4 votes vote down vote up
/**
 * Handles an activity result that's part of the purchase flow in in-app billing. If you
 * are calling {@link #launchPurchaseFlow}, then you must call this method from your
 * Activity's {@link [email protected]} method. This method
 * MUST be called from the UI thread of the Activity.
 *
 * @param requestCode The requestCode as you received it.
 * @param resultCode The resultCode as you received it.
 * @param data The data (Intent) as you received it.
 * @return Returns true if the result was related to a purchase flow and was handled;
 *     false if the result was not related to a purchase, in which case you should
 *     handle it normally.
 */
public boolean handleActivityResult(int requestCode, int resultCode, Intent data) {
    IabResult result;
    if (requestCode != mRequestCode) return false;

    checkNotDisposed();
    checkSetupDone("handleActivityResult");

    // end of async purchase operation that started on launchPurchaseFlow
    flagEndAsync();

    if (data == null) {
        logError("Null data in IAB activity result.");
        result = new IabResult(IABHELPER_BAD_RESPONSE, "Null data in IAB result");
        if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null);
        return true;
    }

    int responseCode = getResponseCodeFromIntent(data);
    String purchaseData = data.getStringExtra(RESPONSE_INAPP_PURCHASE_DATA);
    String dataSignature = data.getStringExtra(RESPONSE_INAPP_SIGNATURE);

    if (resultCode == Activity.RESULT_OK && responseCode == BILLING_RESPONSE_RESULT_OK) {
        logDebug("Successful resultcode from purchase activity.");
        logDebug("Purchase data: " + purchaseData);
        logDebug("Data signature: " + dataSignature);
        logDebug("Extras: " + data.getExtras());
        logDebug("Expected item type: " + mPurchasingItemType);

        if (purchaseData == null || dataSignature == null) {
            logError("BUG: either purchaseData or dataSignature is null.");
            logDebug("Extras: " + data.getExtras().toString());
            result = new IabResult(IABHELPER_UNKNOWN_ERROR, "IAB returned null purchaseData or dataSignature");
            if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null);
            return true;
        }

        Purchase purchase = null;
        try {
            purchase = new Purchase(mPurchasingItemType, purchaseData, dataSignature);
            String sku = purchase.getSku();

            // Verify signature
            if (!Security.verifyPurchase(mSignatureBase64, purchaseData, dataSignature)) {
                logError("Purchase signature verification FAILED for sku " + sku);
                result = new IabResult(IABHELPER_VERIFICATION_FAILED, "Signature verification failed for sku " + sku);
                if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, purchase);
                return true;
            }
            logDebug("Purchase signature successfully verified.");
        }
        catch (JSONException e) {
            logError("Failed to parse purchase data.");
            e.printStackTrace();
            result = new IabResult(IABHELPER_BAD_RESPONSE, "Failed to parse purchase data.");
            if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null);
            return true;
        }

        if (mPurchaseListener != null) {
            mPurchaseListener.onIabPurchaseFinished(new IabResult(BILLING_RESPONSE_RESULT_OK, "Success"), purchase);
        }
    }
    else if (resultCode == Activity.RESULT_OK) {
        // result code was OK, but in-app billing response was not OK.
        logDebug("Result code was OK but in-app billing response was not OK: " + getResponseDesc(responseCode));
        if (mPurchaseListener != null) {
            result = new IabResult(responseCode, "Problem purchashing item.");
            mPurchaseListener.onIabPurchaseFinished(result, null);
        }
    }
    else if (resultCode == Activity.RESULT_CANCELED) {
        logDebug("Purchase canceled - Response: " + getResponseDesc(responseCode));
        result = new IabResult(IABHELPER_USER_CANCELLED, "User canceled.");
        if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null);
    }
    else {
        logError("Purchase failed. Result code: " + Integer.toString(resultCode)
                + ". Response: " + getResponseDesc(responseCode));
        result = new IabResult(IABHELPER_UNKNOWN_PURCHASE_RESPONSE, "Unknown purchase response.");
        if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null);
    }
    return true;
}
 
Example 20
/**
 * Add the book to the server
 *
 * @param locationObject The location at which to create the book, if <code>null</code>, uses
 *                       the user's preferred location
 */
private void createBookOnServer(final JSONObject locationObject) {

    try {

        final JSONObject requestObject = new JSONObject();
        final JSONObject bookJson = new JSONObject();
        bookJson.put(HttpConstants.TITLE, mTitleEditText.getText()
                                                        .toString());
        bookJson.put(HttpConstants.AUTHOR, mAuthorEditText.getText()
                                                          .toString());
        bookJson.put(HttpConstants.DESCRIPTION, mDescriptionEditText
                .getText().toString());
        if (!mSellPriceEditText.getText().toString().equals("")) {
            bookJson.put(HttpConstants.VALUE, mSellPriceEditText.getText()
                                                                .toString());
        }

        bookJson.put(HttpConstants.PUBLICATION_YEAR, mPublicationYear);
        if (mIsbnEditText.getText().toString().length() == 13) {
            bookJson.put(HttpConstants.ISBN_13, mIsbnEditText.getText()
                                                             .toString());
        } else if (mIsbnEditText.getText().toString().length() == 10) {
            bookJson.put(HttpConstants.ISBN_10, mIsbnEditText.getText()
                                                             .toString());
        }
        bookJson.put(HttpConstants.TAG_NAMES, getBarterTagsArray());
        bookJson.put(HttpConstants.EXT_IMAGE_URL, mImage_Url);

        if (locationObject != null) {
            bookJson.put(HttpConstants.LOCATION, locationObject);
        }
        requestObject.put(HttpConstants.BOOK, bookJson);

        final BlRequest createBookRequest = new BlRequest(Method.POST,
                                                          HttpConstants.getApiBaseUrl()
                                                                  + ApiEndpoints.BOOKS,
                                                          requestObject.toString(),
                                                          mVolleyCallbacks
        );
        createBookRequest.setRequestId(RequestId.CREATE_BOOK);
        addRequestToQueue(createBookRequest, true, 0, true);

    } catch (final JSONException e) {
        e.printStackTrace();
    }
}