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.tune.reporting.base.endpoints.ReportExportWorker.java

/**
 * Poll export status and upon completion gather download URL
 * referencing requested report.//from  w  w  w.j  av a  2s  .com
 *
 * @return Boolean If True upon successful completion.
 * @throws TuneSdkException If error within SDK.
 * @throws TuneServiceException If service fails to handle post request.
 */
public final Boolean run() throws TuneSdkException, TuneServiceException {
    String status = null;
    TuneServiceResponse response = null;
    int attempt = 0;
    int timeout = 0;

    Map<String, String> mapQueryString = new HashMap<String, String>();
    mapQueryString.put("job_id", jobId);

    TuneServiceClient client = null;
    try {
        client = new TuneServiceClient(this.exportController, this.exportAction, this.authKey, this.authType,
                mapQueryString);
    } catch (IllegalArgumentException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    while (true) {
        if (this.timeout > 0) {
            if (timeout >= this.timeout) {
                throw new TuneSdkException(String.format(
                        "Fetch request for Job ID '%s' has expired after '%d' seconds. Service request URL: %s",
                        jobId, timeout, client.getServiceUrl()));
            }

            timeout += sleep;
        }

        try {
            client.call(this.authKey, this.authType);
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        response = client.getResponse();

        // Failed to return response.
        if (null == response) {
            throw new TuneSdkException("No response returned from export request.");
        }

        String requestUrl = response.getRequestUrl();
        int responseHttpCode = response.getHttpCode();

        // Failed to get successful service response.
        if ((response.getHttpCode() != HTTP_STATUS_OK) || (null != response.getErrors())) {
            throw new TuneServiceException(String.format("Service failed request: %d: %s",
                    response.getHttpCode(), response.toString()));
        }

        // Failed to get data.
        JSONObject jdata = (JSONObject) response.getData();
        if (null == jdata) {
            throw new TuneServiceException("Report request failed to get export data.");
        }

        try {
            status = jdata.getString("status");
        } catch (JSONException ex) {
            throw new TuneSdkException(ex.getMessage(), ex);
        } catch (Exception ex) {
            throw new TuneSdkException(ex.getMessage(), ex);
        }

        if (this.verbose) {
            System.out.println(String.format("= status: %s", status));
        }

        if (status.equals("fail") || status.equals("complete")) {
            break;
        }

        attempt += 1;
        if (this.verbose) {
            System.out.println(String.format("= attempt: %d\n= timeout: %d\n= response: %s", attempt, timeout,
                    response.toString()));
        }

        try {
            Thread.sleep(this.sleep * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    if (!status.equals("complete")) {
        throw new TuneServiceException(
                String.format("= status: %s, response: %s", status, response.toString()));
    }

    if (this.verbose) {
        System.out.println(String.format("= attempt: %d\n= timeout: %d\n= response: %s", attempt, timeout,
                response.toString()));
    }

    this.response = response;

    return true;
}

From source file:com.polyvi.plugins.weibo.Weibo.java

/**
 * Executes the request and returns PluginResult.
 *
 * @param action//from   ww  w .  j  a  v  a2 s.c o m
 *            The action to execute.
 * @param args
 *            JSONArry of arguments for the plugin.
 * @param callbackContext
 *            The callback id used when calling back into JavaScript.
 * @return True if the action was valid, false if not.
 */
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    mCallbackContext = callbackContext;
    if (action.equals(TAG_WEIBO_LOGIN)) {
        try {
            weiboLogin(args.getString(0), args.getString(1));
        } catch (JSONException e) {
            mCallbackContext.error(e.getMessage());
            return false;
        }
    } else {
        return false;
    }
    return true;
}

From source file:de.liedtke.format.JSONFormatter.java

@Override
public <T extends BasicEntity> T reformat(final String object, final Class<T> entityClass)
        throws FormatException {
    T result = null;//  w  w w .j  av a 2 s  .  c  o m
    final Map<String, Field> fieldMap = new HashMap<String, Field>();
    if (entityClass.isAnnotationPresent(Entity.class)) {
        final Field[] fields = entityClass.getDeclaredFields();
        for (final Field field : fields) {
            if (field.isAnnotationPresent(FormatPart.class)) {
                fieldMap.put(field.getAnnotation(FormatPart.class).key(), field);
            }
        }
        try {
            final JSONObject json = new JSONObject(object);
            result = entityClass.newInstance();
            for (final String key : fieldMap.keySet()) {
                if (json.has(key)) {
                    final Field field = fieldMap.get(key);
                    final Method method = entityClass.getMethod(this.getSetter(field.getName()),
                            new Class<?>[] { field.getType() });
                    if (FindInterface.class.isAssignableFrom(field.getType())) {
                        final Method find = field.getType().getMethod("find", new Class<?>[] { String.class });
                        if (find != null) {
                            final Object enumObject = find.invoke(Enum.class, json.get(key));
                            method.invoke(result, enumObject);
                        }
                    } else {
                        final String type = field.getType().toString();
                        if (type.equals("class com.google.appengine.api.datastore.Key")) {
                            method.invoke(result, KeyFactory.stringToKey(json.getString(key)));
                        } else if (type.equals("class com.google.appengine.api.datastore.Text")) {
                            method.invoke(result, new Text(json.getString(key)));
                        } else if (type.equals("boolean")) {
                            method.invoke(result, json.getBoolean(key));
                        } else if (type.equals("long")) {
                            method.invoke(result, json.getLong(key));
                        } else if (type.equals("int")) {
                            method.invoke(result, json.getInt(key));
                        } else {
                            method.invoke(result, json.get(key));
                        }
                    }
                }
            }
        } catch (JSONException e) {
            logger.warning("JSONException occured: " + e.getMessage());
            throw new FormatException();
        } catch (NoSuchMethodException e) {
            logger.warning("NoSuchMethodException occured: " + e.getMessage());
            throw new FormatException();
        } catch (SecurityException e) {
            logger.warning("SecurityException occured: " + e.getMessage());
            throw new FormatException();
        } catch (IllegalAccessException e) {
            logger.warning("IllegalAccessException occured: " + e.getMessage());
            throw new FormatException();
        } catch (IllegalArgumentException e) {
            logger.warning("IllegalArgumentException occured: " + e.getMessage());
            throw new FormatException();
        } catch (InvocationTargetException e) {
            logger.warning("InvocationTargetException occured: " + e.getMessage());
            throw new FormatException();
        } catch (InstantiationException e) {
            logger.warning("InstantiationException occured: " + e.getMessage());
            throw new FormatException();
        }
    }
    return result;
}

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

@Override
public void onError(int errorCode) {
    setState(INIT);//w  w w.  j  av a 2 s  . com
    JSONObject error = new JSONObject();
    Status status = Status.ERROR;
    try {
        error.put("code", errorCode);
        error.put("source", mFilePath);
        error.put("target", mServer);
    } catch (JSONException e) {
        status = Status.JSON_EXCEPTION;
        XLog.e(CLASS_NAME, e.getMessage());
    }
    PluginResult result = new PluginResult(status, error);
    mCallbackCtx.sendPluginResult(result);
}

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

@Override
public void onProgressUpdated(int completeSize, long totalSize) {
    JSONObject jsonObj = new JSONObject();
    try {//from w w w.  j  av a 2 s.com
        jsonObj.put("loaded", completeSize);
        jsonObj.put("total", totalSize);
    } 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.galactogolf.serialization.JSONSerializer.java

public static LevelSet fromLevelSetJSON(JSONObject levelSetJSON) throws JSONException {

    LevelSet levelSet = new LevelSet(levelSetJSON.getString(JSONTags.LEVEL_SET_ID),
            levelSetJSON.getString(JSONTags.LEVEL_SET_NAME));
    levelSet.setDescription(levelSetJSON.optString(JSONTags.LEVEL_SET_DESCRIPTION));
    JSONArray levelsJSON = null;/*  w w  w.j  a va 2 s. com*/
    try {
        levelsJSON = levelSetJSON.getJSONArray(JSONTags.LEVEL_SET_LEVELS);
    } catch (JSONException ex) {
        Log.e("Level Loading Exception", ex.getMessage());
        levelSet.add(
                JSONSerializer.fromLevelDefinitionJSON(levelSetJSON.getJSONObject(JSONTags.LEVEL_SET_LEVELS)));
        return levelSet;
    }
    for (int i = 0; i < levelsJSON.length(); i++) {
        levelSet.add(JSONSerializer.fromLevelDefinitionJSON(levelsJSON.getJSONObject(i)));
    }

    return levelSet;
}

From source file:com.rapid.actions.Mobile.java

@Override
public String getJavaScript(RapidRequest rapidRequest, Application application, Page page, Control control,
        JSONObject jsonDetails) {// w w  w  .  j  a v a  2 s.c o  m
    // start the js
    String js = "";
    // get the servlet
    RapidHttpServlet rapidServlet = rapidRequest.getRapidServlet();
    // get the type
    String type = getProperty("actionType");
    // check we got something
    if (type != null) {

        // check the type
        if ("dial".equals(type) || "sms".equals(type)) {
            // get the number control id
            String numberControlId = getProperty("numberControlId");
            // get the control
            Control numberControl = Control.getControl(rapidServlet.getServletContext(), application, page,
                    numberControlId);
            // check we got one
            if (numberControl == null) {
                js += "// phone number control " + numberControlId + " not found\n";
            } else {
                // get the number field
                String numberField = getProperty("numberField");
                // mobile check with alert
                js += getMobileCheck(true);
                // get number
                js += "  var number = " + Control.getDataJavaScript(rapidServlet.getServletContext(),
                        application, page, numberControlId, numberField) + ";\n";
                // sms has a message too
                if ("sms".equals(type)) {
                    // get the message control id
                    String messageControlId = getProperty("messageControlId");
                    // get the messagecontrol
                    Control messageControl = Control.getControl(rapidServlet.getServletContext(), application,
                            page, messageControlId);
                    // check we got one
                    if (messageControl == null) {
                        js += "// message control " + numberControlId + " not found\n";
                    } else {
                        // get the field
                        String messageField = getProperty("messageField");
                        // get the message
                        js += "  var message = " + Control.getDataJavaScript(rapidServlet.getServletContext(),
                                application, page, messageControlId, messageField) + ";\n";
                        // send the message
                        js += "  _rapidmobile.openSMS(number, message);\n";
                    }
                } else {
                    // dial number
                    js += "  _rapidmobile.openPhone(number);\n";
                }
                // close mobile check
                js += "}";
            }

        } else if ("email".equals(type)) {

            // get the email control id
            String emailControlId = getProperty("emailControlId");
            // check we got one
            if (checkControl(rapidServlet.getServletContext(), application, page, emailControlId)) {
                // get the email field
                String emailField = getProperty("emailField");
                // get the email
                js += "var email = " + Control.getDataJavaScript(rapidServlet.getServletContext(), application,
                        page, emailControlId, emailField) + ";\n";
                // get the subject js
                String subjectGetDataJS = Control.getDataJavaScript(rapidServlet.getServletContext(),
                        application, page, getProperty("subjectControlId"), getProperty("subjectField"));
                // add the subject js
                js += "var subject = "
                        + (("".equals(subjectGetDataJS) || subjectGetDataJS == null) ? "''" : subjectGetDataJS)
                        + ";\n";
                // subject safety check
                js += "if (!subject) subject = ''\n";
                // get the message js               
                String messageGetDataJS = Control.getDataJavaScript(rapidServlet.getServletContext(),
                        application, page, getProperty("messageControlId"), getProperty("messageField"));
                // get the message 
                js += "var message = "
                        + (("".equals(messageGetDataJS) || messageGetDataJS == null) ? "''" : messageGetDataJS)
                        + ";\n";
                // message safety check
                js += "if (!message) message = ''\n";

                // start the alernative mobile check
                js += getMobileCheckAlternative();
                // start the check for the addBarcode function
                js += "  if (_rapidmobile.openEmail) {\n";
                // send the message
                js += "    _rapidmobile.openEmail(email, subject, message);\n";
                // close the open url check
                js += "  } else alert('Opening emails is not supported in this version of Rapid Mobile');\n";
                // else
                js += "} else {\n";
                // no rapid mobile so just open in new tab
                js += "  window.location.href = 'mailto:' + email + '?subject=' + subject + '&body=' + message;\n";
                // close the mobile check
                js += "}\n";

            } else {
                js += "// email control " + emailControlId + " not found\n";
            }

        } else if ("url".equals(type)) {

            // get the url control id
            String urlControlId = getProperty("urlControlId");
            // check we got one
            if (checkControl(rapidServlet.getServletContext(), application, page, urlControlId)) {
                // get the field
                String urlField = getProperty("urlField");
                // get the url
                js += "var url = " + Control.getDataJavaScript(rapidServlet.getServletContext(), application,
                        page, urlControlId, urlField) + ";\n";
                // start the alernative mobile check
                js += getMobileCheckAlternative();
                // start the check for the addBarcode function
                js += "  if (_rapidmobile.openURL) {\n";
                // send the message
                js += "    _rapidmobile.openURL(url);\n";
                // close the open url check
                js += "  } else alert('Opening URLs is not supported in this version of Rapid Mobile');\n";
                // else
                js += "} else {\n";
                // no rapid mobile so just open in new tab
                js += "  window.open(url, '_blank');\n";
                // close the mobile check
                js += "}\n";
            } else {
                js += "// url control " + urlControlId + " not found\n";
            }

        } else if ("addImage".equals(type)) {

            // get the gallery control Id
            String galleryControlId = getProperty("galleryControlId");
            // get the gallery control
            Control galleryControl = page.getControl(galleryControlId);
            // check if we got one
            if (galleryControl == null) {
                js += "  //gallery control " + galleryControlId + " not found\n";
            } else {
                // mobile check with alert
                js += getMobileCheck(true);
                int maxSize = Integer.parseInt(getProperty("imageMaxSize"));
                int quality = Integer.parseInt(getProperty("imageQuality"));
                js += "  _rapidmobile.addImage('" + galleryControlId + "'," + maxSize + "," + quality + ");\n";
                // close mobile check
                js += "}\n";
            }

        } else if ("uploadImages".equals(type)) {

            // make a list of control ids
            List<String> galleryControlIds = new ArrayList<String>();

            // get the old style gallery id
            String galleryControlIdProperty = getProperty("galleryControlId");
            // if we got one
            if (galleryControlIdProperty != null) {
                //  add to list if it contains something
                if (galleryControlIdProperty.trim().length() > 0)
                    galleryControlIds.add(galleryControlIdProperty);
            }

            // get the new style gallery ids
            String galleryControlIdsProperty = getProperty("galleryControlIds");
            // if we got one
            if (galleryControlIdsProperty != null) {
                // clean it up
                galleryControlIdsProperty = galleryControlIdsProperty.replace("\"", "").replace("[", "")
                        .replace("]", "");
                // if anything is left
                if (galleryControlIdsProperty.length() > 0) {
                    // split and loop
                    for (String id : galleryControlIdsProperty.split(",")) {
                        // add to collection
                        galleryControlIds.add(id);
                    }
                }
            }

            // check if we got one
            if (galleryControlIds.size() == 0) {
                js += "  // no galleryControls specified\n";
            } else {
                // assume no success call back
                String successCallback = "null";
                // update to name of callback if we have any success actions
                if (_successActions != null)
                    successCallback = "'" + getId() + "success'";
                // assume no error call back
                String errorCallback = "null";
                // update to name of callback  if we have any error actions
                if (_errorActions != null)
                    errorCallback = "'" + getId() + "error'";
                // start building the js
                js += "var urls = '';\n";
                // get any urls from the gallery controls
                for (String id : galleryControlIds) {
                    js += "$('#" + id
                            + "').find('img').each( function() { urls += $(this).attr('src') + ',' });\n";
                }
                // if we got any urls
                js += "if (urls) { \n";
                // mobile check with alert
                js += "  " + getMobileCheck(true).replace("\n", "\n  ");
                // upload the images
                js += "  _rapidmobile.uploadImages('" + getId() + "', urls, " + successCallback + ", "
                        + errorCallback + ");\n";
                // close rapid mobile check 
                js += "  }\n";
                // close urls check and proceed straight to success call back if none
                js += "}";
                // if there is a successCallback call it now
                if (!"null".equals(successCallback) && successCallback.length() > 0)
                    js += " else {\n  " + successCallback.replace("'", "") + "(ev);\n}\n";
            }

        } else if ("navigate".equals(type)) {

            // get the naviagte source control id
            String navigateControlId = getProperty("navigateControlId");
            // get the control
            Control navigateControl = Control.getControl(rapidServlet.getServletContext(), application, page,
                    navigateControlId);
            // check we got one
            if (navigateControl == null) {
                js += "// navigate to control " + navigateControlId + " not found\n";
            } else {
                // get the navigate to field
                String navigateField = getProperty("navigateField");
                // get the mode
                String navigateMode = getProperty("navigateMode");
                // enclose if we got one
                if (navigateMode != null)
                    navigateMode = "'" + navigateMode + "'";
                // mobile check 
                js += getMobileCheck(true);
                // get the data
                js += "  var data = " + Control.getDataJavaScript(rapidServlet.getServletContext(), application,
                        page, navigateControlId, navigateField) + ";\n";
                // assume no search fields
                String searchFields = getProperty("navigateSearchFields");
                // if we got some
                if (searchFields != null) {
                    // if there's something 
                    if (searchFields.trim().length() > 0) {
                        // build the JavaScript object
                        searchFields = "{searchFields:'" + searchFields.replace("'", "\'") + "'}";
                    } else {
                        // set to null
                        searchFields = null;
                    }
                }
                // get a position object
                js += "  var pos = getMapPosition(data, 0, null, null, " + searchFields + ");\n";
                // add js, replacing any dodgy inverted commas
                js += "  if (pos && (pos.lat || pos.lng || pos.s)) _rapidmobile.navigateTo(pos.lat, pos.lng, pos.s, "
                        + navigateMode + ");\n";
                // close mobile check
                js += "}\n";
            }

        } else if ("message".equals(type)) {

            // retrieve the message
            String message = getProperty("message");
            // update to empty string if null
            if (message == null)
                message = "";
            // mobile check with silent fail
            js += getMobileCheck(false);
            // add js, replacing any dodgy inverted commas
            js += "  _rapidmobile.showMessage('" + message.replace("'", "\\'") + "');\n";
            // close mobile check
            js += "}\n";

        } else if ("disableBackButton".equals(type)) {

            // mobile check with silent fail
            js += getMobileCheck(false);
            // add js
            js += "    _rapidmobile.disableBackButton();\n";
            // close mobile check
            js += "  }\n";

        } else if ("sendGPS".equals(type)) {

            // mobile check with alert
            js += getMobileCheck(true);

            // get whether to check if gps is enabled
            boolean checkGPS = Boolean.parseBoolean(getProperty("gpsCheck"));
            // if we had one call it
            if (checkGPS)
                js += "  _rapidmobile.checkGPS();\n";

            // get the gps frequency into an int
            int gpsFrequency = Integer.parseInt(getProperty("gpsFrequency"));

            // get the gps destinations
            String gpsDestinationsString = getProperty("gpsDestinations");

            // if we had some
            if (gpsDestinationsString != null) {

                try {

                    // start the getGPS string
                    String getGPSjs = "  _rapidmobile.getGPS(" + gpsFrequency + ",\"[";

                    // add the gpsDestinationsString
                    getGPSjs += getOutputs(rapidServlet, application, page, gpsDestinationsString);

                    // close the get gps string
                    getGPSjs += "]\");\n";

                    // add it into the js
                    js += getGPSjs;

                } catch (JSONException ex) {

                    // print an error into the js instead
                    js += "  // error reading gpsDestinations : " + ex.getMessage();

                }

            } // gps destinations check         

            // close mobile check
            js += "}\n";

        } else if ("stopGPS".equals(type)) {

            // mobile check with silent fail
            js += getMobileCheck(false);
            // call stop gps
            js += "  _rapidmobile.stopGPS();\n";
            // close mobile check
            js += "}\n";

        } else if ("online".equals(type)) {

            // check we have online actions
            if (_onlineActions != null) {
                // check size
                if (_onlineActions.size() > 0) {

                    try {

                        // ensure we have a details object
                        if (jsonDetails == null)
                            jsonDetails = new JSONObject();

                        // add js online check
                        js += "  if (typeof _rapidmobile == 'undefined' ? true : _rapidmobile.isOnline()) {\n";

                        // get any working / loading page
                        String workingPage = getProperty("onlineWorking");
                        // if there was one 
                        if (workingPage != null) {
                            // show working page as a dialogue
                            js += "  if (Action_navigate) Action_navigate('~?a=" + application.getId() + "&v="
                                    + application.getVersion() + "&p=" + workingPage
                                    + "&action=dialogue',true,'" + getId() + "');\n";
                            // record that we have a working page in the details
                            jsonDetails.put("workingPage", getId());
                        }

                        // get the offline dialogue
                        String offlinePage = getProperty("onlineFail");

                        // loop them (this should clean out the working and offline entries in the details)
                        for (Action action : _onlineActions) {

                            // record that we have an offline page
                            jsonDetails.put("offlinePage", offlinePage);

                            js += "  " + action
                                    .getJavaScript(rapidRequest, application, page, control, jsonDetails).trim()
                                    .replace("\n", "\n  ") + "\n";

                        }

                        // get the working details page (in case none of the actions have used it
                        workingPage = jsonDetails.optString("workingPage", null);

                        // js online check fail
                        js += "} else {\n";

                        // if we have an offline page one show it
                        if (offlinePage != null)
                            js += "  if (Action_navigate) Action_navigate('~?a=" + application.getId() + "&v="
                                    + application.getVersion() + "&p=" + offlinePage
                                    + "&action=dialogue',true,'" + getId() + "');\n";

                        // close online check
                        js += "}\n";

                    } catch (Exception ex) {
                        // print an error instead
                        js = "// failed to print action " + getId() + " JavaScript : " + ex.getMessage() + "\n";
                    }

                } // online actions size check

            } // online actions check non-null check

        } else if ("addBarcode".equals(type)) {

            try {

                // mobile check with fail
                String jsBarcode = getMobileCheck(true);

                // get the barcodeDestinations
                String barcodeDestinations = getProperty("barcodeDestinations");

                // start the check for the addBarcode function
                jsBarcode += "  if (_rapidmobile.addBarcode) {\n";

                // start the add barcode call
                jsBarcode += "    _rapidmobile.addBarcode(\"[";

                jsBarcode += getOutputs(rapidServlet, application, page, barcodeDestinations);

                // call get barcode
                jsBarcode += "]\");\n";

                // close function check
                jsBarcode += "  } else alert('Barcode reading is not available in this version of Rapid Mobile');\n";

                // close mobile check
                jsBarcode += "}\n";

                // now safe to add back into main js
                js += jsBarcode;

            } catch (JSONException ex) {

                // print an error into the js instead
                js += "  // error reading barcode : " + ex.getMessage();

            }

        } // mobile action type check

    } // mobile action type non-null check

    // return an empty string
    return js;
}

From source file:com.example.jumpnote.android.jsonrpc.JsonRpcJavaClient.java

public void callBatch(final List<JsonRpcClient.Call> calls, final JsonRpcClient.BatchCallback callback) {
    HttpPost httpPost = new HttpPost(mRpcUrl);
    JSONObject requestJson = new JSONObject();
    JSONArray callsJson = new JSONArray();
    try {//from  w w  w  . j ava2s  .c o  m
        for (int i = 0; i < calls.size(); i++) {
            JsonRpcClient.Call call = calls.get(i);

            JSONObject callJson = new JSONObject();

            callJson.put("method", call.getMethodName());

            if (call.getParams() != null) {
                JSONObject callParams = (JSONObject) call.getParams();
                @SuppressWarnings("unchecked")
                Iterator<String> keysIterator = callParams.keys();
                String key;
                while (keysIterator.hasNext()) {
                    key = keysIterator.next();
                    callJson.put(key, callParams.get(key));
                }
            }

            callsJson.put(i, callJson);
        }

        requestJson.put("calls", callsJson);
        httpPost.setEntity(new StringEntity(requestJson.toString(), "UTF-8"));
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "POST request: " + requestJson.toString());
        }
    } catch (JSONException e) {
        // throw e;
    } catch (UnsupportedEncodingException e) {
        // throw e;
    }

    try {
        HttpResponse httpResponse = mHttpClient.execute(httpPost);
        final int responseStatusCode = httpResponse.getStatusLine().getStatusCode();
        if (200 <= responseStatusCode && responseStatusCode < 300) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"), 8 * 1024);

            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "POST response: " + sb.toString());
            }
            JSONTokener tokener = new JSONTokener(sb.toString());
            JSONObject responseJson = new JSONObject(tokener);
            JSONArray resultsJson = responseJson.getJSONArray("results");
            Object[] resultData = new Object[calls.size()];

            for (int i = 0; i < calls.size(); i++) {
                JSONObject result = resultsJson.getJSONObject(i);
                if (result.has("error")) {
                    callback.onError(i, new JsonRpcException((int) result.getInt("error"),
                            calls.get(i).getMethodName(), result.getString("message"), null));
                    resultData[i] = null;
                } else {
                    resultData[i] = result.get("data");
                }
            }

            callback.onData(resultData);
        } else {
            callback.onError(-1, new JsonRpcException(-1, "Received HTTP status code other than HTTP 2xx: "
                    + httpResponse.getStatusLine().getReasonPhrase()));
        }
    } catch (IOException e) {
        Log.e("JsonRpcJavaClient", e.getMessage());
        e.printStackTrace();
    } catch (JSONException e) {
        Log.e("JsonRpcJavaClient", "Error parsing server JSON response: " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.cubusmail.server.user.PreferencesTypeHandler.java

public Object getResult(ResultGetter getter) throws SQLException {

    String preferencesJson = getter.getString();
    Preferences preferences = null;

    if (preferencesJson != null) {
        preferences = new Preferences();
        try {//from  w  w  w  . j  a v a2s  .  c  o m
            JSONObject object = new JSONObject(preferencesJson);
            Field[] fields = Preferences.class.getFields();
            if (fields != null) {
                for (Field field : fields) {
                    Object value = object.has(field.getName()) ? object.get(field.getName()) : null;
                    if (value != null) {
                        if (value instanceof Integer) {
                            field.setInt(preferences, ((Integer) value).intValue());
                        } else if (value instanceof Boolean) {
                            field.setBoolean(preferences, ((Boolean) value).booleanValue());
                        } else if (value instanceof String) {
                            field.set(preferences, value);
                        }
                    }
                }
            }
        } catch (JSONException e) {
            log.error(e.getMessage(), e);
        } catch (NumberFormatException e) {
            log.error(e.getMessage(), e);
        } catch (IllegalArgumentException e) {
            log.error(e.getMessage(), e);
        } catch (IllegalAccessException e) {
            log.error(e.getMessage(), e);
        }
    }

    return preferences;
}

From source file:parser.GameDataService.java

public void searilizeToJson(String path, String file) {
    String JSON_FILE;// w  w  w  .  ja v a 2 s.c o  m
    ArrayList<Object> gamedata = parse(path + file);
    int i = 0, j = 0;
    DataVO sheetData;
    ArrayList<Object> sheet;
    HashMap<String, Object> rowData;

    JSONArray sheetJsonArray;
    JSONObject sheetJsonObject = null;

    Iterator<String> iterator;

    for (i = 0; i < gamedata.size(); i++) {
        sheetData = (DataVO) gamedata.get(i);
        JSON_FILE = path + (sheetData.type + ".json");
        sheet = sheetData.data;

        sheetJsonArray = new JSONArray();

        for (j = 0; j < sheet.size(); j++) {
            rowData = (HashMap<String, Object>) sheet.get(j);

            iterator = rowData.keySet().iterator();
            sheetJsonObject = new JSONObject();
            while (iterator.hasNext()) {
                String key = (String) iterator.next();

                try {
                    sheetJsonObject.put(key, rowData.get(key));
                } catch (JSONException e) {
                }
            }

            sheetJsonArray.put(sheetJsonObject);

            try {
                FileWriter fstream = new FileWriter(JSON_FILE);
                BufferedWriter out = new BufferedWriter(fstream);
                out.write(sheetJsonArray.toString());
                out.close();
            } catch (IOException e) {
                System.out.println(JSON_FILE + "File Read Error:" + e.getMessage());

            }
        }

    }

}