Example usage for org.json JSONObject putOpt

List of usage examples for org.json JSONObject putOpt

Introduction

In this page you can find the example usage for org.json JSONObject putOpt.

Prototype

public JSONObject putOpt(String key, Object value) throws JSONException 

Source Link

Document

Put a key/value pair in the JSONObject, but only if the key and the value are both non-null.

Usage

From source file:kr.ac.cau.mecs.cass.servletcontextlistener.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    onServletInit(request, response);/*from   w ww .  ja v a2  s  . c o m*/

    response.setContentType("application/json; charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");

    PrintWriter out = response.getWriter();
    JSONObject jobj = new JSONObject();

    Transaction tx = null;
    Session hsession = HibernateSessionFactory.getSessionFactory().getCurrentSession();

    try {
        tx = hsession.beginTransaction();

        jobj = processGet(hsession, request, response);

        tx.commit();
    } catch (Exception e) {
        jobj.putOpt("error", 1);
        jobj.putOpt("reason", "server transaction error");
        jobj.putOpt("msg", e.getMessage());
        e.printStackTrace();
        if (tx != null && tx.isActive()) {
            try {
                tx.rollback();
            } catch (HibernateException e1) {
                e1.printStackTrace();
            }
        }
    }

    jobj.write(out);
    out.close();

}

From source file:kr.ac.cau.mecs.cass.servletcontextlistener.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    onServletInit(request, response);/*from   w  w w.  j a  va2s.  c o  m*/

    response.setContentType("application/json; charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");

    PrintWriter out = response.getWriter();
    JSONObject jobj = new JSONObject();

    Transaction tx = null;
    Session hsession = HibernateSessionFactory.getSessionFactory().getCurrentSession();

    try {
        tx = hsession.beginTransaction();

        jobj = processPost(hsession, request, response);

        tx.commit();
    } catch (Exception e) {
        jobj.putOpt("error", 1);
        jobj.putOpt("reason", "server transaction error");
        jobj.putOpt("msg", e.getMessage());

        e.printStackTrace();
        if (tx != null && tx.isActive()) {
            try {
                tx.rollback();
            } catch (HibernateException e1) {
                e1.printStackTrace();
            }
        }
    }

    jobj.write(out);
    out.close();
}

From source file:com.trk.aboutme.facebook.model.JsonUtil.java

static void jsonObjectPutAll(JSONObject jsonObject, Map<String, Object> map) {
    Set<Map.Entry<String, Object>> entrySet = map.entrySet();
    for (Map.Entry<String, Object> entry : entrySet) {
        try {/*from   www  .j  av  a2  s.co  m*/
            jsonObject.putOpt(entry.getKey(), entry.getValue());
        } catch (JSONException e) {
            throw new IllegalArgumentException(e);
        }
    }
}

From source file:edu.umass.cs.gigapaxos.paxospackets.FailureDetectionPacket.java

@Override
public JSONObject toJSONObjectImpl() throws JSONException {
    JSONObject json = new JSONObject();
    json.put(Keys.MODE.toString(), status);
    json.put(Keys.SNDR.toString(), senderNodeID);
    json.put(Keys.RCVR.toString(), responderNodeID);
    json.putOpt(Keys.SADDR.toString(), this.saddr);
    return json;//ww  w  .  ja  v  a  2 s  .c  o m
}

From source file:com.aniruddhc.acemusic.player.GMusicHelpers.GMusicClientCalls.java

/**************************************************************************************************
 * Retrieves a JSONAray with all songs within the <b><i>specified</b></i> playlist. The JSONArray 
 * contains the fields of the songs such as "id", "clientId", "trackId", etc. (for a list 
 * of all fields, see WebClientSongsSchema.java). Uses the WebClient endpoint.
 * //  ww w  .j  a  v a  2  s. c o m
 * @return A JSONArray object that contains the songs and their fields within the specified playlist.
 * @param context The context to use while retrieving songs from the playlist.
 * @param playlistId The id of the playlist we need to fetch the songs from.
 **************************************************************************************************/
public static final JSONArray getPlaylistEntriesWebClient(Context context, String playlistId)
        throws JSONException, IllegalArgumentException {

    JSONObject jsonParam = new JSONObject();
    jsonParam.putOpt("id", playlistId);

    JSONForm form = new JSONForm();
    form.addField("json", jsonParam.toString());
    form.close();

    mHttpClient.setUserAgent(mMobileClientUserAgent);
    String result = mHttpClient.post(context,
            "https://play.google.com/music/services/loadplaylist?u=0&xt=" + getXtCookieValue(),
            new ByteArrayEntity(form.toString().getBytes()), form.getContentType());

    JSONArray jsonArray = new JSONArray();
    JSONObject jsonObject = new JSONObject(result);

    if (jsonObject != null) {
        jsonArray = jsonObject.getJSONArray("playlist");
    }

    return jsonArray;
}

From source file:biblivre3.cataloging.bibliographic.RecordDTO.java

@Override
public JSONObject toJSONObject(Properties properties) {
    JSONObject data = new JSONObject();
    try {/*from ww w  .  ja  v a2  s.c  o  m*/
        data.putOpt("title", this.getTitle());

        data.putOpt("holdings_count", this.getTotalCount());
        data.putOpt("holdings_available", this.getAvailableCount());
        data.putOpt("holdings_lent", this.getLentCount());
        data.putOpt("holdings_reserved", this.getReservedCount());

        if (this.getMaterialType() != null) {
            data.putOpt("material_type", this.getMaterialType().getCode());
        }

        if (this.getFields() != null) {
            for (String[] field : this.getFields()) {
                JSONObject jsonField = new JSONObject();
                jsonField.put("field", field[0]);
                jsonField.put("label", I18nUtils.getText(properties, field[0]));
                jsonField.put("value", field[1]);

                data.append("fields", jsonField);
            }
        }

        if (this.getLinks() != null) {
            Subfield subF = null;
            Subfield subY = null;
            Subfield subD = null;
            Subfield subU = null;

            String file = null;
            String name = null;
            String path = null;
            String uri = null;

            for (DataField field : this.getLinks()) {
                JSONObject jsonLink = new JSONObject();

                subF = field.getSubfield('f');
                file = subF == null ? "" : subF.getData();
                subY = field.getSubfield('y');
                name = subY == null ? "" : subY.getData();
                subD = field.getSubfield('d');
                path = subD == null ? "" : subD.getData();
                subU = field.getSubfield('u');
                uri = subU == null ? "" : subU.getData();

                if (StringUtils.isBlank(file)) {
                    file = name;
                }

                if (StringUtils.isBlank(file)) {
                    file = uri;
                }

                if (StringUtils.isNotBlank(file)) {
                    if (path == null || path.isEmpty()) {
                        path = Config.getConfigProperty(ConfigurationEnum.DIGITAL_MEDIA);
                    }
                    if (name == null || name.isEmpty()) {
                        name = file;
                    }

                    jsonLink.put("path", path);
                    jsonLink.put("file", file);
                    jsonLink.put("name", name);
                    jsonLink.put("uri", uri);

                    data.append("links", jsonLink);
                }
            }
        }

        if (this.getHoldings() != null) {
            for (HoldingDTO dto : this.getHoldings()) {
                data.append("holdings", dto.toJSONObject(properties));
            }
        }

        if (this.getJson() != null) {
            data.put("data", this.getJson());
        }

        if (this.getMarc() != null) {
            data.put("data", this.getMarc());
        }
    } catch (JSONException e) {
    }

    return data;
}

From source file:com.molice.oneingdufs.androidpn.Notifier.java

public void notify(String notificationId, String apiKey, String title, String message, String uri) {
    Log.d(LOGTAG, "notify()...");

    Log.d(LOGTAG, "notificationId=" + notificationId);
    Log.d(LOGTAG, "notificationApiKey=" + apiKey);
    Log.d(LOGTAG, "notificationTitle=" + title);
    Log.d(LOGTAG, "notificationMessage=" + message);
    Log.d(LOGTAG, "notificationUri=" + uri);

    if (SettingsActivity.getNotificationEnabled(context)) {
        // Show the toast
        //            if (isNotificationToastEnabled()) {
        //                Toast.makeText(context, message, Toast.LENGTH_LONG).show();
        //            }

        // Notification
        Notification notification = new Notification();
        notification.icon = getNotificationIcon();
        //            notification.defaults = Notification.DEFAULT_LIGHTS;
        if (SettingsActivity.getNotificationSound(context)) {
            notification.defaults |= Notification.DEFAULT_SOUND;
        }/*from   ww  w  . j  av  a  2 s .  c o m*/
        if (SettingsActivity.getNotificationVibrate(context)) {
            notification.defaults |= Notification.DEFAULT_VIBRATE;
        }
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.when = System.currentTimeMillis();
        notification.tickerText = message;

        //            Intent intent;
        //            if (uri != null
        //                    && uri.length() > 0
        //                    && (uri.startsWith("http:") || uri.startsWith("https:")
        //                            || uri.startsWith("tel:") || uri.startsWith("geo:"))) {
        //                intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
        //            } else {
        //                String callbackActivityPackageName = sharedPrefs.getString(
        //                        Constants.CALLBACK_ACTIVITY_PACKAGE_NAME, "");
        //                String callbackActivityClassName = sharedPrefs.getString(
        //                        Constants.CALLBACK_ACTIVITY_CLASS_NAME, "");
        //                intent = new Intent().setClassName(callbackActivityPackageName,
        //                        callbackActivityClassName);
        //                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //                intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        //            }

        Intent intent = new Intent(context, MessageDetailActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        JSONObject data = formatMetaFromTitle(title);
        try {
            data.putOpt("id", notificationId);
            data.putOpt("content", message);
        } catch (Exception e) {
            Log.d("JSON", "Notifier#notify, e=" + e.toString());
        }
        intent.putExtra("data", data.toString());
        intent.putExtra("fromNotification", true);
        //            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //            intent.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        //            intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        //            intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        //            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent contentIntent = PendingIntent.getActivity(context, random.nextInt(), intent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        notification.setLatestEventInfo(context, data.optString("title"), message, contentIntent);
        notificationManager.notify(random.nextInt(), notification);

        //            Intent clickIntent = new Intent(
        //                    Constants.ACTION_NOTIFICATION_CLICKED);
        //            clickIntent.putExtra(Constants.NOTIFICATION_ID, notificationId);
        //            clickIntent.putExtra(Constants.NOTIFICATION_API_KEY, apiKey);
        //            clickIntent.putExtra(Constants.NOTIFICATION_TITLE, title);
        //            clickIntent.putExtra(Constants.NOTIFICATION_MESSAGE, message);
        //            clickIntent.putExtra(Constants.NOTIFICATION_URI, uri);
        //            //        positiveIntent.setData(Uri.parse((new StringBuilder(
        //            //                "notif://notification.adroidpn.org/")).append(apiKey).append(
        //            //                "/").append(System.currentTimeMillis()).toString()));
        //            PendingIntent clickPendingIntent = PendingIntent.getBroadcast(
        //                    context, 0, clickIntent, 0);
        //
        //            notification.setLatestEventInfo(context, title, message,
        //                    clickPendingIntent);
        //
        //            Intent clearIntent = new Intent(
        //                    Constants.ACTION_NOTIFICATION_CLEARED);
        //            clearIntent.putExtra(Constants.NOTIFICATION_ID, notificationId);
        //            clearIntent.putExtra(Constants.NOTIFICATION_API_KEY, apiKey);
        //            //        negativeIntent.setData(Uri.parse((new StringBuilder(
        //            //                "notif://notification.adroidpn.org/")).append(apiKey).append(
        //            //                "/").append(System.currentTimeMillis()).toString()));
        //            PendingIntent clearPendingIntent = PendingIntent.getBroadcast(
        //                    context, 0, clearIntent, 0);
        //            notification.deleteIntent = clearPendingIntent;
        //
        //            notificationManager.notify(random.nextInt(), notification);

    } else {
        Log.w(LOGTAG, "Notificaitons disabled.");
    }
}

From source file:com.molice.oneingdufs.androidpn.Notifier.java

/**
* METAtitletitlekey-valueJSONObject<br/>
* <pre>{/*ww  w.j a  va 2s  .  c om*/
* "title": "",// 
* "from": "",// 
* "date": "",// 
* "type": "msg|no",// [|]
* }</pre>
* @param title Notificationtitle"title=;from=MoLice;date=2012-4-24 22:57;type=msg;"
* @return JSONObject
*/
public JSONObject formatMetaFromTitle(String title) {
    JSONObject data = new JSONObject();
    String[] meta = title.split(";");
    for (int i = 0; i < meta.length; i++) {
        String[] kv = meta[i].split("=");
        try {
            data.putOpt(kv[0], kv[1]);
        } catch (Exception e) {
            Log.d("JSON", "MessageDetailActivity#formatMetaFromTitle, e=" + e.toString());
        }
    }
    return data;
}

From source file:com.futureplatforms.kirin.internal.attic.ProxyGenerator.java

protected void handleSetter(JSONObject obj, String key, Object value) {
    if (value == null) {
        obj.remove(key);/*  w  ww .j  av  a  2 s  . c om*/
    } else {
        try {
            obj.putOpt(key, value);
        } catch (JSONException e) {
            Log.e(C.TAG, "Problem putting " + value + " into a JSONObject with key " + key, e);
        }
    }
}

From source file:com.chaosinmotion.securechat.network.SCNetwork.java

/**
 * Attempt to log in. Returns the results in a callback run asynchronously
 * @param creds/*  www. j av  a2  s .  co m*/
 * @param callback
 */
public void doLogin(final SCNetworkCredentials creds, final LoginCallback callback) {
    // Enqueue the login request
    request("login/token", null, this, new ResponseInterface() {
        @Override
        public void responseResult(Response response) {
            if (response.isSuccess()) {
                try {
                    String token = response.getData().optString("token");

                    JSONObject params = new JSONObject();
                    params.putOpt("username", creds.getUsername());
                    params.putOpt("password", creds.hashPasswordWithToken(token));

                    request("login/login", params, this, new ResponseInterface() {
                        @Override
                        public void responseResult(Response response) {
                            if (response.isSuccess()) {
                                callback.loginResult(LOGIN_SUCCESS);
                            } else if (response.getError() == 2) {
                                callback.loginResult(LOGIN_FAILURE);
                            } else {
                                callback.loginResult(LOGIN_SERVERERROR);
                            }
                        }
                    });
                } catch (JSONException e) {
                    // I don't know a better way to handle this.
                    callback.loginResult(LOGIN_SERVERERROR);
                }
            } else {
                showError(response);
                callback.loginResult(LOGIN_SERVERERROR);
            }
        }
    });
}