Example usage for org.json JSONObject optBoolean

List of usage examples for org.json JSONObject optBoolean

Introduction

In this page you can find the example usage for org.json JSONObject optBoolean.

Prototype

public boolean optBoolean(String key, boolean defaultValue) 

Source Link

Document

Get an optional boolean associated with a key.

Usage

From source file:org.eclipse.orion.server.cf.handlers.v1.AppsHandlerV1.java

@Override
protected CFJob handlePut(App resource, HttpServletRequest request, HttpServletResponse response,
        final String pathString) {
    final JSONObject targetJSON2 = extractJSONData(
            IOUtilities.getQueryParameter(request, CFProtocolConstants.KEY_TARGET));

    IPath path = pathString != null ? new Path(pathString) : new Path("");
    final String appGuid = path.segment(0);
    boolean addRoute = "routes".equals(path.segment(1));
    final String routeGuid = addRoute ? path.segment(2) : null;

    if (addRoute)
        return new CFJob(request, false) {
            @Override// w ww .ja v a2s. c o m
            protected IStatus performJob() {
                try {
                    ComputeTargetCommand computeTarget = new ComputeTargetCommand(this.userId, targetJSON2);
                    IStatus status = computeTarget.doIt();
                    if (!status.isOK())
                        return status;
                    Target target = computeTarget.getTarget();

                    GetAppByGuidCommand getAppByGuid = new GetAppByGuidCommand(target.getCloud(), appGuid);
                    IStatus getAppByGuidStatus = getAppByGuid.doIt();
                    if (!getAppByGuidStatus.isOK())
                        return getAppByGuidStatus;
                    App app = getAppByGuid.getApp();

                    GetRouteByGuidCommand getRouteByGuid = new GetRouteByGuidCommand(target.getCloud(),
                            routeGuid);
                    IStatus getRouteByGuidStatus = getRouteByGuid.doIt();
                    if (!getRouteByGuidStatus.isOK())
                        return getRouteByGuidStatus;
                    Route route = getRouteByGuid.getRoute();

                    MapRouteCommand unmapRoute = new MapRouteCommand(target, app, route.getGuid());
                    return unmapRoute.doIt();
                } catch (Exception e) {
                    String msg = NLS.bind("Failed to handle request for {0}", pathString); //$NON-NLS-1$
                    ServerStatus status = new ServerStatus(IStatus.ERROR,
                            HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
                    logger.error(msg, e);
                    return status;
                }
            }
        };

    final JSONObject jsonData = extractJSONData(request);
    final JSONObject targetJSON = jsonData.optJSONObject(CFProtocolConstants.KEY_TARGET);

    final String state = jsonData.optString(CFProtocolConstants.KEY_STATE, null);
    final String appName = jsonData.optString(CFProtocolConstants.KEY_NAME, null);
    final String contentLocation = ServletResourceHandler.toOrionLocation(request,
            jsonData.optString(CFProtocolConstants.KEY_CONTENT_LOCATION, null));

    /* default application startup is one minute */
    int userTimeout = jsonData.optInt(CFProtocolConstants.KEY_TIMEOUT, 60);
    final int timeout = (userTimeout > 0) ? userTimeout : 0;

    /* TODO: The force shouldn't be always with us */
    final boolean force = jsonData.optBoolean(CFProtocolConstants.KEY_FORCE, true);

    return new CFJob(request, false) {
        @Override
        protected IStatus performJob() {
            try {
                ComputeTargetCommand computeTarget = new ComputeTargetCommand(this.userId, targetJSON);
                IStatus status = computeTarget.doIt();
                if (!status.isOK())
                    return status;
                Target target = computeTarget.getTarget();

                /* parse the application manifest */
                String manifestAppName = null;
                ParseManifestCommand parseManifestCommand = null;
                if (contentLocation != null) {
                    parseManifestCommand = new ParseManifestCommand(target, this.userId, contentLocation);
                    status = parseManifestCommand.doIt();
                    if (!status.isOK())
                        return status;

                    /* get the manifest name */
                    ManifestParseTree manifest = parseManifestCommand.getManifest();
                    if (manifest != null) {
                        ManifestParseTree applications = manifest.get(CFProtocolConstants.V2_KEY_APPLICATIONS);
                        if (applications.getChildren().size() > 0)
                            manifestAppName = applications.get(0).get(CFProtocolConstants.V2_KEY_NAME)
                                    .getValue();
                    }
                }

                GetAppCommand getAppCommand = new GetAppCommand(target,
                        appName != null ? appName : manifestAppName);
                status = getAppCommand.doIt();
                App app = getAppCommand.getApp();

                if (CFProtocolConstants.KEY_STARTED.equals(state)) {
                    if (!status.isOK())
                        return status;
                    return new StartAppCommand(target, app, timeout).doIt();
                } else if (CFProtocolConstants.KEY_STOPPED.equals(state)) {
                    if (!status.isOK())
                        return status;
                    return new StopAppCommand(target, app).doIt();
                } else {
                    if (parseManifestCommand == null) {
                        String msg = NLS.bind("Failed to handle request for {0}", pathString); //$NON-NLS-1$
                        status = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                msg, null);
                        logger.error(msg);
                        return status;
                    }
                }

                // push new application
                if (app == null)
                    app = new App();

                app.setName(appName != null ? appName : manifestAppName);
                app.setManifest(parseManifestCommand.getManifest());

                status = new PushAppCommand(target, app, parseManifestCommand.getAppStore(), force).doIt();
                if (!status.isOK())
                    return status;

                // get the app again
                getAppCommand = new GetAppCommand(target, app.getName());
                getAppCommand.doIt();
                app = getAppCommand.getApp();
                app.setManifest(parseManifestCommand.getManifest());

                new StartAppCommand(target, app).doIt();

                return status;
            } catch (Exception e) {
                String msg = NLS.bind("Failed to handle request for {0}", pathString); //$NON-NLS-1$
                ServerStatus status = new ServerStatus(IStatus.ERROR,
                        HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
                logger.error(msg, e);
                return status;
            }
        }
    };
}

From source file:net.geco.model.iojson.PersistentStore.java

public void importCourses(JSONStore store, Registry registry, Factory factory) throws JSONException {
    JSONArray courses = store.getJSONArray(K.COURSES);
    for (int i = 0; i < courses.length(); i++) {
        JSONObject c = courses.getJSONObject(i);
        Course course = store.register(factory.createCourse(), c.getInt(K.ID));
        course.setName(c.getString(K.NAME));
        course.setLength(c.getInt(K.LENGTH));
        course.setClimb(c.getInt(K.CLIMB));
        course.setMassStartTime(new Date(c.optLong(K.START, TimeManager.NO_TIME_l))); // MIGR v2.x -> v2.2
        course.setCourseSet(store.retrieve(c.optInt(K.COURSESET, 0), CourseSet.class));
        JSONArray codez = c.getJSONArray(K.CODES);
        int[] codes = new int[codez.length()];
        for (int j = 0; j < codes.length; j++) {
            codes[j] = codez.getInt(j);//from  www. j a v a  2 s  .  com
        }
        course.setCodes(codes);
        if (c.has(K.SECTIONS)) {
            JSONArray sectionz = c.getJSONArray(K.SECTIONS);
            for (int j = 0; j < sectionz.length(); j++) {
                JSONObject sectionTuple = sectionz.getJSONObject(j);
                Section section = store.register(factory.createSection(), sectionTuple.getInt(K.ID));
                section.setStartIndex(sectionTuple.getInt(K.START_ID));
                section.setName(sectionTuple.getString(K.NAME));
                section.setType(SectionType.valueOf(sectionTuple.getString(K.TYPE)));
                section.setNeutralized(sectionTuple.optBoolean(K.NEUTRALIZED, false));
                course.putSection(section);
            }
            course.refreshSectionCodes();
        }
        registry.addCourse(course);
    }
    registry.ensureAutoCourse(factory);
}

From source file:com.example.wcl.test_weiboshare.Status.java

public static Status parse(JSONObject jsonObject) {
    if (null == jsonObject) {
        return null;
    }//from www .  java  2  s . c  o  m

    Status status = new Status();
    status.created_at = jsonObject.optString("created_at");
    status.id = jsonObject.optString("id");
    status.mid = jsonObject.optString("mid");
    status.idstr = jsonObject.optString("idstr");
    status.text = jsonObject.optString("text");
    status.source = jsonObject.optString("source");
    status.favorited = jsonObject.optBoolean("favorited", false);
    status.truncated = jsonObject.optBoolean("truncated", false);

    // Have NOT supported
    status.in_reply_to_status_id = jsonObject.optString("in_reply_to_status_id");
    status.in_reply_to_user_id = jsonObject.optString("in_reply_to_user_id");
    status.in_reply_to_screen_name = jsonObject.optString("in_reply_to_screen_name");

    status.thumbnail_pic = jsonObject.optString("thumbnail_pic");
    status.bmiddle_pic = jsonObject.optString("bmiddle_pic");
    status.original_pic = jsonObject.optString("original_pic");
    status.geo = Geo.parse(jsonObject.optJSONObject("geo"));
    status.user = User.parse(jsonObject.optJSONObject("user"));
    status.retweeted_status = Status.parse(jsonObject.optJSONObject("retweeted_status"));
    status.reposts_count = jsonObject.optInt("reposts_count");
    status.comments_count = jsonObject.optInt("comments_count");
    status.attitudes_count = jsonObject.optInt("attitudes_count");
    status.mlevel = jsonObject.optInt("mlevel", -1); // Have NOT supported
    status.visible = Visible.parse(jsonObject.optJSONObject("visible"));

    JSONArray picUrlsArray = jsonObject.optJSONArray("pic_urls");
    if (picUrlsArray != null && picUrlsArray.length() > 0) {
        int length = picUrlsArray.length();
        status.pic_urls = new ArrayList<String>(length);
        JSONObject tmpObject = null;
        for (int ix = 0; ix < length; ix++) {
            tmpObject = picUrlsArray.optJSONObject(ix);
            if (tmpObject != null) {
                status.pic_urls.add(tmpObject.optString("thumbnail_pic"));
            }
        }
    }

    //status.ad = jsonObject.optString("ad", "");

    return status;
}

From source file:com.marianhello.cordova.bgloc.Config.java

public static Config fromJSONArray(JSONArray data) throws JSONException {
    JSONObject jObject = data.getJSONObject(0);
    Config config = new Config();
    config.setStationaryRadius((float) jObject.optDouble("stationaryRadius", config.getStationaryRadius()));
    config.setDistanceFilter(jObject.optInt("distanceFilter", config.getDistanceFilter()));
    config.setDesiredAccuracy(jObject.optInt("desiredAccuracy", config.getDesiredAccuracy()));
    config.setDebugging(jObject.optBoolean("debug", config.isDebugging()));
    config.setNotificationTitle(jObject.optString("notificationTitle", config.getNotificationTitle()));
    config.setNotificationText(jObject.optString("notificationText", config.getNotificationText()));
    config.setStopOnTerminate(jObject.optBoolean("stopOnTerminate", config.getStopOnTerminate()));
    config.setStartOnBoot(jObject.optBoolean("startOnBoot", config.getStartOnBoot()));
    config.setServiceProvider(jObject.optInt("locationService", config.getServiceProvider().asInt()));
    config.setInterval(jObject.optInt("interval", config.getInterval()));
    config.setFastestInterval(jObject.optInt("fastestInterval", config.getFastestInterval()));
    config.setActivitiesInterval(jObject.optInt("activitiesInterval", config.getActivitiesInterval()));
    config.setNotificationIconColor(//from  ww w . j  ava 2 s  .c om
            jObject.optString("notificationIconColor", config.getNotificationIconColor()));
    config.setLargeNotificationIcon(
            jObject.optString("notificationIconLarge", config.getLargeNotificationIcon()));
    config.setSmallNotificationIcon(
            jObject.optString("notificationIconSmall", config.getSmallNotificationIcon()));
    config.setStartForeground(jObject.optBoolean("startForeground", config.getStartForeground()));
    config.setUrl(jObject.optString("url", config.getUrl()));
    config.setMethod(jObject.optString("method", config.getMethod()));
    config.setHeaders(jObject.optJSONObject("headers"));
    config.setParams(jObject.optJSONObject("params"));
    return config;
}

From source file:org.uiautomation.ios.wkrdp.internal.WebKitRemoteDebugProtocol.java

public synchronized JSONObject sendWebkitCommand(JSONObject command, int pageId) {
    String sender = generateSenderString(pageId);
    try {//  ww  w .  j  a va  2 s  . c  o  m
        commandId++;
        command.put("id", commandId);

        long start = System.currentTimeMillis();

        String xml = plist.JSONCommand(command);
        Map<String, String> var = ImmutableMap.of("$WIRConnectionIdentifierKey", connectionId, "$bundleId",
                bundleId, "$WIRSenderKey", sender, "$WIRPageIdentifierKey", "" + pageId);
        for (String key : var.keySet()) {
            xml = xml.replace(key, var.get(key));
        }
        sendMessage(xml);
        JSONObject response = handler.getResponse(command.getInt("id"));
        JSONObject error = response.optJSONObject("error");
        if (error != null) {
            throw new RemoteExceptionException(error, command);
        } else if (response.optBoolean("wasThrown", false)) {
            throw new WebDriverException("remote JS exception " + response.toString(2));
        } else {
            log.fine(System.currentTimeMillis() + "\t\t" + (System.currentTimeMillis() - start) + "ms\t"
                    + command.getString("method") + " " + command);
            JSONObject res = response.getJSONObject("result");
            if (res == null) {
                System.err.println("GOT a null result from " + response.toString(2));
            }
            return res;
        }
    } catch (JSONException e) {
        throw new WebDriverException(e);
    }
}

From source file:com.app.plugins.childBrowser.ChildBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 * @param jsonObject /*  w w w. ja va2  s  . co m*/
 */
public String showWebPage(final String url, JSONObject options) {
    // Determine if we should hide the location bar.
    if (options != null) {
        showLocationBar = options.optBoolean("showLocationBar", false);
    }

    final WebView parent = this.webView;

    // Create dialog in new thread 
    Runnable runnable = new Runnable() {
        public void run() {
            dialog = new Dialog(cordova.getActivity(), android.R.style.Theme_Black_NoTitleBar_Fullscreen);

            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);
            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                public void onDismiss(DialogInterface dialog) {
                    try {
                        JSONObject obj = new JSONObject();
                        obj.put("type", CLOSE_EVENT);

                        sendUpdate(obj, false);
                    } catch (JSONException e) {
                        Log.d(LOG_TAG, "Should never happen");
                    }
                }
            });

            //LinearLayout.LayoutParams backParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
            //LinearLayout.LayoutParams forwardParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
            //LinearLayout.LayoutParams editParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT, 1.0f);
            LinearLayout.LayoutParams closeParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            LinearLayout.LayoutParams wvParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
                    LayoutParams.FILL_PARENT);

            LinearLayout main = new LinearLayout(cordova.getActivity());
            main.setOrientation(LinearLayout.VERTICAL);

            LinearLayout toolbar = new LinearLayout(cordova.getActivity());
            toolbar.setOrientation(LinearLayout.HORIZONTAL);

            /*
            ImageButton back = new ImageButton((Context) ctx);
            back.getBackground().setAlpha(0);
            back.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                goBack();
            }
            });
            back.setId(1);
            try {
            back.setImageBitmap(loadDrawable("plugins/childbrowser/icon_arrow_left.png"));
            } catch (IOException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
            }
            back.setLayoutParams(backParams);
                    
            ImageButton forward = new ImageButton((Context) ctx);
            forward.getBackground().setAlpha(0);
            forward.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                goForward();
            }
            });
            forward.setId(2);
            try {
            forward.setImageBitmap(loadDrawable("plugins/childbrowser/icon_arrow_right.png"));
            } catch (IOException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
            }               
            forward.setLayoutParams(forwardParams);
            */

            /*
            edittext = new EditText((Context) ctx);
            edittext.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // If the event is a key-down event on the "enter" button
                if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                  navigate(edittext.getText().toString());
                  return true;
                }
                return false;
            }
            });
            edittext.setId(3);
            edittext.setSingleLine(true);
            edittext.setText(url);
            edittext.setLayoutParams(editParams);
            */
            //edittext = new EditText((Context) ctx);
            //edittext.setVisibility(View.GONE);

            LinearLayout.LayoutParams titleParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.FILL_PARENT, 1.0f);
            TextView title = new TextView(cordova.getActivity());
            title.setId(1);
            title.setLayoutParams(titleParams);
            title.setGravity(Gravity.CENTER_VERTICAL);
            title.setTypeface(null, Typeface.BOLD);

            ImageButton close = new ImageButton(cordova.getActivity());
            close.getBackground().setAlpha(0);
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });
            close.setId(4);
            try {
                close.setImageBitmap(loadDrawable("plugins/childbrowser/icon_close.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            close.setLayoutParams(closeParams);

            childWebView = new WebView(cordova.getActivity());
            childWebView.getSettings().setJavaScriptEnabled(true);
            childWebView.getSettings().setBuiltInZoomControls(true);
            WebViewClient client = new ChildBrowserClient(parent, ctx, title/*, edittext*/);
            childWebView.setWebViewClient(client);
            childWebView.loadUrl(url);
            childWebView.setId(5);
            childWebView.setInitialScale(0);
            childWebView.setLayoutParams(wvParams);
            childWebView.requestFocus();
            childWebView.requestFocusFromTouch();

            //toolbar.addView(back);
            //toolbar.addView(forward);
            //toolbar.addView(edittext);
            toolbar.addView(close);
            toolbar.addView(title);

            if (getShowLocationBar()) {
                main.addView(toolbar);
            }
            main.addView(childWebView);

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(dialog.getWindow().getAttributes());
            lp.width = WindowManager.LayoutParams.FILL_PARENT;
            lp.height = WindowManager.LayoutParams.FILL_PARENT;
            lp.verticalMargin = 0f;
            lp.horizontalMargin = 0f;

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
        }

        private Bitmap loadDrawable(String filename) throws java.io.IOException {
            InputStream input = cordova.getActivity().getAssets().open(filename);
            return BitmapFactory.decodeStream(input);
        }
    };
    this.cordova.getActivity().runOnUiThread(runnable);
    return "";
}

From source file:com.mparticle.internal.ConfigManager.java

public synchronized void updateConfig(JSONObject responseJSON, boolean persistJson) throws JSONException {
    SharedPreferences.Editor editor = mPreferences.edit();
    if (persistJson) {
        saveConfigJson(responseJSON);/*from   ww  w. ja  v a 2s .  c  om*/
    }

    if (responseJSON.has(KEY_UNHANDLED_EXCEPTIONS)) {
        mLogUnhandledExceptions = responseJSON.getString(KEY_UNHANDLED_EXCEPTIONS);
    }

    if (responseJSON.has(KEY_PUSH_MESSAGES)) {
        sPushKeys = responseJSON.getJSONArray(KEY_PUSH_MESSAGES);
        editor.putString(KEY_PUSH_MESSAGES, sPushKeys.toString());
    }

    mRampValue = responseJSON.optInt(KEY_RAMP, -1);

    if (responseJSON.has(KEY_OPT_OUT)) {
        mSendOoEvents = responseJSON.getBoolean(KEY_OPT_OUT);
    } else {
        mSendOoEvents = false;
    }

    if (responseJSON.has(ProviderPersistence.KEY_PERSISTENCE)) {
        setProviderPersistence(new ProviderPersistence(responseJSON, mContext));
    } else {
        setProviderPersistence(null);
    }

    mSessionTimeoutInterval = responseJSON.optInt(KEY_SESSION_TIMEOUT, -1);
    mUploadInterval = responseJSON.optInt(KEY_UPLOAD_INTERVAL, -1);

    mTriggerMessageMatches = null;
    mTriggerMessageHashes = null;
    if (responseJSON.has(KEY_TRIGGER_ITEMS)) {
        try {
            JSONObject items = responseJSON.getJSONObject(KEY_TRIGGER_ITEMS);
            if (items.has(KEY_MESSAGE_MATCHES)) {
                mTriggerMessageMatches = items.getJSONArray(KEY_MESSAGE_MATCHES);
            }
            if (items.has(KEY_TRIGGER_ITEM_HASHES)) {
                mTriggerMessageHashes = items.getJSONArray(KEY_TRIGGER_ITEM_HASHES);
            }
        } catch (JSONException jse) {

        }

    }

    if (responseJSON.has(KEY_INFLUENCE_OPEN)) {
        mInfluenceOpenTimeout = responseJSON.getLong(KEY_INFLUENCE_OPEN) * 60 * 1000;
    } else {
        mInfluenceOpenTimeout = 30 * 60 * 1000;
    }

    mRestrictAAIDfromLAT = responseJSON.optBoolean(KEY_AAID_LAT, true);
    mIncludeSessionHistory = responseJSON.optBoolean(KEY_INCLUDE_SESSION_HISTORY, true);
    if (responseJSON.has(KEY_DEVICE_PERFORMANCE_METRICS_DISABLED)) {
        MParticle.setDevicePerformanceMetricsDisabled(
                responseJSON.optBoolean(KEY_DEVICE_PERFORMANCE_METRICS_DISABLED, false));
    }

    editor.apply();
    applyConfig();

    MParticle.getInstance().getKitManager().updateKits(responseJSON.optJSONArray(KEY_EMBEDDED_KITS));
}

From source file:com.phonegap.plugins.childbrowser.ChildBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 * @param jsonObject//from   www .  j  ava 2s . co m
 */
public String showWebPage(final String url, JSONObject options) {
    // Determine if we should hide the location bar.
    if (options != null) {
        showLocationBar = options.optBoolean("showLocationBar", true);
        showNavigationBar = options.optBoolean("showNavigationBar", true);
        showAddress = options.optBoolean("showAddress", true);
    }

    // Create dialog in new thread
    Runnable runnable = new Runnable() {
        public void run() {
            dialog = new Dialog((Context) cordova.getActivity());

            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);
            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                public void onDismiss(DialogInterface dialog) {
                    webview.stopLoading();
                    try {
                        JSONObject obj = new JSONObject();
                        obj.put("type", CLOSE_EVENT);

                        sendUpdate(obj, false);
                    } catch (JSONException e) {
                        Log.d(LOG_TAG, "Should never happen");
                    }
                }
            });

            LinearLayout.LayoutParams backParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            LinearLayout.LayoutParams forwardParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            LinearLayout.LayoutParams editParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT, 1.0f);
            LinearLayout.LayoutParams closeParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            LinearLayout.LayoutParams wvParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
                    LayoutParams.FILL_PARENT);
            if (!showAddress) // larger buttons if address bar is not visible
            {
                backParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT,
                        1.0f);
                forwardParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
                        LayoutParams.WRAP_CONTENT, 1.0f);
                closeParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT,
                        1.0f);
            }

            LinearLayout main = new LinearLayout((Context) cordova.getActivity());
            main.setOrientation(LinearLayout.VERTICAL);

            LinearLayout toolbar = new LinearLayout((Context) cordova.getActivity());
            toolbar.setOrientation(LinearLayout.HORIZONTAL);

            ImageButton back = new ImageButton((Context) cordova.getActivity());
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });
            back.setId(1);
            try {
                back.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_left.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            back.setLayoutParams(backParams);

            ImageButton forward = new ImageButton((Context) cordova.getActivity());
            forward.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goForward();
                }
            });
            forward.setId(2);
            try {
                forward.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_right.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            forward.setLayoutParams(forwardParams);

            edittext = new EditText((Context) cordova.getActivity());
            edittext.setOnKeyListener(new View.OnKeyListener() {
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    // If the event is a key-down event on the "enter" button
                    if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                        navigate(edittext.getText().toString());
                        return true;
                    }
                    return false;
                }
            });
            edittext.setId(3);
            edittext.setSingleLine(true);
            edittext.setText(url);
            edittext.setLayoutParams(editParams);

            ImageButton close = new ImageButton(cordova.getActivity());
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });
            close.setId(4);
            try {
                close.setImageBitmap(loadDrawable("www/childbrowser/icon_close.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            close.setLayoutParams(closeParams);

            webview = new WebView((Context) cordova.getActivity());
            webview.getSettings().setJavaScriptEnabled(true);
            webview.getSettings().setBuiltInZoomControls(true);
            WebViewClient client = new ChildBrowserClient(cordova, edittext);
            webview.setWebViewClient(client);
            webview.loadUrl(url);
            webview.setId(5);
            webview.setInitialScale(0);
            webview.setLayoutParams(wvParams);
            webview.requestFocus();
            webview.requestFocusFromTouch();
            webview.getSettings().setUseWideViewPort(true);
            webview.getSettings().setLoadWithOverviewMode(true);
            toolbar.addView(back);
            toolbar.addView(forward);
            toolbar.addView(edittext);
            toolbar.addView(close);

            if (getShowLocationBar()) {
                main.addView(toolbar);
            }
            main.addView(webview);

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(dialog.getWindow().getAttributes());
            lp.width = WindowManager.LayoutParams.FILL_PARENT;
            lp.height = WindowManager.LayoutParams.FILL_PARENT;

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);

            if (!showNavigationBar) {
                back.setVisibility(View.GONE);
                forward.setVisibility(View.GONE);
                close.setVisibility(View.GONE);
            }
            if (!showAddress) {
                edittext.setVisibility(View.GONE);
            }
        }

        private Bitmap loadDrawable(String filename) throws java.io.IOException {
            InputStream input = cordova.getActivity().getAssets().open(filename);
            return BitmapFactory.decodeStream(input);
        }
    };
    cordova.getActivity().runOnUiThread(runnable);
    return "";
}

From source file:com.taobao.wuzhong.plugins.ChildBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 * @param jsonObject// w w  w .  j  a  v a  2  s . c  o  m
 */
public String showWebPage(final String url, JSONObject options) {
    // Determine if we should hide the location bar.
    if (options != null) {
        showLocationBar = options.optBoolean("showLocationBar", true);
    }

    // Create dialog in new thread
    Runnable runnable = new Runnable() {
        public void run() {
            dialog = new Dialog(ctx.getContext(), android.R.style.Theme_Translucent_NoTitleBar);

            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);
            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                public void onDismiss(DialogInterface dialog) {
                    try {
                        JSONObject obj = new JSONObject();
                        obj.put("type", CLOSE_EVENT);

                        sendUpdate(obj, false);
                    } catch (JSONException e) {
                        Log.d(LOG_TAG, "Should never happen");
                    }
                }
            });

            LinearLayout.LayoutParams backParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            LinearLayout.LayoutParams forwardParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            LinearLayout.LayoutParams editParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT, 1.0f);
            LinearLayout.LayoutParams closeParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            LinearLayout.LayoutParams wvParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
                    LayoutParams.FILL_PARENT);

            LinearLayout main = new LinearLayout(ctx.getContext());
            main.setOrientation(LinearLayout.VERTICAL);

            LinearLayout toolbar = new LinearLayout(ctx.getContext());
            toolbar.setLayoutParams(
                    new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            toolbar.setOrientation(LinearLayout.HORIZONTAL);

            ImageButton back = new ImageButton(ctx.getContext());
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });
            back.setId(1);
            try {
                back.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_left.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            back.setLayoutParams(backParams);

            ImageButton forward = new ImageButton(ctx.getContext());
            forward.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goForward();
                }
            });
            forward.setId(2);
            try {
                forward.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_right.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            forward.setLayoutParams(forwardParams);

            edittext = new EditText(ctx.getContext());
            edittext.setOnKeyListener(new View.OnKeyListener() {
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    // If the event is a key-down event on the "enter" button
                    if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                        navigate(edittext.getText().toString());
                        return true;
                    }
                    return false;
                }
            });
            edittext.setId(3);
            edittext.setSingleLine(true);
            edittext.setText(url);
            edittext.setLayoutParams(editParams);

            ImageButton close = new ImageButton(ctx.getContext());
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });
            close.setId(4);
            try {
                close.setImageBitmap(loadDrawable("www/childbrowser/icon_close.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            close.setLayoutParams(closeParams);

            webview = new WebView(ctx.getContext());
            webview.setWebChromeClient(new WebChromeClient());
            WebViewClient client = new ChildBrowserClient(edittext);
            webview.setWebViewClient(client);
            WebSettings settings = webview.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setBuiltInZoomControls(true);
            settings.setPluginsEnabled(true);
            settings.setDomStorageEnabled(true);
            webview.loadUrl(url);
            webview.setId(5);
            webview.setInitialScale(0);
            webview.setLayoutParams(wvParams);
            webview.requestFocus();
            webview.requestFocusFromTouch();

            toolbar.addView(back);
            toolbar.addView(forward);
            toolbar.addView(edittext);
            toolbar.addView(close);

            if (getShowLocationBar()) {
                main.addView(toolbar);
            }
            main.addView(webview);

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(dialog.getWindow().getAttributes());
            lp.width = WindowManager.LayoutParams.FILL_PARENT;
            lp.height = WindowManager.LayoutParams.FILL_PARENT;

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
        }

        private Bitmap loadDrawable(String filename) throws java.io.IOException {
            InputStream input = ctx.getAssets().open(filename);
            return BitmapFactory.decodeStream(input);
        }
    };
    this.ctx.runOnUiThread(runnable);
    return "";
}

From source file:com.nokia.example.capturetheflag.network.model.Game.java

public Game(final JSONObject jsonObj) throws JSONException {
    this(jsonObj.getInt(ModelConstants.ID_KEY));
    setName(jsonObj.getString(ModelConstants.NAME_KEY));
    JSONArray jsonArray = jsonObj.getJSONArray(ModelConstants.PLAYERS_KEY);

    for (int i = 0; i < jsonArray.length(); i++) {
        Player p = new Player(jsonArray.getJSONObject(i));
        addPlayer(p);//ww  w.  j  a  va 2  s.  c om
    }

    JSONObject redflag = jsonObj.getJSONObject(ModelConstants.RED_FLAG_KEY);
    JSONObject blueflag = jsonObj.getJSONObject(ModelConstants.BLUE_FLAG_KEY);

    mRedFlag = new Flag(redflag.getDouble(ModelConstants.LATITUDE_KEY),
            redflag.getDouble(ModelConstants.LONGITUDE_KEY));
    mBlueFlag = new Flag(blueflag.getDouble(ModelConstants.LATITUDE_KEY),
            blueflag.getDouble(ModelConstants.LONGITUDE_KEY));

    mIsPremium = jsonObj.optBoolean(ModelConstants.IS_PREMIUM_KEY, false);
}