Example usage for com.google.gwt.http.client Response getText

List of usage examples for com.google.gwt.http.client Response getText

Introduction

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

Prototype

public abstract String getText();

Source Link

Document

Returns the text associated with the response.

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);
                    }//from  w  w  w .j  a  v  a 2s .c  om
                });
            } 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:bufferings.ktr.wjr.client.service.KtrWjrJsonServiceAsync.java

License:Apache License

/**
 * {@inheritDoc}/*from  w ww  . j a v  a  2  s  .co m*/
 */
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}/*  ww  w .ja v  a  2s  .  c om*/
 */
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 a  v a 2 s . com*/
 */
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
 * /*w  w w.j a  va  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));
        }/*w  w w  . j  av  a2  s  .c  o m*/
    }
    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  ww  .jav  a 2  s .c  o 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  . j  a v  a 2s.  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_;
}

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

License:Apache License

public SemesterModelView getSemesterModel() {
    if (!semesterLoaded_) {
        Service.defaultInstance().askSemesters(new RequestCallback() {

            public void onError(Request request, Throwable exception) {
                app_.error(ApplicationController.OOPS, exception);
            }//w  w  w  .  j av a2s. c o  m

            public void onResponseReceived(Request request, Response response) {
                try {
                    String text = response.getText();
                    JSONValue value = JSONParser.parse(text);
                    semester_.loadJSON(value);
                    semesterLoaded_ = true;
                } catch (Exception e) {
                    app_.error("Error: " + response.getText(), e);
                }
            }

        });
    }

    return semester_;
}

From source file:cc.kune.core.client.actions.xml.XMLActionsParser.java

License:GNU Affero Public License

/**
 * Instantiates a new xML actions parser.
 *
 * @param errHandler/*  w w w.  j a  va 2  s  .  c o  m*/
 *          the err handler
 * @param contentViewer
 *          the content viewer
 * @param actionRegistry
 *          the action registry
 * @param contentService
 *          the content service
 * @param session
 *          the session
 * @param stateManager
 *          the state manager
 * @param i18n
 *          the i18n
 * @param newMenusRegistry
 *          the new menus registry
 * @param services
 *          the services
 */
@Inject
public XMLActionsParser(final ErrorHandler errHandler, final ContentViewerPresenter contentViewer,
        final ActionRegistryByType actionRegistry, final Provider<ContentServiceAsync> contentService,
        final Session session, final StateManager stateManager, final I18nTranslationService i18n,
        final NewMenusForTypeIdsRegistry newMenusRegistry, final Services services) {
    this.errHandler = errHandler;
    this.contentViewer = contentViewer;
    this.actionRegistry = actionRegistry;
    this.contentService = contentService;
    this.session = session;
    this.stateManager = stateManager;
    this.i18n = i18n;
    this.newMenusRegistry = newMenusRegistry;
    submenus = new HashMap<String, SubMenuDescriptor>();
    // Based on:
    // http://www.roseindia.net/tutorials/gwt/retrieving-xml-data.shtml
    final RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET,
            XMLActionsConstants.ACTIONS_XML_LOCATION_PATH_ABS);
    session.onAppStart(false, new AppStartHandler() {
        @Override
        public void onAppStart(final AppStartEvent event) {
            try {
                requestBuilder.sendRequest(null, new RequestCallback() {
                    @Override
                    public void onError(final Request request, final Throwable ex) {
                        onFailed(ex);
                    }

                    @Override
                    public void onResponseReceived(final Request request, final Response response) {
                        parse(new XMLKuneClientActions(services, response.getText()));
                    }
                });
            } catch (final RequestException ex) {
                onFailed(ex);
            }
        }
    });
}