Example usage for com.google.gwt.http.client RequestCallback RequestCallback

List of usage examples for com.google.gwt.http.client RequestCallback RequestCallback

Introduction

In this page you can find the example usage for com.google.gwt.http.client RequestCallback RequestCallback.

Prototype

RequestCallback

Source Link

Usage

From source file:anzsoft.xmpp4gwt.client.Bosh2Connector.java

License:Open Source License

public Bosh2Connector(final User user) {
    this.setUser(user);
    standardHandler = new RequestCallback() {

        public void onError(Request request, Throwable exception) {
            final String lastSendedBody = activeRequests.remove(request);
            if (exception instanceof RequestTimeoutException) {
                GWT.log("Request too old. Trying again.", null);
                DeferredCommand.addCommand(new Command() {
                    public void execute() {
                        if (lastSendedBody != null && state == State.connected && sid != null
                                && sid.length() > 0)
                            send(lastSendedBody, standardHandler);
                        else
                            continuousConnection(null);
                    }// w  w w.j a v a 2s .com
                });
            } else if (exception.getMessage().startsWith("Unable to read XmlHttpRequest.status;")) {
                GWT.log("Lost request. Ignored. Resend.", null);
                if (lastSendedBody != null) {
                    DeferredCommand.addCommand(new Command() {
                        public void execute() {
                            if (state == State.connected && sid != null && sid.length() > 0) {
                                send(lastSendedBody, standardHandler);
                            }
                        }
                    });
                }
            } else {
                state = State.disconnected;
                GWT.log("Connection error", exception);
                exception.printStackTrace();
                fireEventError(BoshErrorCondition.remote_connection_failed, null,
                        "Response error: " + exception.getMessage());
            }
        }

        public void onResponseReceived(Request request, Response response) {
            if (state == State.disconnected)
                return;

            final String httpResponse = response.getText();
            final int httpStatusCode = response.getStatusCode();
            final String lastSendedBody = activeRequests.remove(request);

            System.out.println(" IN (" + httpStatusCode + "): " + httpResponse);
            fireOnBodyReceive(response, httpResponse);

            final Packet body = parse2(response.getText().replaceAll(";", ";"));

            final String type = body == null ? null : body.getAtribute("type");
            final String receivedSid = body == null ? null : body.getAtribute("sid");
            String $tmp = body == null ? null : body.getAtribute("rid");
            //final Long rid = $tmp == null ? null : Long.valueOf($tmp);
            final String ack = body == null ? null : body.getAtribute("ack");
            $tmp = body == null ? null : body.getAtribute("condition");
            if ($tmp != null)
                $tmp = $tmp.replace("-", "_");
            final BoshErrorCondition boshCondition = $tmp == null ? null : BoshErrorCondition.valueOf($tmp);

            final String wait = body == null ? null : body.getAtribute("wait");
            final String inactivity = body == null ? null : body.getAtribute("inactivity");
            if (wait != null && inactivity != null) {
                try {
                    int w = Integer.parseInt(wait);
                    int i = Integer.parseInt(inactivity);
                    int t = (w + i / 2) * 1000;
                    builder.setTimeoutMillis(t);
                    GWT.log("New timeout: " + t + "ms", null);
                } catch (Exception e) {
                    GWT.log("Error in wait and inactivity attributes", e);
                }
            }

            if (httpStatusCode != 200 || body == null
                    || type != null && ("terminate".equals(type) || "error".equals(type))) {
                GWT.log("ERROR (" + httpStatusCode + "): " + httpResponse, null);
                ErrorCondition condition = body == null ? ErrorCondition.bad_request
                        : ErrorCondition.undefined_condition;
                String msg = null;
                Packet error = body == null ? null : body.getFirstChild("error");
                if (error != null) {
                    for (Packet c : error.getChildren()) {
                        String xmlns = c.getAtribute("xmlns");
                        if ("text".equals(c.getName())) {
                            msg = c.getCData();
                            break;
                        } else if (xmlns != null && "urn:ietf:params:xml:ns:xmpp-stanzas".equals(xmlns)) {
                            condition = getCondition(c.getName(), httpStatusCode);
                        }
                    }
                }

                if (condition == ErrorCondition.item_not_found) {
                    state = State.disconnected;
                    fireEventError(boshCondition, condition, msg);
                } else if (errorCounter < MAX_ERRORS) {
                    errorCounter++;
                    send(lastSendedBody, standardHandler);
                } else if (type != null && "terminate".equals(type)) {
                    GWT.log("Disconnected by server", null);
                    state = State.disconnected;
                    fireDisconnectByServer(boshCondition, condition, msg);
                } else {
                    state = State.disconnected;
                    if (msg == null) {
                        msg = "[" + httpStatusCode + "] " + condition.name().replace('_', '-');
                    }
                    fireEventError(boshCondition, condition, msg);
                }
            } else {
                errorCounter = 0;
                if (receivedSid != null && sid != null && !receivedSid.equals(sid)) {
                    state = State.disconnected;
                    fireEventError(BoshErrorCondition.policy_violation, ErrorCondition.unexpected_request,
                            "Unexpected session initialisation.");
                } else if (receivedSid != null && sid == null) {
                    sid = receivedSid;
                    Cookies.setCookie(user.getResource() + "sid", sid, null, null, "/", false);
                    state = State.connected;
                }

                final List<? extends Packet> children = body.getChildren();
                if (children.size() > 0) {
                    fireEventReceiveStanzas(children);
                }
                continuousConnection(ack);
            }
            System.out.println("............sid value is:" + sid);
        }
    };

    //added by zhongfanglin@antapp.com
    scriptHandler = new ScriptSyntaxRequestCallback() {
        public void onError(String callbackID) {
            state = State.disconnected;
            GWT.log("Connection error", null);
            fireEventError(BoshErrorCondition.remote_connection_failed, null,
                    "Response error: request timeout or 404!");
        }

        public void onResponseReceived(String callbackID, String responseText) {

            if (state == State.disconnected)
                return;

            final String httpResponse = responseText;
            final String lastSendedBody = activeScriptRequests.remove(callbackID);

            System.out.println(" IN:" + httpResponse);
            fireOnBodyReceive(null, httpResponse);

            final Packet body = parse2(responseText.replaceAll("&semi;", ";"));

            final String type = body == null ? null : body.getAtribute("type");
            final String receivedSid = body == null ? null : body.getAtribute("sid");
            String $tmp = body == null ? null : body.getAtribute("rid");
            //final Long rid = $tmp == null ? null : Long.valueOf($tmp);
            final String ack = body == null ? null : body.getAtribute("ack");
            $tmp = body == null ? null : body.getAtribute("condition");
            if ($tmp != null)
                $tmp = $tmp.replace("-", "_");
            final BoshErrorCondition boshCondition = $tmp == null ? null : BoshErrorCondition.valueOf($tmp);

            final String wait = body == null ? null : body.getAtribute("wait");
            final String inactivity = body == null ? null : body.getAtribute("inactivity");
            if (wait != null && inactivity != null) {
                try {
                    int w = Integer.parseInt(wait);
                    int i = Integer.parseInt(inactivity);
                    int t = (w + i / 2) * 1000;
                    scriptBuilder.setTimeoutMillis(t);
                    GWT.log("New timeout: " + t + "ms", null);
                } catch (Exception e) {
                    GWT.log("Error in wait and inactivity attributes", e);
                }
            }

            if (body == null || type != null && ("terminate".equals(type) || "error".equals(type))) {
                GWT.log("ERROR : " + httpResponse, null);
                ErrorCondition condition = body == null ? ErrorCondition.bad_request
                        : ErrorCondition.undefined_condition;
                String msg = null;
                Packet error = body == null ? null : body.getFirstChild("error");
                if (error != null) {
                    for (Packet c : error.getChildren()) {
                        String xmlns = c.getAtribute("xmlns");
                        if ("text".equals(c.getName())) {
                            msg = c.getCData();
                            break;
                        } else if (xmlns != null && "urn:ietf:params:xml:ns:xmpp-stanzas".equals(xmlns)) {
                            condition = getCondition(c.getName(), -1);
                        }
                    }
                }

                if (condition == ErrorCondition.item_not_found) {
                    state = State.disconnected;
                    fireEventError(boshCondition, condition, msg);
                } else if (errorCounter < MAX_ERRORS) {
                    errorCounter++;
                    send(lastSendedBody, scriptHandler);
                } else if (type != null && "terminate".equals(type)) {
                    GWT.log("Disconnected by server", null);
                    state = State.disconnected;
                    fireDisconnectByServer(boshCondition, condition, msg);
                } else {
                    state = State.disconnected;
                    if (msg == null) {
                        msg = condition.name().replace('_', '-');
                    }
                    fireEventError(boshCondition, condition, msg);
                }
            } else {
                errorCounter = 0;
                if (receivedSid != null && sid != null && !receivedSid.equals(sid)) {
                    state = State.disconnected;
                    fireEventError(BoshErrorCondition.policy_violation, ErrorCondition.unexpected_request,
                            "Unexpected session initialisation.");
                } else if (receivedSid != null && sid == null) {
                    sid = receivedSid;
                    Cookies.setCookie(user.getResource() + "sid", sid, null, null, "/", false);
                    state = State.connected;
                }

                List<? extends Packet> children = body.getChildren();
                if (children.size() > 0) {
                    fireEventReceiveStanzas(children);
                }
                continuousConnection(ack);
            }
        }

    };
    //end added 
}

From source file:br.com.pegasus.solutions.smartgwt.lib.client.view.impl.advanced.bar.infra.ExporterData.java

License:Apache License

private static void processRequest(String params) {
    try {/*from   ww w  . j  a va  2 s .  c  om*/
        RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.POST,
                GWT.getModuleBaseURL() + "ExportServlet");
        requestBuilder.setHeader("Content-type", "application/x-www-form-urlencoded");

        requestBuilder.sendRequest(params, new RequestCallback() {
            public void onResponseReceived(Request request, Response response) {
                if (200 == response.getStatusCode()) {
                    ExporterData.callExportServlet
                            .fireEvent(new ClickEvent(ExporterData.callExportServlet.getJsObj()));
                } else {
                    MessageUtil
                            .showError("An Error occurred response status code: " + response.getStatusCode());
                }
            }

            public void onError(Request request, Throwable exception) {
                MessageUtil.showError(exception.getMessage());
            }
        });
    } catch (RequestException e) {
        MessageUtil.showError(e.getMessage());
    }
}

From source file:br.com.pegasus.solutions.smartgwt.lib.client.view.impl.util.HttpRequestUtil.java

License:Apache License

/**
 * do request// w w  w. j  a va  2  s  .  c  o m
 * 
 * @param servletName {@link String}
 * @param params {@link String}
 * @param iRequestBuilderSucessAction {@link IRequestBuilderFailedAction}
 * @param iFailedAction {@link IRequestBuilderFailedAction}
 * @throws RequestException
 * @return void
 */
private static void doRequest(final IRequestBuilderSucessAction iRequestBuilderSucessAction,
        final IRequestBuilderFailedAction iFailedAction, String url, String params,
        RequestBuilder.Method method) throws RequestException {

    RequestBuilder requestBuilder = new RequestBuilder(method, url);
    requestBuilder.setHeader("Content-type", "application/x-www-form-urlencoded");
    requestBuilder.sendRequest(params, new RequestCallback() {
        public void onResponseReceived(Request request, Response response) {
            if (200 == response.getStatusCode() && iRequestBuilderSucessAction != null) {
                iRequestBuilderSucessAction.executeAction(request, response);
            }
        }

        public void onError(Request request, Throwable exception) {
            if (iFailedAction != null) {
                iFailedAction.executeAction(request, exception);
            } else {
                MessageUtil.showError(exception.getMessage());
            }
        }
    });
}

From source file:bufferings.ktr.wjr.client.service.KtrWjrJsonServiceAsync.java

License:Apache License

/**
 * {@inheritDoc}/*from   www.  j a  v a  2  s  .  com*/
 */
public void loadConfig(String configId, final AsyncCallback<WjrConfig> callback) {
    final List<Pair> params = new ArrayList<Pair>();
    params.add(new Pair(KEY_METHOD, METHOD_LOAD_CONFIG));
    params.add(new Pair(KEY_CONFIG_ID, configId));
    try {
        sendRequest(params, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
                callback.onFailure(exception);
            }

            public void onResponseReceived(Request request, Response response) {
                try {
                    callback.onSuccess(createWjrConfigFromJson(response.getText()));
                } catch (Exception e) {
                    callback.onFailure(e);
                }
            }
        });
    } catch (RequestException e) {
        callback.onFailure(e);
    }
}

From source file:bufferings.ktr.wjr.client.service.KtrWjrJsonServiceAsync.java

License:Apache License

/**
 * {@inheritDoc}/*w ww  .jav a 2  s.  c  o m*/
 */
public void loadStore(final AsyncCallback<WjrStore> callback) {
    final List<Pair> params = new ArrayList<Pair>();
    params.add(new Pair(KEY_METHOD, METHOD_LOAD_STORE));
    try {
        sendRequest(params, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
                callback.onFailure(exception);
            }

            public void onResponseReceived(Request request, Response response) {
                try {
                    callback.onSuccess(createWjrStoreFromJson(response.getText()));
                } catch (Exception e) {
                    callback.onFailure(e);
                }
            }
        });
    } catch (RequestException e) {
        callback.onFailure(e);
    }
}

From source file:bufferings.ktr.wjr.client.service.KtrWjrJsonServiceAsync.java

License:Apache License

/**
 * {@inheritDoc}/*from w  w  w. j av a2 s  .  c o  m*/
 */
public void runTest(WjrMethodItem methodItem, boolean cpumsEnabled, boolean apimsEnabled,
        boolean logHookEnabled, String logHookTimezone, final AsyncCallback<WjrMethodItem> callback) {
    final List<Pair> params = new ArrayList<Pair>();
    params.add(new Pair(KEY_METHOD, METHOD_RUN_TEST));
    params.add(new Pair(KEY_RUN_CLASS_NAME, methodItem.getClassName()));
    params.add(new Pair(KEY_RUN_METHOD_NAME, methodItem.getMethodName()));
    params.add(new Pair(KEY_CPUMS_ENABLED, Boolean.toString(cpumsEnabled)));
    params.add(new Pair(KEY_APIMS_ENABLED, Boolean.toString(apimsEnabled)));
    params.add(new Pair(KEY_LOGHOOK_ENABLED, Boolean.toString(logHookEnabled)));
    params.add(new Pair(KEY_LOGHOOK_TIMEZONE, logHookTimezone));
    try {
        sendRequest(params, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
                callback.onFailure(exception);
            }

            public void onResponseReceived(Request request, Response response) {
                try {
                    callback.onSuccess(createWjrMethodItemFromJson(response.getText()));
                } catch (Exception e) {
                    callback.onFailure(e);
                }
            }
        });
    } catch (RequestException e) {
        callback.onFailure(e);
    }
}

From source file:ca.upei.ic.timetable.client.CourseDetailController.java

License:Apache License

/**
 * Show the details of a course in a dialog box
 * //  www . ja v a 2  s.  c  o  m
 * @param courseId
 */
public void showCourseDetail(final int courseId) {

    Service.defaultInstance().cancelCourseDetailRequest();

    Service.defaultInstance().askCourseDetail(courseId, new RequestCallback() {

        public void onError(Request request, Throwable exception) {
            app_.error("Cannot get course details for course " + courseId, exception);
        }

        public void onResponseReceived(Request request, Response response) {
            try {
                String result = response.getText();
                JSONValue value = JSONParser.parse(result);
                try {
                    getView().loadJSON(value);
                    getView().showAt(265, 28);
                } catch (Exception ex) {
                    // do nothing
                }
            } catch (Exception ex) {
                app_.error("Cannot get course details for course " + courseId, ex);
            }
        }

    });
}

From source file:ca.upei.ic.timetable.client.CourseViewController.java

License:Apache License

public void search() {
    JSONObject department = new JSONObject();
    for (String d : departmentCriteria_.keySet()) {
        if (departmentCriteria_.get(d)) {
            department.put(d, JSONBoolean.getInstance(true));
        }//from  w  ww  . j a  v a  2  s  . c  om
    }
    JSONObject level = new JSONObject();
    for (String l : levelCriteria_.keySet()) {
        if (levelCriteria_.get(l)) {
            level.put(l, JSONBoolean.getInstance(true));
        }
    }
    JSONObject semester = new JSONObject();
    for (String s : semesterCriteria_.keySet()) {
        if (semesterCriteria_.get(s))
            semester.put(s, JSONBoolean.getInstance(true));
    }

    JSONObject value = new JSONObject();
    value.put("department", department);
    value.put("level", level);
    value.put("semester", semester);
    value.put("day", new JSONString(courseDay_));
    value.put("startTime", new JSONString(courseStartTime_));

    Service.defaultInstance().askCourses(value.toString(), new RequestCallback() {

        public void onError(Request request, Throwable exception) {
            app_.error(ApplicationController.OOPS, exception);
        }

        public void onResponseReceived(Request request, Response response) {

            try {
                JSONArray parsedArray = (JSONArray) JSONParser.parse(response.getText());
                // remove the selected courses
                // filtered array
                JSONArray filteredArray = new JSONArray();
                int filtered_index = 0;
                for (int i = 0; i < parsedArray.size(); i++) {
                    JSONObject o = (JSONObject) parsedArray.get(i);
                    int id = (int) ((JSONNumber) o.get("id")).doubleValue();
                    if (!isSelected(id)) {
                        filteredArray.set(filtered_index++, o);
                    }
                }
                // clear out the view so we can add courses
                view_.clear();
                // add the selected values first
                for (int index : selectionIndexes_) {
                    view_.addCourse(index, selectionValues_.get(index), true);
                }
                // add the remaining courses
                view_.loadJSON(filteredArray);
            } catch (Throwable e) {
                app_.error("Error: " + response.getText(), e);
            }
        }

    });
}

From source file:ca.upei.ic.timetable.client.FindCourseViewController.java

License:Apache License

/**
 * Get the department model/*  w w w.  j  ava 2 s .co  m*/
 * 
 * @return the department model
 */
public DepartmentModelView getDepartmentModel() {
    if (!departmentLoaded_) {
        Service.defaultInstance().askDepartments(new RequestCallback() {

            public void onError(Request request, Throwable exception) {
                app_.error(ApplicationController.OOPS, exception);
            }

            public void onResponseReceived(Request request, Response response) {
                JSONValue value = JSONParser.parse(response.getText());
                department_.loadJSON(value);
                departmentLoaded_ = true;
            }

        });
    }

    return department_;
}

From source file:ca.upei.ic.timetable.client.FindCourseViewController.java

License:Apache License

/**
 * Get the level model//from   w  w w.ja v a 2 s .  c o m
 * 
 * @return the level model
 */
public LevelModelView getLevelModel() {
    if (!levelLoaded_) {
        Service.defaultInstance().askCourseLevels(new RequestCallback() {

            public void onError(Request request, Throwable exception) {
                app_.error(ApplicationController.OOPS, exception);
            }

            public void onResponseReceived(Request request, Response response) {
                JSONValue value = JSONParser.parse(response.getText());
                level_.loadJSON(value);
                levelLoaded_ = true;
            }

        });
    }

    return level_;
}