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

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

Introduction

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

Prototype

public abstract String getHeader(String header);

Source Link

Document

Returns the value of the requested header or null if the header was not specified.

Usage

From source file:com.data2semantics.yasgui.client.helpers.SparqlQuery.java

License:Open Source License

public void doRequest() {
    if (!view.getConnHelper().isOnline() && !JsMethods.corsEnabled(endpoint)) {
        //cors disabled and not online: problem!
        String errorMsg = "YASGUI is current not connected to the YASGUI server. "
                + "This mean you can only access endpoints on your own computer (e.g. localhost), which are <a href=\"http://enable-cors.org/\" target=\"_blank\">CORS enabled</a>.<br>"
                + "The endpoint you try to access is either not running on your computer, or not CORS-enabled.<br>"
                + corsNotification;//from w  ww .jav  a 2 s  . c  o  m
        view.getErrorHelper().onQueryError(errorMsg, endpoint, queryString, customQueryArgs);
        return;
    }

    view.getElements().onQueryStart();
    RequestBuilder builder;
    HashMultimap<String, String> queryArgs = customQueryArgs;
    RequestBuilder.Method requestMethod = queryRequestMethod;
    queryArgs.put("query", queryString);
    if (JsMethods.corsEnabled(endpoint)) {
        String params = Helper.getParamsAsString(queryArgs);
        String url = endpoint;
        if (queryRequestMethod == RequestBuilder.GET) {
            url += "?" + params;
        }
        builder = new RequestBuilder(queryRequestMethod, url);
        if (queryRequestMethod == RequestBuilder.POST) {
            builder.setHeader("Content-Type", "application/x-www-form-urlencoded");
            builder.setRequestData(params);
        }
    } else {
        requestMethod = RequestBuilder.POST;
        queryArgs.put("endpoint", endpoint);
        queryArgs.put("requestMethod", (queryRequestMethod == RequestBuilder.POST ? "POST" : "GET"));
        builder = new RequestBuilder(RequestBuilder.POST, GWT.getModuleBaseURL() + "sparql"); //send via proxy
        builder.setHeader("Content-Type", "application/x-www-form-urlencoded");
    }
    builder.setHeader("Accept", acceptHeader);
    try {
        final long startTime = System.currentTimeMillis();
        builder.sendRequest((requestMethod == RequestBuilder.POST ? Helper.getParamsAsString(queryArgs) : null),
                new RequestCallback() {
                    public void onError(Request request, Throwable e) {
                        //e.g. a timeout
                        queryErrorHandler(e);
                    }

                    @Override
                    public void onResponseReceived(Request request, Response response) {
                        view.getElements().onQueryFinish();
                        if (!response.getStatusText().equals("Abort")) {
                            //if user cancels query, textStatus will be 'abort'. No need to show error window then
                            if (response.getStatusCode() >= 200 && response.getStatusCode() < 300) {
                                if (view.getSettings().useGoogleAnalytics()) {
                                    long stopTime = System.currentTimeMillis();
                                    GoogleAnalytics.trackEvent(new GoogleAnalyticsEvent(endpoint,
                                            JsMethods.getUncommentedSparql(queryString),
                                            Integer.toString((int) (stopTime - startTime)),
                                            (int) (stopTime - startTime)));
                                }
                                drawResults(response.getText(), response.getHeader("Content-Type"));
                            } else {
                                queryErrorHandler(response);

                            }
                        }

                    }
                });
    } catch (RequestException e) {
        queryErrorHandler(e);
    }
}

From source file:com.google.gerrit.client.account.NewAgreementScreen.java

License:Apache License

private void showCLA(final ContributorAgreement cla) {
    current = cla;//from   w  w w. j a  v  a2 s  . c  om
    String url = cla.getAgreementUrl();
    if (url != null && url.length() > 0) {
        agreementGroup.setVisible(true);
        agreementHtml.setText(Gerrit.C.rpcStatusWorking());
        if (!url.startsWith("http:") && !url.startsWith("https:")) {
            url = GWT.getHostPageBaseURL() + url;
        }
        final RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, url);
        rb.setCallback(new RequestCallback() {
            public void onError(Request request, Throwable exception) {
                new ErrorDialog(exception).center();
            }

            public void onResponseReceived(Request request, Response response) {
                final String ct = response.getHeader("Content-Type");
                if (response.getStatusCode() == 200 && ct != null
                        && (ct.equals("text/html") || ct.startsWith("text/html;"))) {
                    agreementHtml.setHTML(response.getText());
                } else {
                    new ErrorDialog(response.getStatusText()).center();
                }
            }
        });
        try {
            rb.send();
        } catch (RequestException e) {
            new ErrorDialog(e).show();
        }
    } else {
        agreementGroup.setVisible(false);
    }

    if (contactPanel == null && cla.isRequireContactInformation()) {
        contactPanel = new ContactPanelFull();
        contactGroup.add(contactPanel);
        contactPanel.hideSaveButton();
    }
    contactGroup.setVisible(cla.isRequireContactInformation() && cla.getAutoVerify() != null);
    finalGroup.setVisible(cla.getAutoVerify() != null);
    yesIAgreeBox.setText("");
    submit.setEnabled(false);
}

From source file:com.google.gerrit.client.rpc.RestApi.java

License:Apache License

private static boolean isContentType(Response res, String want) {
    String type = res.getHeader("Content-Type");
    if (type == null) {
        return false;
    }/*w w w.  j a  v  a2s . com*/
    int semi = type.indexOf(';');
    if (semi >= 0) {
        type = type.substring(0, semi).trim();
    }
    return want.equals(type);
}

From source file:com.google.gwt.sample.authrequest.client.SampleAuthRequestTransport.java

License:Apache License

@Override
protected RequestCallback createRequestCallback(final TransportReceiver receiver) {
    final RequestCallback superCallback = super.createRequestCallback(receiver);

    return new RequestCallback() {
        @Override/*from  ww  w  . j a v  a2s. com*/
        public void onError(Request request, Throwable exception) {
            superCallback.onError(request, exception);
        }

        @Override
        public void onResponseReceived(Request request, Response response) {
            /*
             * The GaeAuthFailure filter responds with Response.SC_UNAUTHORIZED and
             * adds a "login" url header if the user is not logged in. When we
             * receive that combo, post an event so that the app can handle things
             * as it sees fit.
             */
            if (Response.SC_UNAUTHORIZED == response.getStatusCode()) {
                String loginUrl = response.getHeader("login");
                if (loginUrl != null) {
                    /*
                     * Hand the receiver a non-fatal callback, so that
                     * com.google.web.bindery.requestfactory.shared.Receiver will not
                     * post a runtime exception.
                     */
                    receiver.onTransportFailure(new ServerFailure("Unauthenticated user", null, null, false));
                    eventBus.fireEvent(new SampleAuthenticationFailureEvent(loginUrl));
                    return;
                }
            }
            superCallback.onResponseReceived(request, response);
        }
    };
}

From source file:com.google.gwt.sample.gaerequest.client.GaeAuthRequestTransport.java

License:Apache License

@Override
protected RequestCallback createRequestCallback(final TransportReceiver receiver) {
    final RequestCallback superCallback = super.createRequestCallback(receiver);

    return new RequestCallback() {
        @Override/* w w w.  j a  v  a 2 s  . com*/
        public void onError(Request request, Throwable exception) {
            superCallback.onError(request, exception);
        }

        @Override
        public void onResponseReceived(Request request, Response response) {
            /*
             * The GaeAuthFailure filter responds with Response.SC_UNAUTHORIZED and
             * adds a "login" url header if the user is not logged in. When we
             * receive that combo, post an event so that the app can handle things
             * as it sees fit.
             */
            if (Response.SC_UNAUTHORIZED == response.getStatusCode()) {
                String loginUrl = response.getHeader("login");
                if (loginUrl != null) {
                    /*
                     * Hand the receiver a non-fatal callback, so that
                     * com.google.web.bindery.requestfactory.shared.Receiver will not
                     * post a runtime exception.
                     */
                    receiver.onTransportFailure(new ServerFailure("Unauthenticated user", null, null, false));
                    eventBus.fireEvent(new GaeAuthenticationFailureEvent(loginUrl));
                    return;
                }
            }
            superCallback.onResponseReceived(request, response);
        }
    };
}

From source file:com.gwtplatform.dispatch.rest.client.core.DefaultResponseDeserializer.java

License:Apache License

private <R> R getDeserializedResponse(RestAction<R> action, Response response) throws ActionException {
    String resultClass = action.getResultClass();

    if (resultClass != null) {
        ContentType contentType = ContentType.valueOf(response.getHeader(HttpHeaders.CONTENT_TYPE));
        Serialization serialization = findSerialization(resultClass, contentType);

        if (serialization != null) {
            return deserializeValue(serialization, resultClass, contentType, response.getText());
        }//  ww  w.  j av a  2  s  .c o  m
    }

    throw new ActionException("Unable to deserialize response. No serializer found.");
}

From source file:com.totsp.gwittir.rest.client.transports.HTTPTransport.java

License:Open Source License

/** Handles a response and returns the appropriate String value, or throws an exception
 *
 * @param response the response object to read
 * @param acceptableCodes the acceptable HTTP status codes for the method that was used to generate the response
 * @param requireBody whether a full String body is required (GET requests)
 * @return The String value that is the result of the call or, where appropriate, the Location header.
 * @throws HTTPTransportException thrown if there is a problem with the call.
 *//*from   w  w w .j a  v a2 s.  c  o m*/
protected static String handleResponse(Response response, int[] acceptableCodes, boolean requireBody)
        throws HTTPTransportException {
    if (Arrays.binarySearch(acceptableCodes, response.getStatusCode()) < 0) {
        throw new HTTPTransportException("Unexpected response code " + response.getStatusCode(),
                response.getStatusCode(), response.getText());
    }

    if (requireBody) {
        if (response.getText() == null) {
            throw new HTTPTransportException("Did not receive payload.", response.getStatusCode(),
                    response.getText());
        }

        return response.getText();
    } else {
        String locationHeader = response.getHeader("Location");

        if (locationHeader != null) {
            return locationHeader;
        } else {
            return response.getText();
        }
    }
}

From source file:com.vaadin.terminal.gwt.client.ApplicationConnection.java

License:Open Source License

/**
 * Sends an asynchronous or synchronous UIDL request to the server using the
 * given URI./*from w  w  w. j a  v  a  2 s. c  o m*/
 * 
 * @param uri
 *            The URI to use for the request. May includes GET parameters
 * @param payload
 *            The contents of the request to send
 * @param synchronous
 *            true if the request should be synchronous, false otherwise
 */
protected void doUidlRequest(final String uri, final String payload, final boolean synchronous) {
    if (!synchronous) {
        RequestCallback requestCallback = new RequestCallback() {
            public void onError(Request request, Throwable exception) {
                showCommunicationError(exception.getMessage());
                endRequest();
            }

            public void onResponseReceived(Request request, Response response) {
                VConsole.log("Server visit took "
                        + String.valueOf((new Date()).getTime() - requestStartTime.getTime()) + "ms");

                int statusCode = response.getStatusCode();

                switch (statusCode) {
                case 0:
                    showCommunicationError("Invalid status code 0 (server down?)");
                    endRequest();
                    return;

                case 401:
                    /*
                     * Authorization has failed. Could be that the session
                     * has timed out and the container is redirecting to a
                     * login page.
                     */
                    showAuthenticationError("");
                    endRequest();
                    return;

                case 503:
                    // We'll assume msec instead of the usual seconds
                    int delay = Integer.parseInt(response.getHeader("Retry-After"));
                    VConsole.log("503, retrying in " + delay + "msec");
                    (new Timer() {
                        @Override
                        public void run() {
                            decrementActiveRequests();
                            doUidlRequest(uri, payload, synchronous);
                        }
                    }).schedule(delay);
                    return;

                }

                if ((statusCode / 100) == 4) {
                    // Handle all 4xx errors the same way as (they are
                    // all permanent errors)
                    showCommunicationError(
                            "UIDL could not be read from server. Check servlets mappings. Error code: "
                                    + statusCode);
                    endRequest();
                    return;
                }

                // for(;;);[realjson]
                final String jsonText = response.getText().substring(9, response.getText().length() - 1);
                handleJSONText(jsonText);
            }

        };
        try {
            doAsyncUIDLRequest(uri, payload, requestCallback);
        } catch (RequestException e) {
            VConsole.error(e);
            endRequest();
        }
    } else {
        // Synchronized call, discarded response (leaving the page)
        SynchronousXHR syncXHR = (SynchronousXHR) SynchronousXHR.create();
        syncXHR.synchronousPost(uri + "&" + PARAM_UNLOADBURST + "=1", payload);
        /*
         * Although we are in theory leaving the page, the page may still
         * stay open. End request properly here too. See #3289
         */
        endRequest();
    }

}

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() {

                /*/*w ww  . j av a  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:fi.jyu.student.jatahama.onlineinquirytool.client.OnlineInquiryTool.java

License:Open Source License

@Override
public void onResponseReceived(Request request, Response response) {
    String serverHello = null;// w  w  w.  ja  v a  2s. c  om
    try {
        // Let's check both header and content in case some proxy filters custom headers or something
        serverHello = response.getHeader(Utils.httpHeaderNameHello);
        boolean helloInText = response.getText().contains(Utils.httpHeaderNameHello);
        if ((serverHello != null && serverHello.length() > 0) || helloInText) {
            remoteServerAvailable = true;
        } else {
            remoteServerAvailable = false;
            servletRetry();
        }
    } catch (Exception e) {
        remoteServerAvailable = false;
        servletRetry();
    }
    // Do we want UI or just check load/save link states
    if (needUI) {
        appLoadingPopup.hide();
        createUI();
    } else {
        checkLoadSaveState();
    }
}