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

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

Introduction

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

Prototype

public abstract Header[] getHeaders();

Source Link

Document

Returns an array of HTTP headers associated with this response.

Usage

From source file:com.ait.tooling.nativetools.client.resting.NResting.java

License:Open Source License

protected IRestingRequest call(final NMethod type, final String url, final String data,
        final NRestingHeaders headers, final IRestingResponseCallback callback) {
    Objects.requireNonNull(callback);

    final long cntr = ++m_docntr;

    final long time = System.currentTimeMillis();

    final NRequestBuilder builder = makeRequestBuilder(type, url);

    if (false == isActive()) {
        callback.onFailure(new InactiveRestingException(type, builder.getUrl(), cntr, time));

        return null;
    }//from  w ww .  j  a v  a  2s  . c  om
    final NRestingHeaders head = headers.doRESTHeaders();

    for (String k : head.keys()) {
        builder.setHeader(k, head.get(k));
    }
    int mils = head.getTimeout();

    if (mils > 0) {
        builder.setTimeoutMillis(mils);
    }
    String user = head.getUsername();

    if ((null != user) && (false == user.isEmpty())) {
        builder.setUser(user);

        String pass = head.getPassword();

        if ((null != pass) && (false == pass.isEmpty())) {
            builder.setPassword(pass);
        }
        builder.setIncludeCredentials(head.getIncludeCredentials());
    }
    try {
        return new NRestingRequest(builder.getUrl(), head, type, cntr, time,
                builder.sendRequest(data, new RequestCallback() {
                    @Override
                    public void onResponseReceived(final Request request, final Response response) {
                        callback.onResponse(new NRestingResponse(response.getStatusCode(), response.getText(),
                                new NRestingHeaders(response.getHeaders()).setOptions(head), type,
                                new NRestingRequest(builder.getUrl(), head, type, cntr, time, request),
                                System.currentTimeMillis() - time));
                    }

                    @Override
                    public void onError(final Request request, final Throwable e) {
                        callback.onFailure(new RestingException(e, type, builder.getUrl(), cntr, time));
                    }
                }));
    } catch (RequestException e) {
        callback.onFailure(new RestingException(e, type, builder.getUrl(), cntr, time));
    }
    return null;
}

From source file:com.smartgwt.mobile.client.data.DataSource.java

License:Open Source License

@SGWTInternal
protected void _sendGWTRequest(DSRequest dsRequest) {
    final int transactionNum = com.smartgwt.mobile.client.rpc.RPCManager._getNextTransactionNum();
    dsRequest._setTransactionNum(transactionNum);
    // For the time being, the request ID and transactionNum are the same.
    dsRequest.setRequestId(Integer.toString(transactionNum));

    final boolean strictJSON = Canvas._booleanValue(getStrictJSON(), false);
    final DSOperationType opType = dsRequest.getOperationType();
    final OperationBinding opBinding = getOperationBinding(dsRequest);

    final DSDataFormat dataFormat;
    if (opBinding == null)
        dataFormat = DSDataFormat.JSON;/*from  w ww . j a  v a  2  s . c o  m*/
    else if (opBinding.getDataFormat() != null)
        dataFormat = opBinding.getDataFormat();
    else
        dataFormat = DSDataFormat.JSON;
    assert dataFormat != null;

    DSProtocol protocol;
    if (opBinding != null && opBinding.getDataProtocol() != null) {
        protocol = opBinding.getDataProtocol();
    } else {
        protocol = getDataProtocol();
        if (protocol == null) {
            protocol = (opType == null || opType == DSOperationType.FETCH) ? null : DSProtocol.POSTMESSAGE;
        }
    }

    final Object originalData = dsRequest.getData();
    Object transformedData;
    switch (protocol == null ? DSProtocol.GETPARAMS : protocol) {
    case GETPARAMS:
    case POSTPARAMS:
        transformedData = transformRequest(dsRequest);
        if (transformedData == null)
            transformedData = Collections.EMPTY_MAP;
        else if (!(transformedData instanceof Map)) {
            // TODO Issue a warning.
            transformedData = Collections.EMPTY_MAP;
        }
        break;
    case POSTMESSAGE:
        transformedData = transformRequest(dsRequest);
        if (!(transformedData instanceof String)) {
            if (dataFormat != DSDataFormat.JSON) {
                throw new UnsupportedOperationException(
                        "Only serialization of DSRequests in JSON format is supported.");
            }
            transformedData = dsRequest._serialize(strictJSON);
            if (dsRequest.getContentType() == null) {
                // For best interoperability with ASP.NET AJAX services, send Content-Type:application/json.
                // http://weblogs.asp.net/scottgu/archive/2007/04/04/json-hijacking-and-how-asp-net-ajax-1-0-mitigates-these-attacks.aspx
                dsRequest.setContentType("application/json;charset=UTF-8");
            }
        }
        break;
    default:
        assert protocol != null;
        throw new UnsupportedOperationException(
                "In transforming the DSRequest, failed to handle case:  protocol:" + protocol.getValue());
    }
    if (transformedData != dsRequest) {
        dsRequest.setData(transformedData);
    }
    dsRequest.setOriginalData(originalData);
    if (dsRequest.getDataSource() == null)
        dsRequest.setDataSource(getID());
    final DSRequest finalDSRequest = dsRequest;
    assert finalDSRequest.getOperationType() == opType;

    if (protocol == null) {
        assert opType == DSOperationType.FETCH;
        if (transformedData == null
                || (transformedData instanceof Map && ((Map<?, ?>) transformedData).isEmpty())) {
            protocol = DSProtocol.GETPARAMS;
        } else {
            protocol = DSProtocol.POSTMESSAGE;
            transformedData = dsRequest._serialize(strictJSON);
            if (dsRequest.getContentType() == null) {
                dsRequest.setContentType("application/json;charset=UTF-8");
            }
        }
    }

    URIBuilder workBuilder;

    {
        String work = finalDSRequest.getDataURL();

        if (work == null) {
            if (opType != null) {
                switch (opType) {
                case FETCH:
                    work = getFetchDataURL();
                    break;
                case ADD:
                    work = getAddDataURL();
                    break;
                case UPDATE:
                    work = getUpdateDataURL();
                    break;
                case REMOVE:
                    work = getRemoveDataURL();
                    break;
                case VALIDATE:
                    work = getValidateDataURL();
                    break;
                case CUSTOM:
                    work = getCustomDataURL();
                    break;
                }
            }

            // common url
            if (work == null) {
                work = getDataURL();

                // construct default url
                if (work == null) {
                    work = RPCManager.getActionURL();
                    if (work.endsWith("/")) {
                        work = work.substring(0, work.length() - 1);
                    }
                }
            }
        }

        workBuilder = new URIBuilder(work);
    }

    // build up the query string
    final DateTimeFormat datetimeFormat = finalDSRequest._getDatetimeFormat();

    {
        Map<String, Object> params = finalDSRequest.getParams();

        if (protocol == DSProtocol.GETPARAMS || protocol == DSProtocol.POSTPARAMS) {
            if (params == null)
                params = new LinkedHashMap<String, Object>();

            if (protocol == DSProtocol.GETPARAMS) {
                assert transformedData instanceof Map;
                @SuppressWarnings("unchecked")
                final Map<String, Object> m = (Map<String, Object>) transformedData;
                params.putAll(m);
            }

            if (getSendMetaData()) {
                String metaDataPrefix = getMetaDataPrefix();
                if (metaDataPrefix == null)
                    metaDataPrefix = "_";

                params.put(metaDataPrefix + "operationType", opType);
                params.put(metaDataPrefix + "operationId", finalDSRequest.getOperationId());
                params.put(metaDataPrefix + "startRow", finalDSRequest.getStartRow());
                params.put(metaDataPrefix + "endRow", finalDSRequest.getEndRow());
                params.put(metaDataPrefix + "sortBy", finalDSRequest._getSortByString());
                params.put(metaDataPrefix + "useStrictJSON", Boolean.TRUE);
                params.put(metaDataPrefix + "textMatchStyle", finalDSRequest.getTextMatchStyle());
                params.put(metaDataPrefix + "oldValues", finalDSRequest.getOldValues());
                params.put(metaDataPrefix + "componentId", finalDSRequest.getComponentId());

                params.put(metaDataPrefix + "dataSource", dsRequest.getDataSource());
                params.put("isc_metaDataPrefix", metaDataPrefix);
            }

            params.put("isc_dataFormat", dataFormat.getValue());
        }

        if (params != null) {
            for (final Map.Entry<String, Object> e : params.entrySet()) {
                workBuilder.setQueryParam(e.getKey(), e.getValue(), strictJSON, false, datetimeFormat);
            }
        }
    }

    // automatically add the data format even to user-provided dataURLs unless they contain the param already
    if (!workBuilder.containsQueryParam("isc_dataFormat")) {
        workBuilder.appendQueryParam("isc_dataFormat", dataFormat.getValue());
    }

    if (protocol == DSProtocol.POSTPARAMS) {
        assert transformedData instanceof Map;
        @SuppressWarnings("unchecked")
        final Map<String, Object> m = (Map<String, Object>) transformedData;

        String requestContentType = finalDSRequest.getContentType();
        if (requestContentType != null)
            requestContentType = requestContentType.trim();

        if (requestContentType == null || requestContentType.startsWith("application/x-www-form-urlencoded")) {
            URIBuilder postBodyBuilder = new URIBuilder("");
            for (final Map.Entry<String, Object> e : m.entrySet()) {
                postBodyBuilder.setQueryParam(e.getKey(), e.getValue(), strictJSON, false, datetimeFormat);
            }
            // Exclude the '?'.
            transformedData = postBodyBuilder.toString().substring(1);
        } //else if (requestContentType.startsWith("multipart/form-data")) {} // TODO
        else {
            throw new IllegalArgumentException(
                    "Request content type '" + requestContentType + "' is not supported.");
        }
    }

    RequestBuilder.Method httpMethod = getHttpMethod(finalDSRequest.getHttpMethod());
    if (httpMethod == null) {
        if (protocol == DSProtocol.GETPARAMS)
            httpMethod = RequestBuilder.GET;
        else if (protocol == DSProtocol.POSTPARAMS || protocol == DSProtocol.POSTMESSAGE) {
            httpMethod = RequestBuilder.POST;
        } else {
            if (opType == null || opType == DSOperationType.FETCH) {
                httpMethod = RequestBuilder.GET;
            } else {
                httpMethod = RequestBuilder.POST;
            }
        }
    } else if (httpMethod == RequestBuilder.GET) {
        if (protocol == DSProtocol.POSTPARAMS ||
        //protocol == DSProtocol.POSTXML
                protocol == DSProtocol.POSTMESSAGE) {
            // TODO Warn that GET requests do not support bodies.
            httpMethod = RequestBuilder.POST;
        }
    }

    String requestContentType = finalDSRequest.getContentType();
    if (requestContentType != null) {
        if (httpMethod == RequestBuilder.GET) {
            // TODO Warn that GET requests do not support bodies.
            requestContentType = null;
        }
    } else {
        if (protocol == DSProtocol.POSTPARAMS)
            requestContentType = "application/x-www-form-urlencoded";
        //else if (protocol == DSProtocol.POSTXML) requestContentType = "text/xml";
    }

    final RequestBuilder rb = new RequestBuilder(httpMethod, workBuilder.toString());
    final Integer timeoutMillis = finalDSRequest.getTimeout();
    rb.setTimeoutMillis(timeoutMillis == null ? RPCManager._getDefaultTimeoutMillis()
            : Math.max(1, timeoutMillis.intValue()));

    final String authorization = finalDSRequest.getAuthorization();
    if (authorization != null)
        rb.setHeader("Authorization", authorization);

    final Map<String, String> httpHeaders = finalDSRequest.getHttpHeaders();
    if (httpHeaders != null) {
        for (Map.Entry<String, String> entry : httpHeaders.entrySet()) {
            rb.setHeader(entry.getKey(), entry.getValue());
        }
    }

    if (dataFormat == DSDataFormat.XML) {
        rb.setHeader("Accept", "application/xml,text/xml,*/*");
    } else if (dataFormat == DSDataFormat.JSON) {
        rb.setHeader("Accept", "application/json,*/*");
    }

    if (requestContentType != null) {
        rb.setHeader("Content-Type", requestContentType);
    }

    if (httpMethod != RequestBuilder.GET) {
        switch (protocol) {
        case POSTPARAMS: // `transformedData` has already been created and is now a String.
        case POSTMESSAGE:
            rb.setRequestData((String) transformedData);
            break;
        case GETPARAMS:
            // Already handled earlier when the query params were appended to `workBuilder'.
            break;
        default:
            throw new UnsupportedOperationException(
                    "In setting the request data, failed to handle case protocol:" + protocol);
        }
    }

    rb.setCallback(new RequestCallback() {
        @Override
        public void onError(Request request, Throwable exception) {
            final DSResponse dsResponse = new DSResponse(finalDSRequest);
            final int status;
            if (exception instanceof RequestTimeoutException)
                status = RPCResponse.STATUS_SERVER_TIMEOUT;
            else
                status = RPCResponse.STATUS_FAILURE;
            dsResponse.setStatus(status);
            onError(dsResponse);
        }

        private void onError(DSResponse dsResponse) {
            final DSRequest dsRequest = finalDSRequest;
            final boolean errorEventCancelled = ErrorEvent._fire(DataSource.this, dsRequest, dsResponse);
            if (!errorEventCancelled)
                RPCManager._handleError(dsResponse, dsRequest);
        }

        @Override
        public void onResponseReceived(Request request, Response response) {
            assert response != null;

            String responseText = response.getText();
            if (responseText == null)
                responseText = "";
            assert responseText != null;

            int httpResponseCode = response.getStatusCode();

            final HTTPHeadersMap responseHTTPHeaders = new HTTPHeadersMap();
            for (final Header h : response.getHeaders()) {
                if (h != null) {
                    responseHTTPHeaders.put(h.getName(), h.getValue());
                }
            }

            int status = 0;
            if (0 == httpResponseCode || // file:// requests (e.g. if Showcase is packaged with PhoneGap.)
            (200 <= httpResponseCode && httpResponseCode < 300) || httpResponseCode == 304) // 304 Not Modified
            {
                status = RPCResponse.STATUS_SUCCESS;
            } else {
                status = RPCResponse.STATUS_FAILURE;
                final DSResponse errorResponse = new DSResponse(finalDSRequest);
                errorResponse.setStatus(RPCResponse.STATUS_FAILURE);
                errorResponse.setHttpResponseCode(httpResponseCode);
                errorResponse._setHttpHeaders(responseHTTPHeaders);
                onError(errorResponse);
                return;
            }

            Object rawResponse;
            final DSResponse dsResponse;

            String origResponseContentType = responseHTTPHeaders.get("Content-Type");
            if (origResponseContentType == null
                    || (origResponseContentType = origResponseContentType.trim()).length() == 0) {
                origResponseContentType = "application/octet-stream";
            }

            String responseContentType = origResponseContentType;
            // remove the media type parameter if present
            // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7
            final int semicolonPos = responseContentType.indexOf(';');
            if (semicolonPos != -1) {
                responseContentType = responseContentType.substring(0, semicolonPos).trim();
                if (responseContentType.length() == 0)
                    responseContentType = "application/octet-stream";
            }

            if (dataFormat == DSDataFormat.CUSTOM) {
                rawResponse = responseText;

                dsResponse = new DSResponse(finalDSRequest, status);
                dsResponse.setHttpResponseCode(httpResponseCode);
                dsResponse._setHttpHeaders(responseHTTPHeaders);
                dsResponse.setContentType(origResponseContentType);

                transformResponse(dsResponse, finalDSRequest, responseText);
            } else {
                if (dataFormat == DSDataFormat.XML) {
                    final Element rootEl;
                    if (responseText.isEmpty()) {
                        rawResponse = rootEl = null;
                        dsResponse = new DSResponse(finalDSRequest, status);
                    } else {
                        final Document document;
                        try {
                            document = XMLParser.parse(responseText);
                        } catch (DOMParseException ex) {
                            onError(request, ex);
                            return;
                        }

                        rootEl = document.getDocumentElement();
                        rawResponse = rootEl;

                        dsResponse = new DSResponse(finalDSRequest, status, rootEl);

                        String dataTagName, recordName;
                        if (opBinding == null) {
                            dataTagName = _getDataTagName();
                            recordName = null;
                        } else {
                            dataTagName = opBinding._getDataTagName(_getDataTagName());
                            recordName = opBinding.getRecordName();
                        }
                        if (recordName == null)
                            recordName = _getRecordName();

                        final Element dataEl = extractDataElement(rootEl, dataTagName);
                        final List<Element> recordNodes = extractRecordElements(dataEl, recordName);

                        if (recordNodes != null && !recordNodes.isEmpty()) {
                            final RecordList records = extractRecordList(recordNodes);
                            dsResponse.setData(records);
                        } else if (rootEl.equals(dataEl)) {
                            dsResponse._setData(XMLUtil.getTextContent(dataEl));
                        }
                    }
                    dsResponse.setHttpResponseCode(httpResponseCode);
                    dsResponse._setHttpHeaders(responseHTTPHeaders);

                    transformResponse(dsResponse, finalDSRequest, rootEl);
                } else {
                    String jsonPrefix = getJsonPrefix();
                    if (jsonPrefix == null)
                        jsonPrefix = "";
                    String jsonSuffix = getJsonSuffix();
                    if (jsonSuffix == null)
                        jsonSuffix = "";

                    // auto-detect default wrapper text returned by RestHandler
                    if (responseText.startsWith(jsonPrefix) && responseText.endsWith(jsonSuffix)) {
                        responseText = responseText.substring(jsonPrefix.length(),
                                responseText.length() - jsonSuffix.length());
                        responseContentType = "application/json";
                    }

                    if (dataFormat == DSDataFormat.JSON) {
                        if (responseText.isEmpty()) {
                            rawResponse = null;
                            dsResponse = new DSResponse(finalDSRequest, status);
                        } else {
                            JSONObject responseObj;
                            try {
                                responseObj = JSONParser.parseLenient(responseText).isObject();
                            } catch (JSONException ex) {
                                onError(request, ex);
                                return;
                            }
                            if (responseObj != null && responseObj.containsKey("response")) {
                                JSONValue val = responseObj.get("response");
                                responseObj = (val == null ? null : val.isObject());
                            }
                            rawResponse = responseObj;

                            dsResponse = new DSResponse(finalDSRequest, status, responseObj);

                            if (responseObj != null && responseObj.containsKey("data")) {
                                final JSONValue dataVal = responseObj.get("data");
                                assert dataVal != null;

                                final JSONString dataStr = dataVal.isString();
                                if (dataStr != null) {
                                    dsResponse._setData(dataStr.stringValue());
                                } else {
                                    JSONArray dataArr = dataVal.isArray();
                                    if (dataArr == null) {
                                        JSONObject datumObj = dataVal.isObject();
                                        if (datumObj != null) {
                                            dataArr = new JSONArray();
                                            dataArr.set(0, datumObj);
                                        }
                                    }
                                    if (dataArr != null) {
                                        final RecordList records = extractRecordList(dataArr);
                                        dsResponse.setData(records);
                                    }
                                }
                            }
                        }
                        dsResponse.setHttpResponseCode(httpResponseCode);
                        dsResponse._setHttpHeaders(responseHTTPHeaders);

                        transformResponse(dsResponse, finalDSRequest, rawResponse);
                    } else {
                        throw new UnsupportedOperationException("Unhandled dataFormat:" + dataFormat);
                    }
                }
            }

            if (dsResponse.getInvalidateCache()) {
                //invalidateDataSourceDataChangedHandlers(finalDSRequest, dsResponse);
            }

            status = dsResponse.getStatus();
            if (status >= 0) {
                DSDataChangedEvent.fire(DataSource.this, dsResponse, finalDSRequest);
            } else {
                // Unless it was a validation error, or the request specified willHandleError,
                // go through centralized error handling (if alerting the failure string
                // can be dignified with such a name!)
                if (status != -4 && !finalDSRequest._getWillHandleError()) {
                    onError(dsResponse);
                    return;
                }
            }

            // fireResponseCallbacks
            final DSCallback callback = finalDSRequest.getCallback(),
                    afterFlowCallback = finalDSRequest._getAfterFlowCallback();
            if (callback != null) {
                callback.execute(dsResponse, rawResponse, finalDSRequest);
            }
            if (afterFlowCallback != null && afterFlowCallback != callback) {
                afterFlowCallback.execute(dsResponse, rawResponse, finalDSRequest);
            }
        }
    });

    try {
        rb.send();
    } catch (RequestException re) {
        re.printStackTrace();
    }
    ++_numDSRequestsSent;
}

From source file:com.teardrop.client.PerformSearch.java

License:Apache License

private void parseCookies(final Response pResponse) {
    final Header[] headers = pResponse.getHeaders();
    if (headers == null || headers.length == 0) {
        return;//from  www .  j  a  v a2 s .  c o m
    }
    for (int i = 0; i < headers.length; i++) {
        if (headers[i] != null && "Set-TDSession".equalsIgnoreCase(headers[i].getName())) {
            tdsession = headers[i].getValue();
        }
    }
}

From source file:fi.jasoft.uidlcompressor.client.ui.UIDLCompressorApplicationConnection.java

License:Apache License

@Override
protected void doAsyncUIDLRequest(String uri, String payload, final RequestCallback requestCallback)
        throws RequestException {

    // Wrap the request callback
    RequestCallback wrappedCallback = new RequestCallback() {
        public void onResponseReceived(Request request, final Response response) {

            Response jsonResponse = new Response() {

                /*/*ww  w  .  java  2 s .c o  m*/
                 * Caching the decoded json string in case getText() is
                 * called several times
                 */
                private String decodedJson;

                @Override
                public String getText() {
                    String base64 = response.getText();
                    if (base64.startsWith("for(")) {
                        // Server is sending json, digress
                        return base64;
                    }

                    if (decodedJson == null) {
                        long start = new Date().getTime();
                        decodedJson = decompressBase64Gzip(base64);
                        long end = new Date().getTime();
                        VConsole.log("Decoding JSON took " + (end - start) + "ms");
                    }

                    return decodedJson;
                }

                @Override
                public String getStatusText() {
                    return response.getStatusText();
                }

                @Override
                public int getStatusCode() {
                    return response.getStatusCode();
                }

                @Override
                public String getHeadersAsString() {
                    return response.getHeadersAsString();
                }

                @Override
                public Header[] getHeaders() {
                    return response.getHeaders();
                }

                @Override
                public String getHeader(String header) {
                    return response.getHeader(header);
                }
            };

            requestCallback.onResponseReceived(request, jsonResponse);
        }

        public void onError(Request request, Throwable exception) {
            requestCallback.onError(request, exception);
        }
    };

    // TODO Add payload compression here
    super.doAsyncUIDLRequest(uri, payload, wrappedCallback);
}

From source file:io.reinert.requestor.RequestDispatcherImpl.java

License:Apache License

private <D> RequestCallback getRequestCallback(final Request request, final XMLHttpRequest xhr,
        final Deferred<D> deferred, final Class<D> resolveType, final Class<?> parametrizedType) {
    return new RequestCallback() {
        public void onResponseReceived(com.google.gwt.http.client.Request gwtRequest,
                com.google.gwt.http.client.Response gwtResponse) {
            final String responseType = xhr.getResponseType();

            final Payload payload = responseType.isEmpty() || responseType.equalsIgnoreCase("text")
                    ? new Payload(xhr.getResponseText())
                    : new Payload(xhr.getResponse());

            final RawResponseImpl response = new RawResponseImpl(gwtResponse.getStatusCode(),
                    gwtResponse.getStatusText(), new Headers(gwtResponse.getHeaders()),
                    ResponseType.of(responseType), payload);

            evalResponse(request, deferred, resolveType, parametrizedType, response);
        }/*from   www.j av a 2  s  .c o  m*/

        public void onError(com.google.gwt.http.client.Request gwtRequest, Throwable exception) {
            if (exception instanceof com.google.gwt.http.client.RequestTimeoutException) {
                // reject as timeout
                com.google.gwt.http.client.RequestTimeoutException e = (com.google.gwt.http.client.RequestTimeoutException) exception;
                deferred.reject(new RequestTimeoutException(request, e.getTimeoutMillis()));
            } else {
                // reject as generic request exception
                deferred.reject(new RequestException(exception));
            }
        }
    };
}

From source file:org.bonitasoft.web.toolkit.client.data.api.callback.HttpCallback.java

License:Open Source License

@Override
public final void onResponseReceived(final Request request, final Response response) {

    // Same origne policy violation
    // hack to avoid error on timeout exception generating same origne policy violation
    // Need to deal with specific exception in processes, not in toolkit
    if (response.getStatusCode() == 0) {
        return;/*from   w w w . java  2  s .co  m*/
    }
    //        // Session expired
    else if (response.getStatusCode() == 401) {
        Window.Location.reload();
    }
    // 302 redirect
    else if (response.getStatusCode() == 302) {
        Window.Location.assign(response.getHeader("Location"));
    }
    // Other HTTP problems
    else if (response.getStatusCode() >= 300) {
        onError(response.getText(), response.getStatusCode());
    }
    // Success
    else {

        final Map<String, String> headersMap = new LinkedHashMap<String, String>();
        final Header[] headers = response.getHeaders();
        for (int i = 0; i < headers.length; i++) {
            if (headers[i] != null) {
                if (headersMap.containsKey(headers[i].getName())) {
                    headersMap.put(headers[i].getName(),
                            headersMap.get(headers[i].getName()) + "," + headers[i].getValue());
                } else {
                    headersMap.put(headers[i].getName(), headers[i].getValue());
                }
            }
        }

        onSuccess(response.getStatusCode(), response.getText(), headersMap);
    }
}

From source file:org.idwebmail.client.IDRequest.java

private void preparar(String url, final IDFunction usrFunction) {
    this.url = url;
    final IDFunction function = new IDFunction() {
        @Override/*from w ww  .  j  ava2 s . c  o m*/
        public void execute(Response response) {
            try {
                JSONObject JSON = (JSONObject) JSONParser.parse(response.getText());
                usrFunction.execute(response);
            } catch (Exception e) {
                usrFunction.execute(response);
            }
        };
    };
    this.requestBuilder = new RequestBuilder(RequestBuilder.POST, url);
    this.requestBuilder.setHeader("Content-Type", "application/x-www-form-urlencoded");
    this.requestBuilder.setTimeoutMillis(this.timeoutMillis);
    this.requestBuilder.setCallback(new RequestCallback() {
        @Override
        public void onResponseReceived(com.google.gwt.http.client.Request request, final Response response) {
            if (response.getStatusCode() == Response.SC_OK) {
                JSONObject JSON = null;
                try {
                    JSON = (JSONObject) JSONParser.parse(response.getText());
                    if (MainEntryPoint.getBoolean(JSON.get("STDOUT"))) {
                        final String JSONRespuesta = MainEntryPoint.getString(JSON.get("data"));
                        final Response tmp = new Response() {
                            @Override
                            public String getHeader(String arg0) {
                                return response.getHeader(arg0);
                            }

                            @Override
                            public Header[] getHeaders() {
                                return response.getHeaders();
                            }

                            @Override
                            public String getHeadersAsString() {
                                return response.getHeadersAsString();
                            }

                            @Override
                            public int getStatusCode() {
                                return response.getStatusCode();
                            }

                            @Override
                            public String getStatusText() {
                                return response.getStatusText();
                            }

                            @Override
                            public String getText() {
                                return JSONRespuesta;
                            }
                        };
                        function.execute(tmp);
                    } else
                        JSON = null;
                } catch (Exception e) {
                    function.execute(response);
                }
            }
        }

        @Override
        public void onError(Request request, Throwable exception) {
            Window.alert("Error: " + exception.getMessage());
        }
    });
}

From source file:org.turbogwt.net.http.client.DeferredCollectionResult.java

License:Apache License

@Override
public DeferredRequest<Collection<T>> resolve(Response response) {
    final Headers headers = new Headers(response.getHeaders());
    final String responseContentType = headers.getValue("Content-Type");

    final Deserializer<T> deserializer = serdesManager.getDeserializer(responseType, responseContentType);
    final DeserializationContext context = new HttpDeserializationContext(headers, containerFactoryManager);
    @SuppressWarnings("unchecked")
    Collection<T> result = deserializer.deserializeAsCollection(containerType, response.getText(), context);

    super.resolve(result);
    return this;
}

From source file:org.turbogwt.net.http.client.DeferredSingleResult.java

License:Apache License

@Override
public DeferredRequest<T> resolve(Response response) {
    // Check if access to Response was requested
    if (responseType == org.turbogwt.net.http.client.Response.class) {
        @SuppressWarnings("unchecked")
        final T result = (T) new ResponseImpl(response);
        super.resolve(result);
        return this;
    }/*w  ww  . ja  va  2 s .  c om*/

    final Headers headers = new Headers(response.getHeaders());
    final String responseContentType = headers.getValue("Content-Type");

    final Deserializer<T> deserializer = serdesManager.getDeserializer(responseType, responseContentType);
    final DeserializationContext context = new HttpDeserializationContext(headers, containerFactoryManager);
    T result = deserializer.deserialize(response.getText(), context);

    super.resolve(result);
    return this;
}