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

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

Introduction

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

Prototype

void onError(Request request, Throwable exception);

Source Link

Document

Called when a com.google.gwt.http.client.Request does not complete normally.

Usage

From source file:org.apache.hupa.client.ioc.AppGinModule.java

License:Apache License

@Provides
@Singleton/*from   www .j  a  va 2s.  c om*/
HupaRequestFactory getRequestFactory(final EventBus eventBus) {
    InstrumentationLoggerProvider.get().instrument(
            "org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x0_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x10x1_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x1_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x2_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x10x0");
    InstrumentationLoggerProvider.get()
            .instrument("org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f");
    InstrumentationLoggerProvider.get().instrument(
            "org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x00x0_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x0_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x00x10x0_____org_apache_hupa_client_ioc_AppGinModule_java0x0_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x00x1");
    HupaRequestFactory rf = GWT.create(HupaRequestFactory.class);
    InstrumentationLoggerProvider.get().instrument(
            "org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x0_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x0_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x0_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x1_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1");
    rf.initialize(eventBus, new DefaultRequestTransport() {
        @Override
        protected RequestCallback createRequestCallback(TransportReceiver receiver) {
            InstrumentationLoggerProvider.get().instrument(
                    "org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x175546543");
            InstrumentationLoggerProvider.get().instrument(
                    "org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x0_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x20x0_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x3_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x2_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x1");
            InstrumentationLoggerProvider.get().instrument(
                    "org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x00x20x0_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x00x0_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x00x1_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x0_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x00x2");
            final RequestCallback superCallback = super.createRequestCallback(receiver);
            InstrumentationLoggerProvider.get().instrument(
                    "org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x1_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x00x1_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x0_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x00x0");
            return new RequestCallback() {
                @Override
                public void onResponseReceived(Request request, Response response) {
                    InstrumentationLoggerProvider.get().instrument(
                            "org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x00x1163a3f9f");
                    InstrumentationLoggerProvider.get().instrument(
                            "org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x00x1163a3f9f0x2_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x00x1163a3f9f0x30x0_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x00x1163a3f9f0x3_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x00x1163a3f9f0x20x0_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x00x1163a3f9f0x4_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x00x1163a3f9f0x1_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x00x1163a3f9f0x0");
                    InstrumentationLoggerProvider.get().instrument(
                            "org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x00x1163a3f9f0x40x0_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x00x1163a3f9f0x40x00x1_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x00x1163a3f9f0x40x00x0_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x00x1163a3f9f0x40x00x00x0");
                    if (response.getText().contains(User.NOT_FOUND)) {
                        InstrumentationLoggerProvider.get().instrument(
                                "org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x00x1163a3f9f0x40x00x10x00x0_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x00x1163a3f9f0x40x00x10x00x00x00x0_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x00x1163a3f9f0x40x00x10x0_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x00x1163a3f9f0x40x00x10x00x00x0");
                        eventBus.fireEvent(new LogoutEvent(null));
                    } else {
                        InstrumentationLoggerProvider.get().instrument(
                                "org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x00x1163a3f9f0x40x00x2");
                        InstrumentationLoggerProvider.get().instrument(
                                "org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x00x1163a3f9f0x40x00x20x00x0_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x00x1163a3f9f0x40x00x20x0");
                        superCallback.onResponseReceived(request, response);
                    }
                }

                @Override
                public void onError(Request request, Throwable exception) {
                    InstrumentationLoggerProvider.get().instrument(
                            "org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x00x12a6f6c13");
                    InstrumentationLoggerProvider.get().instrument(
                            "org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x00x12a6f6c130x30x0_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x00x12a6f6c130x3_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x00x12a6f6c130x1_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x00x12a6f6c130x0_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x00x12a6f6c130x2_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x00x12a6f6c130x20x0_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x00x12a6f6c130x4");
                    InstrumentationLoggerProvider.get().instrument(
                            "org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x00x12a6f6c130x40x00x0_____org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x10x00x00x1755465430x30x10x00x12a6f6c130x40x0");
                    superCallback.onError(request, exception);
                }
            };
        }
    });
    InstrumentationLoggerProvider.get()
            .instrument("org_apache_hupa_client_ioc_AppGinModule_java0x0d734f59aa2505a3f0x20x2");
    return rf;
}

From source file:org.fusesource.restygwt.client.callback.CachingCallbackFilter.java

License:Apache License

/**
 * the real filter method, called independent of the response code
 *
 * TODO method.getResponse() is not equal to response. unfortunately
 *//*ww  w. ja  va  2 s .co  m*/
@Override
public RequestCallback filter(final Method method, final Response response, RequestCallback callback) {
    final int code = response.getStatusCode();

    final CacheKey ck = cacheKey(method.builder);
    final List<RequestCallback> removedCallbacks = cache.removeCallbacks(ck);

    if (removedCallbacks != null) {
        callback = new RequestCallback() {
            @Override
            public void onResponseReceived(Request request, Response response) {
                if (GWT.isClient() && LogConfiguration.loggingIsEnabled()) {
                    Logger.getLogger(CachingCallbackFilter.class.getName())
                            .finer("call " + removedCallbacks.size() + " more queued callbacks for " + ck);
                }

                // call all callbacks found in cache
                for (RequestCallback cb : removedCallbacks) {
                    cb.onResponseReceived(request, response);
                }
            }

            @Override
            public void onError(Request request, Throwable exception) {
                if (LogConfiguration.loggingIsEnabled()) {
                    Logger.getLogger(CachingCallbackFilter.class.getName())
                            .severe("cannot call " + (removedCallbacks.size() + 1) + " callbacks for " + ck
                                    + " due to error: " + exception.getMessage());
                }

                if (LogConfiguration.loggingIsEnabled()) {
                    Logger.getLogger(CachingCallbackFilter.class.getName())
                            .finer("call " + removedCallbacks.size() + " more queued callbacks for " + ck);
                }

                // and all the others, found in cache
                for (RequestCallback cb : removedCallbacks) {
                    cb.onError(request, exception);
                }
            }
        };
    } else {
        if (GWT.isClient() && LogConfiguration.loggingIsEnabled()) {
            Logger.getLogger(CachingCallbackFilter.class.getName())
                    .finer("removed one or no " + "callback for cachekey " + ck);
        }
    }

    if (isCachingStatusCode(code)) {
        cacheResult(method, response);
        return callback;
    }

    if (GWT.isClient() && LogConfiguration.loggingIsEnabled()) {
        Logger.getLogger(CachingCallbackFilter.class.getName())
                .info("cannot cache due to invalid response code: " + code);
    }
    return callback;
}

From source file:org.fusesource.restygwt.client.callback.FilterawareRetryingCallback.java

License:Apache License

public void handleErrorGracefully(Request request, Response response, RequestCallback requestCallback) {
    // error handling...:
    if (currentRetryCounter < numberOfRetries) {
        if (LogConfiguration.loggingIsEnabled()) {
            Logger.getLogger(FilterawareRetryingCallback.class.getName())
                    .severe("error handling in progress for: " + method.builder.getHTTPMethod() + " "
                            + method.builder.getUrl());
        }/*from   ww w  . j av  a2s .c o  m*/

        currentRetryCounter++;

        Timer t = new Timer() {
            public void run() {
                try {
                    method.builder.send();
                } catch (RequestException ex) {
                    if (LogConfiguration.loggingIsEnabled()) {
                        Logger.getLogger(FilterawareRetryingCallback.class.getName()).severe(ex.getMessage());
                    }
                }
            }
        };

        t.schedule(gracePeriod);
        gracePeriod = gracePeriod * 2;
    } else {
        if (LogConfiguration.loggingIsEnabled()) {
            Logger.getLogger(FilterawareRetryingCallback.class.getName())
                    .severe("Request failed: " + method.builder.getHTTPMethod() + " " + method.builder.getUrl()
                            + " after " + currentRetryCounter + " tries.");
        }

        if (null != request && null != response && null != requestCallback) {
            // got the original callback, call error here
            requestCallback.onError(request,
                    new RuntimeException("Response " + response.getStatusCode() + " for "
                            + method.builder.getHTTPMethod() + " " + method.builder.getUrl() + " after "
                            + numberOfRetries + " retries."));
        } else {
            // got no callback - well, goodbye
            if (Window.confirm("error")) {
                // Super severe error.
                // reload app or redirect.
                // ===> this breaks the app but that's by intention.
                Window.Location.reload();
            }
        }
    }
}

From source file:org.fusesource.restygwt.client.callback.RetryingFilterawareRequestCallback.java

License:Apache License

private void handleErrorGracefully(Request request, Response response, RequestCallback requestCallback) {
    // error handling...:
    if (currentRetryCounter < numberOfRetries) {
        if (GWT.isClient() && LogConfiguration.loggingIsEnabled()) {
            Logger.getLogger(RetryingFilterawareRequestCallback.class.getName())
                    .severe("error handling in progress for: " + method.builder.getHTTPMethod() + " "
                            + method.builder.getUrl());
        }//from   w  w w . ja  v a  2 s  .  c o  m

        currentRetryCounter++;

        Timer t = new Timer() {
            @Override
            public void run() {
                try {
                    method.builder.send();
                } catch (RequestException ex) {
                    if (GWT.isClient() && LogConfiguration.loggingIsEnabled()) {
                        Logger.getLogger(RetryingFilterawareRequestCallback.class.getName())
                                .severe(ex.getMessage());
                    }
                }
            }
        };

        t.schedule(gracePeriod);
        gracePeriod = gracePeriod * 2;
    } else {
        if (GWT.isClient() && LogConfiguration.loggingIsEnabled()) {
            Logger.getLogger(RetryingFilterawareRequestCallback.class.getName())
                    .severe("Request failed: " + method.builder.getHTTPMethod() + " " + method.builder.getUrl()
                            + " after " + currentRetryCounter + " tries.");
        }

        if (null != request && null != response && null != requestCallback) {
            // got the original callback, call error here
            requestCallback.onError(request,
                    new RuntimeException("Response " + response.getStatusCode() + " for "
                            + method.builder.getHTTPMethod() + " " + method.builder.getUrl() + " after "
                            + numberOfRetries + " retries."));
        } else {
            // got no callback - well, goodbye
            if (Window.confirm("something severly went wrong - error - reload page ?")) {
                // Super severe error.
                // reload app or redirect.
                // ===> this breaks the app but that's by intention.
                Window.Location.reload();
            }
        }
    }
}

From source file:org.jboss.errai.bus.client.framework.transports.HttpPollingHandler.java

License:Apache License

/**
 * Sends the given string oon the outbound communication channel (as a POST
 * request to the server)./* ww  w .j  a  va2 s . c om*/
 *
 * @param payload
 *     The message to send. It is sent verbatim.
 * @param callback
 *     The callback to receive success or error notification. Note that
 *     this callback IS NOT CALLED if the request is cancelled.
 * @param extraParameters
 *     Extra paramets to include in the HTTP request (key is parameter name;
 *     value is parameter value).
 *
 * @throws com.google.gwt.http.client.RequestException
 *     if the request cannot be sent at all.
 */
public Request sendPollingRequest(final String payload, final Map<String, String> extraParameters,
        final RequestCallback callback) throws RequestException {

    // LogUtil.log("[bus] sendPollingRequest(" + payload + ")");

    final String serviceEntryPoint;
    final Map<String, String> parmsMap;
    final boolean waitChannel;
    boolean activeWaitChannel = false;

    final Iterator<RxInfo> iterator = pendingRequests.iterator();
    while (iterator.hasNext()) {
        final RxInfo pendingRx = iterator.next();
        if (pendingRx.getRequest().isPending() && pendingRx.isWaiting()) {
            //  LogUtil.log("[bus] ABORT SEND: " + pendingRx + " is waiting" );
            // return null;
            activeWaitChannel = true;
        }

        if (!pendingRx.getRequest().isPending()) {
            iterator.remove();
        }
    }

    if (!activeWaitChannel && receiveCommCallback.canWait() && !rxActive) {
        parmsMap = new HashMap<String, String>(extraParameters);
        parmsMap.put("wait", "1");
        serviceEntryPoint = messageBus.getInServiceEntryPoint();
        waitChannel = true;
    } else {
        parmsMap = extraParameters;
        serviceEntryPoint = messageBus.getOutServiceEntryPoint();
        waitChannel = false;
    }

    rxActive = true;

    final StringBuilder extraParmsString = new StringBuilder();
    for (final Map.Entry<String, String> entry : parmsMap.entrySet()) {
        extraParmsString.append("&").append(URL.encodePathSegment(entry.getKey())).append("=")
                .append(URL.encodePathSegment(entry.getValue()));
    }

    final long latencyTime = System.currentTimeMillis();

    final RequestBuilder builder = new RequestBuilder(RequestBuilder.POST,
            URL.encode(messageBus.getApplicationLocation(serviceEntryPoint)) + "?z=" + getNextRequestNumber()
                    + "&clientId=" + URL.encodePathSegment(messageBus.getClientId())
                    + extraParmsString.toString());
    builder.setHeader("Content-Type", "application/json; charset=utf-8");

    final RxInfo rxInfo = new RxInfo(System.currentTimeMillis(), waitChannel);

    try {
        // LogUtil.log("[bus] TX: " + payload);
        final Request request = builder.sendRequest(payload, new RequestCallback() {
            @Override
            public void onResponseReceived(final Request request, final Response response) {
                if (!waitChannel) {
                    measuredLatency = (int) (System.currentTimeMillis() - latencyTime);
                }

                pendingRequests.remove(rxInfo);
                callback.onResponseReceived(request, response);
                rxNumber++;
                rxActive = false;
            }

            @Override
            public void onError(final Request request, final Throwable exception) {
                pendingRequests.remove(rxInfo);
                callback.onError(request, exception);
                rxActive = false;
            }
        });

        rxInfo.setRequest(request);
        pendingRequests.add(rxInfo);

        return request;
    } catch (RequestException e) {
        throw e;
    }
}

From source file:org.opencms.ugc.client.CmsRpcCallHelper.java

License:Open Source License

/**
 * Executes the RPC call.<p>/*from  ww w. java  2s.c  o  m*/
 *
 * @param requestBuilder the request builder returned by the service interface
 */
@SuppressWarnings("synthetic-access")
public void executeRpc(RequestBuilder requestBuilder) {

    final RequestCallback callback = requestBuilder.getCallback();
    RequestCallback callbackWrapper = new RequestCallback() {

        public void onError(com.google.gwt.http.client.Request request, Throwable exception) {

            m_requestCounter.decrement();
            callback.onError(request, exception);
        }

        public void onResponseReceived(com.google.gwt.http.client.Request request,
                com.google.gwt.http.client.Response response) {

            m_requestCounter.decrement();
            callback.onResponseReceived(request, response);
        }
    };
    requestBuilder.setCallback(callbackWrapper);
    m_requestCounter.increment();
    try {
        requestBuilder.send();
    } catch (Exception e) {
        m_requestCounter.decrement();
    }
}

From source file:org.openehealth.ipf.platform.camel.flow.admin.client.Rest.java

License:Apache License

public void get(RequestCallback callback) {
    try {//w  ww  . j ava  2  s.c o  m
        RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
        builder.setHeader("Cache-Control", "no-cache");
        builder.sendRequest(null, callback);
    } catch (RequestException e) {
        callback.onError(null, e);
    }
}

From source file:org.openehealth.ipf.platform.camel.flow.admin.client.Rest.java

License:Apache License

public void post(String content, RequestCallback callback) {
    try {//from   ww w.j a va2  s. co m
        RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
        builder.setHeader("Cache-Control", "no-cache");
        builder.setHeader("Content-Type", "application/json");
        builder.sendRequest(content, callback);
    } catch (RequestException e) {
        callback.onError(null, e);
    }
}

From source file:org.openehealth.ipf.platform.camel.flow.admin.client.Rest.java

License:Apache License

public void delete(RequestCallback callback) {
    try {//w  w w  .  ja  v a  2 s .c o  m
        RequestBuilder builder = new WorkaroundRequestBuilder("delete", url);
        builder.setHeader("Cache-Control", "no-cache");
        builder.sendRequest(null, callback);
    } catch (RequestException e) {
        callback.onError(null, e);
    }
}

From source file:org.palaso.languageforge.client.lex.jsonrpc.JsonRpc.java

License:Apache License

/**
 * Executes a json-rpc request.//from   w  w  w .ja  va 2s.c  o  m
 * 
 * @param <R>
 * 
 * @param <R>
 * 
 * @param url
 *            The location of the service
 * @param username
 *            The username for basic authentification
 * @param password
 *            The password for basic authentification
 * @param method
 *            The method name
 * @param params
 *            An array of objects containing the parameters
 * @param callback
 *            A callbackhandler like in gwt's rpc.
 */

// NOTE We will use the Action to 3encode our request and decode the
// response
// of *the object* (DTO)
// NOTE This class will add the rpc elements which wrap the request and
// repsonse.
public <A extends Action<R>, R> void execute(final A action, final AsyncCallback<R> callback) {

    RequestCallback handler = new RequestCallback() {
        public void onResponseReceived(Request request, Response response) {
            try {
                if (response.getStatusCode() != 200) {
                    String errMsg = "";
                    if (response.getStatusCode() == 0) {
                        errMsg = "Error: Can not connect to server, this may be a problem of network or server down.";
                    } else {
                        errMsg = "Error: Unexpected server or network error ["
                                + String.valueOf(response.getStatusCode()) + "]: " + response.getStatusText();
                    }
                    RuntimeException runtimeException = new RuntimeException(errMsg);
                    callback.onFailure(runtimeException);
                    return;
                }

                String resp = response.getText();

                if (resp.equals("")) {
                    RuntimeException runtimeException = new RuntimeException(
                            "Error: Received empty result from server, this could be a server fail.");
                    callback.onFailure(runtimeException);
                }

                JsonRpcResponse<R> reply = action.decodeResponse(resp);

                if (reply == null) { // This implies a decode error. Perhaps
                                     // it would be better if the action
                                     // doing the decode threw a more
                                     // precise exception
                    RuntimeException runtimeException = new RuntimeException(
                            "Error: Received data can not decoded, data: " + response.getText());
                    callback.onFailure(runtimeException);
                }

                if (reply.getResponseModel().isErrorResponse()) {
                    RuntimeException runtimeException = new RuntimeException(
                            "Error: Server failed with message: " + reply.getResponseModel().getError());
                    callback.onFailure(runtimeException);
                } else if (reply.getResponseModel().isSuccessfulResponse()) {
                    R result = (R) reply.getResponseModel().getResult();
                    callback.onSuccess(result);
                } else {
                    RuntimeException runtimeException = new RuntimeException(
                            "Error: Received data has syntax error: " + response.getText());
                    callback.onFailure(runtimeException);
                }
            } catch (RuntimeException e) {
                callback.onFailure(e);
            } finally {
                decreaseRequestCounter(action.isBackgroundRequest());
            }
        }

        public void onError(Request request, Throwable exception) {
            try {
                if (exception instanceof RequestTimeoutException) {
                    RuntimeException runtimeException = new RuntimeException(
                            "Error: Connection timeout, server didn't respose.");
                    callback.onFailure(runtimeException);
                } else {
                    RuntimeException runtimeException = new RuntimeException(
                            "Error: A unknown error happened when try to send request to server");
                    callback.onFailure(runtimeException);
                }
            } catch (RuntimeException e) {
                callback.onFailure(e);
            } finally {
                decreaseRequestCounter(action.isBackgroundRequest());
            }
        }

    };

    increaseRequestCounter(action.isBackgroundRequest());

    // The request builder. Currently we only attempt a request once.
    RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, action.getFullServiceUrl());
    if (requestTimeout > 0)
        builder.setTimeoutMillis(requestTimeout);
    builder.setHeader("Content-Type", "application/json; charset=UTF-8");

    String body = action.getRequestModelAsJsonString(requestSerial++);

    if (body == null)
        builder.setHeader("Content-Length", "0");
    // builder.setHeader("Content-Length", Integer.toString(body.length()));
    if (requestCookie != null)
        if (Cookies.getCookie(requestCookie) != null)
            builder.setHeader("X-Cookie", Cookies.getCookie(requestCookie));

    try {
        builder.sendRequest(body, handler);
    } catch (RequestException exception) {
        handler.onError(null, exception);
    }
}