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:org.rest.client.activity.RequestActivity.java

License:Apache License

private ArrayList<RedirectData> getRedirectData(JSONArray response) {
    ArrayList<RedirectData> result = new ArrayList<RedirectData>();
    if (response == null) {
        return result;
    }//from ww  w. jav a  2  s  .c om
    int size = response.size();
    for (int i = 0; i < size; i++) {
        JSONValue itemValue = response.get(i);
        JSONObject item = itemValue.isObject();
        if (item == null)
            continue;

        boolean fromCache = item.get("fromCache").isBoolean().booleanValue();
        String redirectUrl = item.get("redirectUrl").isString().stringValue();

        String statusLine = null;
        JSONValue statusLineValue = item.get("statusLine");
        if (statusLineValue != null) {
            statusLine = item.get("statusLine").isString().stringValue();
        }
        int statusCode = Integer.parseInt(item.get("statusCode").isNumber().toString());
        ArrayList<Header> headers = extractHeadersExternal(item, "responseHeaders");
        RedirectData redirect = new RedirectData();
        redirect.setRedirectUrl(redirectUrl);
        redirect.setFromCache(fromCache);
        redirect.setResponseHeaders(headers);
        redirect.setStatusCode(statusCode);
        if (statusLine != null)
            redirect.setStatusLine(statusLine);
        result.add(redirect);
    }
    return result;
}

From source file:org.rest.client.activity.RequestActivity.java

License:Apache License

private ArrayList<Header> extractHeadersExternal(JSONObject response, String key) {
    ArrayList<Header> headers = new ArrayList<Header>();
    JSONValue valuesValue = response.get(key);
    if (valuesValue == null) {
        return headers;
    }/*ww  w .  ja  v  a 2 s  .c  om*/
    JSONArray arr = valuesValue.isArray();
    if (arr == null) {
        return headers;
    }
    int len = arr.size();
    for (int i = 0; i < len; i++) {
        JSONValue item = arr.get(i);
        final String name = item.isObject().get("name").isString().stringValue();
        final String value = item.isObject().get("value").isString().stringValue();
        Header header = new Header() {
            @Override
            public String getName() {
                return name;
            }

            @Override
            public String getValue() {
                return value;
            }

            @Override
            public String toString() {
                return name + " : " + value;
            }
        };
        headers.add(header);
    }
    return headers;
}

From source file:org.rest.client.activity.RequestActivity.java

License:Apache License

private void createExternalRequest(final String requestUUID) {
    clientFactory.getChromeMessagePassing().postMessage(ExternalEventsFactory.EXT_GET_EXTERNAL_REQUEST_DATA,
            requestUUID, new BackgroundPageCallback() {
                @Override/*  www  .  ja  v a2  s .  c  o m*/
                public void onSuccess(String result) {
                    if (result.isEmpty()) {
                        StatusNotification.notify("Data from external extension is no longer available :(",
                                StatusNotification.TYPE_CRITICAL, StatusNotification.TIME_MEDIUM);
                        return;
                    }
                    JSONValue parsedValue = null;
                    try {
                        parsedValue = JSONParser.parseStrict(result);
                    } catch (Exception e) {
                    }
                    if (parsedValue == null) {
                        Log.error("Malformed External Data Exception. Passed data: " + result);
                        StatusNotification.notify("Unable to read data from external extension :(",
                                StatusNotification.TYPE_CRITICAL, StatusNotification.TIME_MEDIUM);
                        return;
                    }
                    JSONObject obj = parsedValue.isObject();
                    if (obj.containsKey("error")) {
                        if (obj.get("error").isBoolean().booleanValue()) {
                            Log.error("Error get External Data. Message: "
                                    + obj.get("message").isString().stringValue());
                            StatusNotification.notify(obj.get("message").isString().stringValue(),
                                    StatusNotification.TYPE_CRITICAL, StatusNotification.TIME_MEDIUM);
                            return;
                        }
                    }
                    if (obj.containsKey("data")) {
                        JSONObject dataObj = obj.get("data").isObject();
                        if (dataObj.containsKey("url")) {
                            requestView.setUrl(dataObj.get("url").isString().stringValue());
                        }
                        if (dataObj.containsKey("method")) {
                            requestView.setMethod(dataObj.get("method").isString().stringValue());
                        }
                        if (dataObj.containsKey("headers")) {
                            requestView.setHeaders(dataObj.get("headers").isString().stringValue());
                        }
                        if (dataObj.containsKey("payload")) {
                            requestView.setPayload(dataObj.get("payload").isString().stringValue());
                        }
                        if (dataObj.containsKey("encoding")) {
                            requestView.setEncoding(dataObj.get("encoding").isString().stringValue());
                        }
                    }
                    RestClient.fixChromeLayout();
                }

                @Override
                public void onError(String message) {
                    if (RestClient.isDebug()) {
                        Log.error("Unknown error occured: " + message);
                    }
                }
            });

}

From source file:org.roda.wui.client.common.utils.FormUtilities.java

private static void addList(FlowPanel panel, final FlowPanel layout, final MetadataValue mv,
        final boolean mandatory) {
    // Top Label//w w w  .java2  s . c  o  m
    Label mvLabel = new Label(getFieldLabel(mv));
    mvLabel.addStyleName("form-label");
    if (mandatory) {
        mvLabel.addStyleName("form-label-mandatory");
    }
    // Field
    final ListBox mvList = new ListBox();
    mvList.setTitle(mvLabel.getText());
    mvList.addStyleName("form-textbox");

    String options = mv.get("options");
    JSONArray optionsArray = null;
    if (options != null) {
        optionsArray = JSONParser.parseLenient(options).isArray();
    }

    String list = mv.get("optionsLabels");
    mvList.addItem("");

    if (list != null) {
        JSONArray jsonArray = JSONParser.parseLenient(list).isArray();
        if (jsonArray != null) {
            for (int i = 0; i < jsonArray.size(); i++) {
                String value = jsonArray.get(i).isString().stringValue();
                mvList.addItem(value);

                if (value.equals(mv.get("value"))) {
                    mvList.setSelectedIndex(i + 1);
                }
            }
        } else {
            JSONObject jsonObject = JSONParser.parseLenient(list).isObject();
            if (jsonObject != null) {
                String loc = LocaleInfo.getCurrentLocale().getLocaleName();
                int i = 0;

                if (optionsArray != null) {
                    for (int pos = 0; pos < optionsArray.size(); pos++) {
                        String key = optionsArray.get(pos).isString().stringValue();
                        JSONValue entry = jsonObject.get(key);
                        if (entry.isObject() != null) {
                            JSONValue jsonValue = entry.isObject().get(loc);
                            String value;
                            if (jsonValue != null) {
                                value = jsonValue.isString().stringValue();
                            } else {
                                value = entry.isObject().get(entry.isObject().keySet().iterator().next())
                                        .isString().stringValue();
                            }
                            if (value != null) {
                                mvList.addItem(value, key);
                                if (key.equals(mv.get("value"))) {
                                    mvList.setSelectedIndex(i + 1);
                                }
                            }
                        }
                        i++;
                    }
                } else {
                    for (String key : jsonObject.keySet()) {
                        JSONValue entry = jsonObject.get(key);
                        if (entry.isObject() != null) {
                            JSONValue jsonValue = entry.isObject().get(loc);
                            String value;
                            if (jsonValue != null) {
                                value = jsonValue.isString().stringValue();
                            } else {
                                value = entry.isObject().get(entry.isObject().keySet().iterator().next())
                                        .isString().stringValue();
                            }
                            if (value != null) {
                                mvList.addItem(value, key);
                                if (key.equals(mv.get("value"))) {
                                    mvList.setSelectedIndex(i + 1);
                                }
                            }
                        }
                        i++;
                    }
                }
            }
        }
    } else {
        if (optionsArray != null) {
            int i = 0;
            for (int pos = 0; pos < optionsArray.size(); pos++) {
                String key = optionsArray.get(pos).isString().stringValue();
                if (key != null) {
                    mvList.addItem(key, key);
                    if (key.equals(mv.get("value"))) {
                        mvList.setSelectedIndex(i + 1);
                    }
                }
                i++;
            }
        }
    }

    mvList.addChangeHandler(new ChangeHandler() {
        @Override
        public void onChange(ChangeEvent changeEvent) {
            mv.set("value", mvList.getSelectedValue());
            if (mandatory
                    && (mvList.getSelectedValue() != null && !"".equals(mvList.getSelectedValue().trim()))) {
                mvList.removeStyleName("isWrong");
            }

            if (mandatory && (mvList.getSelectedValue() == null
                    || "".equalsIgnoreCase(mvList.getSelectedValue().trim()))) {
                mvList.removeStyleName("isWrong");
            }
        }
    });

    if (mv.get("value") == null || mv.get("value").isEmpty()) {
        mvList.setSelectedIndex(0);
        mv.set("value", mvList.getSelectedValue());
    }

    layout.add(mvLabel);
    layout.add(mvList);

    // Description
    String description = mv.get("description");
    if (description != null && description.length() > 0) {
        Label mvDescription = new Label(description);
        mvDescription.addStyleName("form-help");
        layout.add(mvDescription);
    }

    if (mv.get("error") != null && !"".equals(mv.get("error").trim())) {
        Label errorLabel = new Label(mv.get("error"));
        errorLabel.addStyleName("form-label-error");
        layout.add(errorLabel);
        mvList.addStyleName("isWrong");
    }
    panel.add(layout);
}

From source file:org.rstudio.core.client.jsonrpc.RpcResponse.java

License:Open Source License

public final static RpcResponse parse(String json) {
    try {//from  w w  w.j a  va  2 s .c o m
        // we first call parseStrict so we can use the browser
        // json parser (for performance) whenever possible)
        JSONValue val = JSONParser.parseStrict(json);
        return val.isObject().getJavaScriptObject().cast();
    } catch (Exception e) {
        try {
            // there are some cases where json emitted by our 
            // server isn't parsable by parseStrict (for example,
            // see bug #3025). for these situations we call 
            // parseLenient (which in turn calls eval)
            JSONValue val = JSONParser.parseLenient(json);
            return val.isObject().getJavaScriptObject().cast();
        } catch (Exception e2) {
            return null;
        }
    }
}

From source file:org.sakaiproject.gradebook.gwt.client.gxt.view.panel.GradeScalePanel.java

License:Educational Community License

private void getStatisticsChartData() {

    /*/*from ww w . j a v  a 2 s . co  m*/
     *  GRBK-1071
     *  No need to get the data if the visualization API hasn't been loaded yet
     */
    if (!canGetStatisticsChartData) {

        return;
    }

    showUserFeedback();

    Gradebook gbModel = Registry.get(AppConstants.CURRENT);

    RestBuilder builder = RestBuilder.getInstance(Method.GET, GWT.getModuleBaseURL(),
            AppConstants.REST_FRAGMENT, AppConstants.STATISTICS_FRAGMENT, AppConstants.COURSE_FRAGMENT,
            gbModel.getGradebookUid());

    builder.sendRequest(200, 400, null, new RestCallback() {

        public void onError(Request request, Throwable caught) {

            hideUserFeedback();
            Dispatcher.forwardEvent(GradebookEvents.Notification.getEventType(), new NotificationEvent(
                    i18n.statisticsDataErrorTitle(), i18n.statisticsDataErrorMsg(), true));
        }

        public void onFailure(Request request, Throwable exception) {

            hideUserFeedback();
            Dispatcher.forwardEvent(GradebookEvents.Notification.getEventType(), new NotificationEvent(
                    i18n.statisticsDataErrorTitle(), i18n.statisticsDataErrorMsg(), true));
        }

        public void onSuccess(Request request, Response response) {

            /*
             * The response text contains a sorted linked-list map, where the keys are the letter grades and the values
             * are the frequency.
             * e.g. {"F":0, "D-":3, "D":1, "D+":0, "C-":5, "C":0, "C+":1, "B-":0, "B":20, "B+":0, "A-":3, "A":12, "A+":1}
             * 
             */
            JSONValue jsonValue = JSONParser.parseStrict(response.getText());
            JSONObject jsonObject = jsonValue.isObject();
            Set<String> keys = jsonObject.keySet();

            // Initialize the DataTable
            DataTable dataTable = statisticsChartPanel.createDataTable();
            dataTable.addColumn(ColumnType.STRING, i18n.statisticsChartLabelDistribution());
            dataTable.addColumn(ColumnType.NUMBER, i18n.statisticsChartLabelFrequency());
            dataTable.addRows(keys.size());

            Iterator<String> iter = keys.iterator();
            int index = 0;
            while (iter.hasNext()) {

                String key = iter.next();
                dataTable.setValue(index, 0, key);
                dataTable.setValue(index, 1, jsonObject.get(key).isNumber().doubleValue());
                index++;
            }

            statisticsChartPanel.show();

            hideUserFeedback();
        }
    });
}

From source file:org.sakaiproject.gradebook.gwt.client.gxt.view.panel.StatisticsPanel.java

License:Educational Community License

private void getCourseStatisticsChartData(String sectionId) {

    // First we check the cache if we have the data already
    String cacheKey = COURSE_CACHE_KEY_PREFIX + sectionId;

    if (dataTableCache.containsKey(cacheKey)) {

        // Cache hit
        dataTable = dataTableCache.get(cacheKey);
        statisticsChartPanel.setDataTable(dataTable);
        statisticsChartPanel.show();/*from w ww  .java 2 s .co m*/
    } else {

        statisticsChartPanel.showUserFeedback(null);

        Gradebook gbModel = Registry.get(AppConstants.CURRENT);

        RestBuilder builder = RestBuilder.getInstance(Method.GET, GWT.getModuleBaseURL(),
                AppConstants.REST_FRAGMENT, AppConstants.STATISTICS_FRAGMENT, AppConstants.COURSE_FRAGMENT,
                gbModel.getGradebookUid(), sectionId);

        selectedSectionId = sectionId;

        builder.sendRequest(200, 400, null, new RestCallback() {

            public void onError(Request request, Throwable caught) {

                statisticsChartPanel.hideUserFeedback(null);
                Dispatcher.forwardEvent(GradebookEvents.Notification.getEventType(), new NotificationEvent(
                        i18n.statisticsDataErrorTitle(), i18n.statisticsDataErrorMsg(), true));
            }

            public void onFailure(Request request, Throwable exception) {

                statisticsChartPanel.hideUserFeedback(null);
                Dispatcher.forwardEvent(GradebookEvents.Notification.getEventType(), new NotificationEvent(
                        i18n.statisticsDataErrorTitle(), i18n.statisticsDataErrorMsg(), true));
            }

            public void onSuccess(Request request, Response response) {

                /*
                 * The response text contains a sorted linked-list map, where the keys are the letter grades and the values
                 * are the frequency.
                 * e.g. {"F":0, "D-":3, "D":1, "D+":0, "C-":5, "C":0, "C+":1, "B-":0, "B":20, "B+":0, "A-":3, "A":12, "A+":1}
                 * 
                 */
                JSONValue jsonValue = JSONParser.parseStrict(response.getText());
                JSONObject jsonObject = jsonValue.isObject();
                Set<String> keys = jsonObject.keySet();

                // Initialize the datatable
                dataTable = statisticsChartPanel.createDataTable();
                dataTable.addColumn(ColumnType.STRING, i18n.statisticsChartLabelDistribution());
                dataTable.addColumn(ColumnType.NUMBER, i18n.statisticsChartLabelFrequency());
                dataTable.addRows(keys.size());

                Iterator<String> iter = keys.iterator();
                int index = 0;
                while (iter.hasNext()) {

                    String key = iter.next();
                    dataTable.setValue(index, 0, key);
                    dataTable.setValue(index, 1, jsonObject.get(key).isNumber().doubleValue());
                    index++;
                }

                statisticsChartPanel.show();

                // adding the dataTable to the cache
                dataTableCache.put(COURSE_CACHE_KEY_PREFIX + selectedSectionId, dataTable);

                statisticsChartPanel.hideUserFeedback(null);
            }
        });
    }
}

From source file:org.sakaiproject.gradebook.gwt.client.gxt.view.panel.StudentPanel.java

License:Educational Community License

private void getCourseStatisticsChartData() {

    // First we check the cache if we have the data already
    String cacheKey = COURSE_CACHE_KEY_PREFIX;

    if (dataTableCache.containsKey(cacheKey)) {

        // Cache hit
        dataTable = dataTableCache.get(cacheKey);
        statisticsChartPanel.setDataTable(dataTable);
        statisticsChartPanel.show();/*  www  . j  ava2s. co  m*/
    } else {

        statisticsChartPanel.showUserFeedback(null);

        Gradebook gbModel = Registry.get(AppConstants.CURRENT);

        RestBuilder builder = RestBuilder.getInstance(Method.GET, GWT.getModuleBaseURL(),
                AppConstants.REST_FRAGMENT, AppConstants.STATISTICS_FRAGMENT, AppConstants.STUDENT_FRAGMENT,
                AppConstants.COURSE_FRAGMENT, gbModel.getGradebookUid(), Base64.encode(AppConstants.ALL));

        builder.sendRequest(200, 400, null, new RestCallback() {

            public void onError(Request request, Throwable caught) {

                statisticsChartPanel.hideUserFeedback(null);
                Dispatcher.forwardEvent(GradebookEvents.Notification.getEventType(), new NotificationEvent(
                        i18n.statisticsDataErrorTitle(), i18n.statisticsDataErrorMsg(), true));
            }

            public void onFailure(Request request, Throwable exception) {

                statisticsChartPanel.hideUserFeedback(null);
                Dispatcher.forwardEvent(GradebookEvents.Notification.getEventType(), new NotificationEvent(
                        i18n.statisticsDataErrorTitle(), i18n.statisticsDataErrorMsg(), true));
            }

            public void onSuccess(Request request, Response response) {

                /*
                 * The response text contains a sorted linked-list map, where the keys are the letter grades and the values
                 * are the frequency.
                 * e.g. {"F":0, "D-":3, "D":1, "D+":0, "C-":5, "C":0, "C+":1, "B-":0, "B":20, "B+":0, "A-":3, "A":12, "A+":1}
                 * 
                 */
                JSONValue jsonValue = JSONParser.parseStrict(response.getText());
                JSONObject jsonObject = jsonValue.isObject();
                Set<String> keys = jsonObject.keySet();

                // Initialize the datatable
                dataTable = statisticsChartPanel.createDataTable();
                dataTable.addColumn(ColumnType.STRING, i18n.statisticsChartLabelDistribution());
                dataTable.addColumn(ColumnType.NUMBER, i18n.statisticsChartLabelFrequency());
                dataTable.addRows(keys.size());

                Iterator<String> iter = keys.iterator();
                int index = 0;
                while (iter.hasNext()) {

                    String key = iter.next();
                    dataTable.setValue(index, 0, key);
                    dataTable.setValue(index, 1, jsonObject.get(key).isNumber().doubleValue());
                    index++;
                }

                statisticsChartPanel.show();

                // adding the dataTable to the cache
                dataTableCache.put(COURSE_CACHE_KEY_PREFIX, dataTable);

                statisticsChartPanel.hideUserFeedback(null);
            }
        });
    }
}

From source file:org.sigmah.offline.status.ApplicationStateManager.java

License:Open Source License

private void updateStatus() {
    final RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, "sigmah/online.nocache.json");
    try {//from w w w. j  av a2s.  c o  m
        requestBuilder.sendRequest(null, new RequestCallback() {
            @Override
            public void onResponseReceived(com.google.gwt.http.client.Request request, Response response) {
                if (response != null && response.getText() != null && !response.getText().isEmpty()) {
                    try {
                        final JSONValue value = JSONParser.parseStrict(response.getText());
                        final JSONObject object = value.isObject();
                        if (object != null) {
                            final JSONValue onlineObject = object.get("online");
                            final JSONBoolean online = onlineObject.isBoolean();
                            setOnline(online != null && online.booleanValue());
                        } else {
                            setOnline(false);
                        }
                    } catch (JSONException ex) {
                        setOnline(false);
                        Log.error(
                                "An error occured while parsing the JSON string: '" + response.getText() + "'.",
                                ex);
                    }
                } else {
                    setOnline(false);
                }
            }

            @Override
            public void onError(com.google.gwt.http.client.Request request, Throwable exception) {
                setOnline(false);
            }
        });

    } catch (RequestException ex) {
        setOnline(false);
        Log.error("An error occured while checking the connection state.", ex);
    }
}

From source file:org.sigmah.offline.status.ConnectionStatus.java

License:Open Source License

public void updateStatus() {
    final RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, "sigmah/online.nocache.json");
    try {//from www.  ja  v a 2 s .c o  m
        requestBuilder.sendRequest(null, new RequestCallback() {
            @Override
            public void onResponseReceived(com.google.gwt.http.client.Request request, Response response) {
                if (response != null && response.getText() != null && !response.getText().isEmpty()) {
                    try {
                        final JSONValue value = JSONParser.parseStrict(response.getText());
                        final JSONObject object = value.isObject();
                        if (object != null) {
                            final JSONValue online = object.get("online");
                            final JSONBoolean isOnline = online.isBoolean();
                            setOnline(isOnline != null && isOnline.booleanValue());
                        } else {
                            setOnline(false);
                        }
                    } catch (JSONException ex) {
                        setOnline(false);
                        Log.error(
                                "An error occured while parsing the JSON string: '" + response.getText() + "'.",
                                ex);
                    }
                } else {
                    setOnline(false);
                }
            }

            @Override
            public void onError(com.google.gwt.http.client.Request request, Throwable exception) {
                setOnline(false);
            }
        });

    } catch (RequestException ex) {
        setOnline(false);
        Log.error("An error occured while checking the connection state.", ex);
    }
}