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:re.notifica.cordova.NotificarePlugin.java

/**
 * Open the notification in NotificationActivity
 * @param args/*from   w  w  w .j  a va  2s .  com*/
 * @param callbackContext
 */
protected void openNotification(JSONArray args, final CallbackContext callbackContext) {
    Log.d(TAG, "OPENNOTIFICATION");
    try {
        JSONObject notificationJSON = args.getJSONObject(0);
        // Workaround for pre-1.1.1 SDK
        notificationJSON.put("_id", notificationJSON.get("notificationId"));
        NotificareNotification notification = new NotificareNotification(notificationJSON);

        Intent notificationIntent = new Intent()
                .setClass(Notificare.shared().getApplicationContext(), NotificationActivity.class)
                .setAction(Notificare.INTENT_ACTION_NOTIFICATION_OPENED)
                .putExtra(Notificare.INTENT_EXTRA_NOTIFICATION, notification)
                .putExtra(Notificare.INTENT_EXTRA_DISPLAY_MESSAGE, Notificare.shared().getDisplayMessage())
                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);

        if (notificationJSON.optString("itemId", null) != null) {
            notificationIntent.putExtra(Notificare.INTENT_EXTRA_INBOX_ITEM_ID,
                    notificationJSON.getString("itemId"));
        }

        cordova.getActivity().startActivity(notificationIntent);
        if (callbackContext == null) {
            return;
        }
        callbackContext.success();
    } catch (JSONException e) {
        if (callbackContext == null) {
            return;
        }
        callbackContext.error("JSON parse error");
    }
}

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

/**
 * Mark a  inbox item as read/*from   w  w  w .  j a va2  s  .c om*/
 * @param args
 * @param callbackContext
 */
protected void markInboxItem(JSONArray args, final CallbackContext callbackContext) {
    Log.i(TAG, "mark inbox item");
    if (Notificare.shared().getInboxManager() != null) {
        try {
            JSONObject item = args.getJSONObject(0);
            item.put("_id", item.getString("itemId"));
            item.put("opened", item.getBoolean("status"));
            item.put("time", item.getString("timestamp"));
            NotificareInboxItem inboxItem = new NotificareInboxItem(item);
            Notificare.shared().getEventLogger()
                    .logOpenNotification(inboxItem.getNotification().getNotificationId());
            Notificare.shared().getInboxManager().markItem(inboxItem);
            if (callbackContext == null) {
                return;
            }
            callbackContext.success();
        } catch (JSONException e) {
            if (callbackContext == null) {
                return;
            }
            callbackContext.error("JSON parse error");
        }
    } else {
        if (callbackContext == null) {
            return;
        }
        callbackContext.error("No inbox manager");
    }
}

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

/**
 * Delete an inbox item/*from ww w  .  j  a va2  s  .com*/
 * @param args
 * @param callbackContext
 */
protected void deleteInboxItem(JSONArray args, final CallbackContext callbackContext) {
    if (Notificare.shared().getInboxManager() != null) {
        try {
            JSONObject item = args.getJSONObject(0);
            item.put("_id", item.getString("itemId"));
            item.put("opened", item.getBoolean("status"));
            item.put("time", item.getString("timestamp"));
            final NotificareInboxItem inboxItem = new NotificareInboxItem(item);
            Notificare.shared().deleteInboxItem(inboxItem.getItemId(), new NotificareCallback<Boolean>() {
                @Override
                public void onSuccess(Boolean result) {
                    Notificare.shared().getInboxManager().removeItem(inboxItem);
                    if (callbackContext == null) {
                        return;
                    }
                    callbackContext.success();
                }

                @Override
                public void onError(NotificareError notificareError) {
                    if (callbackContext == null) {
                        return;
                    }
                    callbackContext.error("Could not delete inbox item");
                }
            });
        } catch (JSONException e) {
            if (callbackContext == null) {
                return;
            }
            callbackContext.error("JSON parse error");
        }
    } else {
        if (callbackContext == null) {
            return;
        }
        callbackContext.error("No inbox manager");
    }
}

From source file:it.moondroid.chatbot.alice.Sraix.java

public static String sraixPannous(String input, String hint, Chat chatSession) {
    try {/*from  w  w w.j  a  v a 2s  .  co  m*/
        String rawInput = input;
        if (hint == null)
            hint = MagicStrings.sraix_no_hint;
        input = " " + input + " ";
        input = input.replace(" point ", ".");
        input = input.replace(" rparen ", ")");
        input = input.replace(" lparen ", "(");
        input = input.replace(" slash ", "/");
        input = input.replace(" star ", "*");
        input = input.replace(" dash ", "-");
        // input = chatSession.bot.preProcessor.denormalize(input);
        input = input.trim();
        input = input.replace(" ", "+");
        int offset = CalendarUtils.timeZoneOffset();
        //System.out.println("OFFSET = "+offset);
        String locationString = "";
        if (chatSession.locationKnown) {
            locationString = "&location=" + chatSession.latitude + "," + chatSession.longitude;
        }
        // https://weannie.pannous.com/api?input=when+is+daylight+savings+time+in+the+us&locale=en_US&login=pandorabots&ip=169.254.178.212&botid=0&key=CKNgaaVLvNcLhDupiJ1R8vtPzHzWc8mhIQDFSYWj&exclude=Dialogues,ChatBot&out=json
        // exclude=Dialogues,ChatBot&out=json&clientFeatures=show-images,reminder,say&debug=true
        String url = "https://ask.pannous.com/api?input=" + input + "&locale=en_US&timeZone=" + offset
                + locationString + "&login=" + MagicStrings.pannous_login + "&ip="
                + NetworkUtils.localIPAddress() + "&botid=0&key=" + MagicStrings.pannous_api_key
                + "&exclude=Dialogues,ChatBot&out=json&clientFeatures=show-images,reminder,say&debug=true";
        MagicBooleans.trace("in Sraix.sraixPannous, url: '" + url + "'");
        String page = NetworkUtils.responseContent(url);
        //MagicBooleans.trace("in Sraix.sraixPannous, page: " + page);
        String text = "";
        String imgRef = "";
        String urlRef = "";
        if (page == null || page.length() == 0) {
            text = MagicStrings.sraix_failed;
        } else {
            JSONArray outputJson = new JSONObject(page).getJSONArray("output");
            //MagicBooleans.trace("in Sraix.sraixPannous, outputJson class: " + outputJson.getClass() + ", outputJson: " + outputJson);
            if (outputJson.length() == 0) {
                text = MagicStrings.sraix_failed;
            } else {
                JSONObject firstHandler = outputJson.getJSONObject(0);
                //MagicBooleans.trace("in Sraix.sraixPannous, firstHandler class: " + firstHandler.getClass() + ", firstHandler: " + firstHandler);
                JSONObject actions = firstHandler.getJSONObject("actions");
                //MagicBooleans.trace("in Sraix.sraixPannous, actions class: " + actions.getClass() + ", actions: " + actions);
                if (actions.has("reminder")) {
                    //MagicBooleans.trace("in Sraix.sraixPannous, found reminder action");
                    Object obj = actions.get("reminder");
                    if (obj instanceof JSONObject) {
                        if (MagicBooleans.trace_mode)
                            System.out.println("Found JSON Object");
                        JSONObject sObj = (JSONObject) obj;
                        String date = sObj.getString("date");
                        date = date.substring(0, "2012-10-24T14:32".length());
                        if (MagicBooleans.trace_mode)
                            System.out.println("date=" + date);
                        String duration = sObj.getString("duration");
                        if (MagicBooleans.trace_mode)
                            System.out.println("duration=" + duration);

                        Pattern datePattern = Pattern.compile("(.*)-(.*)-(.*)T(.*):(.*)");
                        Matcher m = datePattern.matcher(date);
                        String year = "", month = "", day = "", hour = "", minute = "";
                        if (m.matches()) {
                            year = m.group(1);
                            month = String.valueOf(Integer.parseInt(m.group(2)) - 1);
                            day = m.group(3);

                            hour = m.group(4);
                            minute = m.group(5);
                            text = "<year>" + year + "</year>" + "<month>" + month + "</month>" + "<day>" + day
                                    + "</day>" + "<hour>" + hour + "</hour>" + "<minute>" + minute + "</minute>"
                                    + "<duration>" + duration + "</duration>";

                        } else
                            text = MagicStrings.schedule_error;
                    }
                } else if (actions.has("say") && !hint.equals(MagicStrings.sraix_pic_hint)
                        && !hint.equals(MagicStrings.sraix_shopping_hint)) {
                    MagicBooleans.trace("in Sraix.sraixPannous, found say action");
                    Object obj = actions.get("say");
                    //MagicBooleans.trace("in Sraix.sraixPannous, obj class: " + obj.getClass());
                    //MagicBooleans.trace("in Sraix.sraixPannous, obj instanceof JSONObject: " + (obj instanceof JSONObject));
                    if (obj instanceof JSONObject) {
                        JSONObject sObj = (JSONObject) obj;
                        text = sObj.getString("text");
                        if (sObj.has("moreText")) {
                            JSONArray arr = sObj.getJSONArray("moreText");
                            for (int i = 0; i < arr.length(); i++) {
                                text += " " + arr.getString(i);
                            }
                        }
                    } else {
                        text = obj.toString();
                    }
                }
                if (actions.has("show") && !text.contains("Wolfram")
                        && actions.getJSONObject("show").has("images")) {
                    MagicBooleans.trace("in Sraix.sraixPannous, found show action");
                    JSONArray arr = actions.getJSONObject("show").getJSONArray("images");
                    int i = (int) (arr.length() * Math.random());
                    //for (int j = 0; j < arr.length(); j++) System.out.println(arr.getString(j));
                    imgRef = arr.getString(i);
                    if (imgRef.startsWith("//"))
                        imgRef = "http:" + imgRef;
                    imgRef = "<a href=\"" + imgRef + "\"><img src=\"" + imgRef + "\"/></a>";
                    //System.out.println("IMAGE REF="+imgRef);

                }
                if (hint.equals(MagicStrings.sraix_shopping_hint) && actions.has("open")
                        && actions.getJSONObject("open").has("url")) {
                    urlRef = "<oob><url>" + actions.getJSONObject("open").getString("url") + "</oob></url>";

                }
            }
            if (hint.equals(MagicStrings.sraix_event_hint) && !text.startsWith("<year>"))
                return MagicStrings.sraix_failed;
            else if (text.equals(MagicStrings.sraix_failed))
                return AIMLProcessor.respond(MagicStrings.sraix_failed, "nothing", "nothing", chatSession);
            else {
                text = text.replace("&#39;", "'");
                text = text.replace("&apos;", "'");
                text = text.replaceAll("\\[(.*)\\]", "");
                String[] sentences;
                sentences = text.split("\\. ");
                //System.out.println("Sraix: text has "+sentences.length+" sentences:");
                String clippedPage = sentences[0];
                for (int i = 1; i < sentences.length; i++) {
                    if (clippedPage.length() < 500)
                        clippedPage = clippedPage + ". " + sentences[i];
                    //System.out.println(i+". "+sentences[i]);
                }

                clippedPage = clippedPage + " " + imgRef + " " + urlRef;
                clippedPage = clippedPage.trim();
                log(rawInput, clippedPage);
                return clippedPage;
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        System.out.println("Sraix '" + input + "' failed");
    }
    return MagicStrings.sraix_failed;
}

From source file:org.wso2.carbon.connector.integration.test.pivotaltracker.PivotaltrackerConnectorIntegrationTest.java

/**
 * Positive test case for createLabelForStory method with mandatory parameters.
 * // www  .  j  a  v  a 2s .co m
 * @throws JSONException
 * @throws IOException
 */
@Test(groups = { "wso2.esb" }, dependsOnMethods = { "testCreateProjectWithMandatoryParameters",
        "testCreateStoryWithMandatoryParameters" }, description = "pivotaltracker {createLabelForStory} integration test with mandatory parameters.")
public void testCreateLabelForStoryWithMandatoryParameters() throws IOException, JSONException {

    esbRequestHeadersMap.put("Action", "urn:createLabelForStory");
    RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap,
            "esb_createLabelForStory_mandatory.json");
    final String labelId = esbRestResponse.getBody().getString("id");

    final String apiEndpoint = apiEndpointUrl + "/projects/" + connectorProperties.getProperty("projectId")
            + "/stories/" + connectorProperties.getProperty("storyId") + "/labels";
    RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiEndpoint, "GET", apiRequestHeadersMap);
    JSONArray apiOutputArray = new JSONArray(apiRestResponse.getBody().getString("output"));
    JSONObject lableObj = null;
    for (int i = 0; i < apiOutputArray.length(); i++) {
        lableObj = apiOutputArray.getJSONObject(i);
        if (labelId.equals(lableObj.getString("id"))) {
            break;
        }
    }
    Assert.assertEquals(connectorProperties.getProperty("labelName"), lableObj.getString("name"));

}

From source file:com.hichinaschool.flashcards.libanki.sync.BasicHttpSyncer.java

public HttpResponse req(String method, InputStream fobj, int comp, boolean hkey, JSONObject registerData,
        Connection.CancelCallback cancelCallback) {
    File tmpFileBuffer = null;/*from  w  w  w . ja  va 2s . c o  m*/
    try {
        String bdry = "--" + BOUNDARY;
        StringWriter buf = new StringWriter();
        HashMap<String, Object> vars = new HashMap<String, Object>();
        // compression flag and session key as post vars
        vars.put("c", comp != 0 ? 1 : 0);
        if (hkey) {
            vars.put("k", mHKey);
            vars.put("s", mSKey);
        }
        for (String key : vars.keySet()) {
            buf.write(bdry + "\r\n");
            buf.write(String.format(Locale.US, "Content-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n", key,
                    vars.get(key)));
        }
        tmpFileBuffer = File.createTempFile("syncer", ".tmp",
                new File(AnkiDroidApp.getCacheStorageDirectory()));
        FileOutputStream fos = new FileOutputStream(tmpFileBuffer);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        GZIPOutputStream tgt;
        // payload as raw data or json
        if (fobj != null) {
            // header
            buf.write(bdry + "\r\n");
            buf.write(
                    "Content-Disposition: form-data; name=\"data\"; filename=\"data\"\r\nContent-Type: application/octet-stream\r\n\r\n");
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
            // write file into buffer, optionally compressing
            int len;
            BufferedInputStream bfobj = new BufferedInputStream(fobj);
            byte[] chunk = new byte[65536];
            if (comp != 0) {
                tgt = new GZIPOutputStream(bos);
                while ((len = bfobj.read(chunk)) >= 0) {
                    tgt.write(chunk, 0, len);
                }
                tgt.close();
                bos = new BufferedOutputStream(new FileOutputStream(tmpFileBuffer, true));
            } else {
                while ((len = bfobj.read(chunk)) >= 0) {
                    bos.write(chunk, 0, len);
                }
            }
            bos.write(("\r\n" + bdry + "--\r\n").getBytes("UTF-8"));
        } else {
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
        }
        bos.flush();
        bos.close();
        // connection headers
        String url = Collection.SYNC_URL;
        if (method.equals("register")) {
            url = url + "account/signup" + "?username=" + registerData.getString("u") + "&password="
                    + registerData.getString("p");
        } else if (method.startsWith("upgrade")) {
            url = url + method;
        } else {
            url = url + "sync/" + method;
        }
        HttpPost httpPost = new HttpPost(url);
        HttpEntity entity = new ProgressByteEntity(tmpFileBuffer);

        // body
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-type", "multipart/form-data; boundary=" + BOUNDARY);

        // HttpParams
        HttpParams params = new BasicHttpParams();
        params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
        params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
        params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
        params.setParameter(CoreProtocolPNames.USER_AGENT, "AnkiDroid-" + AnkiDroidApp.getPkgVersionName());
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpConnectionParams.setSoTimeout(params, Connection.CONN_TIMEOUT);

        // Registry
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry);
        if (cancelCallback != null) {
            cancelCallback.setConnectionManager(cm);
        }

        try {
            HttpClient httpClient = new DefaultHttpClient(cm, params);
            return httpClient.execute(httpPost);
        } catch (SSLException e) {
            Log.e(AnkiDroidApp.TAG, "SSLException while building HttpClient", e);
            return null;
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        Log.e(AnkiDroidApp.TAG, "BasicHttpSyncer.sync: IOException", e);
        return null;
    } catch (JSONException e) {
        throw new RuntimeException(e);
    } finally {
        if (tmpFileBuffer != null && tmpFileBuffer.exists()) {
            tmpFileBuffer.delete();
        }
    }
}

From source file:jessmchung.groupon.parsers.RedemptionLocationParser.java

@Override
public RedemptionLocation parse(JSONObject json) throws JSONException {
    RedemptionLocation obj = new RedemptionLocation();
    if (json.has("streetAddress1"))
        obj.setStreetAddress1(json.getString("streetAddress1"));
    if (json.has("streetAddress2"))
        obj.setStreetAddress2(json.getString("streetAddress2"));
    if (json.has("state"))
        obj.setState(json.getString("state"));
    if (json.has("city"))
        obj.setCity(json.getString("city"));
    if (json.has("lat"))
        obj.setLat(json.getDouble("lat"));
    if (json.has("lng"))
        obj.setLng(json.getDouble("lng"));
    if (json.has("postalCode"))
        obj.setPostalCode(json.getString("postalCode"));
    if (json.has("name"))
        obj.setName(json.getString("name"));

    return obj;/*from ww  w .j  a  v  a  2 s. c om*/
}

From source file:org.stockchart.series.LinearSeries.java

public void fromJSONObject(JSONObject j) throws JSONException {
    super.fromJSONObject(j);
    fPointSizeInPercents = (float) j.getDouble("pointSize");
    fPointStyle = PointStyle.valueOf(j.getString("pointStyle"));
    fPointsVisible = j.getBoolean("pointsVisible");
    fPointAppearance.fromJSONObject(j.getJSONObject("pointAppearance"));
}

From source file:org.eclipse.flux.client.SingleResponseHandler.java

/**
 * Should inspect the message to determine if it is an 'error'
 * response and throw an exception in that case. Do nothing otherwise.
 *//*from w  w  w  .  ja v  a 2  s . c  o  m*/
protected void errorParse(String messageType, JSONObject message) throws Exception {
    if (message.has(ERROR)) {
        if (message.has("errorDetails")) {
            System.err.println(message.get("errorDetails"));
        }
        throw new Exception(message.getString(ERROR));
    }
}

From source file:org.b3log.solo.processor.util.Filler.java

/**
 * Fills archive dates./*from w w w  .  j av a  2s .  c om*/
 *
 * @param dataModel data model
 * @param preference the specified preference
 * @throws ServiceException service exception
 */
public void fillArchiveDates(final Map<String, Object> dataModel, final JSONObject preference)
        throws ServiceException {
    Stopwatchs.start("Fill Archive Dates");

    try {
        LOGGER.finer("Filling archive dates....");
        final List<JSONObject> archiveDates = archiveDateRepository.getArchiveDates();

        final String localeString = preference.getString(Preference.LOCALE_STRING);
        final String language = Locales.getLanguage(localeString);

        for (final JSONObject archiveDate : archiveDates) {
            final long time = archiveDate.getLong(ArchiveDate.ARCHIVE_TIME);
            final String dateString = ArchiveDate.DATE_FORMAT.format(time);
            final String[] dateStrings = dateString.split("/");
            final String year = dateStrings[0];
            final String month = dateStrings[1];
            archiveDate.put(ArchiveDate.ARCHIVE_DATE_YEAR, year);

            archiveDate.put(ArchiveDate.ARCHIVE_DATE_MONTH, month);
            if ("en".equals(language)) {
                final String monthName = Dates.EN_MONTHS.get(month);
                archiveDate.put(Common.MONTH_NAME, monthName);
            }
        }

        dataModel.put(ArchiveDate.ARCHIVE_DATES, archiveDates);
    } catch (final JSONException e) {
        LOGGER.log(Level.SEVERE, "Fills archive dates failed", e);
        throw new ServiceException(e);
    } catch (final RepositoryException e) {
        LOGGER.log(Level.SEVERE, "Fills archive dates failed", e);
        throw new ServiceException(e);
    } finally {
        Stopwatchs.end();
    }
}