Example usage for org.json JSONException printStackTrace

List of usage examples for org.json JSONException printStackTrace

Introduction

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

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:cn.code.notes.gtask.remote.GTaskManager.java

private void addLocalNode(Node node) throws NetworkFailureException {
    if (mCancelled) {
        return;// w  ww .  jav  a  2 s . c  o  m
    }

    SqlNote sqlNote;
    if (node instanceof TaskList) {
        if (node.getName().equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) {
            sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER);
        } else if (node.getName()
                .equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) {
            sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER);
        } else {
            sqlNote = new SqlNote(mContext);
            sqlNote.setContent(node.getLocalJSONFromContent());
            sqlNote.setParentId(Notes.ID_ROOT_FOLDER);
        }
    } else {
        sqlNote = new SqlNote(mContext);
        JSONObject js = node.getLocalJSONFromContent();
        try {
            if (js.has(GTaskStringUtils.META_HEAD_NOTE)) {
                JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
                if (note.has(NoteColumns.ID)) {
                    long id = note.getLong(NoteColumns.ID);
                    if (DataUtils.existInNoteDatabase(mContentResolver, id)) {
                        // the id is not available, have to create a new one
                        note.remove(NoteColumns.ID);
                    }
                }
            }

            if (js.has(GTaskStringUtils.META_HEAD_DATA)) {
                JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
                for (int i = 0; i < dataArray.length(); i++) {
                    JSONObject data = dataArray.getJSONObject(i);
                    if (data.has(DataColumns.ID)) {
                        long dataId = data.getLong(DataColumns.ID);
                        if (DataUtils.existInDataDatabase(mContentResolver, dataId)) {
                            // the data id is not available, have to create
                            // a new one
                            data.remove(DataColumns.ID);
                        }
                    }
                }

            }
        } catch (JSONException e) {
            Log.w(TAG, e.toString());
            e.printStackTrace();
        }
        sqlNote.setContent(js);

        Long parentId = mGidToNid.get(((Task) node).getParent().getGid());
        if (parentId == null) {
            Log.e(TAG, "cannot find task's parent id locally");
            throw new ActionFailureException("cannot add local node");
        }
        sqlNote.setParentId(parentId.longValue());
    }

    // create the local node
    sqlNote.setGtaskId(node.getGid());
    sqlNote.commit(false);

    // update gid-nid mapping
    mGidToNid.put(node.getGid(), sqlNote.getId());
    mNidToGid.put(sqlNote.getId(), node.getGid());

    // update meta
    updateRemoteMeta(node.getGid(), sqlNote);
}

From source file:nl.hnogames.domoticzapi.Parsers.AuthParser.java

@Override
public void parseResult(String result) {
    try {// w  w w  .ja  v  a  2 s  .  c  o m
        AuthInfo mAuthInfo = new AuthInfo(new JSONObject(result));
        receiver.onReceiveAuthentication(mAuthInfo);
    } catch (JSONException e) {
        Log.e(TAG, "AuthParser JSON exception");
        e.printStackTrace();
        receiver.onError(e);
    }
}

From source file:nl.hnogames.domoticzapi.Parsers.ConfigParser.java

@Override
public void parseResult(String result) {
    try {/*from   www.ja v  a 2  s .c  om*/
        ConfigInfo ConfigInfo = new ConfigInfo(new JSONObject(result));
        receiver.onReceiveConfig(ConfigInfo);
    } catch (JSONException e) {
        Log.e(TAG, "ConfigParser JSON exception");
        e.printStackTrace();
        receiver.onError(e);
    }
}

From source file:edu.umass.cs.protocoltask.examples.ExamplePacketDemultiplexer.java

@Override
public boolean handleMessage(JSONObject json) {
    try {// www .  j  a va  2 s .  co m
        if (DEBUG)
            log.finest("PD " + this.node.getMyID() + " received " + json);
        switch (PingPongPacket.PacketType.intToType.get(JSONPacket.getPacketType(json))) {
        case TEST_PING:
        case TEST_PONG:
            this.node.handleIncoming(json);
            break;
        default:
            return false;
        }
    } catch (JSONException je) {
        je.printStackTrace();
    }
    return true;
}

From source file:feedme.controller.SearchRestServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request//from   ww w  . j  ava2 s  . com
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
    request.setCharacterEncoding("UTF-8");

    String city = request.getParameter("where");//get the city
    int category = Integer.parseInt(request.getParameter("what"));//get the category

    int page = 1;
    int recordsPerPage = 6;

    if (request.getParameter("page") != null) {
        page = Integer.parseInt(request.getParameter("page"));
    }

    List<Restaurant> restaurants = new DbRestaurantsManagement().getNextRecentRestaurantsByCatAndCity(0,
            recordsPerPage, category, city);//getting a list of restaurants by category and cities
    int noOfRecords = restaurants.size();

    int noOfPages = (int) Math.ceil(noOfRecords * 1.0 / recordsPerPage);

    if (isAjaxRequest(request)) {
        try {
            restaurants = new DbRestaurantsManagement().getNextRecentRestaurantsByCatAndCity(
                    (page - 1) * recordsPerPage, recordsPerPage, category, city);//getting a list of restaurants by category and cities
            JSONObject restObj = new JSONObject();
            JSONArray restArray = new JSONArray();
            for (Restaurant rest : restaurants) {
                restArray.put(new JSONObject().put("resturent", rest.toJson()));
            }
            restObj.put("resturent", restArray);
            restObj.put("noOfPages", noOfPages);
            restObj.put("currentPage", page);
            response.setContentType("application/json");
            PrintWriter writer = response.getWriter();
            writer.print(restObj);
            response.getWriter().flush();
            return;
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    request.setAttribute("noOfPages", noOfPages);
    request.setAttribute("currentPage", page);
    request.setAttribute("restaurants", restaurants);//return the restaurants to the client

    RequestDispatcher dispatcher = request.getRequestDispatcher("website/search_rest.jsp");
    dispatcher.forward(request, response);

}

From source file:com.marpies.ane.facedetection.functions.DetectFacesFunction.java

private void dispatchResponse(JSONArray facesResult, int callbackId) {
    JSONObject response = new JSONObject();
    try {/*ww w  .  jav a2 s  . co  m*/
        response.put("faces", facesResult.toString());
        response.put("callbackId", callbackId);
        AIR.dispatchEvent(FaceDetectionEvent.FACE_DETECTION_COMPLETE, response.toString());
    } catch (JSONException e) {
        e.printStackTrace();
        AIR.log("Error creating JSON response");
        AIR.dispatchEvent(FaceDetectionEvent.FACE_DETECTION_ERROR,
                StringUtils.getEventErrorJSON(callbackId, "Error creating JSON response"));
    }
}

From source file:com.marpies.ane.facedetection.functions.DetectFacesFunction.java

private String getFaceJSON(Face face) {
    JSONObject json = new JSONObject();
    try {/*from   ww w .  j  a va 2  s . com*/
        json.put("faceX", face.getPosition().x);
        json.put("faceY", face.getPosition().y);
        json.put("faceWidth", face.getWidth());
        json.put("faceHeight", face.getHeight());
        json.put("leftEyeOpenProbability", face.getIsLeftEyeOpenProbability());
        json.put("rightEyeOpenProbability", face.getIsRightEyeOpenProbability());
        json.put("isSmilingProbability", face.getIsSmilingProbability());
        List<Landmark> landmarks = face.getLandmarks();
        for (Landmark landmark : landmarks) {
            addLandmark(landmark, json);
        }
    } catch (JSONException e) {
        e.printStackTrace();
        return null;
    }
    return json.toString();
}

From source file:com.example.android.sunshine.data.FetchWeatherTask.java

/**
 * Take the String representing the complete forecast in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 *
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us./*from   w  w  w .  j  ava2 s  .  co m*/
 */
private String[] getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException {

    // Now we have a String representing the complete forecast in JSON Format.
    // Fortunately parsing is easy:  constructor takes the JSON string and converts it
    // into an Object hierarchy for us.

    // These are the names of the JSON objects that need to be extracted.

    // Location information
    final String OWM_CITY = "city";
    final String OWM_CITY_NAME = "name";
    final String OWM_COORD = "coord";

    // Location coordinate
    final String OWM_LATITUDE = "lat";
    final String OWM_LONGITUDE = "lon";

    // Weather information.  Each day's forecast info is an element of the "list" array.
    final String OWM_LIST = "list";

    final String OWM_PRESSURE = "pressure";
    final String OWM_HUMIDITY = "humidity";
    final String OWM_WINDSPEED = "speed";
    final String OWM_WIND_DIRECTION = "deg";

    // All temperatures are children of the "temp" object.
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";

    final String OWM_WEATHER = "weather";
    final String OWM_DESCRIPTION = "main";
    final String OWM_WEATHER_ID = "id";

    try {
        JSONObject forecastJson = new JSONObject(forecastJsonStr);
        JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

        JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY);
        String cityName = cityJson.getString(OWM_CITY_NAME);

        JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD);
        double cityLatitude = cityCoord.getDouble(OWM_LATITUDE);
        double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE);

        long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);

        // Insert the new weather information into the database
        Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length());

        // OWM returns daily forecasts based upon the local time of the city that is being
        // asked for, which means that we need to know the GMT offset to translate this data
        // properly.

        // Since this data is also sent in-order and the first day is always the
        // current day, we're going to take advantage of that to get a nice
        // normalized UTC date for all of our weather.

        Time dayTime = new Time();
        dayTime.setToNow();

        // we start at the day returned by local time. Otherwise this is a mess.
        int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);

        // now we work exclusively in UTC
        dayTime = new Time();

        for (int i = 0; i < weatherArray.length(); i++) {
            // These are the values that will be collected.
            long dateTime;
            double pressure;
            int humidity;
            double windSpeed;
            double windDirection;

            double high;
            double low;

            String description;
            int weatherId;

            // Get the JSON object representing the day
            JSONObject dayForecast = weatherArray.getJSONObject(i);

            // Cheating to convert this to UTC time, which is what we want anyhow
            dateTime = dayTime.setJulianDay(julianStartDay + i);

            pressure = dayForecast.getDouble(OWM_PRESSURE);
            humidity = dayForecast.getInt(OWM_HUMIDITY);
            windSpeed = dayForecast.getDouble(OWM_WINDSPEED);
            windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION);

            // Description is in a child array called "weather", which is 1 element long.
            // That element also contains a weather code.
            JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
            description = weatherObject.getString(OWM_DESCRIPTION);
            weatherId = weatherObject.getInt(OWM_WEATHER_ID);

            // Temperatures are in a child object called "temp".  Try not to name variables
            // "temp" when working with temperature.  It confuses everybody.
            JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
            high = temperatureObject.getDouble(OWM_MAX);
            low = temperatureObject.getDouble(OWM_MIN);

            ContentValues weatherValues = new ContentValues();

            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_LOC_KEY, locationId);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DATE, dateTime);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_HUMIDITY, humidity);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_PRESSURE, pressure);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DEGREES, windDirection);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MAX_TEMP, high);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MIN_TEMP, low);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_SHORT_DESC, description);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WEATHER_ID, weatherId);

            cVVector.add(weatherValues);
        }

        // add to database
        if (cVVector.size() > 0) {
            // Student: call bulkInsert to add the weatherEntries to the database here
        }

        // Sort order:  Ascending, by date.
        String sortOrder = WeatherContract.WeatherEntry.COLUMN_DATE + " ASC";
        Uri weatherForLocationUri = WeatherContract.WeatherEntry
                .buildWeatherLocationWithStartDate(locationSetting, System.currentTimeMillis());

        // Students: Uncomment the next lines to display what what you stored in the bulkInsert

        //            Cursor cur = mContext.getContentResolver().query(weatherForLocationUri,
        //                    null, null, null, sortOrder);
        //
        //            cVVector = new Vector<ContentValues>(cur.getCount());
        //            if ( cur.moveToFirst() ) {
        //                do {
        //                    ContentValues cv = new ContentValues();
        //                    DatabaseUtils.cursorRowToContentValues(cur, cv);
        //                    cVVector.add(cv);
        //                } while (cur.moveToNext());
        //            }

        Log.d(LOG_TAG, "FetchWeatherTask Complete. " + cVVector.size() + " Inserted");

        String[] resultStrs = convertContentValuesToUXFormat(cVVector);
        return resultStrs;

    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }
    return null;
}

From source file:fr.bmartel.android.fadecandy.model.FadecandyColor.java

public FadecandyColor(JSONObject color) {

    try {/*from w w  w.j a va2  s .  co m*/
        if (color.has(Constants.CONFIG_GAMMA) && color.has(Constants.CONFIG_WHITEPOINT)) {
            mGamma = (float) color.getDouble(Constants.CONFIG_GAMMA);

            JSONArray whitepoints = color.getJSONArray(Constants.CONFIG_WHITEPOINT);

            for (int i = 0; i < whitepoints.length(); i++) {
                mWhitepoints.add((float) whitepoints.getDouble(i));
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:fr.bmartel.android.fadecandy.model.FadecandyColor.java

public JSONObject toJsonObject() {

    JSONObject color = new JSONObject();

    try {//from  w w  w .j  a v  a2 s.  c om

        JSONArray whitepoints = new JSONArray();
        for (Float item : mWhitepoints) {
            whitepoints.put(item);
        }

        color.put(Constants.CONFIG_GAMMA, mGamma);
        color.put(Constants.CONFIG_WHITEPOINT, whitepoints);

    } catch (JSONException e) {
        e.printStackTrace();
    }

    return color;
}