Example usage for org.json JSONObject JSONObject

List of usage examples for org.json JSONObject JSONObject

Introduction

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

Prototype

public JSONObject() 

Source Link

Document

Construct an empty JSONObject.

Usage

From source file:com.browseengine.bobo.server.protocol.BrowseJSONSerializer.java

/**
 * TODO: need to add support for multiple values.
 * @param doc//w  ww . j  a  v a 2  s .  c om
 * @return
 * @throws JSONException 
 */
public static JSONObject serializeValues(Map<String, String[]> values) throws JSONException {
    JSONObject obj = new JSONObject();
    Iterator<String> iter = values.keySet().iterator();
    while (iter.hasNext()) {
        String name = iter.next();
        String[] vals = values.get(name);
        if (vals.length > 0) {
            obj.put(name, vals[0]);
        }
    }
    return obj;
}

From source file:com.browseengine.bobo.server.protocol.BrowseJSONSerializer.java

public static JSONObject serializeHits(BrowseHit hit) throws JSONException {
    JSONObject obj = new JSONObject();
    obj.put("doc", serializeValues(hit.getFieldValues()));
    obj.put("docid", hit.getDocid());
    obj.put("score", hit.getScore());
    return obj;/*from   ww w  . j  a v  a  2s  . co  m*/
}

From source file:com.browseengine.bobo.server.protocol.BrowseJSONSerializer.java

public static String serialize(BrowseResult result) throws JSONException {
    JSONObject obj = new JSONObject();
    if (result != null) {
        obj.put("time", ((double) result.getTime()) / 1000.0);
        obj.put("hitCount", result.getNumHits());
        obj.put("totalDocs", result.getTotalDocs());

        // serialize choices
        JSONObject choices = new JSONObject();
        Set<Entry<String, FacetAccessible>> facetAccessors = result.getFacetMap().entrySet();
        for (Entry<String, FacetAccessible> entry : facetAccessors) {
            JSONObject choiceObject = new JSONObject();
            JSONArray choiceValArray = new JSONArray();

            choiceObject.put("choicelist", choiceValArray);
            int k = 0;

            String name = entry.getKey();
            FacetAccessible facets = entry.getValue();

            List<BrowseFacet> facetList = facets.getFacets();
            for (BrowseFacet facet : facetList) {
                JSONObject choice = new JSONObject();
                choice.put("val", facet.getValue());
                choice.put("hits", facet.getHitCount());
                choiceValArray.put(k++, choice);
            }/*from   w ww  . ja v  a  2  s.c  o  m*/
            choices.put(name, choiceObject);
        }
        obj.put("choices", choices);

        JSONArray hitsArray = new JSONArray();
        BrowseHit[] hits = result.getHits();
        if (hits != null && hits.length > 0) {
            for (int i = 0; i < hits.length; ++i) {
                hitsArray.put(i, serializeHits(hits[i]));
            }
        }
        obj.put("hits", hitsArray);
        // serialize documents
    }
    return obj.toString();
}

From source file:re.notifica.cordova.NotificarePlugin.java

/**
 * Fetch inbox items/*w  w  w.ja  v  a  2s.co m*/
 * @param args
 * @param callbackContext
 */
protected void fetchInbox(JSONArray args, final CallbackContext callbackContext) {
    Log.d(TAG, "FETCHINBOX");
    if (Notificare.shared().getInboxManager() != null) {
        int size = Notificare.shared().getInboxManager().getItems().size();
        int limit = args.optInt(1, DEFAULT_LIST_SIZE);
        if (limit <= 0) {
            limit = DEFAULT_LIST_SIZE;
        }
        int skip = args.optInt(0);
        if (skip < 0) {
            skip = 0;
        }
        if (skip > size) {
            skip = size;
        }
        int end = limit + skip;
        if (end > size) {
            end = size;
        }
        List<NotificareInboxItem> items = new ArrayList<NotificareInboxItem>(
                Notificare.shared().getInboxManager().getItems()).subList(skip, end);
        JSONArray inbox = new JSONArray();
        for (NotificareInboxItem item : items) {
            try {
                JSONObject result = new JSONObject();
                result.put("itemId", item.getItemId());
                result.put("notification", item.getNotification().getNotificationId());
                result.put("message", item.getNotification().getMessage());
                result.put("status", item.getStatus());
                result.put("timestamp", dateFormatter.format(item.getTimestamp()));
                inbox.put(result);
            } catch (JSONException e) {
                // Ignore this item
                Log.w(TAG, "failed to serialize inboxitem: " + e.getMessage());
            }
        }
        if (callbackContext == null) {
            return;
        }
        JSONObject results = new JSONObject();
        try {
            results.put("inbox", inbox);
            results.put("total", size);
            results.put("unread", Notificare.shared().getInboxManager().getUnreadCount());
        } catch (JSONException e) {
            Log.w(TAG, "failed to serialize inbox: " + e.getMessage());
        }
        callbackContext.success(results);
    } else {
        if (callbackContext == null) {
            return;
        }
        callbackContext.error("No inbox manager");
    }
}

From source file:re.notifica.cordova.NotificarePlugin.java

/**
 * Send a success result to the webview//from w  ww.j av a 2  s. c  om
 * @param type
 * @param data
 */
private void sendSuccessResult(String type, Object data) {
    if (data != null && type != null) {
        JSONObject result = new JSONObject();
        try {
            result.put("type", type);
            result.put("data", data);
            PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, result);
            pluginResult.setKeepCallback(true);
            if (mainCallback != null) {
                Log.d(TAG, "Sending success result: " + pluginResult.getMessage());
                mainCallback.sendPluginResult(pluginResult);
            } else {
                Log.d(TAG, "Queueing success result: " + pluginResult.getMessage());
                resultQueue.add(pluginResult);
            }
        } catch (JSONException e) {
            Log.e(TAG, "could not serialize result for callback");
        }

    }
}

From source file:re.notifica.cordova.NotificarePlugin.java

/**
 * Send an error to the webview//from   w ww.  j  a  v a2  s.com
 * @param type
 * @param message
 */
private void sendErrorResult(String type, String message) {
    if (message != null && type != null) {
        JSONObject result = new JSONObject();
        try {
            result.put("type", type);
            result.put("data", message);
            PluginResult pluginResult = new PluginResult(PluginResult.Status.ERROR, result);
            pluginResult.setKeepCallback(true);
            if (mainCallback != null) {
                mainCallback.sendPluginResult(pluginResult);
            } else {
                resultQueue.add(pluginResult);
            }
        } catch (JSONException e) {
            Log.e(TAG, "could not serialize result for callback");
        }

    }
}

From source file:com.skysql.manager.api.NodeInfo.java

/**
 * Save node info to API.//  w w w  . j  ava  2 s  . c o  m
 *
 * @return true, if successful
 */
public boolean save() {

    APIrestful api = new APIrestful();
    boolean success = false;

    try {
        if (ID != null) {
            JSONObject jsonParam = new JSONObject();
            jsonParam.put("name", this.name);
            jsonParam.put("hostname", this.hostname);
            jsonParam.put("instanceid", this.instanceID);
            jsonParam.put("publicip", this.publicIP);
            jsonParam.put("privateip", this.privateIP);
            if (this.dbUsername != null) {
                jsonParam.put("dbusername", this.dbUsername);
            }
            if (this.dbPassword != null) {
                jsonParam.put("dbpassword", this.dbPassword != null ? this.dbPassword : JSONObject.NULL);
            }
            if (this.repUsername != null) {
                jsonParam.put("repusername", this.repUsername);
            }
            if (this.repPassword != null) {
                jsonParam.put("reppassword", this.repPassword != null ? this.repPassword : JSONObject.NULL);
            }
            success = api.put("system/" + parentID + "/node/" + ID, jsonParam.toString());
        } else {
            StringBuffer regParam = new StringBuffer();
            regParam.append("name=" + URLEncoder.encode(this.name, "UTF-8"));
            regParam.append("&hostname=" + URLEncoder.encode(this.hostname, "UTF-8"));
            regParam.append("&instanceid=" + URLEncoder.encode(this.instanceID, "UTF-8"));
            regParam.append("&publicip=" + URLEncoder.encode(this.publicIP, "UTF-8"));
            regParam.append("&privateip=" + URLEncoder.encode(this.privateIP, "UTF-8"));
            if (this.dbUsername != null) {
                regParam.append("&dbusername=" + URLEncoder.encode(this.dbUsername, "UTF-8"));
            }
            if (this.dbPassword != null) {
                regParam.append("&dbpassword=" + URLEncoder.encode(this.dbPassword, "UTF-8"));
            }
            if (this.repUsername != null) {
                regParam.append("&repusername=" + URLEncoder.encode(this.repUsername, "UTF-8"));
            }
            if (this.repPassword != null) {
                regParam.append("&reppassword=" + URLEncoder.encode(this.repPassword, "UTF-8"));
            }
            success = api.post("system/" + parentID + "/node", regParam.toString());
        }

    } catch (JSONException e) {
        new ErrorDialog(e, "Error encoding API request");
        throw new RuntimeException("Error encoding API request");
    } catch (UnsupportedEncodingException e) {
        new ErrorDialog(e, "Error encoding API request");
        throw new RuntimeException("Error encoding API request");
    }

    if (success) {
        WriteResponse writeResponse = APIrestful.getGson().fromJson(api.getResult(), WriteResponse.class);
        if (writeResponse != null && ID == null && !writeResponse.getInsertKey().isEmpty()) {
            ID = writeResponse.getInsertKey();
            return true;
        } else if (writeResponse != null && ID != null && writeResponse.getUpdateCount() > 0) {
            return true;
        }
    }

    return false;

}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.VideoObj.java

/** 
 * This does NOT do any SCALING!/* w  ww . j a v a2 s  . co  m*/
 */
public static DbObject from(byte[] data) {
    return new DbObject(TYPE, new JSONObject(), data);
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.VideoObj.java

public static DbObject from(Context context, Uri videoUri) throws IOException {
    // Query gallery for camera picture via
    // Android ContentResolver interface
    ContentResolver cr = context.getContentResolver();
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 1;//from w ww .  j ava 2  s  .  c o m
    long videoId = Long.parseLong(videoUri.getLastPathSegment());
    Bitmap curThumb = MediaStore.Video.Thumbnails.getThumbnail(cr, videoId,
            MediaStore.Video.Thumbnails.MINI_KIND, options);
    int targetSize = 200;
    int width = curThumb.getWidth();
    int height = curThumb.getHeight();
    int cropSize = Math.min(width, height);
    float scaleSize = ((float) targetSize) / cropSize;
    Matrix matrix = new Matrix();
    matrix.postScale(scaleSize, scaleSize);
    curThumb = Bitmap.createBitmap(curThumb, 0, 0, width, height, matrix, true);
    JSONObject base = new JSONObject();
    String localIp = ContentCorral.getLocalIpAddress();
    if (localIp != null) {
        try {
            // TODO: Security breach hack?
            base.put(Contact.ATTR_LAN_IP, localIp);
            base.put(LOCAL_URI, videoUri.toString());
            base.put(MIME_TYPE, cr.getType(videoUri));
        } catch (JSONException e) {
            Log.e(TAG, "impossible json error possible!");
        }
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    curThumb.compress(Bitmap.CompressFormat.JPEG, 90, baos);
    byte[] data = baos.toByteArray();
    return from(base, data);
}

From source file:utils.tour.Step.java

/**
 * Get the step as a json object.// w  ww  . j a  v  a  2 s.c  o m
 * 
 * @param uid
 *            the tour uid
 * @param index
 *            the index of the step
 * @param previous
 *            the previous step
 * @param next
 *            the next step
 */
public JSONObject render(String uid, Integer index, Step previous, Step next) {

    JSONObject json = new JSONObject();

    try {
        json.put("title", this.title);
        json.put("content", this.content);
        if (this.element != null) {
            json.put("element", this.element);
            json.put("placement", this.placement);
        } else {
            json.put("orphan", true);
        }
        if (this.route != null) {
            json.put("path", this.route);
        }
        if (previous != null && previous.getRoute() != null && this.route != null
                && !previous.getRoute().equals(this.route)) {
            json.put("onPrev", "function(){ document.location.href = '" + previous.getRoute() + "?tourStep="
                    + (index - 1) + "&tourUid=" + uid + "'; return (new jQuery.Deferred()).promise(); }");
        }
        if (next != null && next.getRoute() != null && this.route != null
                && !next.getRoute().equals(this.route)) {
            json.put("onNext", "function(){ document.location.href = '" + next.getRoute() + "?tourStep="
                    + (index + 1) + "&tourUid=" + uid + "'; return (new jQuery.Deferred()).promise(); }");
        }
        return json;
    } catch (JSONException e) {
        Logger.error("error when render a step tour", e);
    }

    return null;
}