List of usage examples for com.google.gwt.http.client Response getStatusCode
public abstract int getStatusCode();
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 ww . ja v a 2s . c o m*/ }); } 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(";", ";")); 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 w w w.j a v a 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 .ja 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:cc.kune.embed.client.EmbedHelper.java
License:GNU Affero Public License
/** * Process request.//from ww w . j a va 2s .c o m * * @param url * the url * @param callback * the callback */ public static void processRequest(final String url, final Callback<Response, Void> callback) { try { final RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url); // Needed for CORS builder.setIncludeCredentials(true); @SuppressWarnings("unused") final Request request = builder.sendRequest(null, new RequestCallback() { @Override public void onError(final Request request, final Throwable exception) { Log.error("CORS exception: ", exception); callback.onFailure(null); } @Override public void onResponseReceived(final Request request, final Response response) { if (200 == response.getStatusCode()) { callback.onSuccess(response); } else { Log.error("Couldn't retrieve CORS (" + response.getStatusText() + ")"); callback.onFailure(null); } } }); } catch (final RequestException exception) { Log.error("CORS exception: ", exception); callback.onFailure(null); } }
From source file:ch.sebastienzurfluh.swissmuseum.core.client.model.io.CakeConnector.java
License:Open Source License
private <T> void asyncRequest(final Requests request, final int referenceId, String args, final AsyncCallback<T> callback) { final StringBuilder url = new StringBuilder(cakePath + request.getURL()); url.append(CAKE_ARGS_SEPARATOR).append(args); url.append(CAKE_ARGS_SEPARATOR).append(referenceId); url.append(CAKE_SUFFIX);/*from ww w . j a v a 2s.co m*/ System.out.println("Making async request on " + url); RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url.toString()); try { builder.sendRequest(null, new RequestCallback() { public void onError(Request httpRequest, Throwable exception) { System.out.println("JSON request failure. " + exception.getLocalizedMessage()); // we do nothing else than log callback.onFailure(exception); } @SuppressWarnings("unchecked") public void onResponseReceived(Request httpRequest, Response response) { if (200 == response.getStatusCode()) { System.out.println("Got answer from async request."); JsArray<Entry> entries = evalJson(response.getText().trim()); // BLACKBOX!!! DataType dataType = DataType.PAGE; switch (request) { case GETALLGROUPMENUS: dataType = DataType.GROUP; case GETALLPAGEMENUSFROMGROUP: // menu collection LinkedList<MenuData> dataList = new LinkedList<MenuData>(); for (int i = 0; i < entries.length(); i++) { Entry entry = entries.get(i); dataList.add(parseMenuData(entry, referenceId, dataType)); } // give callback callback.onSuccess((T) dataList); break; case GETDATA: case GETFIRSTDATAOFGROUP: // single data Data parsedData = parseData(entries.get(0), referenceId, DataType.PAGE); callback.onSuccess((T) parsedData); break; case GETRESOURCE: ResourceData parsedData2 = parseResourceData(entries.get(0), referenceId); callback.onSuccess((T) parsedData2); } } } }); } catch (Exception e) { callback.onFailure(e); } }
From source file:ch.sebastienzurfluh.swissmuseum.parcours.client.model.SimpleCakeBridge.java
License:Open Source License
public <ResponseType extends JavaScriptObject> void sendRequest(String requestString, final WithResult<ResponseType> withResult) { RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, cakePath + CAKE_ARGS_SEPARATOR + requestString + CAKE_SUFFIX); try {//from w w w . j ava 2 s .c om builder.sendRequest(null, new RequestCallback() { public void onError(Request httpRequest, Throwable exception) { System.out.println("JSON request failure. " + exception.getLocalizedMessage()); // we do nothing else than log } @SuppressWarnings("unchecked") public void onResponseReceived(Request httpRequest, Response response) { if (200 == response.getStatusCode()) { System.out.println("Got answer from async request."); withResult.execute((ResponseType) evalJson(response.getText().trim())); } } }); } catch (Exception e) { System.out.println("JSON request error. " + e.getLocalizedMessage()); // we do nothing else than log } }
From source file:ch.unifr.pai.twice.mousecontrol.client.TouchPadWidget.java
License:Apache License
/** * starts the execution of the component *//* w ww . j a v a 2 s. c o m*/ public void start() { if (!running) { label.setText("looking for available remote-clients"); getAvailableClients(new Command() { @Override public void execute() { label.setText((availableClients == null ? "0" : availableClients.length) + " clients found"); if (getCurrentClient() != null) { label.setText("looking for cursor on client " + getCurrentClient()); lookForCursor = new Timer() { @Override public void run() { try { new RequestBuilder(RequestBuilder.GET, GWT.getHostPageBaseURL() + controlServlet + "?a=x" + (getCurrentClient() != null ? "&targetUUID=" + getCurrentClient() : "") + (uuid != null ? "&uuid=" + uuid : "") + (host != null ? "&host=" + host : "") + (port != null ? "&port=" + port : "")).sendRequest(null, new RequestCallback() { @Override public void onResponseReceived(Request request, Response response) { if (response.getStatusCode() > 400) onError(request, null); label.setText("GOT DATA: " + response.getText()); String color = extractColor(response); if (color == null || color.isEmpty() || color.equals("#null")) color = null; extractLastAction(response); setScreenDimension(extractScreenDimensions(response)); if (color != null) { setColor(color); cursorAssigned(); } else { noCursorAvailable(); } } @Override public void onError(Request request, Throwable exception) { noCursorAvailable(); } }); } catch (RequestException e) { noCursorAvailable(); } } }; lookForCursor.run(); } } }); } }
From source file:ch.unifr.pai.twice.mousecontrol.client.TouchPadWidget.java
License:Apache License
/** * Sends the given query to the mouse pointer controller servlet * /* ww w.java2 s .c om*/ * @param query * @param callback */ protected void send(String query, final Command callback) { try { if (active) { new RequestBuilder(RequestBuilder.GET, GWT.getHostPageBaseURL() + controlServlet + "?" + (query != null ? query : "a=x") + (getCurrentClient() != null ? "&targetUUID=" + getCurrentClient() : "") + (uuid != null ? "&uuid=" + uuid : "") + (host != null ? "&host=" + host : "") + (port != null ? "&port=" + port : "") + ("&user=" + Authentication.getUserName())) .sendRequest(null, new RequestCallback() { @Override public void onResponseReceived(Request request, Response response) { if (response.getStatusCode() > 400) onError(request, null); String color = extractColor(response); if (response.getText().trim().isEmpty()) { label.setText("No connection available"); noConnection = true; } else { if (noConnection) { label.setText(""); noConnection = false; } if (color == null || color.isEmpty() || color.equals("#null")) color = null; extractLastAction(response); setColor(color); setScreenDimension(extractScreenDimensions(response)); if (callback != null) callback.execute(); } } @Override public void onError(Request request, Throwable exception) { setActive(false); } }); } } catch (Exception e) { e.printStackTrace(); } }
From source file:client.net.sf.saxon.ce.Xslt20ProcessorImpl.java
License:Mozilla Public License
public Node renderXML(JavaScriptObject inSourceDoc, DocumentInfo styleDoc, com.google.gwt.dom.client.Node target) { try {/* w w w.j a va2 s.c o m*/ if (styleDoc == null) { throw new Exception("Stylesheet for transform is null"); } docFetchRequired = inSourceDoc != null; CompilerInfo info = config.getDefaultXsltCompilerInfo(); info.setErrorListener(new StandardErrorListener()); String asyncSourceURI = null; // for now - don't use aync when using the JavaScript API calls that return a result if (docFetchRequired && (localController.getApiCommand() == APIcommand.UPDATE_HTML || (successCallback != null))) { asyncSourceURI = SaxonceApi.getAsyncUri(inSourceDoc); if (asyncSourceURI != null && asyncSourceURI.toLowerCase().startsWith("file:")) { asyncSourceURI = null; // force synchronous fetch if using file-system protocol } } // ----------- Start async code ------------- fetchedSourceDoc = null; transformInvoked = false; if (asyncSourceURI != null) { final String URI = asyncSourceURI; final Node transformTarget = target; logger.log(Level.FINE, "Aynchronous GET for: " + asyncSourceURI); final HTTPHandler hr = new HTTPHandler(); hr.doGet(asyncSourceURI, new RequestCallback() { public void onError(Request request, Throwable exception) { //hr.setErrorMessage(exception.getMessage()); String msg = "HTTP Error " + exception.getMessage() + " for URI " + URI; handleException(new RuntimeException(msg), "onError"); } public void onResponseReceived(Request request, Response response) { int statusCode = response.getStatusCode(); if (statusCode == 200) { Logger.getLogger("ResponseReceived").fine("GET Ok for: " + URI); Node responseNode; try { responseNode = (Node) XMLDOM.parseXML(response.getText()); } catch (Exception e) { handleException(new RuntimeException(e.getMessage()), "onResponseReceived"); return; } DocumentInfo responseDoc = config.wrapXMLDocument(responseNode, URI); // now document is here, we can transform it Node result = invokeTransform(responseDoc, transformTarget); hr.setResultNode(result); // TODO: This isn't used yet // handle OK response from the server } else if (statusCode < 400) { // transient } else { String msg = "HTTP Error " + statusCode + " " + response.getStatusText() + " for URI " + URI; handleException(new RuntimeException(msg), "onResponseReceived"); //hr.setErrorMessage(statusCode + " " + response.getStatusText()); } } // ends inner method }// ends inner class ); // ends doGet method call } // -------------- End async code /// we can compile - even while sourcedoc is being fetched asynchronously if (stylesheet == null) { if (LogConfiguration.loggingIsEnabled()) { LogController.InitializeTraceListener(); } logger.log(Level.FINE, "Compiling Stylesheet..."); PreparedStylesheet sheet = new PreparedStylesheet(config, info); sheet.prepare(styleDoc); stylesheet = sheet; logger.log(Level.FINE, "Stylesheet compiled OK"); } // for async operation - this is called within the callback - so don't call here if (asyncSourceURI == null && inSourceDoc != null) { int nodeType = (Node.is(inSourceDoc)) ? ((Node) inSourceDoc).getNodeType() : 0; if (nodeType > 0 && nodeType != Node.DOCUMENT_NODE) { // add a document node wrapper Node sourceNode = (Node) inSourceDoc; Document sourceDoc = sourceNode.getOwnerDocument(); HTMLDocumentWrapper htmlDoc = new HTMLDocumentWrapper(sourceDoc, sourceDoc.getURL(), config, DocType.UNKNOWN); fetchedSourceDoc = htmlDoc.wrap(sourceNode); } else { fetchedSourceDoc = SaxonceApi.getDocSynchronously(inSourceDoc, config); } } // this method only runs if transformInvoked == false - need to get sourceDoc reference if not invoked return invokeTransform(fetchedSourceDoc, target); //method ends - allowing onResponceReceived handler to call invokeTransform for async operation } catch (Exception e) { handleException(e, "renderXML"); return null; } }
From source file:colt.json.gwt.client.JsonClient.java
License:Apache License
public void invoke(final String _url, final String _serviceName, String requestData, final IAsyncJSON result) { try {/* w ww. ja v a 2s .c o m*/ RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.POST, URL.encode(_url + _serviceName)); requestBuilder.setHeader("content-type", "application/x-www-form-urlencoded"); Request request = requestBuilder.sendRequest(requestData, new RequestCallback() { public void onError(Request request, Throwable exception) { result.error(exception); } public void onResponseReceived(Request request, Response response) { if (200 == response.getStatusCode()) { String text = response.getText(); JSONValue parser = JSONParser.parse(text); JSONObject jobj = parser.isObject(); result.done(jobj); } else { result.error(new RuntimeException(_url + _serviceName + " :(")); } } }); } catch (RequestException e) { Window.alert(e.getMessage()); result.error(e); } }