Example usage for org.json JSONException toString

List of usage examples for org.json JSONException toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:com.ofalvai.bpinfo.api.bkkinfo.BkkInfoClient.java

@NonNull
private List<Alert> parseFutureAlerts(JSONObject response) throws JSONException {
    List<Alert> alerts = new ArrayList<>();

    // Future alerts are in two groups: near-future and far-future
    JSONArray soonAlertList = response.getJSONArray("soon");
    for (int i = 0; i < soonAlertList.length(); i++) {
        try {/*from w w w  .  j  a va2s.c  o m*/
            JSONObject alertNode = soonAlertList.getJSONObject(i);
            alerts.add(parseAlert(alertNode));
        } catch (JSONException ex) {
            Crashlytics.log(Log.WARN, TAG, "Alert parse: failed to parse:\n" + ex.toString());
        }
    }

    JSONArray futureAlertList = response.getJSONArray("future");
    for (int i = 0; i < futureAlertList.length(); i++) {
        try {
            JSONObject alertNode = futureAlertList.getJSONObject(i);
            alerts.add(parseAlert(alertNode));
        } catch (JSONException ex) {
            Crashlytics.log(Log.WARN, TAG, "Alert parse: failed to parse:\n" + ex.toString());
        }
    }

    return alerts;
}

From source file:no.ntnu.osnap.social.models.Message.java

/**
 * Gets the sender of this message as a Person.
 *
 * @return the value of the field 'from' as a {@link Person} or {@code null}
 * if no value is associated with such field
 * @see Person//from   w  w  w  .ja va2s  .  c  om
 */
public Person getSenderAsPerson() {
    Person p = null;
    String buf = ((JSONObject) getField("from")).toString();
    try {
        if (mTransl != null) {
            p = new Person(buf, mTransl);
        } else {
            p = new Person(buf);
        }
    } catch (JSONException ex) {
        Log.d(TAG, ex.toString());
    }
    return p;
}

From source file:com.google.enterprise.connector.db.diffing.JsonObjectUtil.java

/**
 * Set a property for JSONObject. If propertyValue is null this does nothing.
 *
 * @param propertyName//from   w  w w  .  j a v  a  2s  . c  o  m
 * @param propertyValue
 */
public void setProperty(String propertyName, String propertyValue) {
    if (propertyValue != null) {
        properties.put(propertyName, ImmutableList.of(Value.getStringValue(propertyValue)));
        try {
            jsonObject.put(propertyName, propertyValue);
        } catch (JSONException e) {
            LOG.warning("Exception for " + propertyName + " with value " + propertyValue + "\n" + e.toString());
        }
    }
}

From source file:com.google.enterprise.connector.db.diffing.JsonObjectUtil.java

/**
 * Adds the last modified date property to the JSON Object.
 *
 * @param propertyName/*from  www. j  av  a2s .co m*/
 * @param propertyValue
 */
public void setLastModifiedDate(String propertyName, Timestamp propertyValue) {
    if (propertyValue != null) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(propertyValue.getTime());
        Value value = Value.getDateValue(cal);
        properties.put(propertyName, ImmutableList.of(value));
        try {
            jsonObject.put(propertyName, value.toString());
        } catch (JSONException e) {
            LOG.warning("Exception for " + propertyName + " with value " + propertyValue + "\n" + e.toString());
        }
    }
}

From source file:com.google.enterprise.connector.db.diffing.JsonObjectUtil.java

/**
 * This method sets the "binary array" property value as the content of
 * JSON Object.//from  w  ww  .j  a v a 2s  .  co  m
 *
 * @param propertyName
 * @param propertyValue
 */
public void setBinaryContent(String propertyName, InputStreamFactory propertyValue) {
    if (propertyValue == null) {
        return;
    }
    properties.put(propertyName, ImmutableList.of(Value.getBinaryValue(propertyValue)));
    try {
        jsonObject.put(propertyName, propertyValue);
    } catch (JSONException e) {
        LOG.warning("Exception for " + propertyName + " with value " + propertyValue + "\n" + e.toString());
    }
}

From source file:dlauncher.modpacks.download.DlauncherModPackListing.java

@Override
public Collection<? extends UnresolvedModPack> readModPacksFromResource(byte[] resourceBytes)
        throws IOException {
    try {/*from  w w w .j  a  v a  2 s .  c om*/
        JSONObject json = new JSONObject(new String(resourceBytes, Charset.forName("UTF-8")));
        List<UnresolvedModPack> mods = new ArrayList<>();
        JSONObject list = json.getJSONObject("ModPacks");
        for (String key : list.keySet()) {
            mods.add(new SimpleModPack(list.getJSONObject(key), key));
        }
        return mods;
    } catch (JSONException jsonException) {
        throw new IOException("Problem while reading json: " + jsonException.toString(), jsonException);
    } catch (EmptyStackException exception) {
        throw new IOException("No valid modpack versions found!", exception);
    }
}

From source file:org.transdroid.daemon.Transmission.TransmissionAdapter.java

@Override
public DaemonTaskResult executeTask(Log log, DaemonTask task) {

    try {/*w  w w .  j  a  v  a  2  s.  c o  m*/

        // Get the server version
        if (rpcVersion <= -1) {
            // Get server session statistics
            JSONObject response = makeRequest(log, buildRequestObject("session-get", new JSONObject()));
            rpcVersion = response.getJSONObject("arguments").getInt("rpc-version");
        }

        JSONObject request = new JSONObject();
        switch (task.getMethod()) {
        case Retrieve:

            // Request all torrents from server
            JSONArray fields = new JSONArray();
            final String[] fieldsArray = new String[] { RPC_ID, RPC_NAME, RPC_ERROR, RPC_ERRORSTRING,
                    RPC_STATUS, RPC_DOWNLOADDIR, RPC_RATEDOWNLOAD, RPC_RATEUPLOAD, RPC_PEERSGETTING,
                    RPC_PEERSSENDING, RPC_PEERSCONNECTED, RPC_ETA, RPC_DOWNLOADSIZE1, RPC_DOWNLOADSIZE2,
                    RPC_UPLOADEDEVER, RPC_TOTALSIZE, RPC_DATEADDED, RPC_DATEDONE, RPC_AVAILABLE, RPC_COMMENT };
            for (String field : fieldsArray) {
                fields.put(field);
            }
            request.put("fields", fields);

            JSONObject result = makeRequest(log, buildRequestObject("torrent-get", request));
            return new RetrieveTaskSuccessResult((RetrieveTask) task,
                    parseJsonRetrieveTorrents(result.getJSONObject("arguments")), null);

        case GetStats:

            // Request the current server statistics
            JSONObject stats = makeRequest(log, buildRequestObject("session-get", new JSONObject()))
                    .getJSONObject("arguments");
            return new GetStatsTaskSuccessResult((GetStatsTask) task, stats.getBoolean("alt-speed-enabled"),
                    rpcVersion >= 12 ? stats.getLong("download-dir-free-space") : -1);

        case GetTorrentDetails:

            // Request fine details of a specific torrent
            JSONArray dfields = new JSONArray();
            dfields.put("trackers");
            dfields.put("trackerStats");

            JSONObject buildDGet = buildTorrentRequestObject(task.getTargetTorrent().getUniqueID(), null,
                    false);
            buildDGet.put("fields", dfields);
            JSONObject getDResult = makeRequest(log, buildRequestObject("torrent-get", buildDGet));
            return new GetTorrentDetailsTaskSuccessResult((GetTorrentDetailsTask) task,
                    parseJsonTorrentDetails(getDResult.getJSONObject("arguments")));

        case GetFileList:

            // Request all details for a specific torrent
            JSONArray ffields = new JSONArray();
            ffields.put("files");
            ffields.put("fileStats");

            JSONObject buildGet = buildTorrentRequestObject(task.getTargetTorrent().getUniqueID(), null, false);
            buildGet.put("fields", ffields);
            JSONObject getResult = makeRequest(log, buildRequestObject("torrent-get", buildGet));
            return new GetFileListTaskSuccessResult((GetFileListTask) task,
                    parseJsonFileList(getResult.getJSONObject("arguments"), task.getTargetTorrent()));

        case AddByFile:

            // Add a torrent to the server by sending the contents of a local .torrent file
            String file = ((AddByFileTask) task).getFile();

            // Encode the .torrent file's data
            InputStream in = new Base64.InputStream(new FileInputStream(new File(URI.create(file))),
                    Base64.ENCODE);
            StringWriter writer = new StringWriter();
            int c;
            while ((c = in.read()) != -1) {
                writer.write(c);
            }
            in.close();

            // Request to add a torrent by Base64-encoded meta data
            request.put("metainfo", writer.toString());

            makeRequest(log, buildRequestObject("torrent-add", request));
            return new DaemonTaskSuccessResult(task);

        case AddByUrl:

            // Request to add a torrent by URL
            String url = ((AddByUrlTask) task).getUrl();
            request.put("filename", url);

            makeRequest(log, buildRequestObject("torrent-add", request));
            return new DaemonTaskSuccessResult(task);

        case AddByMagnetUrl:

            // Request to add a magnet link by URL
            String magnet = ((AddByMagnetUrlTask) task).getUrl();
            request.put("filename", magnet);

            makeRequest(log, buildRequestObject("torrent-add", request));
            return new DaemonTaskSuccessResult(task);

        case Remove:

            // Remove a torrent
            RemoveTask removeTask = (RemoveTask) task;
            makeRequest(log,
                    buildRequestObject("torrent-remove",
                            buildTorrentRequestObject(removeTask.getTargetTorrent().getUniqueID(),
                                    "delete-local-data", removeTask.includingData())));
            return new DaemonTaskSuccessResult(task);

        case Pause:

            // Pause a torrent
            PauseTask pauseTask = (PauseTask) task;
            makeRequest(log, buildRequestObject("torrent-stop",
                    buildTorrentRequestObject(pauseTask.getTargetTorrent().getUniqueID(), null, false)));
            return new DaemonTaskSuccessResult(task);

        case PauseAll:

            // Resume all torrents
            makeRequest(log,
                    buildRequestObject("torrent-stop", buildTorrentRequestObject(FOR_ALL, null, false)));
            return new DaemonTaskSuccessResult(task);

        case Resume:

            // Resume a torrent
            ResumeTask resumeTask = (ResumeTask) task;
            makeRequest(log, buildRequestObject("torrent-start",
                    buildTorrentRequestObject(resumeTask.getTargetTorrent().getUniqueID(), null, false)));
            return new DaemonTaskSuccessResult(task);

        case ResumeAll:

            // Resume all torrents
            makeRequest(log,
                    buildRequestObject("torrent-start", buildTorrentRequestObject(FOR_ALL, null, false)));
            return new DaemonTaskSuccessResult(task);

        case SetDownloadLocation:

            // Change the download location
            SetDownloadLocationTask sdlTask = (SetDownloadLocationTask) task;
            // Build request
            JSONObject sdlrequest = new JSONObject();
            JSONArray sdlids = new JSONArray();
            sdlids.put(Long.parseLong(task.getTargetTorrent().getUniqueID()));
            sdlrequest.put("ids", sdlids);
            sdlrequest.put("location", sdlTask.getNewLocation());
            sdlrequest.put("move", true);
            makeRequest(log, buildRequestObject("torrent-set-location", sdlrequest));
            return new DaemonTaskSuccessResult(task);

        case SetFilePriorities:

            // Set priorities of the files of some torrent
            SetFilePriorityTask prioTask = (SetFilePriorityTask) task;

            // Build request
            JSONObject prequest = new JSONObject();
            JSONArray ids = new JSONArray();
            ids.put(Long.parseLong(task.getTargetTorrent().getUniqueID()));
            prequest.put("ids", ids);
            JSONArray fileids = new JSONArray();
            for (TorrentFile forfile : prioTask.getForFiles()) {
                fileids.put(Integer.parseInt(forfile.getKey())); // The keys are the indices of the files, so always numeric
            }
            switch (prioTask.getNewPriority()) {
            case Off:
                prequest.put("files-unwanted", fileids);
                break;
            case Low:
                prequest.put("files-wanted", fileids);
                prequest.put("priority-low", fileids);
                break;
            case Normal:
                prequest.put("files-wanted", fileids);
                prequest.put("priority-normal", fileids);
                break;
            case High:
                prequest.put("files-wanted", fileids);
                prequest.put("priority-high", fileids);
                break;
            }

            makeRequest(log, buildRequestObject("torrent-set", prequest));
            return new DaemonTaskSuccessResult(task);

        case SetTransferRates:

            // Request to set the maximum transfer rates
            SetTransferRatesTask ratesTask = (SetTransferRatesTask) task;
            if (ratesTask.getUploadRate() == null) {
                request.put("speed-limit-up-enabled", false);
            } else {
                request.put("speed-limit-up-enabled", true);
                request.put("speed-limit-up", ratesTask.getUploadRate().intValue());
            }
            if (ratesTask.getDownloadRate() == null) {
                request.put("speed-limit-down-enabled", false);
            } else {
                request.put("speed-limit-down-enabled", true);
                request.put("speed-limit-down", ratesTask.getDownloadRate().intValue());
            }

            makeRequest(log, buildRequestObject("session-set", request));
            return new DaemonTaskSuccessResult(task);

        case SetAlternativeMode:

            // Request to set the alternative speed mode (Tutle Mode)
            SetAlternativeModeTask altModeTask = (SetAlternativeModeTask) task;
            request.put("alt-speed-enabled", altModeTask.isAlternativeModeEnabled());
            makeRequest(log, buildRequestObject("session-set", request));
            return new DaemonTaskSuccessResult(task);

        case ForceRecheck:

            // Verify torrent data integrity
            ForceRecheckTask verifyTask = (ForceRecheckTask) task;
            makeRequest(log, buildRequestObject("torrent-verify",
                    buildTorrentRequestObject(verifyTask.getTargetTorrent().getUniqueID(), null, false)));
            return new DaemonTaskSuccessResult(task);

        default:
            return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.MethodUnsupported,
                    task.getMethod() + " is not supported by " + getType()));
        }
    } catch (JSONException e) {
        return new DaemonTaskFailureResult(task,
                new DaemonException(ExceptionType.ParsingFailed, e.toString()));
    } catch (DaemonException e) {
        return new DaemonTaskFailureResult(task, e);
    } catch (FileNotFoundException e) {
        return new DaemonTaskFailureResult(task,
                new DaemonException(ExceptionType.FileAccessError, e.toString()));
    } catch (IOException e) {
        return new DaemonTaskFailureResult(task,
                new DaemonException(ExceptionType.FileAccessError, e.toString()));
    }
}

From source file:org.prorefactor.refactor.FileTarget.java

@Override
public String toString() {
    try {/*from   w w  w.  jav  a 2 s.c o  m*/
        return new JSONObject().put("file", filename).put("line", line).put("col", column).toString();
    } catch (JSONException e) {
        return e.toString();
    }
}

From source file:edu.utexas.cs.bevomaps.DataLayer.java

/**
 * Helper method to parse the JSON and insert into HashMaps
 *
 * @param buildingJSON subclass of ParseObject, stores building data in JSON format
 * @return This will return the HashMap of HashMaps or null if there is a problem
 *///www .j  a  va  2 s  . co  m
private static HashMap<String, HashMap<String, String>> extractImageMap(BuildingJSON buildingJSON) {

    HashMap<String, HashMap<String, String>> imageMaps = new HashMap<>();
    JSONObject json = buildingJSON.getBuildingJSON();
    Iterator<String> iter = json.keys();
    while (iter.hasNext()) {
        String building = iter.next();
        JSONObject buildingInfo;
        try {
            buildingInfo = json.getJSONObject(building);
            HashMap<String, String> buildingInfoMap = new HashMap<>();
            Iterator<String> innerIter = buildingInfo.keys();
            while (innerIter.hasNext()) {
                String key = innerIter.next();
                buildingInfoMap.put(key, buildingInfo.getString(key));
            }
            imageMaps.put(building, buildingInfoMap);

        } catch (JSONException jsonException) {
            Log.e(TAG, jsonException.toString());
        }
    }

    if (imageMaps.size() > 0) {
        return imageMaps;
    } else
        return null;
}

From source file:edu.utexas.cs.bevomaps.DataLayer.java

static HashMap<String, String> getSearchMap() {

    HashMap<String, String> searchMap = new HashMap<>();
    ParseQuery<BuildingJSON> query = ParseQuery.getQuery("BuildingJSON");
    query = query.whereEqualTo("pk", "jsonObj");

    try {//from  w w  w  .  j av a  2 s.co  m
        BuildingJSON parseBuildingJSON = query.getFirst();
        if (parseBuildingJSON != null) {
            try {
                JSONObject json = parseBuildingJSON.getSearchMap();
                Iterator<String> iter = json.keys();
                while (iter.hasNext()) {
                    String key = iter.next();
                    searchMap.put(key, json.getString(key));
                }
            } catch (JSONException jsonException) {
                Log.e(TAG, jsonException.toString());
            }
        }
    } catch (ParseException e) {
        Log.e(TAG, e.toString());
    }

    return searchMap;
}