Example usage for org.json JSONException getMessage

List of usage examples for org.json JSONException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:fi.helsinki.cs.iot.hub.IotHubHTTPDTest.java

@Test
public void testEnablerAPI() {
    String res = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("GET",
            "http://127.0.0.1:" + port + "/enablers/", null);
    assertEquals("[]", res.trim());

    //Now I want to create a javascript plugin to attach to my enabler
    String pluginName = "MyPlugin";
    //now I want to had a javascript plugin
    File pluginFile = makePluginFile(pluginName);
    JSONObject jsonObject = makeJsonObjectForPlugin(pluginName, null, Type.JAVASCRIPT, pluginFile, false);
    assertNotNull(jsonObject);//from www .  j  av a2  s  .co m
    String myPluginString = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("POST",
            "http://127.0.0.1:" + port + "/plugins/", jsonObject.toString());
    JSONObject jPlugin = null;
    try {
        jPlugin = new JSONObject(myPluginString);
        long pluginId = jPlugin.getLong("id");
        String name = "MyEnabler";
        String metadata = "A freshly created enabler";
        JSONObject jEnabler = new JSONObject();
        jEnabler.put("plugin", pluginId);
        jEnabler.put("name", "fakeName");
        jEnabler.put("metadata", metadata);

        // I should get an enable with no features as it is not configured
        res = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("POST",
                "http://127.0.0.1:" + port + "/enablers/", jEnabler.toString());
        JSONObject jexpectedEnabler = new JSONObject();
        jexpectedEnabler.put("id", 1);
        jexpectedEnabler.put("name", "fakeName");
        jexpectedEnabler.put("metadata", metadata);
        jexpectedEnabler.put("plugin", jPlugin);
        JSONArray array = new JSONArray();
        jexpectedEnabler.put("features", array);
        assertEquals(jexpectedEnabler.toString(), res.trim());

        String featureName = "MyFeature";
        JSONObject config = new JSONObject();
        config.put("name", featureName);
        config.put("isSupported", true);
        config.put("isAvailable", true);
        config.put("isReadable", true);
        config.put("isWritable", true);
        config.put("getNumberOfFeatures", 1);
        config.put("getFeatureDescription", featureName);
        config.put("value", "Uksomatonta");
        JSONObject data = new JSONObject();
        data.put("configuration", config);

        res = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("PUT",
                "http://127.0.0.1:" + port + "/enablers/fakeName", data.toString());
        JSONObject expectedFeature = new JSONObject();
        expectedFeature.put("id", 1);
        expectedFeature.put("isSupported", true);
        expectedFeature.put("isAtomicFeed", false);
        expectedFeature.put("name", featureName);
        expectedFeature.put("isWritable", true);
        expectedFeature.put("isReadable", true);
        expectedFeature.put("type", "whatever");
        expectedFeature.put("isAvailable", true);
        array.put(expectedFeature);
        jexpectedEnabler.put("features", array);
        jexpectedEnabler.put("config", config.toString());
        assertEquals(jexpectedEnabler.toString().length(), res.trim().length());

        //Now just change quicky the configuration
        config.put("value", "Hard to believe");
        data.put("configuration", config);
        data.put("name", name);
        res = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("PUT",
                "http://127.0.0.1:" + port + "/enablers/fakeName", data.toString());
        jexpectedEnabler.put("name", name);
        jexpectedEnabler.put("config", config.toString());
        assertEquals(jexpectedEnabler.toString().length(), res.trim().length());

        //Now I want to change the feature as an atomic feed
        data = new JSONObject();
        data.put("enableAsAtomicFeed", true);
        res = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("PUT",
                "http://127.0.0.1:" + port + "/enablers/" + name + "/" + featureName, data.toString());
        expectedFeature.put("id", 2);
        expectedFeature.put("isAtomicFeed", true);
        assertEquals(expectedFeature.toString(), res.trim());

        //Now I will check for feeds
        res = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("GET",
                "http://127.0.0.1:" + port + "/feeds/", null);
        JSONArray feedArray = new JSONArray(res);
        assertEquals(1, feedArray.length());
        JSONObject feed1 = feedArray.getJSONObject(0);
        String feedName = feed1.getString("name");
        res = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("GET",
                "http://127.0.0.1:" + port + "/feeds/" + feedName, null);
        assertEquals("\"Hard to believe\"", res.trim());

        JSONObject toPostToFeed = new JSONObject("{\"test\": \"Unbelievable\"}");
        res = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("POST",
                "http://127.0.0.1:" + port + "/feeds/" + feedName, toPostToFeed.toString());
        assertEquals(toPostToFeed.toString(), res.trim());

        res = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("GET",
                "http://127.0.0.1:" + port + "/feeds/" + feedName, null);
        assertEquals(toPostToFeed.toString(), res.trim());

        data.put("enableAsAtomicFeed", false);
        res = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("PUT",
                "http://127.0.0.1:" + port + "/enablers/" + name + "/" + featureName, data.toString());
        expectedFeature.put("isAtomicFeed", false);
        assertEquals(expectedFeature.toString(), res.trim());

        res = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("GET",
                "http://127.0.0.1:" + port + "/feeds/" + feedName, null);
        JSONObject jerror = new JSONObject(res);
        assertEquals("Error", jerror.getString("status"));

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        fail(e.getMessage());
    }
}

From source file:org.mapfish.print.map.readers.WMSCMapReader.java

public void render(Transformer transformer, ParallelMapTileLoader parallelMapTileLoader, String srs,
        boolean first) {
    PJsonObject customParams = params.optJSONObject("customParams");

    // store the rotation to not change for other layers
    double oldAngle = transformer.getRotation();

    // native WMS rotation - only works in singleTile mode
    if (customParams != null && customParams.optString("angle") != null) { // For GeoServer
        transformer.setRotation(0);// w  w  w  . j  a  va 2 s.co m
    }
    if (params.optBool("useNativeAngle", false)) {
        String angle = String.valueOf(-Math.toDegrees(transformer.getRotation()));
        try {
            if (customParams != null) {
                customParams.getInternalObj().put("angle", angle); // For GeoServer
                customParams.getInternalObj().put("map_angle", angle); // For MapServer
            } else {
                Map customMap = new HashMap();
                customMap.put("angle", angle); // For GeoServer
                customMap.put("map_angle", angle); // For MapServer
                params.getInternalObj().put("customParams", customMap);
            }
            transformer.setRotation(0);
        } catch (org.json.JSONException e) {
            LOGGER.error("Unable to set angle: " + e.getClass().getName() + " - " + e.getMessage());
        }
    }
    super.render(transformer, parallelMapTileLoader, srs, first);
    // restore the rotation for other layers
    transformer.setRotation(oldAngle);
}

From source file:dk.iface.cordova.plugin.googlenavigate.GoogleNavigate.java

private boolean navigate(JSONArray args, CallbackContext callbackContext) {
    boolean result;

    try {//from  w w w. j a  v a 2 s.co m
        String query = args.getString(0);

        if (query != null && query.length() > 0) {
            Log.d(LOG_TAG, "Navigating to " + query);
            Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("google.navigation:q=" + query));
            this.cordova.getActivity().startActivity(i);
            callbackContext.success();
        } else {
            Log.d(LOG_TAG, "Expected non-empty string arguments for query.");
            callbackContext.error("Expected non-empty string arguments for query.");
        }
        result = true;
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Exception occurred: ".concat(e.getMessage()));
        result = false;
    }
    return result;
}

From source file:com.linkedin.platform.listeners.ApiResponse.java

public static synchronized ApiResponse buildApiResponse(JSONObject apiResponseAsJson) {
    try {/*from w w w. j a v a2s  .c  om*/
        int statusCode = apiResponseAsJson.optInt(STATUS_CODE);
        String locationHeader = apiResponseAsJson.optString(LOCATION);
        String responseData = apiResponseAsJson.getString(DATA);
        return new ApiResponse(statusCode, responseData, locationHeader);
    } catch (JSONException e) {
        Log.d(TAG, e.getMessage());
    }
    return null;
}

From source file:com.linkedin.platform.listeners.ApiResponse.java

public JSONObject getResponseDataAsJson() {
    if (responseData == null || "".equals(responseData)) {
        return null;
    }/* ww w  .  j  ava2s  . c  o m*/
    try {
        return new JSONObject(responseData);
    } catch (JSONException e) {
        Log.d(TAG, e.getMessage(), e);
    }
    return null;
}

From source file:com.linkedin.platform.listeners.ApiResponse.java

@Override
public String toString() {
    JSONObject apiResponseAsJson = new JSONObject();
    try {/*  ww w . j  a v a2 s  .c o  m*/
        apiResponseAsJson.put(STATUS_CODE, statusCode);
        apiResponseAsJson.put(DATA, responseData);
        apiResponseAsJson.put(LOCATION, locationHeader);
    } catch (JSONException e) {
        Log.d(TAG, e.getMessage());
    }
    return apiResponseAsJson.toString();
}

From source file:org.sc.probro.servlets.RequestStateServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from  ww  w . java2  s  . c o  m

        String format = getOptionalParam(request, "format", String.class);
        if (format == null) {
            format = "html";
        }

        Log.info(String.format("RequestStateServlet: format=%s", format));

        Integer fromIdx = getOptionalParam(request, "from", Integer.class);
        String from = fromIdx != null ? STATES.backward(fromIdx) : null;

        Log.info(String.format("RequestStateServlet: from=%s", String.valueOf(from)));

        if (format.equals("html")) {

            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("text/html");
            PrintWriter writer = response.getWriter();

            writer.println("<table>");

            for (int i = 0; i < STATES.size(); i++) {
                String to = STATES.backward(i);
                if (from == null || MACHINE.isReachable(from, to)) {
                    writer.println(String.format("<tr><td>%d</td><td>%s</td></tr>", i, to));
                }
            }

            writer.println("</table>");

        } else if (format.equals("fieldset")) {

            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("text/html");
            PrintWriter writer = response.getWriter();

            writer.println("<fieldset><legend>New Status</legend>");

            for (int i = 0; i < STATES.size(); i++) {
                String to = STATES.backward(i);
                if (from == null || MACHINE.isReachable(from, to)) {
                    //writer.println(String.format("<tr><td>%d</td><td>%s</td></tr>", i, to));
                    String field = String
                            .format("<input type=\"radio\" name=\"status\" value=\"%d\">%s</input>", i, to);
                    writer.println(field);
                }
            }

            writer.println("</fieldset>");

        } else if (format.equals("json")) {

            Log.info("RequestStateServlet: writing JSON response.");

            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("application/json");

            JSONObject top = new JSONObject();
            JSONArray array = new JSONArray();
            try {

                top.put("from", from);
                top.put("states", array);

                for (int i = 0; i < STATES.size(); i++) {
                    String to = STATES.backward(i);

                    if (from == null || MACHINE.isReachable(from, to)) {
                        array.put(i);
                    }
                }
            } catch (JSONException e) {
                throw new BrokerException(e);
            }

            PrintWriter writer = response.getWriter();
            writer.println(top.toString());

            Log.info(String.format("RequestStateServlet: %s", top.toString()));

        } else {
            throw new BrokerException(HttpServletResponse.SC_BAD_REQUEST, "Unknown 'format' value " + format);
        }

    } catch (BrokerException e) {
        Log.warn(e);
        Log.warn(String.format("RequestStateServlet.doGet() : %s", e.getMessage()));
        handleException(response, e);
    }
}

From source file:io.fluo.webindex.data.util.ArchiveUtil.java

public static Page buildPage(ArchiveRecord archiveRecord) throws IOException, ParseException {
    if (archiveRecord.getHeader().getMimetype().equalsIgnoreCase("application/json")) {
        byte[] rawData = IOUtils.toByteArray(archiveRecord, archiveRecord.available());
        if (rawData.length == 0) {
            return Page.EMPTY;
        }//from www  .  ja va2  s  .c  om
        String jsonString = new String(rawData);
        if (jsonString.isEmpty()) {
            return Page.EMPTY;
        }
        JSONObject json;
        try {
            json = new JSONObject(new String(rawData));
        } catch (JSONException e) {
            throw new ParseException(e.getMessage(), 0);
        }
        String rawPageUrl = archiveRecord.getHeader().getUrl();
        URL pageUrl;
        try {
            pageUrl = DataUrl.from(rawPageUrl);
        } catch (IllegalArgumentException e) {
            return Page.EMPTY;
        } catch (Exception e) {
            log.error("Unexpected exception while parsing raw page URL: " + rawPageUrl, e);
            return Page.EMPTY;
        }
        Page page = new Page(pageUrl.toPageID());
        page.setCrawlDate(archiveRecord.getHeader().getDate());
        try {
            JSONObject responseMeta = json.getJSONObject("Envelope").getJSONObject("Payload-Metadata")
                    .getJSONObject("HTTP-Response-Metadata");

            if (archiveRecord.getHeader().getMimetype().equals("application/json")) {
                try {
                    JSONArray links = responseMeta.getJSONObject("HTML-Metadata").getJSONArray("Links");
                    for (int i = 0; i < links.length(); i++) {
                        JSONObject link = links.getJSONObject(i);
                        if (link.has("path") && link.get("path").equals("A@/href") && link.has("url")) {
                            String anchorText = "";
                            if (link.has("text")) {
                                anchorText = link.getString("text");
                            } else if (link.has("title")) {
                                anchorText = link.getString("title");
                            }
                            String rawLinkUrl = link.getString("url");
                            URL linkUrl;
                            try {
                                linkUrl = DataUrl.from(rawLinkUrl);
                                if (!page.getDomain().equals(linkUrl.getDomain())) {
                                    page.addOutbound(Link.of(linkUrl, anchorText));
                                }
                            } catch (IllegalArgumentException e) {
                                log.debug("Failed to parse link: " + rawLinkUrl);
                            } catch (Exception e) {
                                log.error("Unexpected exception while parsing link URL: " + rawLinkUrl, e);
                            }
                        }
                    }
                } catch (JSONException e) {
                    log.debug("Exception trying retrieve links", e);
                }
            }
            try {
                page.setTitle(
                        responseMeta.getJSONObject("HTML-Metadata").getJSONObject("Head").getString("Title"));
            } catch (JSONException e) {
                log.debug("Failed to retrieve title", e);
            }
            try {
                page.setServer(responseMeta.getJSONObject("Headers").getString("Server"));
            } catch (JSONException e) {
                log.debug("Failed to retrieve server", e);
            }
        } catch (JSONException e) {
            log.debug("Exception trying retrieve responseMeta", e);
        }
        return page;
    }
    return Page.EMPTY;
}

From source file:com.oakesville.mythling.prefs.PlaybackPrefs.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getActivity().getActionBar().setTitle(R.string.title_playback_settings);
    addPreferencesFromResource(R.xml.playback_prefs);

    // none of these prefs trigger cache refresh

    AppSettings appSettings = new AppSettings(getPreferenceScreen().getContext());

    SwitchPreference swPref = (SwitchPreference) getPreferenceScreen()
            .findPreference(AppSettings.FRONTEND_PLAYBACK);
    swPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            doCategoryEnablement(!Boolean.valueOf(newValue.toString()));
            return true;
        }//w w  w. ja va 2 s  . c  om
    });
    doCategoryEnablement(appSettings.isDevicePlayback());

    Preference pref = getPreferenceScreen().findPreference(AppSettings.ALWAYS_PROMPT_FOR_PLAYBACK_OPTIONS);
    pref.setOnPreferenceChangeListener(new PrefChangeListener(false, false) {
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            boolean update = super.onPreferenceChange(preference, newValue);
            if (Boolean.parseBoolean(newValue.toString())) {
                AppSettings settings = new AppSettings(getPreferenceScreen().getContext());
                try {
                    settings.getPlaybackOptions().clearAlwaysDoThisSettings();
                } catch (JSONException ex) {
                    Log.e(TAG, ex.getMessage(), ex);
                    if (settings.isErrorReportingEnabled())
                        new Reporter(ex).send();
                    settings.getPlaybackOptions().clearAll();
                }
            }
            return update;
        }
    });

    pref = getPreferenceScreen().findPreference(AppSettings.SKIP_BACK_INTERVAL);
    pref.setOnPreferenceChangeListener(new PrefChangeListener(true, false, getString(R.string.seconds)));
    pref.setSummary("" + appSettings.getSkipBackInterval() + " " + getString(R.string.seconds));

    pref = getPreferenceScreen().findPreference(AppSettings.SKIP_FORWARD_INTERVAL);
    pref.setOnPreferenceChangeListener(new PrefChangeListener(true, false, getString(R.string.seconds)));
    pref.setSummary("" + appSettings.getSkipForwardInterval() + " " + getString(R.string.seconds));

    pref = getPreferenceScreen().findPreference(AppSettings.JUMP_INTERVAL);
    pref.setOnPreferenceChangeListener(new PrefChangeListener(true, false, getString(R.string.seconds)));
    pref.setSummary("" + appSettings.getJumpInterval() + " " + getString(R.string.seconds));

    pref = getPreferenceScreen().findPreference(AppSettings.AUTO_SKIP);
    pref.setOnPreferenceChangeListener(
            new PrefChangeListener(true, false, R.array.auto_skip_values, R.array.auto_skip_entries) {
                public boolean onPreferenceChange(Preference preference, Object newValue) {
                    super.onPreferenceChange(preference, newValue);
                    if (!AppSettings.AUTO_SKIP_OFF.equals(newValue.toString())) {
                        AppSettings settings = new AppSettings(getPreferenceScreen().getContext());
                        int scTol = settings.getSeekCorrectionTolerance();
                        if (scTol == 0) {
                            settings.setSeekCorrectionTolerance(3);
                            getPreferenceScreen().findPreference(AppSettings.SEEK_CORRECTION_TOLERANCE)
                                    .setSummary("3");
                            ;
                        }
                    }
                    return true;
                }
            });
    pref.setSummary(Localizer.getStringArrayEntry(R.array.auto_skip_values, R.array.auto_skip_entries,
            appSettings.getAutoSkip()));

    pref = getPreferenceScreen().findPreference(AppSettings.SEEK_CORRECTION_TOLERANCE);
    pref.setOnPreferenceChangeListener(new PrefChangeListener(true, false, getString(R.string.seconds)));
    pref.setSummary("" + appSettings.getSeekCorrectionTolerance() + " " + getString(R.string.seconds));

    pref = getPreferenceScreen().findPreference(AppSettings.LIBVLC_PARAMETERS);
    pref.setOnPreferenceChangeListener(new PrefChangeListener(true, false));
    pref.setSummary(appSettings.getLibVlcParameters());

    swPref = (SwitchPreference) getPreferenceScreen().findPreference(AppSettings.INTERNAL_MUSIC_PLAYER);
    swPref.setOnPreferenceChangeListener(new PrefChangeListener(false, false));

    pref = getPreferenceScreen().findPreference(AppSettings.MYTH_FRONTEND_HOST);
    pref.setOnPreferenceChangeListener(new PrefChangeListener(true, false));
    pref.setSummary(appSettings.getFrontendHost());

    pref = getPreferenceScreen().findPreference(AppSettings.MYTH_FRONTEND_SOCKET_PORT);
    pref.setOnPreferenceChangeListener(new PrefChangeListener(true, false));
    pref.setSummary("" + appSettings.getFrontendSocketPort());

    pref = getPreferenceScreen().findPreference(AppSettings.MYTH_FRONTEND_SERVICE_PORT);
    pref.setOnPreferenceChangeListener(new PrefChangeListener(true, false));
    pref.setSummary("" + appSettings.getFrontendServicePort());
}

From source file:com.facebook.android.Places.java

@Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
    if (!Utility.mFacebook.isSessionValid()) {
        Util.showAlert(this, "Warning", "You must first log in.");
    } else {//from  w w  w.j  a  v a  2s. co  m
        try {
            final String message = "Check-in from the " + getString(R.string.app_name);
            final String name = jsonArray.getJSONObject(position).getString("name");
            final String placeID = jsonArray.getJSONObject(position).getString("id");
            new AlertDialog.Builder(this).setTitle(R.string.check_in_title)
                    .setMessage(String.format(getString(R.string.check_in_at), name))
                    .setPositiveButton(R.string.checkin, new DialogInterface.OnClickListener() {
                        /*
                         * Source tag: check_in_tag Check-in user at the
                         * selected location posting to the me/checkins
                         * endpoint. More info here:
                         * https://developers.facebook
                         * .com/docs/reference/api/user/ - checkins
                         */
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Bundle params = new Bundle();
                            params.putString("place", placeID);
                            params.putString("message", message);
                            params.putString("coordinates", location.toString());
                            Utility.mAsyncRunner.request("me/checkins", params, "POST",
                                    new placesCheckInListener(), null);
                        }
                    }).setNegativeButton(R.string.cancel, null).show();
        } catch (JSONException e) {
            showToast("Error: " + e.getMessage());
        }
    }
}