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:de.kp.ames.webdav.WebDAVClient.java

/**
 * Determines all level 1 resources of a certain webdav resource, 
 * referred by the given uri; this is a method for a folder-like 
 * listing//  www  .  ja  v a 2s  .  c  o m
 * 
 * @return
 */
public JSONArray getResources() {

    /*
     * Sorter to sort WebDAV folder by name
     */
    Map<String, JSONObject> collector = new TreeMap<String, JSONObject>(new Comparator<String>() {
        public int compare(String name1, String name2) {
            return name1.compareTo(name2);
        }
    });

    try {

        DavMethod method = new PropFindMethod(uri, DavConstants.PROPFIND_ALL_PROP, DavConstants.DEPTH_1);
        client.executeMethod(method);

        MultiStatus multiStatus = method.getResponseBodyAsMultiStatus();

        MultiStatusResponse[] responses = multiStatus.getResponses();
        MultiStatusResponse response;

        /* 
         * Determine base uri from uri
         */
        String base_uri = null;

        int first_slash = uri.indexOf("/", 8); // after http://
        if (uri.endsWith("/"))
            base_uri = uri.substring(first_slash);

        int status = 200; // http ok

        for (int i = 0; i < responses.length; i++) {

            response = responses[i];
            String href = response.getHref();

            /* 
             * Ignore the current directory
             */
            if (href.equals(base_uri))
                continue;

            String name = href.substring(base_uri.length());
            // remove the final / from the name for directories
            if (name.endsWith("/"))
                name = name.substring(0, name.length() - 1);

            // ============= properties =================================

            DavPropertySet properties = response.getProperties(status);

            /* 
             * creationdate
             */
            String creationdate = null;

            DavProperty<?> creationDate = properties.get("creationdate");
            if ((creationDate != null) && (creationDate.getValue() != null))
                creationdate = creationDate.getValue().toString();

            /* 
             * lastModifiedDate
             */
            String lastmodified = null;

            DavProperty<?> lastModifiedDate = properties.get("getlastmodified");
            if ((lastModifiedDate != null) && (lastModifiedDate.getValue() != null)) {
                lastmodified = lastModifiedDate.getValue().toString();

            } else {
                lastmodified = creationdate;
            }

            /* 
             * contenttype
             */
            String contenttype = "text/plain";

            DavProperty<?> contentType = properties.get("getcontenttype");
            if ((contentType != null) && (contentType.getValue() != null))
                contenttype = contentType.getValue().toString();

            /* 
             * getcontentlength
             */
            String contentlength = "0";

            DavProperty<?> contentLength = properties.get("getcontentlength");
            if ((contentLength != null) && (contentLength.getValue() != null))
                contentlength = contentLength.getValue().toString();

            /* 
             * resource type
             */
            String resourcetype = null;

            DavProperty<?> resourceType = properties.get("resourcetype");
            if ((resourceType != null) && (resourceType.getValue() != null))
                resourcetype = resourceType.getValue().toString();

            // title
            //DavProperty title = properties.get("title");

            // supportedlock
            //DavProperty supportedLock = properties.get("supportedlock");

            // displayname
            //DavProperty displayName = properties.get("displayname");

            /* 
             * distinguish folder & file resource
             */
            boolean isfolder = false;
            if ((resourcetype != null) && (resourcetype.indexOf("collection") != -1))
                isfolder = true;

            /* 
             * determine absolute url
             */
            String resource_uri = uri + name;
            if (isfolder == true)
                resource_uri = resource_uri + "/";

            // this is a tribute to plone webdav server
            // we ignore file-like resources with content length = 0
            if ((isfolder == false) && (contentlength == "0"))
                continue;

            /*
             * Convert to JSON object
             */
            JSONObject jResource = new JSONObject();

            jResource.put("name", name);
            jResource.put("uri", resource_uri);

            jResource.put("creationDate", creationdate);
            jResource.put("lastModified", lastmodified);

            jResource.put("isFolder", isfolder);

            if (isfolder == false) {

                jResource.put("contentLength", contentlength);
                jResource.put("contentType", contenttype);
            }

            collector.put(name, jResource);

        }

        return new JSONArray(collector.values());

    } catch (Exception e) {
        e.printStackTrace();

    } finally {
    }

    return new JSONArray();

}

From source file:edu.stanford.mobisocial.dungbeetle.DBIdentityProvider.java

public String userProfile() {
    Cursor c = mHelper.getReadableDatabase().rawQuery("SELECT * FROM " + MyInfo.TABLE, new String[] {});

    try {/*  w w  w.  j av  a2 s  .  c  om*/
        c.moveToFirst();
        JSONObject obj = new JSONObject();
        try {
            obj.put("name", c.getString(c.getColumnIndexOrThrow(MyInfo.NAME)));
        } catch (JSONException e) {
        }
        return JSON.fastAddBase64(obj.toString(), "picture",
                c.getBlob(c.getColumnIndexOrThrow(MyInfo.PICTURE)));
    } finally {
        c.close();
    }
}

From source file:fr.cobaltians.cobalt.fragments.CobaltFlipperFragment.java

private void swipe(final int direction) {
    mHandler.post(new Runnable() {
        @Override//from  w  ww. j  ava  2 s.  com
        public void run() {
            JSONObject jsonObj = new JSONObject();
            try {
                jsonObj.put(Cobalt.kJSType, Cobalt.JSTypeEvent);
                if (direction == GESTURE_SWIPE_LEFT) {
                    jsonObj.put(Cobalt.kJSEvent, JSEventSwipeLeft);
                    if (Cobalt.DEBUG)
                        Log.i(Cobalt.TAG, TAG + " - swipe: next");
                } else if (direction == GESTURE_SWIPE_RIGHT) {
                    jsonObj.put(Cobalt.kJSEvent, JSEventSwipeRight);
                    if (Cobalt.DEBUG)
                        Log.i(Cobalt.TAG, TAG + " - swipe: previous");
                }
                sendMessage(jsonObj);
            } catch (JSONException exception) {
                exception.printStackTrace();
            }
        }
    });
}

From source file:org.ohmage.request.user.UserStatsReadRequest.java

/**
 * Responds to the user's request.//from w w w .j av  a 2 s . com
 */
@Override
public void respond(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
    JSONObject jsonResult = new JSONObject();

    if (!isFailed()) {
        try {
            jsonResult.put(JSON_KEY_HOURS_SINCE_LAST_SURVEY_UPLOAD, hoursSinceLastSurveyUpload);

            jsonResult.put(JSON_KEY_HOURS_SINCE_LAST_MOBILITY_UPLOAD,
                    ((hoursSinceLastMobilityUpload == null) ? DEFAULT_VALUE_IF_NO_MOBILITY_UPLOADS
                            : hoursSinceLastMobilityUpload));

            jsonResult.put(JSON_KEY_PAST_DAY_SUCCESSFUL_SURVEY_LOCATION_UPDATES_PERCENTAGE,
                    pastDaySuccessfulSurveyLocationUpdatesPercentage);

            jsonResult.put(JSON_KEY_PAST_DAY_SUCCESSFUL_MOBILITY_LOCATION_UPDATES_PERCENTAGE,
                    ((pastDatSuccessfulMobilityLocationUpdatesPercentage == null)
                            ? DEFAULT_VALUE_IF_NO_MOBILITY_UPLOADS_IN_LAST_DAY
                            : pastDatSuccessfulMobilityLocationUpdatesPercentage));
        } catch (JSONException e) {
            LOGGER.error("There was an error creating the JSONArray result object.", e);
            setFailed();
        }
    }

    super.respond(httpRequest, httpResponse, JSON_KEY_RESULT, jsonResult);
}

From source file:org.entando.entando.plugins.jptrello.aps.system.services.trello.TrelloConfig.java

public String toXml() throws Throwable {
    JSONObject json = new JSONObject();

    json.put(CONFIG_ORGANIZATION, _organization);
    json.put(CONFIG_KEY, _apiKey);/*from  ww w  .  j  a  v  a2  s  .c  om*/
    json.put(CONFIG_SECRET, _apiSecret);
    json.put(CONFIG_TOKEN, _token);
    return XML.toString(json, CONFIG_ROOT);
}

From source file:com.sfalma.trace.Sfalma.java

public static String createJSON(String app_package, String version, String phoneModel, String android_version,
        String stackTrace, String wifi_status, String mob_net_status, String gps_status, Date occuredAt)
        throws Exception {
    JSONObject json = new JSONObject();

    JSONObject request_json = new JSONObject();
    JSONObject exception_json = new JSONObject();
    JSONObject application_json = new JSONObject();
    JSONObject client_json = new JSONObject();

    request_json.put("remote_ip", "");
    json.put("request", request_json);

    // stackTrace contains many info we need to extract
    BufferedReader reader = new BufferedReader(new StringReader(stackTrace));

    if (occuredAt == null)
        exception_json.put("occured_at", reader.readLine());
    else/*from   w ww .  j ava  2 s  .co  m*/
        exception_json.put("occured_at", occuredAt);
    exception_json.put("message", reader.readLine()); //get message

    String exception_class = reader.readLine();
    exception_json.put("where",
            exception_class.substring(exception_class.lastIndexOf("(") + 1, exception_class.lastIndexOf(")")));

    exception_json.put("klass", getClass(stackTrace));
    exception_json.put("backtrace", stackTrace);

    json.put("exception", exception_json);

    reader.close();

    application_json.put("phone", phoneModel);
    application_json.put("appver", version);
    application_json.put("appname", app_package);
    application_json.put("osver", android_version); //os_ver
    application_json.put("wifi_on", wifi_status);
    application_json.put("mobile_net_on", mob_net_status);
    application_json.put("gps_on", gps_status);
    json.put("application_environment", application_json);

    client_json.put("version", "sfalma-version-0.6");
    client_json.put("name", "sfalma-android");
    json.put("client", client_json);

    return json.toString();
}

From source file:org.uiautomation.ios.server.command.web.ExecuteScriptHandler.java

@Override
public Response handle() throws Exception {
    String script = getRequest().getPayload().getString("script");
    JSONArray args = getRequest().getPayload().getJSONArray("args");
    Object res = getSession().getWebInspector().executeScript(script, args);

    Response resp = new Response();
    resp.setSessionId(getSession().getSessionId());
    resp.setStatus(0);/*from w  w  w.  ja  v  a2s.co  m*/

    if (res instanceof RemoteObject) {
        RemoteObject ro = (RemoteObject) res;
        RemoteWebElement rwe = ro.getWebElement();
        JSONObject jo = new JSONObject().put("ELEMENT", rwe.getNodeId().getId());
        resp.setValue(jo);
    } else if (res instanceof Integer) {
        resp.setValue(res);
    } else if (res instanceof Boolean) {
        resp.setValue(res);
    } else if (res instanceof Collection) {

        List<Object> rwes = new ArrayList<Object>();

        Collection<Object> all = (Collection<Object>) res;
        for (Object ro : all) {
            if (ro instanceof RemoteObject) {
                JSONObject jo = new JSONObject().put("ELEMENT",
                        "" + ((RemoteObject) ro).getWebElement().getNodeId().getId());
                rwes.add(jo);
            } else {
                rwes.add(ro);
            }
        }

        resp.setValue(rwes);
    } else {
        resp.setValue(res);
    }

    return resp;

}

From source file:edu.asu.bscs.ihattend.jsonrpcapp.JsonRPCCalculator.java

public Double calculate(Double op1, Double op2, String operation) {
    try {/*from  w  ww . ja va  2 s . c  o  m*/
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("jsonrpc", "2.0");
        jsonObject.put("id", ++id);
        jsonObject.put("method", operation);

        String params = String.format(",\"params\":[%.2f,%.2f]", op1, op2);
        String almost = jsonObject.toString();
        String begin = almost.substring(0, almost.length() - 1);
        String end = almost.substring(almost.length() - 1);
        String call = begin + params + end;

        Log.d(TAG, "call: " + call);
        String responseString = server.call(call);
        Log.d(TAG, "response: " + responseString);
        JSONObject response = new JSONObject(responseString);
        Double result = response.optDouble("result");
        Log.d(TAG, "result: " + result);

        return result;
    } catch (Exception e) {
        e.printStackTrace();
    }
    // should really throw an exception...
    return 0.0;
}

From source file:com.eTilbudsavis.etasdk.network.Request.java

/**
 * Creates a new request with the given method (one of the values from {@link Method}),
 * URL, and error listener.  Note that the normal response listener is not provided here as
 * delivery of responses is provided by subclasses, who have a better idea of how to deliver
 * an already-parsed response.//from   w ww .  ja v a 2s . c o  m
 */
public Request(Method method, String url, Listener<T> listener) {
    mMethod = method;
    mUrl = url;
    mListener = listener;
    mEventLog = new EventLog();
    mNetworkLog = new JSONObject();
}

From source file:com.cdd.bao.importer.KeywordMapping.java

public void save() throws IOException {
    JSONObject json = new JSONObject();
    JSONArray listID = new JSONArray(), listText = new JSONArray(), listProp = new JSONArray();
    JSONArray listVal = new JSONArray(), listLit = new JSONArray(), listRef = new JSONArray(),
            listAsrt = new JSONArray();

    for (Identifier id : identifiers) {
        JSONObject obj = new JSONObject();
        obj.put("regex", id.regex);
        obj.put("prefix", id.prefix);
        listID.put(obj);/*from  ww w. jav a2s  .c  o m*/
    }
    for (TextBlock txt : textBlocks) {
        JSONObject obj = new JSONObject();
        obj.put("regex", txt.regex);
        obj.put("title", txt.title);
        listText.put(obj);
    }
    for (Property prop : properties) {
        JSONObject obj = new JSONObject();
        obj.put("regex", prop.regex);
        obj.put("propURI", prop.propURI);
        obj.put("groupNest", prop.groupNest);
        listProp.put(obj);
    }
    for (Value val : values) {
        JSONObject obj = new JSONObject();
        obj.put("regex", val.regex);
        obj.put("valueRegex", val.valueRegex);
        obj.put("valueURI", val.valueURI);
        obj.put("propURI", val.propURI);
        obj.put("groupNest", val.groupNest);
        listVal.put(obj);
    }
    for (Literal lit : literals) {
        JSONObject obj = new JSONObject();
        obj.put("regex", lit.regex);
        obj.put("valueRegex", lit.valueRegex);
        obj.put("propURI", lit.propURI);
        obj.put("groupNest", lit.groupNest);
        listLit.put(obj);
    }
    for (Reference ref : references) {
        JSONObject obj = new JSONObject();
        obj.put("regex", ref.regex);
        obj.put("valueRegex", ref.valueRegex);
        obj.put("prefix", ref.prefix);
        obj.put("propURI", ref.propURI);
        obj.put("groupNest", ref.groupNest);
        listRef.put(obj);
    }
    for (Assertion asrt : assertions) {
        JSONObject obj = new JSONObject();
        obj.put("propURI", asrt.propURI);
        obj.put("groupNest", asrt.groupNest);
        obj.put("valueURI", asrt.valueURI);
        listAsrt.put(obj);
    }

    json.put("identifiers", listID);
    json.put("textBlocks", listText);
    json.put("properties", listProp);
    json.put("values", listVal);
    json.put("literals", listLit);
    json.put("references", listRef);
    json.put("assertions", listAsrt);

    Writer wtr = new FileWriter(file);
    wtr.write(json.toString(2));
    wtr.close();
}