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(String source) throws JSONException 

Source Link

Document

Construct a JSONObject from a source JSON text string.

Usage

From source file:org.mozilla.gecko.gfx.PlaceholderLayerClient.java

private PlaceholderLayerClient(Context context) {
    mContext = context;/*w  w w  . j  a va2s . c  om*/
    String viewport = GeckoApp.mAppContext.getLastViewport();
    mViewportUnknown = true;
    if (viewport != null) {
        try {
            JSONObject viewportObject = new JSONObject(viewport);
            mViewport = new ViewportMetrics(viewportObject);
            mViewportUnknown = false;
        } catch (JSONException e) {
            Log.e(LOGTAG, "Error parsing saved viewport!");
            mViewport = new ViewportMetrics();
        }
    } else {
        mViewport = new ViewportMetrics();
    }
    loadScreenshot();
}

From source file:com.sina.weibo.sdk_lib.openapi.models.OffsetGeo.java

public static OffsetGeo parse(String jsonString) {
    if (TextUtils.isEmpty(jsonString)) {
        return null;
    }/*www.  j  a  va2 s  .  co  m*/

    OffsetGeo offsetGeo = new OffsetGeo();
    try {
        JSONObject jsonObject = new JSONObject(jsonString);

        JSONArray jsonArray = jsonObject.optJSONArray("geos");
        if (jsonArray != null && jsonArray.length() > 0) {
            int length = jsonArray.length();
            offsetGeo.Geos = new ArrayList<Coordinate>(length);
            for (int ix = 0; ix < length; ix++) {
                offsetGeo.Geos.add(Coordinate.parse(jsonArray.optJSONObject(ix)));
            }
        }

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

    return offsetGeo;
}

From source file:com.daskiworks.ghwatch.backend.AuthenticationManager.java

private String remoteLogin(Context context, GHCredentials cred, String otp)
        throws JSONException, NoRouteToHostException, AuthenticationException, ClientProtocolException,
        URISyntaxException, IOException {
    Map<String, String> headers = null;
    otp = Utils.trimToNull(otp);//  ww  w  . j a v  a 2 s  .c o  m
    if (otp != null) {
        headers = new HashMap<String, String>();
        headers.put("X-GitHub-OTP", otp);
    }
    Response<String> resp = RemoteSystemClient.putToURL(context, cred, GH_AUTH_REQ_URL, headers,
            GH_AUTH_REQ_CONTENT);
    JSONObject jo = new JSONObject(resp.data);
    return jo.getString("token");
}

From source file:org.wso2.emm.agent.services.ProcessMessage.java

public ProcessMessage(Context context, int mode, String message, String recepient) {
    // TODO Auto-generated constructor stub
    JSONParser jp = new JSONParser();
    params = new HashMap<String, String>();
    try {/* w  w w  .j av  a 2  s .  c  o m*/

        JSONObject jobj = new JSONObject(message);
        params.put("code", (String) jobj.get("message"));
        if (jobj.has("data")) {
            params.put("data", ((JSONObject) jobj.get("data")).toString());
        }

        operation = new Operation(context, mode, params, recepient);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.example.vendrisample.HelloEffects.java

License:asdf

@Override
public void onDrawFrame(final GL10 gl) {
    if (!mInitialized) {
        // Only need to do this once
        mEffectContext = EffectContext.createWithCurrentGlContext();
        mTexRenderer.init();/*from   w ww  .  ja  v  a 2  s .c o m*/
        loadTextures();
        mInitialized = true;
    }
    if (mCurrentEffect != R.id.none) {
        // if an effect is chosen initialize it and apply it to the texture
        initEffect();
        applyEffect();

        // manual play request (bypasses or works in addition to triggers)
        //            String json = "{\"adTags\":[\"http://ad3.liverail.com/?LR_PUBLISHER_ID=1331&LR_CAMPAIGN_ID=229&LR_SCHEMA=vast2\"],\"width\":640,\"height\":480,\"minWidth\":300,\"minHeight\":34,\"retry\":0,\"theme\":\"light\",\"autoplay\":true,\"volume\":0.7,\"controls\":{\"play\":true,\"volume\":true,\"mute\":true,\"progress\":true},\"map\":[{\"name\":\"asdf\",\"callback\":\"{vendriVar}\"}],\"events\":[{\"name\":\"adFinished\",\"callback\":\"helloWorld\"}],\"preferredType\":\"html5\",\"constraints\":{\"startTime\":3,\"playTime\":false},\"bitrate\":{\"check\":true,\"default\":600,\"async\":false},\"audioClickthrough\":false,\"debug\":false}";
        String json = "{}";
        try {

            JSONObject obj = new JSONObject(json);

            Vendri.play(obj, 6);
            Log.d("My App", obj.toString());

        } catch (Throwable t) {
            Log.e("My App", "Could not parse malformed JSON: " + json + "");
        }

    }
    renderResult();
}

From source file:com.clearcenter.mobile_demo.mdRest.java

static public String Login(String host, String username, String password, String token) throws JSONException {
    if (password == null)
        Log.i(TAG, "Login by cookie, host: " + host + ", username: " + username);
    else//from   ww  w. j  a  va 2 s . com
        Log.i(TAG, "Login by password, host: " + host + ", username: " + username);

    try {
        URL url = new URL("https://" + host + URL_LOGIN);

        HttpsURLConnection http = CreateConnection(url);

        if (password != null) {
            // Setup HTTPS POST request
            String urlParams = "username=" + URLEncoder.encode(username, "UTF-8") + "&password="
                    + URLEncoder.encode(password, "UTF-8") + "&submit=submit";

            http.setRequestMethod("POST");
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setRequestProperty("Content-Length", Integer.toString(urlParams.getBytes().length));

            // Write request
            DataOutputStream outputStream = new DataOutputStream(http.getOutputStream());
            outputStream.writeBytes(urlParams);
            outputStream.flush();
            outputStream.close();
        } else {
            http.setRequestMethod("GET");
            http.setRequestProperty("Cookie", token);
        }

        final StringBuffer response = ProcessRequest(http);

        // Process response
        JSONObject json_data = null;
        try {
            Log.i(TAG, "response: " + response.toString());
            json_data = new JSONObject(response.toString());
        } catch (JSONException e) {
            Log.e(TAG, "JSONException", e);
            return "";
        }
        if (json_data.has("result")) {
            final String cookie = http.getHeaderField("Set-Cookie");
            Integer result = RESULT_UNKNOWN;
            try {
                result = Integer.valueOf(json_data.getString("result"));
            } catch (NumberFormatException e) {
            }

            Log.i(TAG, "result: " + result.toString() + ", cookie: " + cookie);

            if (result == RESULT_SUCCESS) {
                if (cookie != null)
                    return cookie;
                else
                    return token;
            }

            // All other results are failures...
            return "";
        }
    } catch (Exception e) {
        Log.e(TAG, "Exception", e);
    }

    Log.i(TAG, "Malformed result");
    return "";
}

From source file:com.clearcenter.mobile_demo.mdRest.java

static public String GetSystemInfo(String host, String token, long last_sample)
        throws JSONException, ParseException, IOException, AuthenticationException {
    try {/*from  ww w. j a  v  a 2  s.c om*/
        URL url = new URL("https://" + host + URL_SYSINFO + "/" + last_sample);
        Log.v(TAG, "GetSystemInfo: host: " + host + ", token: " + token + ", URL: " + url);

        HttpsURLConnection http = CreateConnection(url);

        http.setRequestMethod("GET");
        http.setRequestProperty("Cookie", token);

        final StringBuffer response = ProcessRequest(http);

        // Process response
        JSONObject json_data = null;
        try {
            //Log.i(TAG, "response: " + response.toString());
            json_data = new JSONObject(response.toString());
        } catch (JSONException e) {
            Log.e(TAG, "JSONException", e);
            return "";
        }
        if (json_data.has("result")) {
            Integer result = RESULT_UNKNOWN;
            try {
                result = Integer.valueOf(json_data.getString("result"));
            } catch (NumberFormatException e) {
            }

            Log.d(TAG, "result: " + result.toString());

            if (result == RESULT_SUCCESS && json_data.has("data")) {
                //Log.i(TAG, "data: " + json_data.getString("data"));
                return json_data.getString("data");
            }

            if (result == RESULT_ACCESS_DENIED)
                throw new AuthenticationException();

            // New cookies?
            final String cookie = http.getHeaderField("Set-Cookie");
            if (cookie != null) {
                Log.d(TAG, "New cookie!");
            }

            // All other results are failures...
            throw new IOException();
        }
    } catch (MalformedURLException e) {
        Log.e(TAG, "MalformedURLException", e);
        throw new ParseException();
    }

    Log.i(TAG, "Malformed result");
    throw new IOException();
}

From source file:android.locationprivacy.algorithm.Webservice.java

@Override
public Location obfuscate(Location location) {
    // We do it this way to run network connection in main thread. This
    // way is not the normal one and does not comply to best practices,
    // but the main thread must wait for the obfuscation service reply anyway.
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);//from   ww  w . ja  va 2 s .c  om

    final String HOST_ADDRESS = configuration.getString("host");
    String username = configuration.getString("username");
    String password = configuration.getString("secret_password");

    Location newLoc = new Location(location);
    double lat = location.getLatitude();
    double lon = location.getLongitude();

    String urlString = HOST_ADDRESS;
    urlString += "?lat=" + lat;
    urlString += "&lon=" + lon;
    URL url;
    try {
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        Log.e(TAG, "Error: could not build URL");
        Log.e(TAG, e.getMessage());
        return null;
    }
    HttpsURLConnection connection = null;
    JSONObject json = null;
    InputStream is = null;
    try {
        connection = (HttpsURLConnection) url.openConnection();
        connection.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        connection.setRequestProperty("Authorization",
                "Basic " + Base64.encodeToString((username + ":" + password).getBytes(), Base64.NO_WRAP));
        is = connection.getInputStream();

    } catch (IOException e) {
        Log.e(TAG, "Error while connectiong to " + url.toString());
        Log.e(TAG, e.getMessage());
        return null;
    }
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    try {
        String line = reader.readLine();
        System.out.println("Line " + line);
        json = new JSONObject(line);
        newLoc.setLatitude(json.getDouble("lat"));
        newLoc.setLongitude(json.getDouble("lon"));
    } catch (IOException e) {
        Log.e(TAG, "Error: could not read from BufferedReader");
        Log.e(TAG, e.getMessage());
        return null;
    } catch (JSONException e) {
        Log.e(TAG, "Error: could not read from JSON");
        Log.e(TAG, e.getMessage());
        return null;
    }
    connection.disconnect();
    return newLoc;
}

From source file:org.privatenotes.Note.java

public JSONObject toJson() throws JSONException {
    return new JSONObject("{'guid':'" + getGuid() + "', 'title':'" + getTitle() + "', 'note-content':'"
            + getJsonPreparedXmlContent() + "', 'last-change-date':'" + getLastChangeDate().format3339(false)
            + "', 'note-content-version':0.1}");
}

From source file:eu.codeplumbers.cosi.services.CosiFileService.java

private void getAllRemoteFiles() {
    URL urlO = null;/*from w  ww .j a v  a2 s . c  o m*/
    try {
        urlO = new URL(fileUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject fileJson = jsonArray.getJSONObject(i).getJSONObject("value");
                File file = File.getByRemoteId(fileJson.get("_id").toString());

                if (file == null) {
                    file = new File(fileJson, false);
                } else {
                    file.setName(fileJson.getString("name"));
                    file.setPath(fileJson.getString("path"));
                    file.setCreationDate(fileJson.getString("creationDate"));
                    file.setLastModification(fileJson.getString("lastModification"));
                    file.setTags(fileJson.getString("tags"));

                    if (fileJson.has("binary")) {
                        file.setBinary(fileJson.getJSONObject("binary").toString());
                    }

                    file.setIsFile(true);
                    file.setFileClass(fileJson.getString("class"));
                    file.setMimeType(fileJson.getString("mime"));
                    file.setSize(fileJson.getLong("size"));
                }

                mBuilder.setProgress(jsonArray.length(), i, false);
                mBuilder.setContentText("Indexing file : " + file.getName());
                mNotifyManager.notify(notification_id, mBuilder.build());

                EventBus.getDefault()
                        .post(new FileSyncEvent(SYNC_MESSAGE, "Indexing file : " + file.getName()));

                file.setDownloaded(FileUtils.checkFileExists(Environment.getExternalStorageDirectory()
                        + java.io.File.separator + Constants.APP_DIRECTORY + java.io.File.separator + "files"
                        + file.getPath() + "/" + file.getName()));
                file.save();

                allFiles.add(file);
            }
        } else {
            EventBus.getDefault()
                    .post(new FileSyncEvent(SERVICE_ERROR, new JSONObject(result).getString("error")));
            mNotifyManager.notify(notification_id, mBuilder.build());
            stopSelf();
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
}