Example usage for org.json JSONObject getString

List of usage examples for org.json JSONObject getString

Introduction

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

Prototype

public String getString(String key) throws JSONException 

Source Link

Document

Get the string associated with a key.

Usage

From source file:jGW2API.util.event.Event.java

public Event(JSONObject json) {
    this.eventID = json.getString("event_id");
    this.mapID = new Integer(json.getInt("map_id"));
    this.worldID = new Integer(json.getInt("world_id"));
    this.eventState = Event.EventState.valueOf(json.getString("state"));
}

From source file:se.anyro.tagtider.model.Transfer.java

public Transfer(JSONObject station) throws JSONException {
    id = station.getInt("id");
    arrival = station.getString("arrival");
    departure = station.getString("departure");
    origin = station.getString("origin");
    destination = station.getString("destination");
    track = station.getInt("track");
    train = station.getInt("train");
    type = station.getString("type");
    comment = station.getString("comment");
    detected = station.getString("detected");
    updated = station.getString("updated");
}

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

@Override
public void onResume() {
    super.onResume();
    if (mIntent.hasExtra("image_url")) {
        String url = mIntent.getStringExtra("image_url");
        ((App) getApplication()).objectImages.lazyLoadImage(url.hashCode(), Uri.parse(url), im);
        bitmap = mgr.getBitmap(url.hashCode(), url);
    } else if (mIntent.hasExtra("b64Bytes")) {
        String b64Bytes = mIntent.getStringExtra("b64Bytes");
        ((App) getApplication()).objectImages.lazyLoadImage(b64Bytes.hashCode(), b64Bytes, im);
        bitmap = mgr.getBitmapB64(b64Bytes.hashCode(), b64Bytes);
    } else if (mIntent.hasExtra("bytes")) {
        byte[] bytes = mIntent.getByteArrayExtra("bytes");
        ((App) getApplication()).objectImages.lazyLoadImage(bytes.hashCode(), bytes, im);
        bitmap = mgr.getBitmap(bytes.hashCode(), bytes);
    } else if (mIntent.hasExtra("obj")) {
        try {/*w  w w. ja  va2  s .  c om*/
            final JSONObject content = new JSONObject(mIntent.getStringExtra("obj"));
            byte[] bytes = FastBase64.decode(content.optString(PictureObj.DATA));
            ((App) getApplication()).objectImages.lazyLoadImage(bytes.hashCode(), bytes, im);
            bitmap = mgr.getBitmap(bytes.hashCode(), bytes);
        } catch (JSONException e) {
        }
    }

    if (mIntent.hasExtra("objHash")) {
        if (!ContentCorral.CONTENT_CORRAL_ENABLED) {
            return;
        }

        long objHash = mIntent.getLongExtra("objHash", -1);
        final DbObj obj = App.instance().getMusubi().objForHash(objHash);
        final JSONObject json = obj.getJson();
        if (json.has(CorralClient.OBJ_LOCAL_URI)) {
            // TODO: this is a proof-of-concept.
            new Thread() {
                public void run() {
                    try {
                        if (!mCorralClient.fileAvailableLocally(obj)) {
                            //toast("Trying to go HD...");
                        }
                        // Log.d(TAG, "Trying to go HD...");
                        final Uri fileUri = mCorralClient.fetchContent(obj);
                        if (fileUri == null) {
                            try {
                                Log.d(TAG, "Failed to go HD for " + json.getString(CorralClient.OBJ_LOCAL_URI));
                            } catch (JSONException e) {
                                Log.d(TAG, "Failed to go HD for " + json);
                            }
                            return;
                        }
                        // Log.d(TAG, "Opening HD file " + fileUri);

                        InputStream is = getContentResolver().openInputStream(fileUri);
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inSampleSize = 4;

                        Matrix matrix = new Matrix();
                        float rotation = PhotoTaker.rotationForImage(ImageViewerActivity.this, fileUri);
                        if (rotation != 0f) {
                            matrix.preRotate(rotation);
                        }
                        bitmap = BitmapFactory.decodeStream(is, null, options);

                        int width = bitmap.getWidth();
                        int height = bitmap.getHeight();
                        bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                im.setImageBitmap(bitmap);
                            }
                        });
                    } catch (IOException e) {
                        // toast("Failed to go HD");
                        Log.e(TAG, "Failed to get hd content", e);
                        // continue
                    }
                };
            }.start();
        }
    }
}

From source file:org.everit.json.schema.TestSuiteTest.java

@Parameters(name = "{2}")
public static List<Object[]> params() {
    List<Object[]> rval = new ArrayList<>();
    Reflections refs = new Reflections("org.everit.json.schema.draft4", new ResourcesScanner());
    Set<String> paths = refs.getResources(Pattern.compile(".*\\.json"));
    for (String path : paths) {
        if (path.indexOf("/optional/") > -1 || path.indexOf("/remotes/") > -1) {
            continue;
        }/* ww  w .  j a va 2 s .co m*/
        String fileName = path.substring(path.lastIndexOf('/') + 1);
        JSONArray arr = loadTests(TestSuiteTest.class.getResourceAsStream("/" + path));
        for (int i = 0; i < arr.length(); ++i) {
            JSONObject schemaTest = arr.getJSONObject(i);
            JSONArray testcaseInputs = schemaTest.getJSONArray("tests");
            for (int j = 0; j < testcaseInputs.length(); ++j) {
                JSONObject input = testcaseInputs.getJSONObject(j);
                Object[] params = new Object[5];
                params[0] = "[" + fileName + "]/" + schemaTest.getString("description");
                params[1] = schemaTest.get("schema");
                params[2] = "[" + fileName + "]/" + input.getString("description");
                params[3] = input.get("data");
                params[4] = input.getBoolean("valid");
                rval.add(params);
            }
        }
    }
    return rval;
}

From source file:com.nginious.http.application.Http11SerializerTestCase.java

private void testResponse(String body) throws Exception {
    JSONObject bean = new JSONObject(body);
    assertTrue(bean.has("testBean1"));
    bean = bean.getJSONObject("testBean1");

    assertEquals(true, bean.getBoolean("first"));
    assertEquals(1.1d, bean.getDouble("second"));
    assertEquals(1.2f, (float) bean.getDouble("third"));
    assertEquals(2, bean.getInt("fourth"));
    assertEquals(5L, bean.getLong("fifth"));
    assertEquals((short) 3, (short) bean.getInt("sixth"));
    assertEquals("Seven", bean.getString("seventh"));
    assertTrue(bean.has("eight"));
    assertTrue(bean.has("ninth"));
}

From source file:net.cellcloud.talk.HttpSpeaker.java

@Override
public boolean call(List<String> identifiers) {
    if (SpeakerState.CALLING == this.state) {
        //  Call  false
        return false;
    }/*from w  ww  .j  a  v  a  2s .c om*/

    if (this.client.isStarting()) {
        // ?
        return false;
    }

    if (null != identifiers) {
        for (String identifier : identifiers) {
            if (this.identifierList.contains(identifier)) {
                continue;
            }

            this.identifierList.add(identifier);
        }
    }

    if (this.identifierList.isEmpty()) {
        return false;
    }

    // ??
    if (!this.client.isStarted()) {
        try {
            // ?
            this.client.start();

            int counts = 0;
            while (!this.client.isStarted()) {
                Thread.sleep(10);

                ++counts;
                if (counts > 150) {
                    break;
                }
            }
        } catch (Exception e) {
            Logger.log(HttpSpeaker.class, e, LogLevel.ERROR);
            return false;
        }
    }

    // ?
    this.state = SpeakerState.CALLING;

    //  URL
    StringBuilder url = new StringBuilder("http://");
    url.append(this.address.getHostString()).append(":").append(this.address.getPort());
    url.append(URI_INTERROGATION);

    try {
        ContentResponse response = this.client.newRequest(url.toString()).method(HttpMethod.GET).send();
        if (response.getStatus() == HttpResponse.SC_OK) {
            // ???? Cookie
            this.cookie = response.getHeaders().get(HttpHeader.SET_COOKIE);

            // ??
            JSONObject data = this.readContent(response.getContent());
            String ciphertextBase64 = data.getString(HttpInterrogationHandler.Ciphertext);
            final String key = data.getString(HttpInterrogationHandler.Key);
            final byte[] ciphertext = Cryptology.getInstance().decodeBase64(ciphertextBase64);
            // ?? Check 
            TalkService.getInstance().executor.execute(new Runnable() {
                @Override
                public void run() {
                    requestCheck(ciphertext, key.getBytes(Charset.forName("UTF-8")));
                }
            });
            return true;
        }
    } catch (InterruptedException | TimeoutException | ExecutionException | JSONException e) {
        Logger.log(HttpSpeaker.class, e, LogLevel.ERROR);
        // ?
        this.state = SpeakerState.HANGUP;
    }

    return false;
}

From source file:net.cellcloud.talk.HttpSpeaker.java

/**
 *  Check /* w w  w  .  j  av  a2 s.  co  m*/
 */
private void requestCheck(byte[] ciphertext, byte[] key) {
    if (null == this.address) {
        return;
    }

    // 
    byte[] plaintext = Cryptology.getInstance().simpleDecrypt(ciphertext, key);

    JSONObject data = new JSONObject();
    try {
        // 
        data.put(HttpCheckHandler.Plaintext, new String(plaintext, Charset.forName("UTF-8")));
        //  Tag
        data.put(HttpCheckHandler.Tag, Nucleus.getInstance().getTagAsString());
    } catch (JSONException e) {
        Logger.log(HttpSpeaker.class, e, LogLevel.ERROR);
        return;
    }

    //  URL
    StringBuilder url = new StringBuilder("http://");
    url.append(this.address.getHostString()).append(":").append(this.address.getPort());
    url.append(URI_CHECK);

    StringContentProvider content = new StringContentProvider(data.toString(), "UTF-8");
    try {
        // ??
        ContentResponse response = this.client.newRequest(url.toString()).method(HttpMethod.POST)
                .header(HttpHeader.COOKIE, this.cookie).content(content).send();
        if (response.getStatus() == HttpResponse.SC_OK) {
            // ??
            JSONObject responseData = this.readContent(response.getContent());
            if (null != responseData) {
                this.remoteTag = responseData.getString(HttpCheckHandler.Tag);

                // ? Cellet
                TalkService.getInstance().executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        requestCellets();
                    }
                });
            } else {
                Logger.e(HttpSpeaker.class, "Can not get tag data from check action");
            }
        } else {
            Logger.e(HttpSpeaker.class, "Request check failed: " + response.getStatus());

            TalkServiceFailure failure = new TalkServiceFailure(TalkFailureCode.CALL_FAILED, this.getClass());
            failure.setSourceCelletIdentifiers(this.identifierList);
            this.fireFailed(failure);
        }
    } catch (InterruptedException | TimeoutException | ExecutionException | JSONException e) {
        Logger.log(HttpSpeaker.class, e, LogLevel.ERROR);
    }

    url = null;
}

From source file:net.cellcloud.talk.HttpSpeaker.java

private void doDialogue(JSONObject data) throws JSONException {
    String identifier = data.getString(HttpDialogueHandler.Identifier);
    JSONObject primData = data.getJSONObject(HttpDialogueHandler.Primitive);
    // ?//  ww  w .  j a v  a 2s.c  o m
    Primitive primitive = new Primitive(this.remoteTag);
    primitive.setCelletIdentifier(identifier);
    PrimitiveSerializer.read(primitive, primData);

    this.fireDialogue(identifier, primitive);
}

From source file:com.phonegap.FileTransfer.java

/**
 * Uploads the specified file to the server URL provided using an HTTP 
 * multipart request. /*w w  w.jav a2 s  . co m*/
 * @param file      Full path of the file on the file system
 * @param server        URL of the server to receive the file
 * @param fileKey       Name of file request parameter
 * @param fileName      File name to be used on server
 * @param mimeType      Describes file content type
 * @param params        key:value pairs of user-defined parameters
 * @return FileUploadResult containing result of upload request
 */
public FileUploadResult upload(String file, String server, final String fileKey, final String fileName,
        final String mimeType, JSONObject params, boolean trustEveryone) throws IOException, SSLException {
    // Create return object
    FileUploadResult result = new FileUploadResult();

    // Get a input stream of the file on the phone
    InputStream fileInputStream = getPathFromUri(file);

    HttpURLConnection conn = null;
    DataOutputStream dos = null;

    int bytesRead, bytesAvailable, bufferSize;
    long totalBytes;
    byte[] buffer;
    int maxBufferSize = 8096;

    //------------------ CLIENT REQUEST
    // open a URL connection to the server 
    URL url = new URL(server);

    // Open a HTTP connection to the URL based on protocol 
    if (url.getProtocol().toLowerCase().equals("https")) {
        // Using standard HTTPS connection. Will not allow self signed certificate
        if (!trustEveryone) {
            conn = (HttpsURLConnection) url.openConnection();
        }
        // Use our HTTPS connection that blindly trusts everyone.
        // This should only be used in debug environments
        else {
            // Setup the HTTPS connection class to trust everyone
            trustAllHosts();
            HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
            // Save the current hostnameVerifier
            defaultHostnameVerifier = https.getHostnameVerifier();
            // Setup the connection not to verify hostnames 
            https.setHostnameVerifier(DO_NOT_VERIFY);
            conn = https;
        }
    }
    // Return a standard HTTP conneciton
    else {
        conn = (HttpURLConnection) url.openConnection();
    }

    // Allow Inputs
    conn.setDoInput(true);

    // Allow Outputs
    conn.setDoOutput(true);

    // Don't use a cached copy.
    conn.setUseCaches(false);

    // Use a post method.
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDRY);

    // Set the cookies on the response
    String cookie = CookieManager.getInstance().getCookie(server);
    if (cookie != null) {
        conn.setRequestProperty("Cookie", cookie);
    }

    dos = new DataOutputStream(conn.getOutputStream());

    // Send any extra parameters
    try {
        for (Iterator iter = params.keys(); iter.hasNext();) {
            Object key = iter.next();
            dos.writeBytes(LINE_START + BOUNDRY + LINE_END);
            dos.writeBytes("Content-Disposition: form-data; name=\"" + key.toString() + "\"; ");
            dos.writeBytes(LINE_END + LINE_END);
            dos.writeBytes(params.getString(key.toString()));
            dos.writeBytes(LINE_END);
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }

    dos.writeBytes(LINE_START + BOUNDRY + LINE_END);
    dos.writeBytes("Content-Disposition: form-data; name=\"" + fileKey + "\";" + " filename=\"" + fileName
            + "\"" + LINE_END);
    dos.writeBytes("Content-Type: " + mimeType + LINE_END);
    dos.writeBytes(LINE_END);

    // create a buffer of maximum size
    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];

    // read file and write it into form...
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    totalBytes = 0;

    while (bytesRead > 0) {
        totalBytes += bytesRead;
        result.setBytesSent(totalBytes);
        dos.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }

    // send multipart form data necesssary after file data...
    dos.writeBytes(LINE_END);
    dos.writeBytes(LINE_START + BOUNDRY + LINE_START + LINE_END);

    // close streams
    fileInputStream.close();
    dos.flush();
    dos.close();

    //------------------ read the SERVER RESPONSE
    StringBuffer responseString = new StringBuffer("");
    DataInputStream inStream = new DataInputStream(conn.getInputStream());
    String line;
    while ((line = inStream.readLine()) != null) {
        responseString.append(line);
    }
    Log.d(LOG_TAG, "got response from server");
    Log.d(LOG_TAG, responseString.toString());

    // send request and retrieve response
    result.setResponseCode(conn.getResponseCode());
    result.setResponse(responseString.toString());

    inStream.close();
    conn.disconnect();

    // Revert back to the proper verifier and socket factories
    if (trustEveryone && url.getProtocol().toLowerCase().equals("https")) {
        ((HttpsURLConnection) conn).setHostnameVerifier(defaultHostnameVerifier);
        HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
    }

    return result;
}