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:com.ironsmile.cordova.mediaevents.MediaEventListener.java

/**
 * Creates a JSONObject with the current event type
 *
 * @param eventMediaIntent the current audio event
 * @return a JSONObject containing the type of the event
 *///from   w  w w . ja v a2 s . c  o m
private JSONObject constructMediaEvent(Intent eventMediaIntent) {
    JSONObject obj = new JSONObject();
    try {
        obj.put("type", "becomingnoisy");
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }
    return obj;
}

From source file:com.ironsmile.cordova.mediaevents.MediaEventListener.java

/**
 * Updates the JavaScript side with new audio focus event
 *
 * @param focusEvent the received event//ww w  .j  a va  2  s  .c  o  m
 * @return
 */
private void sendFocusEvent(int focusEvent) {
    JSONObject obj = new JSONObject();
    try {
        switch (focusEvent) {
        case AudioManager.AUDIOFOCUS_GAIN:
        case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT:
        case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE:
        case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK:
            obj.put("type", "audiofocusgain");
            break;
        case AudioManager.AUDIOFOCUS_LOSS:
            obj.put("type", "audiofocusloss");
            break;
        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
            obj.put("type", "audiofocuslosstransient");
            break;
        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
            obj.put("type", "audiofocuslosstransientcanduck");
            break;
        }

    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }
    sendUpdate(obj, true);
}

From source file:de.langerhans.wallet.ui.send.RequestWalletBalanceTask.java

public void requestWalletBalance(final Address address) {
    backgroundHandler.post(new Runnable() {
        @Override// www . j a  v a  2  s .  com
        public void run() {
            // Use either dogechain or chain.so
            List<String> urls = new ArrayList<String>(2);
            urls.add(Constants.DOGECHAIN_API_URL);
            urls.add(Constants.CHAINSO_API_URL);
            Collections.shuffle(urls, new Random(System.nanoTime()));

            final StringBuilder url = new StringBuilder(urls.get(0));
            url.append(address.toString());

            log.debug("trying to request wallet balance from {}", url);

            HttpURLConnection connection = null;
            Reader reader = null;

            try {
                connection = (HttpURLConnection) new URL(url.toString()).openConnection();

                connection.setInstanceFollowRedirects(false);
                connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
                connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
                connection.setUseCaches(false);
                connection.setDoInput(true);
                connection.setDoOutput(false);

                connection.setRequestMethod("GET");
                if (userAgent != null)
                    connection.addRequestProperty("User-Agent", userAgent);
                connection.connect();

                final int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024),
                            Charsets.UTF_8);
                    final StringBuilder content = new StringBuilder();
                    Io.copy(reader, content);

                    final JSONObject json = new JSONObject(content.toString());

                    final int success = json.getInt("success");
                    if (success != 1)
                        throw new IOException("api status " + success + " when fetching unspent outputs");

                    final JSONArray jsonOutputs = json.getJSONArray("unspent_outputs");

                    final Map<Sha256Hash, Transaction> transactions = new HashMap<Sha256Hash, Transaction>(
                            jsonOutputs.length());

                    for (int i = 0; i < jsonOutputs.length(); i++) {
                        final JSONObject jsonOutput = jsonOutputs.getJSONObject(i);

                        final Sha256Hash uxtoHash = new Sha256Hash(jsonOutput.getString("tx_hash"));
                        final int uxtoIndex = jsonOutput.getInt("tx_output_n");
                        final byte[] uxtoScriptBytes = HEX.decode(jsonOutput.getString("script"));
                        final Coin uxtoValue = Coin.valueOf(Long.parseLong(jsonOutput.getString("value")));

                        Transaction tx = transactions.get(uxtoHash);
                        if (tx == null) {
                            tx = new FakeTransaction(Constants.NETWORK_PARAMETERS, uxtoHash);
                            tx.getConfidence().setConfidenceType(ConfidenceType.BUILDING);
                            transactions.put(uxtoHash, tx);
                        }

                        if (tx.getOutputs().size() > uxtoIndex)
                            throw new IllegalStateException("cannot reach index " + uxtoIndex
                                    + ", tx already has " + tx.getOutputs().size() + " outputs");

                        // fill with dummies
                        while (tx.getOutputs().size() < uxtoIndex)
                            tx.addOutput(new TransactionOutput(Constants.NETWORK_PARAMETERS, tx,
                                    Coin.NEGATIVE_SATOSHI, new byte[] {}));

                        // add the real output
                        final TransactionOutput output = new TransactionOutput(Constants.NETWORK_PARAMETERS, tx,
                                uxtoValue, uxtoScriptBytes);
                        tx.addOutput(output);
                    }

                    log.info("fetched unspent outputs from {}", url);

                    onResult(transactions.values());
                } else {
                    final String responseMessage = connection.getResponseMessage();

                    log.info("got http error '{}: {}' from {}", responseCode, responseMessage, url);

                    onFail(R.string.error_http, responseCode, responseMessage);
                }
            } catch (final JSONException x) {
                log.info("problem parsing json from " + url, x);

                onFail(R.string.error_parse, x.getMessage());
            } catch (final IOException x) {
                log.info("problem querying unspent outputs from " + url, x);

                onFail(R.string.error_io, x.getMessage());
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException x) {
                        // swallow
                    }
                }

                if (connection != null)
                    connection.disconnect();
            }
        }
    });
}

From source file:org.apache.nifi.processors.ConvertJSONtoCSV.ConvertJSONtoCSV.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final String includeHeaders = context.getProperty(INCLUDE_HEADERS).getValue();

    FlowFile flowFile = session.get();/*from   ww w  .ja  v  a 2  s.  co m*/
    if (flowFile == null) {
        return;
    }

    try {
        flowFile = session.write(flowFile, new StreamCallback() {
            @Override
            public void process(final InputStream inputStream, final OutputStream outputStream)
                    throws IOException {
                List<Map<String, String>> flatJson;
                try {
                    flatJson = JSONParser.parseJSON(IOUtils.toString(inputStream, "UTF-8"), getRemoveKeySet());
                    if (flatJson == null) {
                        throw new IOException(
                                "Unable to parse JSON file. Please check the file contains valid JSON structure");
                    }
                } catch (JSONException ex) {
                    throw new JSONException("Unable to parse as JSON appears to be malformed: " + ex);
                }
                outputStream.write(CSVGenerator.generateCSV(flatJson, delimiter, emptyFields, includeHeaders)
                        .toString().getBytes());
            }
        });

        session.transfer(flowFile, RELATIONSHIP_SUCCESS);
    } catch (ProcessException | JSONException ex) {
        getLogger().error("Error converting FlowFile to CSV due to {}", new Object[] { ex.getMessage() }, ex);
        session.transfer(flowFile, RELATIONSHIP_FAILURE);
    }
}

From source file:com.phonegap.plugins.statusBarNotification.StatusBarNotification.java

/**
 *    Executes the request and returns PluginResult
 *
 *    @param action      Action to execute
 *    @param data         JSONArray of arguments to the plugin
 *  @param callbackContext   The callback context used when calling back into JavaScript.
 *
 *  @return            A PluginRequest object with a status
 * *//*from  www.  ja va  2 s  .  co m*/
@Override
public boolean execute(String action, JSONArray data, CallbackContext callbackContext) {
    boolean actionValid = true;
    if (NOTIFY.equals(action)) {
        try {
            String tag = data.getString(0);
            String title = data.getString(1);
            String body = data.getString(2);
            String flag = data.getString(3);
            Log.d("NotificationPlugin", "Notification: " + tag + ", " + title + ", " + body);
            int notificationFlag = getFlagValue(flag);
            showNotification(tag, title, body, notificationFlag);
        } catch (JSONException jsonEx) {
            Log.d("NotificationPlugin", "Got JSON Exception " + jsonEx.getMessage());
            actionValid = false;
        }
    } else if (CLEAR.equals(action)) {
        try {
            String tag = data.getString(0);
            Log.d("NotificationPlugin", "Notification cancel: " + tag);
            clearNotification(tag);
        } catch (JSONException jsonEx) {
            Log.d("NotificationPlugin", "Got JSON Exception " + jsonEx.getMessage());
            actionValid = false;
        }
    } else {
        actionValid = false;
        Log.d("NotificationPlugin", "Invalid action : " + action + " passed");
    }
    return actionValid;
}

From source file:com.polyvi.xface.extension.advancedfiletransfer.FileDownloader.java

@Override
public void onSuccess() {
    mFileTransferRecorder.deleteDownloadInfo(mUrl);
    mFileTransferManager.removeFileTranferTask(mUrl);
    setState(INIT);//from  w  ww  . j av  a2 s.  c  o m
    JSONObject jsonObj = new JSONObject();
    try {
        File file = new File(mLocalFilePath);
        // create FileEntry object
        FileUtils filePlugin = (FileUtils) mWebView.pluginManager.getPlugin("File");
        if (filePlugin != null) {
            jsonObj = filePlugin.getEntryForFile(file);
            jsonObj.put("start", 0);
            jsonObj.put("end", file.length());
            jsonObj.put("status", "finished");
        }
    } catch (JSONException e) {
        XLog.e(CLASS_NAME, e.getMessage());
    }
    mCallbackCtx.success(jsonObj);
}

From source file:com.polyvi.xface.extension.advancedfiletransfer.FileDownloader.java

@Override
public void onError(int errorCode) {
    setState(INIT);/*  w ww  . j  a v a2 s .c om*/
    String fullPath = null;
    fullPath = mLocalFilePath;
    JSONObject error = new JSONObject();
    try {
        error.put("code", errorCode);
        error.put("source", mUrl);
        error.put("target", fullPath);
    } catch (JSONException e) {
        XLog.e(CLASS_NAME, e.getMessage());
    }
    mCallbackCtx.error(error);
}

From source file:com.polyvi.xface.extension.advancedfiletransfer.FileDownloader.java

@Override
public void onProgressUpdated(int completeSize, long totalSize) {
    mDownloadInfo.setCompleteSize(completeSize);
    JSONObject jsonObj = new JSONObject();
    try {//from   www  .j  ava 2s.  com
        File file = new File(mLocalFilePath);
        FileUtils filePlugin = (FileUtils) mWebView.pluginManager.getPlugin("File");
        if (filePlugin != null) {
            jsonObj = filePlugin.getEntryForFile(file);
            jsonObj.put("loaded", completeSize);
            jsonObj.put("total", totalSize);
            jsonObj.put("status", "unfinished");
        }
    } catch (JSONException e) {
        XLog.e(CLASS_NAME, e.getMessage());
    }
    PluginResult result = new PluginResult(PluginResult.Status.OK, jsonObj);
    result.setKeepCallback(true);
    mCallbackCtx.sendPluginResult(result);
}

From source file:com.strato.hidrive.api.bll.free.CheckEmailGateway.java

@Override
protected Request prepareRequest() {
    List<BaseParam<?>> params = new ArrayList<BaseParam<?>>();
    JSONObject json = new JSONObject();
    try {//w w  w  .jav  a  2s .c  o m
        json.put("email", this.emailForCheck);
        json.put("country", this.country);
        json.put("language", this.language);
        json.put("product_name", "HiDriveFree");
        json.put("product", "freemium");
    } catch (JSONException e) {
        if (e != null && e.getMessage() != null) {
            Log.e(getClass().getSimpleName(), e.getMessage());
        }
    }
    params.add(new Param("postdata", json.toString()));
    return new PostRequest("check_email", params);
}

From source file:com.github.gorbin.asne.linkedin.LinkedInSocialNetwork.java

private String checkInputStream(HttpURLConnection connection) {
    String code = null, errorMessage = null;
    InputStream inputStream = connection.getErrorStream();
    String response = streamToString(inputStream);
    try {//  w  ww. j  a  va  2  s. c  om
        JSONObject jsonResponse = (JSONObject) new JSONTokener(response).nextValue();
        if (jsonResponse.has("status")) {
            code = jsonResponse.getString("status");
        }
        if (jsonResponse.has("message")) {
            errorMessage = jsonResponse.getString("message");
        }
        return "ERROR CODE: " + code + " ERROR MESSAGE: " + errorMessage;
    } catch (JSONException e) {
        return e.getMessage();
    }
}