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.microsoft.office365.starter.models.O365FileListModel.java

private String getErrorMessage(String result) {
    String errorMessage = "";
    try {/*w ww.  j  av a2  s .com*/
        String responseString = result;
        String responsejSON = responseString.substring(responseString.indexOf("{"), responseString.length());
        JSONObject jObject = new JSONObject(responsejSON);

        JSONObject error = (JSONObject) jObject.get("error");
        errorMessage = error.getString("message");

    } catch (JSONException e) {
        e.printStackTrace();
        errorMessage = e.getMessage();
    }
    return errorMessage;
}

From source file:com.nonobay.fana.udacityandroidproject1popularmovies.FetchMovieTask.java

/**
 * Take the String representing the complete movies in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 * <p/>//  w w w .j ava  2 s  .co  m
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.
 */
private void getMovieDataFromJson(String moviesJsonStr) throws JSONException {

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

    /* example
    {
    "page": 1,
    "results": [
        {
            "adult": false,
                "backdrop_path": "/razvUuLkF7CX4XsLyj02ksC0ayy.jpg",
                "genre_ids": [
            80,
                    28,
                    53
            ],
            "id": 260346,
                "original_language": "en",
                "original_title": "Taken 3",
                "overview": "Ex-government operative Bryan Mills finds his life is shattered when he's falsely accused of a murder that hits close to home. As he's pursued by a savvy police inspector, Mills employs his particular set of skills to track the real killer and exact his unique brand of justice.",
                "release_date": "2015-01-09",
                "poster_path": "/c2SSjUVYawDUnQ92bmTqsZsPEiB.jpg",
                "popularity": 11.737899,
                "title": "Taken 3",
                "video": false,
                "vote_average": 6.2,
                "vote_count": 698
        }
    ],
    "total_pages": 11543,
    "total_results": 230847
    }*/

    // These are the names of the JSON objects that need to be extracted.
    final String JSON_PAGE = "page";
    final String JSON_PAGE_TOTAL = "total_pages";
    final String JSON_MOVIE_LIST = "results";
    final String JSON_MOVIE_TOTAL = "total_results";

    final String JSON_MOVIE_ID = "id";
    final String JSON_MOVIE_TITLE = "original_title";
    final String JSON_MOVIE_DATE = "release_date";
    final String JSON_MOVIE_POSTER = "poster_path";
    final String JSON_MOVIE_OVERVIEW = "overview";
    final String JSON_MOVIE_VOTE_AVERAGE = "vote_average";

    try {

        JSONObject moviesJson = new JSONObject(moviesJsonStr);

        JSONArray movieArray = moviesJson.getJSONArray(JSON_MOVIE_LIST);

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

        // These are the values that will be collected.
        String releaseTime;
        long movieId;
        double vote_average;
        String overview;
        String original_title;
        String poster_path;

        for (int i = 0; i < movieArray.length(); i++) {

            // Get the JSON object representing the movie
            JSONObject eachMovie = movieArray.getJSONObject(i);

            movieId = eachMovie.getLong(JSON_MOVIE_ID);
            original_title = eachMovie.getString(JSON_MOVIE_TITLE);
            overview = eachMovie.getString(JSON_MOVIE_OVERVIEW);
            poster_path = eachMovie.getString(JSON_MOVIE_POSTER);
            vote_average = eachMovie.getDouble(JSON_MOVIE_VOTE_AVERAGE);
            releaseTime = eachMovie.getString(JSON_MOVIE_DATE);

            ContentValues movieValues = new ContentValues();
            movieValues.put(MovieContract.MovieEntry.COLUMN_MOVIE_ID, movieId);
            movieValues.put(MovieContract.MovieEntry.COLUMN_ORIGINAL_TITLE, original_title);
            movieValues.put(MovieContract.MovieEntry.COLUMN_POSTER_THUMBNAIL, poster_path);
            movieValues.put(MovieContract.MovieEntry.COLUMN_SYNOPSIS, overview);
            movieValues.put(MovieContract.MovieEntry.COLUMN_RELEASE_DATE, releaseTime);
            movieValues.put(MovieContract.MovieEntry.COLUMN_USER_RATING, vote_average);

            cVVector.add(movieValues);
        }

        // add to database
        if (cVVector.size() > 0) {
            // Student: call bulkInsert to add the weatherEntries to the database here
            mContext.getContentResolver().delete(MovieContract.MovieEntry.CONTENT_URI, null, null);
            mContext.getContentResolver().bulkInsert(MovieContract.MovieEntry.CONTENT_URI,
                    cVVector.toArray(new ContentValues[cVVector.size()]));
        }

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

From source file:de.damdi.fitness.activity.settings.sync.RestClient.java

private String parseJsonError(String json) {
    try {//from www.  j a va 2 s  .  c  om
        JSONObject obj = new JSONObject(json);
        return obj.getString("error");
    } catch (JSONException e) {
        Log.e(TAG, "JSONException", e);
        return e.getMessage();
    }
}

From source file:org.eclipse.orion.server.authentication.formopenid.FormOpenIdLoginServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    String pathInfo = req.getPathInfo() == null ? "" : req.getPathInfo(); //$NON-NLS-1$

    if (pathInfo.startsWith("/form")) { //$NON-NLS-1$
        try {//from  ww w  . j a  va2 s.c  o m
            LoginResult authResult = FormAuthHelper.performAuthentication(req, resp);
            if (authResult == LoginResult.OK) {
                // redirection from
                // FormAuthenticationService.setNotAuthenticated
                String versionString = req.getHeader("Orion-Version"); //$NON-NLS-1$
                Version version = versionString == null ? null : new Version(versionString);

                // TODO: This is a workaround for calls
                // that does not include the WebEclipse version header
                String xRequestedWith = req.getHeader("X-Requested-With"); //$NON-NLS-1$

                if (version == null && !"XMLHttpRequest".equals(xRequestedWith)) { //$NON-NLS-1$
                    if (req.getParameter(OpenIdHelper.REDIRECT) != null
                            && !req.getParameter(OpenIdHelper.REDIRECT).equals("")) { //$NON-NLS-1$
                        resp.sendRedirect(req.getParameter(OpenIdHelper.REDIRECT));
                    }
                } else {
                    resp.setStatus(HttpServletResponse.SC_OK);
                    PrintWriter writer = resp.getWriter();
                    String uid = (String) req.getSession().getAttribute("user");
                    JSONObject userJson;
                    try {
                        userJson = FormAuthHelper.getUserJson(uid, req.getContextPath());
                        writer.print(userJson);
                        resp.setContentType("application/json"); //$NON-NLS-1$
                    } catch (JSONException e) {/* ignore */
                    }
                }
                resp.flushBuffer();
            } else if (authResult == LoginResult.BLOCKED) {
                displayError("Your account is not active. Please confirm your email before logging in.", req,
                        resp);
            } else {
                displayError("Invalid user or password", req, resp);
            }
        } catch (UnsupportedUserStoreException e) {
            LogHelper.log(e);
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        }
        return;
    }

    if (pathInfo.startsWith("/openid")) { //$NON-NLS-1$
        String openid = req.getParameter(OpenIdHelper.OPENID);
        if (openid != null) {
            try {
                consumer = OpenIdHelper.redirectToOpenIdProvider(req, resp, consumer);
            } catch (OpenIdException e) {
                LogHelper.log(new Status(IStatus.ERROR, Activator.PI_AUTHENTICATION_SERVLETS,
                        "An error occurred redirecting to OpenId provider", e));
                displayError(e.getMessage(), req, resp);
            }
            return;
        }

        String op_return = req.getParameter(OpenIdHelper.OP_RETURN);
        if (op_return != null) {
            try {
                OpenIdHelper.handleOpenIdReturnAndLogin(req, resp, consumer);
            } catch (OpenIdException e) {
                displayError(e.getMessage(), req, resp);
            }
            return;
        }
    }

    if (pathInfo.startsWith("/persona")) { //$NON-NLS-1$
        String assertion = req.getParameter(PersonaConstants.PARAM_ASSERTION);
        if (assertion != null) {
            try {
                new PersonaHelper().handleCredentialsAndLogin(req, resp);
            } catch (PersonaException e) {
                displayError(e.getMessage(), req, resp);
            }
        }
    }

    if (pathInfo.startsWith("/canaddusers")) {
        JSONObject jsonResp = new JSONObject();
        try {
            jsonResp.put("CanAddUsers", FormAuthHelper.canAddUsers());
            jsonResp.put("ForceEmail", FormAuthHelper.forceEmail());
            jsonResp.put("RegistrationURI", FormAuthHelper.registrationURI());
        } catch (JSONException e) {
        }
        resp.getWriter().print(jsonResp);
        resp.setContentType("application/json");
        return;
    }

    String user = req.getRemoteUser();
    if (user == null) {
        user = authenticationService.getAuthenticatedUser(req, resp,
                authenticationService.getDefaultAuthenticationProperties());
    }

    if (user != null) {
        resp.setStatus(HttpServletResponse.SC_OK);
        try {
            resp.getWriter().print(FormAuthHelper.getUserJson(user, req.getContextPath()));
        } catch (JSONException e) {
            handleException(resp, "An error occured when creating JSON object for logged in user", e);
        }
        return;
    }
}

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

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mHandler = new Handler();

    setContentView(R.layout.upload_photo_response);
    LayoutParams params = getWindow().getAttributes();
    params.width = LayoutParams.FILL_PARENT;
    params.height = LayoutParams.FILL_PARENT;
    getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);

    mOutput = (TextView) findViewById(R.id.apiOutput);
    mUsefulTip = (TextView) findViewById(R.id.usefulTip);
    mViewPhotoButton = (Button) findViewById(R.id.view_photo_button);
    mTagPhotoButton = (Button) findViewById(R.id.tag_photo_button);
    mUploadedPhoto = (ImageView) findViewById(R.id.uploadedPhoto);

    JSONObject json;//  w ww  . j  a  v a2s . co m
    try {
        json = Util.parseJson(response);
        final String photo_id = json.getString("id");
        this.photo_id = photo_id;

        mOutput.setText(json.toString(2));
        mUsefulTip.setText(activity.getString(R.string.photo_tip));
        Linkify.addLinks(mUsefulTip, Linkify.WEB_URLS);

        mViewPhotoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (hidePhoto) {
                    mViewPhotoButton.setText(R.string.view_photo);
                    hidePhoto = false;
                    mUploadedPhoto.setImageBitmap(null);
                } else {
                    hidePhoto = true;
                    mViewPhotoButton.setText(R.string.hide_photo);
                    /*
                     * Source tag: view_photo_tag
                     */
                    Bundle params = new Bundle();
                    params.putString("fields", "picture");
                    dialog = ProgressDialog.show(activity, "", activity.getString(R.string.please_wait), true,
                            true);
                    dialog.show();
                    Utility.mAsyncRunner.request(photo_id, params, new ViewPhotoRequestListener());
                }
            }
        });
        mTagPhotoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*
                 * Source tag: tag_photo_tag
                 */
                setTag();
            }
        });
    } catch (JSONException e) {
        setText(activity.getString(R.string.exception) + e.getMessage());
    } catch (FacebookError e) {
        setText(activity.getString(R.string.facebook_error) + e.getMessage());
    }
}

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 ww.jav  a  2  s.  c o  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:com.ifraag.facebookclient.FacebookClient.java

private Request prepPublishReq(String a_endPoint, Bundle a_postParams) {

    Request.Callback callback = new Request.Callback() {
        public void onCompleted(Response response) {
            JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
            String postId = null;
            try {
                postId = graphResponse.getString("id");
            } catch (JSONException e) {
                Log.i(FB_CLIENT_TAG, "JSON error " + e.getMessage());
            }/*from  w ww .  j  a  v  a  2 s . c om*/
            FacebookRequestError error = response.getError();
            if (error != null) {
                Log.i(FB_CLIENT_TAG, "Posting to wall faces an error which is: " + error.getErrorMessage());
            } else {
                Log.i(FB_CLIENT_TAG, "Posting to wall successfully with the following FB id: " + postId);
            }
        }
    };

    /* feed endpoint is used to post text only in your status while
    * checkins endpoint is used to post(check in) a place map into your status */
    return new Request(session, a_endPoint, a_postParams, HttpMethod.POST, callback);
}

From source file:com.wikitude.phonegap.WikitudePlugin.java

@Override
public boolean execute(final String action, final JSONArray args, final CallbackContext callContext) {

    /* hide architect-view -> destroy and remove from activity */
    if (WikitudePlugin.ACTION_CLOSE.equals(action)) {
        if (this.architectView != null) {
            this.cordova.getActivity().runOnUiThread(new Runnable() {

                @Override//from   ww w .  j  av a  2  s  .c  o  m
                public void run() {
                    removeArchitectView();
                }
            });
            callContext.success(action + ": architectView is present");
        } else {
            callContext.error(action + ": architectView is not present");
        }
        return true;
    }

    /* return success only if view is opened (no matter if visible or not) */
    if (WikitudePlugin.ACTION_STATE_ISOPEN.equals(action)) {
        if (this.architectView != null) {
            callContext.success(action + ": architectView is present");
        } else {
            callContext.error(action + ": architectView is not present");
        }
        return true;
    }

    /* return success only if view is opened (no matter if visible or not) */
    if (WikitudePlugin.ACTION_IS_DEVICE_SUPPORTED.equals(action)) {
        if (ArchitectView.isDeviceSupported(this.cordova.getActivity()) && hasNeonSupport()) {
            callContext.success(action + ": this device is ARchitect-ready");
        } else {
            callContext.error(action + action + ":Sorry, this device is NOT ARchitect-ready");
        }
        return true;
    }

    if (WikitudePlugin.ACTION_CAPTURE_SCREEN.equals(action)) {
        if (architectView != null) {

            int captureMode = ArchitectView.CaptureScreenCallback.CAPTURE_MODE_CAM_AND_WEBVIEW;

            try {
                captureMode = (args.getBoolean(0))
                        ? ArchitectView.CaptureScreenCallback.CAPTURE_MODE_CAM_AND_WEBVIEW
                        : ArchitectView.CaptureScreenCallback.CAPTURE_MODE_CAM;
            } catch (Exception e) {
                // unexpected error;
            }

            architectView.captureScreen(captureMode, new CaptureScreenCallback() {

                @Override
                public void onScreenCaptured(Bitmap screenCapture) {
                    try {
                        // final File imageDirectory = cordova.getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
                        final File imageDirectory = Environment.getExternalStorageDirectory();
                        if (imageDirectory == null) {
                            callContext.error("External storage not available");
                        }

                        final File screenCaptureFile = new File(imageDirectory,
                                System.currentTimeMillis() + ".jpg");

                        if (screenCaptureFile.exists()) {
                            screenCaptureFile.delete();
                        }
                        final FileOutputStream out = new FileOutputStream(screenCaptureFile);
                        screenCapture.compress(Bitmap.CompressFormat.JPEG, 90, out);
                        out.flush();
                        out.close();

                        cordova.getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                final String absoluteCaptureImagePath = screenCaptureFile.getAbsolutePath();
                                callContext.success(absoluteCaptureImagePath);

                                //                         in case you want to sent the pic to other applications, uncomment these lines (for future use)
                                //                        final Intent share = new Intent(Intent.ACTION_SEND);
                                //                        share.setType("image/jpg");
                                //                        share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(screenCaptureFile));
                                //                        final String chooserTitle = "Share Snaphot";
                                //                        cordova.getActivity().startActivity(Intent.createChooser(share, chooserTitle));
                            }
                        });
                    } catch (Exception e) {
                        callContext.error(e.getMessage());
                    }

                }
            });
            return true;
        }
    }

    /* life-cycle's RESUME */
    if (WikitudePlugin.ACTION_ON_RESUME.equals(action)) {

        if (this.architectView != null) {
            this.cordova.getActivity().runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    WikitudePlugin.this.architectView.onResume();
                    callContext.success(action + ": architectView is present");
                    locationProvider.onResume();
                }
            });

            // callContext.success( action + ": architectView is present" );
        } else {
            callContext.error(action + ": architectView is not present");
        }
        return true;
    }

    /* life-cycle's PAUSE */
    if (WikitudePlugin.ACTION_ON_PAUSE.equals(action)) {
        if (architectView != null) {
            this.cordova.getActivity().runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    WikitudePlugin.this.architectView.onPause();
                    locationProvider.onPause();
                }
            });

            callContext.success(action + ": architectView is present");
        } else {
            callContext.error(action + ": architectView is not present");
        }
        return true;
    }

    /* set visibility to "visible", return error if view is null */
    if (WikitudePlugin.ACTION_SHOW.equals(action)) {

        this.cordova.getActivity().runOnUiThread(new Runnable() {

            @Override
            public void run() {
                if (architectView != null) {
                    architectView.setVisibility(View.VISIBLE);
                    callContext.success(action + ": architectView is present");
                } else {
                    callContext.error(action + ": architectView is not present");
                }
            }
        });

        return true;
    }

    /* set visibility to "invisible", return error if view is null */
    if (WikitudePlugin.ACTION_HIDE.equals(action)) {

        this.cordova.getActivity().runOnUiThread(new Runnable() {

            @Override
            public void run() {
                if (architectView != null) {
                    architectView.setVisibility(View.INVISIBLE);
                    callContext.success(action + ": architectView is present");
                } else {
                    callContext.error(action + ": architectView is not present");
                }
            }
        });

        return true;
    }

    /* define call-back for url-invocations */
    if (WikitudePlugin.ACTION_ON_URLINVOKE.equals(action)) {
        this.urlInvokeCallback = callContext;
        final PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT,
                action + ": registered callback");
        result.setKeepCallback(true);
        callContext.sendPluginResult(result);
        return true;
    }

    /* location update */
    if (WikitudePlugin.ACTION_SET_LOCATION.equals(action)) {
        if (this.architectView != null) {
            try {
                final double lat = args.getDouble(0);
                final double lon = args.getDouble(1);
                float alt = Float.MIN_VALUE;
                try {
                    alt = (float) args.getDouble(2);
                } catch (Exception e) {
                    // invalid altitude -> ignore it
                }
                final float altitude = alt;
                Double acc = null;
                try {
                    acc = args.getDouble(3);
                } catch (Exception e) {
                    // invalid accuracy -> ignore it
                }
                final Double accuracy = acc;
                if (this.cordova != null && this.cordova.getActivity() != null) {
                    cordova.getActivity().runOnUiThread(
                            //                  this.cordova.getThreadPool().execute( 
                            new Runnable() {

                                @Override
                                public void run() {
                                    if (accuracy != null) {
                                        WikitudePlugin.this.architectView.setLocation(lat, lon, altitude,
                                                accuracy.floatValue());
                                    } else {
                                        WikitudePlugin.this.architectView.setLocation(lat, lon, altitude);
                                    }
                                }
                            });
                }

            } catch (Exception e) {
                callContext.error(
                        action + ": exception thrown, " + e != null ? e.getMessage() : "(exception is NULL)");
                return true;
            }
            callContext.success(action + ": updated location");
            return true;
        } else {
            /* return error if there is no architect-view active*/
            callContext.error(action + ": architectView is not present");
        }
        return true;
    }

    if (WikitudePlugin.ACTION_CALL_JAVASCRIPT.equals(action)) {

        String logMsg = null;
        try {
            final String callJS = args.getString(0);
            logMsg = callJS;

            this.cordova.getActivity().runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if (architectView != null) {
                        WikitudePlugin.this.architectView.callJavascript(callJS);
                    } else {
                        callContext.error(action + ": architectView is not present");
                    }
                }
            });

        } catch (JSONException je) {
            callContext.error(
                    action + ": exception thrown, " + je != null ? je.getMessage() : "(exception is NULL)");
            return true;
        }
        callContext.success(action + ": called js, '" + logMsg + "'");

        return true;
    }

    /* initial set-up, show ArchitectView full-screen in current screen/activity */
    if (WikitudePlugin.ACTION_OPEN.equals(action)) {
        this.openCallback = callContext;
        PluginResult result = null;
        try {
            final String apiKey = args.getString(0);
            final String filePath = args.getString(1);

            this.cordova.getActivity().runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    try {
                        WikitudePlugin.this.addArchitectView(apiKey, filePath);

                        /* call success method once architectView was added successfully */
                        if (openCallback != null) {
                            PluginResult result = new PluginResult(PluginResult.Status.OK);
                            result.setKeepCallback(false);
                            openCallback.sendPluginResult(result);
                        }
                    } catch (Exception e) {
                        /* in case "addArchitectView" threw an exception -> notify callback method asynchronously */
                        openCallback.error(e != null ? e.getMessage() : "Exception is 'null'");
                    }
                }
            });

        } catch (Exception e) {
            result = new PluginResult(PluginResult.Status.ERROR,
                    action + ": exception thown, " + e != null ? e.getMessage() : "(exception is NULL)");
            result.setKeepCallback(false);
            callContext.sendPluginResult(result);
            return true;
        }

        /* adding architect-view is done in separate thread, ensure to setKeepCallback so one can call success-method properly later on */
        result = new PluginResult(PluginResult.Status.NO_RESULT,
                action + ": no result required, just registered callback-method");
        result.setKeepCallback(true);
        callContext.sendPluginResult(result);
        return true;
    }

    /* fall-back return value */
    callContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "no such action: " + action));
    return false;
}

From source file:org.jabsorb.ng.serializer.impl.DictionarySerializer.java

@Override
public Object marshall(final SerializerState state, final Object p, final Object o) throws MarshallException {

    final Dictionary<?, ?> dictionary = (Dictionary<?, ?>) o;
    final JSONObject obj = new JSONObject();
    final JSONObject mapdata = new JSONObject();

    try {/*from   w w w. j  av  a2s .c om*/
        if (ser.getMarshallClassHints()) {
            obj.put("javaClass", o.getClass().getName());
        }
        obj.put("map", mapdata);
        state.push(o, mapdata, "map");
    } catch (final JSONException e) {
        throw new MarshallException("Could not put data" + e.getMessage(), e);
    }

    Object key = null;
    try {
        final Enumeration<?> en = dictionary.keys();
        while (en.hasMoreElements()) {
            key = en.nextElement();
            final String keyString = key.toString(); // only support String
                                                     // keys

            final Object json = ser.marshall(state, mapdata, dictionary.get(key), keyString);

            // omit the object entirely if it's a circular reference or
            // duplicate
            // it will be regenerated in the fixups phase
            if (JSONSerializer.CIRC_REF_OR_DUPLICATE != json) {
                mapdata.put(keyString, json);
            }
        }
    } catch (final MarshallException e) {
        throw new MarshallException("map key " + key + " " + e.getMessage(), e);
    } catch (final JSONException e) {
        throw new MarshallException("map key " + key + " " + e.getMessage(), e);
    } finally {
        state.pop();
    }
    return obj;
}

From source file:org.jabsorb.ng.serializer.impl.DictionarySerializer.java

@Override
public ObjectMatch tryUnmarshall(final SerializerState state, final Class<?> clazz, final Object o)
        throws UnmarshallException {

    final JSONObject jso = (JSONObject) o;
    String java_class;

    // Hint presence
    try {/*w  ww  . j av a  2 s. co m*/
        java_class = jso.getString("javaClass");
    } catch (final JSONException e) {
        throw new UnmarshallException("Could not read javaClass", e);
    }
    if (java_class == null) {
        throw new UnmarshallException("no type hint");
    }

    // Class compatibility check
    if (!classNameCheck(java_class)) {
        throw new UnmarshallException("not a Dictionary");
    }

    // JSON Format check
    JSONObject jsonmap;
    try {
        jsonmap = jso.getJSONObject("map");
    } catch (final JSONException e) {
        throw new UnmarshallException("map missing", e);
    }
    if (jsonmap == null) {
        throw new UnmarshallException("map missing");
    }

    // Content check
    final ObjectMatch m = new ObjectMatch(-1);
    state.setSerialized(o, m);

    final Iterator<?> i = jsonmap.keys();
    String key = null;
    try {
        while (i.hasNext()) {
            key = (String) i.next();
            m.setMismatch(ser.tryUnmarshall(state, null, jsonmap.get(key)).max(m).getMismatch());
        }
    } catch (final UnmarshallException e) {
        throw new UnmarshallException("key " + key + " " + e.getMessage(), e);
    } catch (final JSONException e) {
        throw new UnmarshallException("key " + key + " " + e.getMessage(), e);
    }

    return m;
}