Example usage for com.google.gwt.json.client JSONValue isObject

List of usage examples for com.google.gwt.json.client JSONValue isObject

Introduction

In this page you can find the example usage for com.google.gwt.json.client JSONValue isObject.

Prototype

public JSONObject isObject() 

Source Link

Document

Returns non-null if this JSONValue is really a JSONObject.

Usage

From source file:net.wespot.gwt.client.Account.java

License:Open Source License

public void loadPage() {
    final DynamicForm form = new DynamicForm();

    form.setUseAllDataSourceFields(true);

    HeaderItem header = new HeaderItem();
    header.setDefaultValue("Registration Form");
    LengthRangeValidator lengthRangeValidator = new LengthRangeValidator();
    lengthRangeValidator.setMin(3);/*from  w  w  w . java  2s.  c  o  m*/
    lengthRangeValidator.setErrorMessage("Value should be longer then 3 characters");

    final TextItem userName = new TextItem();
    userName.setName("username");
    userName.setTitle("Choose a username");
    userName.addChangedHandler(new ChangedHandler() {
        @Override
        public void onChanged(ChangedEvent event) {
            final String username = (String) event.getValue();
            AccountClient.getInstance().accountExists(form.getValueAsString("username"), new JsonCallback() {
                public void onJsonReceived(JSONValue jsonValue) {
                    //                        SC.showPrompt(jsonValue.toString());
                    if (jsonValue.isObject() != null) {
                        accountExistsMap.put(username,
                                jsonValue.isObject().get("accountExists").isBoolean().booleanValue());
                        userName.validate();
                    }
                }
            });
        }
    });
    CustomValidator accountDoesNotExist = new CustomValidator() {
        @Override
        protected boolean condition(Object value) {
            if (accountExistsMap.containsKey(form.getValueAsString("username"))) {
                return !accountExistsMap.get(form.getValueAsString("username"));
            }
            return false;
        }
    };
    accountDoesNotExist.setErrorMessage("Name exists, choose another username");

    CustomValidator notNullValidator = new CustomValidator() {
        @Override
        protected boolean condition(Object value) {

            return value != null;
        }
    };
    notNullValidator.setErrorMessage("Value must not be empty");

    userName.setValidators(accountDoesNotExist, lengthRangeValidator, notNullValidator);

    TextItem name = new TextItem();
    name.setName("firstname");
    name.setTitle("First Name");
    name.setValidators(notNullValidator, lengthRangeValidator);

    TextItem familyName = new TextItem();
    familyName.setName("familyName");
    familyName.setTitle("Last Name");
    familyName.setValidators(notNullValidator, lengthRangeValidator);

    TextItem email = new TextItem();
    email.setName("email");
    email.setTitle("E-mail");
    RegExpValidator emailValidator = new RegExpValidator();
    emailValidator.setErrorMessage("Invalid email address");
    emailValidator.setExpression("^([a-zA-Z0-9_.\\-+])+@(([a-zA-Z0-9\\-])+\\.)+[a-zA-Z0-9]{2,4}$");

    email.setValidators(notNullValidator, emailValidator);

    TextItem pictureUrl = new TextItem();
    pictureUrl.setName("pictureUrl");
    pictureUrl.setTitle("Picture url (optional)");

    PasswordItem passwordItem = new PasswordItem();
    passwordItem.setName("password");
    passwordItem.setValidators(notNullValidator);

    PasswordItem passwordItem2 = new PasswordItem();
    passwordItem2.setName("password2");
    passwordItem2.setTitle("Password Again");
    passwordItem2.setRequired(true);
    passwordItem2.setLength(20);

    MatchesFieldValidator matchesValidator = new MatchesFieldValidator();
    matchesValidator.setOtherField("password");
    matchesValidator.setErrorMessage("Passwords do not match");
    passwordItem2.setValidators(matchesValidator);

    CheckboxItem acceptItem = new CheckboxItem();
    acceptItem.setName("acceptTerms");
    acceptItem.setTitle("I accept the terms of use.");
    acceptItem.setDefaultValue(false);
    CustomValidator isTrueValidator = new CustomValidator() {

        @Override
        protected boolean condition(Object value) {
            if (new Boolean(true).equals(value))
                return true;
            return false;
        }

    };
    isTrueValidator.setErrorMessage("You must accept the terms of use to continue");
    acceptItem.setValidators(isTrueValidator);

    acceptItem.setWidth(150);

    ButtonItem validateItem = new ButtonItem();
    validateItem.setTitle("Validate");
    validateItem.addClickHandler(new ClickHandler() {
        public void onClick(ClickEvent event) {
            if (form.validate(false)) {
                AccountClient.getInstance().createAccount(form.getValueAsString("username"),
                        form.getValueAsString("password"), form.getValueAsString("firstname"),
                        form.getValueAsString("familyName"), form.getValueAsString("email"),
                        form.getValueAsString("pictureUrl"), new JsonCallback() {
                            public void onJsonReceived(JSONValue jsonValue) {
                                if (jsonValue.isObject() != null) {
                                    Window.open("Login.html", "_self", "");

                                }
                            }
                        });
            }
        }
    });

    form.setFields(header, userName, name, familyName, email, pictureUrl, passwordItem, passwordItem2,
            acceptItem, validateItem);

    RootPanel.get("new-account").add(form);

}

From source file:net.wespot.gwt.client.Login.java

License:Open Source License

public void loadPage() {
    final DynamicForm form = new DynamicForm();

    form.setUseAllDataSourceFields(true);

    HeaderItem header = new HeaderItem();
    header.setDefaultValue("Login");
    TextItem userName = new TextItem();
    userName.setName("username");
    userName.setTitle("Username");

    final PasswordItem passwordItem = new PasswordItem();

    passwordItem.setName("password");
    passwordItem.setTitle("Password");

    ButtonItem submit = new ButtonItem();
    submit.setTitle("Submit");
    submit.addClickHandler(new ClickHandler() {
        public void onClick(ClickEvent event) {

            AccountClient.getInstance().authenticate(form.getValueAsString("username"),
                    form.getValueAsString("password"), new JsonCallback() {
                        public void onJsonReceived(JSONValue jsonValue) {
                            if (jsonValue.isObject() != null) {
                                if (jsonValue.isObject().containsKey("userName")) {
                                    SC.ask("result", "username incorrect", new BooleanCallback() {
                                        @Override
                                        public void execute(Boolean value) {

                                        }
                                    });/*from w  ww.  j a va2  s.co  m*/
                                    //                                    SC.showPrompt("username incorrect");
                                }

                                if (jsonValue.isObject().containsKey("password")) {
                                    SC.ask("result", "password incorrect", new BooleanCallback() {
                                        @Override
                                        public void execute(Boolean value) {

                                        }
                                    });
                                }
                                if (jsonValue.isObject().containsKey("token")) {

                                    Cookies.setCookie(AUTH_COOKIE,
                                            jsonValue.isObject().get("token").isString().stringValue());
                                    if (Window.Location.getParameter("redirect_uri") != null) {
                                        //                                        SC.ask("result", "about to open "+"/oauth/auth?redirect_uri="+Window.Location.getParameter("redirect_uri")+
                                        //                                                "&client_id="+Window.Location.getParameter("client_id")+
                                        //                                                "&response_type="+Window.Location.getParameter("response_type")+
                                        //                                                "&scope="+Window.Location.getParameter("scope"), new BooleanCallback() {
                                        //                                            @Override
                                        //                                            public void execute(Boolean value) {
                                        //
                                        //                                            }
                                        //                                        });
                                        //                                        Window.open("/oauth/auth?redirect_uri="+Window.Location.getParameter("redirect_uri")+
                                        //                                                "&client_id="+Window.Location.getParameter("client_id")+
                                        //                                                "&response_type="+Window.Location.getParameter("response_type")+
                                        //                                                "&scope="+Window.Location.getParameter("scope"), "_self", "");

                                        Window.Location.replace("/oauth/auth?redirect_uri="
                                                + Window.Location.getParameter("redirect_uri") + "&client_id="
                                                + Window.Location.getParameter("client_id") + "&response_type="
                                                + Window.Location.getParameter("response_type") + "&scope="
                                                + Window.Location.getParameter("scope"));
                                    } else {

                                        SC.say("Login Successful");
                                    }
                                }
                            }
                        };

                    });
            //                final String oldValue = form.getValueAsString("password");
            //                CustomValidator matchesValidator = new CustomValidator(){
            //                    @Override
            //                    protected boolean condition(Object value) {
            //                        return !oldValue.equals(form.getValue("password"));
            //
            //                    }
            //                };
            //                matchesValidator.setErrorMessage("Username/password incorrect");
            //                passwordItem.setValidators(matchesValidator);
            //                form.validate();

        }
    });

    form.setFields(header, userName, passwordItem, submit);

    RootPanel.get("login").add(form);

}

From source file:net.wespot.gwt.client.network.JsonCallback.java

License:Open Source License

public void onJsonReceivedNoProcessing(JSONValue jsonValue) {
    if (type != null && jsonValue.isObject().get(type) != null
            && jsonValue.isObject().get(type).isArray() != null) {
        this.jsonValue = jsonValue.isObject().get(type).isArray();
    }//w w w .  java2 s .c o  m

}

From source file:net.wespot.gwt.client.network.JsonCallback.java

License:Open Source License

public void onJsonReceived(JSONValue jsonValue) {
    if (type != null && jsonValue.isObject().get(type) != null
            && jsonValue.isObject().get(type).isArray() != null) {
        this.jsonValue = jsonValue.isObject().get(type).isArray();
    }//from ww w .j  a  v  a2s.c om

    onReceived();
}

From source file:nl.sense_os.commonsense.main.client.viz.panels.table.SensorDataGrid.java

License:Open Source License

private List<ColumnConfig> createColConfig(final List<ExtSensor> sensors) {
    List<ColumnConfig> colConf = new ArrayList<ColumnConfig>();

    ColumnConfig idCol = new ColumnConfig();
    idCol.setId("id");
    idCol.setHeaderText("row id");
    idCol.setDataIndex("id");
    idCol.setWidth(50);/*from w  ww . ja  v  a  2 s  .  c om*/
    colConf.add(idCol);

    ColumnConfig sensorCol = new ColumnConfig();
    sensorCol.setId("sensor_id");
    sensorCol.setHeaderText("sensor");
    sensorCol.setDataIndex("sensor_id");
    sensorCol.setWidth(250);
    sensorCol.setRenderer(new GridCellRenderer<ModelData>() {

        @Override
        public Object render(ModelData model, String property, ColumnData config, int rowIndex, int colIndex,
                ListStore<ModelData> store, Grid<ModelData> grid) {
            int id = (int) model.<Double>get(property).doubleValue();
            for (ExtSensor sensor : sensors) {
                LOG.fine("id='" + id + "', sensor.id='" + sensor.getId() + "'");
                if (id == sensor.getId()) {
                    String name = sensor.getName();
                    String deviceType = sensor.getDescription();
                    if (deviceType != null && deviceType.length() > 0 || name.equals(deviceType)) {
                        return id + ". " + name;
                    }
                    return id + ". " + name + " (" + deviceType + ")";
                }
            }
            return "" + id;
        }
    });
    colConf.add(sensorCol);

    ColumnConfig valueCol = new ColumnConfig();
    valueCol.setId("value");
    valueCol.setHeaderText("value");
    valueCol.setDataIndex("value");
    valueCol.setWidth(300);
    valueCol.setRenderer(new GridCellRenderer<ModelData>() {
        @Override
        public Object render(ModelData model, String property, ColumnData config, int rowIndex, int colIndex,
                ListStore<ModelData> store, Grid<ModelData> grid) {

            String value = model.<String>get("value");

            // special rendering for json values
            if ((value.charAt(0) == '{') && (value.charAt(value.length() - 1) == '}')) {
                JSONValue jsonValue = JSONParser.parseStrict(value);
                JSONObject jsonObj = jsonValue.isObject();
                if (null != jsonObj) {
                    return renderJsonValue(jsonObj);
                }
            }

            // return the normal value for non-JSON input
            return value;
        }
    });
    colConf.add(valueCol);

    ColumnConfig timeCol = new ColumnConfig();
    timeCol.setId("date");
    timeCol.setHeaderText("date");
    timeCol.setDataIndex("date");
    timeCol.setWidth(150);
    timeCol.setRenderer(new GridCellRenderer<ModelData>() {
        @Override
        public String render(ModelData model, String property, ColumnData config, int rowIndex, int colIndex,
                ListStore<ModelData> store, Grid<ModelData> grid) {
            double timeInSecs = -1;
            try {
                timeInSecs = Double.parseDouble(model.<String>get("date"));
            } catch (ClassCastException e) {
                timeInSecs = model.get("date");
            }
            long timeInMSecs = (long) (1000 * timeInSecs);
            DateTimeFormat format = DateTimeFormat.getFormat(PredefinedFormat.DATE_TIME_MEDIUM);
            return format.format(new Date(timeInMSecs));
        }
    });
    colConf.add(timeCol);

    return colConf;
}

From source file:org.aksw.TripleCheckMate.client.widgets.StartPage.java

License:Apache License

private final void handleUserInfo(String authToken) {
    try {/*ww  w .ja v  a2  s .  co m*/
        String profileURL = "https://www.googleapis.com/oauth2/v1/userinfo";
        RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, profileURL);
        rb.setHeader("Content-type", "application/atom+xml");
        rb.setHeader("Host", "spreadsheets.google.com");
        rb.setHeader("Authorization", "Bearer " + authToken);
        rb.setCallback(new RequestCallback() {

            public void onResponseReceived(Request request, Response response) {
                if (response.getStatusCode() == 200) {
                    JSONValue value = JSONParser.parseLenient(response.getText());
                    JSONObject obj = value.isObject();

                    if (obj.get("id") != null && obj.get("id").isString() != null)
                        SessionContext.user.googleID = obj.get("id").isString().stringValue();
                    if (obj.get("name") != null && obj.get("name").isString() != null)
                        SessionContext.user.name = obj.get("name").isString().stringValue();
                    if (obj.get("picture") != null && obj.get("picture").isString() != null)
                        SessionContext.user.picture = obj.get("picture").isString().stringValue();
                    if (obj.get("link") != null && obj.get("link").isString() != null)
                        SessionContext.user.profile = obj.get("link").isString().stringValue();
                    if (SessionContext.user.picture.equals(""))
                        SessionContext.user.picture = "https://ssl.gstatic.com/s2/profiles/images/silhouette96.png";

                    // uses SessionContext.user
                    searchForUserinStorageService();

                } else {
                    Window.alert("Cannot retrieve user info!\n Return HTTP Code: " + response.getStatusCode()
                            + " / " + response.getText());
                    SessionContext.hidePopup();
                }
            }

            public void onError(Request request, Throwable exception) {
                Window.alert("Cannot retrieve user info!\nERROR : " + exception.getMessage());
                SessionContext.hidePopup();
            }
        });
        rb.send();
    } catch (RequestException e) {
        Window.alert("Cannot retrieve user info!\nERROR : " + e.getMessage());
        SessionContext.hidePopup();
    }

}

From source file:org.aksw.TripleCheckMate.shared.sparql.JsonSparqlResult.java

License:Apache License

public JsonSparqlResult(String json) throws Exception {
    try {//from w w  w. j av  a 2s  .c  o m
        // Parse json and get the Object
        JSONValue value = JSONParser.parseLenient(json);
        JSONObject obj = value.isObject();

        //First we need to take the description
        //{ "head": { "link": [], "vars": ["p", "o"] },
        JSONObject headObj = obj.get("head").isObject();
        JSONArray headVars = headObj.get("vars").isArray();
        if (headVars != null) {
            for (int i = 0; i < headVars.size(); i++) {
                String varName = headVars.get(i).isString().stringValue();
                head.add(varName);
            }
        }

        // "results": { "distinct": false, "ordered": true, "bindings": [ ... ]
        JSONObject resultsObj = obj.get("results").isObject();
        JSONArray bindings = resultsObj.get("bindings").isArray();
        if (bindings != null) {
            for (int i = 0; i < bindings.size(); i++) {

                JSONObject current = bindings.get(i).isObject();
                List<ResultItem> item = new ArrayList<ResultItem>();
                for (int j = 0; j < head.size(); j++) {
                    JSONObject rowItem = current.get(head.get(j)).isObject();
                    String sValue = "";
                    if (rowItem.get("value") != null)
                        sValue = rowItem.get("value").isString().stringValue().trim();
                    String sType = "";
                    if (rowItem.get("type") != null)
                        sType = rowItem.get("type").isString().stringValue().trim();
                    String sLang = "";
                    if (rowItem.get("xml:lang") != null)
                        sLang = rowItem.get("xml:lang").isString().stringValue().trim();
                    String sDatatype = "";
                    if (rowItem.get("datatype") != null)
                        sDatatype = rowItem.get("datatype").isString().stringValue().trim();
                    item.add(new ResultItem(sValue, sType, sLang, sDatatype));
                }
                data.add(item);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception();
    }

}

From source file:org.bonitasoft.console.client.user.process.action.ProcessInstantiationCallbackBehavior.java

License:Open Source License

protected String getAttributeValue(final String responseContent, final String attributeName) {
    String attributeValueAsString = null;
    if (responseContent != null && !responseContent.isEmpty()) {
        final JSONValue root = JSONParser.parseLenient(responseContent);
        final JSONObject dataObject = root.isObject();
        if (dataObject != null) {
            final JSONValue attributeValue = dataObject.get(attributeName);
            if (attributeValue != null) {
                attributeValueAsString = Double.toString(attributeValue.isNumber().doubleValue());
            }//from w ww .  ja  va  2  s. c  o m
        }
    }
    return attributeValueAsString;
}

From source file:org.bonitasoft.web.toolkit.client.common.json.JSonUnserializerClient.java

License:Open Source License

private AbstractTreeNode<String> unserializeTreeNode(final JSONValue value) {
    if (value.isArray() != null) {
        return unserializeTreeNode(value.isArray());
    } else if (value.isObject() != null) {
        return unserializeTreeNode(value.isObject());
    } else if (value.isBoolean() != null) {
        return new TreeLeaf<String>(value.isBoolean().booleanValue() ? "1" : "0");
    } else if (value.isNumber() != null) {
        return new TreeLeaf<String>(value.isNumber().toString());
    } else if (value.isString() != null) {
        return new TreeLeaf<String>(value.isString().stringValue());
    }/*from ww  w . jav  a  2 s.co m*/
    return null;
}

From source file:org.bonitasoft.web.toolkit.client.ui.component.form.AbstractForm.java

License:Open Source License

public void setJson(final String json) {
    // TODO Improve filling multilevel arrays

    final JSONValue parsedJson = JSONParser.parseStrict(json);
    if (parsedJson.isArray() != null) {
        final JSONArray jsonArray = parsedJson.isArray();
        for (int i = 0; i < jsonArray.size(); i++) {
            setJson((JSONObject) jsonArray.get(i));
        }//from   w  w  w.  j  ava  2s .c  o  m
    } else if (parsedJson.isObject() != null) {
        setJson(parsedJson.isObject());
    } else {
        throw new IllegalArgumentException("Malformed JSON");
    }
}