Search in sources :

Example 16 with JSONObject

use of com.google.gwt.json.client.JSONObject in project perun by CESNET.

the class JsonClient method retrieveData.

/**
	 * Sends the data
	 */
public void retrieveData(String url, String params, final JsonCallback callback) {
    // create events
    if (callback != null) {
        this.events = new JsonCallbackEvents() {

            @Override
            public void onFinished(JavaScriptObject jso) {
                callback.onFinished(jso);
            }

            @Override
            public void onError(PerunError error) {
                callback.onError(error);
            }

            @Override
            public void onLoadingStart() {
                callback.onLoadingStart();
            }
        };
    }
    final PerunRequest perunRequest = new JSONObject().getJavaScriptObject().cast();
    perunRequest.setStartTime();
    // url to call
    final String requestUrl = URL.encode(PerunWebSession.getInstance().getRpcUrl() + url + "?callback=" + perunRequest.getStartTime() + "&" + params);
    perunRequest.setManager(url.split("\\/")[0]);
    perunRequest.setMethod(url.split("\\/")[1]);
    perunRequest.setParamString("?callback=" + perunRequest.getStartTime() + "&" + params);
    // request building
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, requestUrl);
    try {
        // sends the request
        onRequestLoadingStart();
        if (isCacheEnabled) {
            if (cache.get(requestUrl) != null) {
                // jso
                JavaScriptObject jso = cache.get(requestUrl);
                // Return DATA if not error, otherwise start new call
                PerunError error = (PerunError) jso;
                if ("".equalsIgnoreCase(error.getErrorId()) && "".equalsIgnoreCase(error.getErrorInfo())) {
                    // not error, OK
                    if (session.getUiElements() != null) {
                        session.getUiElements().setLogText("Response not NULL, not ERROR.");
                    }
                    onRequestFinished(jso);
                    return;
                }
            }
        }
        final Request request = builder.sendRequest("", new RequestCallback() {

            @Override
            public void onResponseReceived(Request req, Response resp) {
                // if response = OK
                if (resp.getStatusCode() == 200) {
                    // jso
                    JavaScriptObject jso = parseResponse(perunRequest.getStartTime() + "", resp.getText());
                    // if null - finished
                    if (jso == null) {
                        if (session.getUiElements() != null) {
                            session.getUiElements().setLogText("Response NULL.");
                        }
                        runningRequests.remove(requestUrl);
                        onRequestFinished(null);
                        return;
                    }
                    // if error?
                    PerunError error = (PerunError) jso;
                    if ("".equalsIgnoreCase(error.getErrorId()) && "".equalsIgnoreCase(error.getErrorInfo())) {
                        // not error, OK
                        if (session.getUiElements() != null) {
                            session.getUiElements().setLogText("Response not NULL, not ERROR.");
                        }
                        runningRequests.remove(requestUrl);
                        onRequestFinished(jso);
                        if (isCacheEnabled) {
                            cache.put(requestUrl, jso);
                        }
                        return;
                    }
                    // triggers onError
                    if (session.getUiElements() != null) {
                        session.getUiElements().setLogText("Response ERROR.");
                    }
                    error.setRequest(perunRequest);
                    error.setRequestURL(requestUrl);
                    error.setPostData("");
                    onRequestError(error);
                    runningRequests.remove(requestUrl);
                    return;
                } else {
                    // if response not OK
                    PerunError error = new JSONObject().getJavaScriptObject().cast();
                    error.setErrorId("" + resp.getStatusCode());
                    error.setName(resp.getStatusText());
                    error.setErrorInfo("Server responded with HTTP error: " + resp.getStatusCode() + " - " + resp.getStatusText());
                    error.setObjectType("PerunError");
                    error.setPostData("");
                    error.setRequestURL(requestUrl);
                    error.setRequest(perunRequest);
                    if (resp.getStatusCode() == 401 || resp.getStatusCode() == 403) {
                        error.setErrorInfo("You are not authorized to server. Your session might have expired. Please refresh the browser window to re-login.");
                    } else if (resp.getStatusCode() == 500) {
                        if (runningRequests.get(requestUrl) != null) {
                            if ((runningRequests.get(requestUrl).getDuration() / (1000 * 60)) >= 5) {
                                // 5 minute timeout
                                error.setName("Request Timeout");
                                error.setErrorInfo("Your request couldn't be handled within 5 minutes. Please refresh your view (table) to try it again.");
                            } else {
                                error.setName("Server Internal Error");
                                error.setErrorInfo("Server encounter internal error while processing your request. Please report this error and retry.");
                            }
                        }
                    } else if (resp.getStatusCode() == 503) {
                        error.setName("Server Temporarily Unavailable");
                        error.setErrorInfo("Server is temporarily unavailable. Please try again later.");
                    } else if (resp.getStatusCode() == 404) {
                        error.setName("Not found");
                        error.setErrorInfo("Server is probably being restarted at the moment. Please try again later.");
                    } else if (resp.getStatusCode() == 0) {
                        error.setName("Can't contact remote server.");
                        error.setErrorInfo("You are either without network connection or your session has expired. Click \"OK\" to reload the page (all unsaved changes will be lost).");
                        // force reload page if it's first GUI call, otherwise keep it to alert box
                        if (!hidden && runningRequests.get(requestUrl).getManager().equals("authzResolver") && runningRequests.get(requestUrl).getMethod().equals("getPerunPrincipal")) {
                            Window.Location.reload();
                        }
                    }
                    runningRequests.remove(requestUrl);
                    onRequestError(error);
                    return;
                }
            }

            @Override
            public void onError(Request req, Throwable exc) {
                // request not sent
                runningRequests.remove(requestUrl);
                onRequestError(parseResponse(perunRequest.getStartTime() + "", exc.toString()));
            }
        });
        runningRequests.put(requestUrl, perunRequest);
    } catch (RequestException exc) {
        // usually couldn't connect to server
        onRequestError(parseResponse(perunRequest.getStartTime() + "", exc.toString()));
    }
}
Also used : PerunRequest(cz.metacentrum.perun.webgui.model.PerunRequest) JSONObject(com.google.gwt.json.client.JSONObject) JavaScriptObject(com.google.gwt.core.client.JavaScriptObject) PerunError(cz.metacentrum.perun.webgui.model.PerunError) PerunRequest(cz.metacentrum.perun.webgui.model.PerunRequest)

Example 17 with JSONObject

use of com.google.gwt.json.client.JSONObject in project perun by CESNET.

the class JsonErrorHandler method reportBox.

/**
	 * Creates and display a report box used for reporting errors
	 *
	 * @param error Error object returned from RPC
	 */
public static void reportBox(final PerunError error) {
    // clear password fields if present
    final JSONObject postObject = new JSONObject(JsonUtils.parseJson(error.getPostData()));
    if (postObject.getJavaScriptObject() != null) {
        clearPasswords(postObject);
    }
    String s = "unknown";
    if (PerunWebSession.getInstance().getTabManager() != null) {
        s = PerunWebSession.getInstance().getTabManager().getCurrentUrl(true);
    }
    final String status = s;
    final TextBox boxSubject = new TextBox();
    boxSubject.setValue("Reported error: " + error.getRequest().getManager() + "/" + error.getRequest().getMethod() + " (" + error.getErrorId() + ")");
    boxSubject.setWidth("100%");
    final TextArea messageTextBox = new TextArea();
    messageTextBox.setSize("335px", "100px");
    // ok click - report
    ClickHandler sendReportHandler = new ClickHandler() {

        public void onClick(ClickEvent event) {
            String text = getErrorFullMessage(messageTextBox, error, postObject, status);
            final String finalText = text;
            // request itself
            SendMessageToRt msg = new SendMessageToRt(new JsonCallbackEvents() {

                @Override
                public void onError(PerunError error) {
                    FlexTable layout = new FlexTable();
                    TextArea scrollPanel = new TextArea();
                    scrollPanel.setText(finalText);
                    layout.setWidget(0, 0, new HTML("<p>" + new Image(LargeIcons.INSTANCE.errorIcon())));
                    layout.setHTML(0, 1, "<p>Reporting errors is not working at the moment. We are sorry for inconvenience. <p>Please send following text to <strong>perun@cesnet.cz</strong>.");
                    layout.getFlexCellFormatter().setColSpan(1, 0, 2);
                    layout.setWidget(1, 0, scrollPanel);
                    scrollPanel.setSize("350px", "150px");
                    layout.getFlexCellFormatter().setAlignment(0, 0, HasHorizontalAlignment.ALIGN_LEFT, HasVerticalAlignment.ALIGN_TOP);
                    layout.getFlexCellFormatter().setAlignment(0, 1, HasHorizontalAlignment.ALIGN_LEFT, HasVerticalAlignment.ALIGN_TOP);
                    layout.getFlexCellFormatter().setStyleName(0, 0, "alert-box-image");
                    Confirm c = new Confirm("Error report is not working", layout, true);
                    c.setNonScrollable(true);
                    c.setAutoHide(false);
                    c.show();
                }
            });
            if (boxSubject.getValue().isEmpty()) {
                msg.sendMessage(SendMessageToRt.DEFAULT_QUEUE, "Reported error: " + error.getRequest().getManager() + "/" + error.getRequest().getMethod() + " (" + error.getErrorId() + ")", text);
            } else {
                msg.sendMessage(SendMessageToRt.DEFAULT_QUEUE, boxSubject.getValue(), text);
            }
        }
    };
    FlexTable baseLayout = new FlexTable();
    baseLayout.setStyleName("alert-box-table");
    baseLayout.setWidth("350px");
    baseLayout.setHTML(0, 0, "<p>You can provide any message for this error report (e.g. describing what you tried to do). When you are done, click on send button.");
    baseLayout.setHTML(1, 0, "<strong>Subject:</strong>");
    baseLayout.setWidget(2, 0, boxSubject);
    baseLayout.setHTML(3, 0, "<strong>Message:</strong>");
    baseLayout.setWidget(4, 0, messageTextBox);
    final Anchor showDetails = new Anchor("Show message preview");
    final TextArea fullMessage = new TextArea();
    fullMessage.setReadOnly(true);
    fullMessage.setVisible(false);
    fullMessage.setSize("335px", "100px");
    showDetails.addClickHandler(new ClickHandler() {

        boolean pressed = false;

        @Override
        public void onClick(ClickEvent clickEvent) {
            if (pressed) {
                showDetails.setText("Show message preview");
                fullMessage.setVisible(false);
            } else {
                showDetails.setText("Hide preview");
                fullMessage.setText(getErrorFullMessage(messageTextBox, error, postObject, status));
                fullMessage.setVisible(true);
            }
            pressed = !pressed;
        }
    });
    messageTextBox.addChangeHandler(new ChangeHandler() {

        @Override
        public void onChange(ChangeEvent changeEvent) {
            if (fullMessage.isVisible()) {
                fullMessage.setText(getErrorFullMessage(messageTextBox, error, postObject, status));
            }
        }
    });
    baseLayout.setWidget(5, 0, showDetails);
    baseLayout.setWidget(6, 0, fullMessage);
    // box definition
    final Confirm conf = new Confirm(WidgetTranslation.INSTANCE.jsonClientSendErrorButton(), baseLayout, sendReportHandler, WidgetTranslation.INSTANCE.jsonClientSendErrorButton(), true);
    conf.setOkIcon(SmallIcons.INSTANCE.emailIcon());
    conf.setNonScrollable(true);
    conf.setAutoHide(false);
    conf.setFocusOkButton(true);
    conf.show();
    messageTextBox.setFocus(true);
}
Also used : ClickEvent(com.google.gwt.event.dom.client.ClickEvent) SendMessageToRt(cz.metacentrum.perun.webgui.json.rtMessagesManager.SendMessageToRt) Confirm(cz.metacentrum.perun.webgui.widgets.Confirm) JSONString(com.google.gwt.json.client.JSONString) ClickHandler(com.google.gwt.event.dom.client.ClickHandler) JSONObject(com.google.gwt.json.client.JSONObject) ChangeEvent(com.google.gwt.event.dom.client.ChangeEvent) ChangeHandler(com.google.gwt.event.dom.client.ChangeHandler) PerunError(cz.metacentrum.perun.webgui.model.PerunError)

Example 18 with JSONObject

use of com.google.gwt.json.client.JSONObject in project perun by CESNET.

the class JsonPostClient method send.

/**
	 * Sends the data
	 */
private void send() {
    final PerunRequest perunRequest = new JSONObject().getJavaScriptObject().cast();
    perunRequest.setStartTime();
    // url to call
    final String requestUrl = URL.encode(PerunWebSession.getInstance().getRpcUrl() + url + "?callback=" + perunRequest.getStartTime());
    String data = "";
    if (sendNative) {
        data = json;
    } else {
        data = jsonObject.toString();
    }
    perunRequest.setManager(url.split("\\/")[0]);
    perunRequest.setMethod(url.split("\\/")[1]);
    perunRequest.setParamString("?callback=" + perunRequest.getStartTime() + "&" + data);
    // request building
    RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, requestUrl);
    try {
        // sends the request
        onRequestLoadingStart();
        final String payload = data;
        builder.sendRequest(payload, new RequestCallback() {

            @Override
            public void onResponseReceived(Request req, Response resp) {
                // if response = OK
                if (resp.getStatusCode() == 200) {
                    // jso
                    JavaScriptObject jso = parseResponse(perunRequest.getStartTime() + "", resp.getText());
                    // if null - finished
                    if (jso == null) {
                        if (session.getUiElements() != null) {
                            session.getUiElements().setLogText("Response NULL.");
                        }
                        runningRequests.remove(requestUrl);
                        onRequestFinished(null);
                        return;
                    }
                    // if error?
                    PerunError error = (PerunError) jso;
                    if ("".equalsIgnoreCase(error.getErrorId()) && "".equalsIgnoreCase(error.getErrorInfo())) {
                        // not error, OK
                        if (session.getUiElements() != null) {
                            session.getUiElements().setLogText("Response not NULL, not ERROR.");
                        }
                        runningRequests.remove(requestUrl);
                        onRequestFinished(jso);
                        return;
                    }
                    // triggers onError
                    if (session.getUiElements() != null) {
                        session.getUiElements().setLogText("Response ERROR.");
                    }
                    error.setRequestURL(requestUrl);
                    error.setRequest(perunRequest);
                    error.setPostData(payload);
                    runningRequests.remove(requestUrl);
                    onRequestError(error);
                    return;
                } else {
                    // if response not OK
                    PerunError error = new JSONObject().getJavaScriptObject().cast();
                    error.setErrorId("" + resp.getStatusCode());
                    error.setName(resp.getStatusText());
                    error.setErrorInfo("Server responded with HTTP error: " + resp.getStatusCode() + " - " + resp.getStatusText());
                    error.setObjectType("PerunError");
                    error.setPostData(payload);
                    error.setRequest(perunRequest);
                    error.setRequestURL(requestUrl);
                    if (resp.getStatusCode() == 401 || resp.getStatusCode() == 403) {
                        error.setName("Not Authorized");
                        error.setErrorInfo("You are not authorized to server. Your session might have expired. Please refresh the browser window to re-login.");
                    } else if (resp.getStatusCode() == 500) {
                        if (runningRequests.get(requestUrl) != null) {
                            // 5 minute timeout
                            if ((runningRequests.get(requestUrl).getDuration() / (1000 * 60)) >= 5) {
                                counter++;
                                layout.setHTML(0, 1, "<p>" + "Processing of your request(s) is taking longer than usual, but it's actively processed by the server.<p>Please do not close opened window/tab nor repeat your action. You will be notified once operation completes.<p>Remaining requests: " + counter);
                                if (!c.isShowing() && counter > 0)
                                    c.show();
                                Scheduler.get().scheduleFixedDelay(new Scheduler.RepeatingCommand() {

                                    boolean again = true;

                                    @Override
                                    public boolean execute() {
                                        GetPendingRequests req = new GetPendingRequests(perunRequest.getStartTime(), new JsonCallbackEvents() {

                                            @Override
                                            public void onFinished(JavaScriptObject jso) {
                                                final PerunRequest req = jso.cast();
                                                if ((req.getCallbackId().equals(perunRequest.getStartTime() + "")) && req.getEndTime() > 0) {
                                                    if (again) {
                                                        again = false;
                                                        counter--;
                                                        layout.setHTML(0, 1, "<p>" + "Processing of your request(s) is taking longer than usual, but it's actively processed by the server.<p>Please do not close opened window/tab nor repeat your action. You will be notified once operation completes.<p>Remaining requests: " + counter);
                                                        // hide notification
                                                        if (c.isShowing() && counter <= 0)
                                                            c.hide();
                                                        JavaScriptObject result = req.getResult();
                                                        // if null - finished
                                                        if (result == null) {
                                                            if (session.getUiElements() != null) {
                                                                session.getUiElements().setLogText("Response NULL.");
                                                            }
                                                            runningRequests.remove(requestUrl);
                                                            onRequestFinished(null);
                                                            return;
                                                        }
                                                        // if error?
                                                        PerunError error = (PerunError) result;
                                                        if ("".equalsIgnoreCase(error.getErrorId()) && "".equalsIgnoreCase(error.getErrorInfo())) {
                                                            // not error, OK
                                                            if (session.getUiElements() != null) {
                                                                session.getUiElements().setLogText("Response not NULL, not ERROR.");
                                                            }
                                                            runningRequests.remove(requestUrl);
                                                            onRequestFinished(result);
                                                            return;
                                                        }
                                                        // triggers onError
                                                        if (session.getUiElements() != null) {
                                                            session.getUiElements().setLogText("Response ERROR.");
                                                        }
                                                        error.setRequestURL(requestUrl);
                                                        error.setRequest(perunRequest);
                                                        error.setPostData(payload);
                                                        runningRequests.remove(requestUrl);
                                                        onRequestError(error);
                                                        return;
                                                    }
                                                }
                                            }
                                        });
                                        req.retrieveData();
                                        return again;
                                    }
                                }, ((PerunWebConstants) GWT.create(PerunWebConstants.class)).pendingRequestsRefreshInterval());
                                return;
                            } else {
                                error.setName("ServerInternalError");
                                error.setErrorInfo("Server encounter internal error while processing your request. Please report this error and retry.");
                            }
                        }
                    } else if (resp.getStatusCode() == 503) {
                        error.setName("Server Temporarily Unavailable");
                        error.setErrorInfo("Server is temporarily unavailable. Please try again later.");
                    } else if (resp.getStatusCode() == 404) {
                        error.setName("Not found");
                        error.setErrorInfo("Server is probably being restarted at the moment. Please try again later.");
                    } else if (resp.getStatusCode() == 0) {
                        error.setName("Aborted");
                        error.setErrorInfo("Can't contact remote server, connection was lost.");
                    }
                    runningRequests.remove(requestUrl);
                    onRequestError(error);
                    return;
                }
            }

            @Override
            public void onError(Request req, Throwable exc) {
                // request not sent
                runningRequests.remove(requestUrl);
                onRequestError(parseResponse(perunRequest.getStartTime() + "", exc.toString()));
            }
        });
        runningRequests.put(requestUrl, perunRequest);
    } catch (RequestException exc) {
        // usually couldn't connect to server
        onRequestError(parseResponse(perunRequest.getStartTime() + "", exc.toString()));
    }
}
Also used : Scheduler(com.google.gwt.core.client.Scheduler) PerunRequest(cz.metacentrum.perun.webgui.model.PerunRequest) JSONObject(com.google.gwt.json.client.JSONObject) JavaScriptObject(com.google.gwt.core.client.JavaScriptObject) PerunRequest(cz.metacentrum.perun.webgui.model.PerunRequest) PerunError(cz.metacentrum.perun.webgui.model.PerunError)

Example 19 with JSONObject

use of com.google.gwt.json.client.JSONObject in project perun by CESNET.

the class ApplicationFormPage method tryToFindUserByName.

/**
	 * Try to find user by name
	 *
	 * If user found, message box shown
	 *
	 * @param jso returned data
	 */
private void tryToFindUserByName(JavaScriptObject jso) {
    // try to find
    JsonPostClient jspc = new JsonPostClient(new JsonCallbackEvents() {

        @Override
        public void onFinished(JavaScriptObject jso) {
            ArrayList<Identity> users = JsonUtils.<Identity>jsoAsList(jso);
            if (users != null && !users.isEmpty())
                similarUsersFound(users);
        }
    });
    JSONObject query = new JSONObject();
    if (jso == null) {
        // before app submission
        jspc.sendData("registrarManager/checkForSimilarUsers", query);
    } else {
        // after app submission
        query.put("voId", new JSONNumber(vo.getId()));
        if (group != null) {
            query.put("groupId", new JSONNumber(group.getId()));
        } else {
            query.put("groupId", new JSONNumber(0));
        }
        query.put("type", new JSONString(type));
        jspc.sendData("registrarManager/checkForSimilarUsers", query);
    }
}
Also used : JsonCallbackEvents(cz.metacentrum.perun.webgui.json.JsonCallbackEvents) JSONObject(com.google.gwt.json.client.JSONObject) JavaScriptObject(com.google.gwt.core.client.JavaScriptObject) JsonPostClient(cz.metacentrum.perun.webgui.json.JsonPostClient) ArrayList(java.util.ArrayList) JSONNumber(com.google.gwt.json.client.JSONNumber) JSONString(com.google.gwt.json.client.JSONString)

Example 20 with JSONObject

use of com.google.gwt.json.client.JSONObject in project perun by CESNET.

the class JsonUtils method parseJsonToMap.

/**
	 * Parses a JavaScript map into a Java map.
	 * @param jso
	 * @return
	 */
public static final Map<String, JSONValue> parseJsonToMap(JavaScriptObject jso) {
    if (jso == null) {
        // when null, return empty map
        return new HashMap<String, JSONValue>();
    }
    JSONObject obj = new JSONObject(jso);
    HashMap<String, JSONValue> m = new HashMap<String, JSONValue>();
    for (String key : obj.keySet()) {
        m.put(key, obj.get(key));
    }
    return m;
}
Also used : JSONValue(com.google.gwt.json.client.JSONValue) JSONObject(com.google.gwt.json.client.JSONObject) JsArrayString(com.google.gwt.core.client.JsArrayString)

Aggregations

JSONObject (com.google.gwt.json.client.JSONObject)227 JSONNumber (com.google.gwt.json.client.JSONNumber)109 JSONString (com.google.gwt.json.client.JSONString)74 JSONArray (com.google.gwt.json.client.JSONArray)62 PerunError (cz.metacentrum.perun.webgui.model.PerunError)55 JavaScriptObject (com.google.gwt.core.client.JavaScriptObject)54 JsonCallbackEvents (cz.metacentrum.perun.webgui.json.JsonCallbackEvents)54 JsonPostClient (cz.metacentrum.perun.webgui.json.JsonPostClient)50 JSONValue (com.google.gwt.json.client.JSONValue)13 HashMap (java.util.HashMap)12 Map (java.util.Map)8 ArrayList (java.util.ArrayList)6 JsArrayString (com.google.gwt.core.client.JsArrayString)3 User (cz.metacentrum.perun.webgui.model.User)3 ClickEvent (com.google.gwt.event.dom.client.ClickEvent)2 ClickHandler (com.google.gwt.event.dom.client.ClickHandler)2 Command (com.google.gwt.user.client.Command)2 Contact (com.googlecode.gwtphonegap.client.contacts.Contact)2 ContactField (com.googlecode.gwtphonegap.client.contacts.ContactField)2 StringCallback (com.gwtmobile.phonegap.client.plugins.Bluetooth.StringCallback)2