Example usage for com.google.gwt.user.client.rpc StatusCodeException StatusCodeException

List of usage examples for com.google.gwt.user.client.rpc StatusCodeException StatusCodeException

Introduction

In this page you can find the example usage for com.google.gwt.user.client.rpc StatusCodeException StatusCodeException.

Prototype

public StatusCodeException(int statusCode, String encodedResponse) 

Source Link

Document

Construct an exception with the given status code and description.

Usage

From source file:com.gdevelop.gwt.syncrpc.android.GetCookieRunnable.java

License:Apache License

/**
 * @see java.lang.Runnable#run()/*ww  w  . j a  va2 s. c  o  m*/
 */
@Override
public void run() {
    HttpURLConnection connection = null;
    try {
        connection = (HttpURLConnection) this.loginUrl.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Length", "" + this.request.length());
    } catch (Exception e) {
        if (connection != null) {
            connection.disconnect();
        }
        throw new RuntimeException(e);
    }

    CookieHandler oldCookieHandler = CookieHandler.getDefault();
    final CookieManager cookieManager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
    CookieHandler.setDefault(cookieManager);
    try {
        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(this.request);
        writer.flush();
        writer.close();

        int statusCode = connection.getResponseCode();
        if (statusCode != HttpURLConnection.HTTP_OK && statusCode != HttpURLConnection.HTTP_MOVED_TEMP) {
            String responseText = Utils.getResposeText(connection);
            throw new StatusCodeException(statusCode, responseText);
        }
        if (connection.getHeaderField("Set-Cookie").length() == 0) {
            this.parent.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    GetCookieRunnable.this.listener.onAuthFailure();
                }
            });
        } else {
            if (this.parent != null) {
                this.parent.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        GetCookieRunnable.this.listener.onCMAvailable(cookieManager);
                    }
                });
            } else {
                this.listener.onCMAvailable(cookieManager);
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("Failure in attempt to get cookie: ", e);
    } finally {
        CookieHandler.setDefault(oldCookieHandler);
        connection.disconnect();
    }
}

From source file:com.gdevelop.gwt.syncrpc.LoginUtils.java

License:Apache License

/**
 * //from   w  w  w. java2 s .  c  o m
 * @param loginUrl
 *            Should be http://localhost:8888 for local development mode or
 *            https://example.appspot.com for deployed app
 * @param serviceUrl
 *            Should be http://localhost:8888/yourApp.html
 * @param email
 * @param password
 * @return The CookieManager for subsequence call
 * @throws IOException
 * @throws AuthenticationException
 */
public static CookieManager loginAppEngine(String loginUrl, String serviceUrl, String email, String password)
        throws IOException, AuthenticationException {
    boolean localDevMode = false;

    if (loginUrl.startsWith("http://localhost")) {
        localDevMode = true;
    }

    CookieHandler oldCookieHandler = CookieHandler.getDefault();
    try {
        CookieManager cookieManager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
        CookieHandler.setDefault(cookieManager);

        if (localDevMode) {
            loginUrl += "/_ah/login";
            URL url = new URL(loginUrl);
            email = URLEncoder.encode(email, "UTF-8");
            serviceUrl = URLEncoder.encode(serviceUrl, "UTF-8");
            String requestData = "email=" + email + "&continue=" + serviceUrl;
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setInstanceFollowRedirects(false);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Length", "" + requestData.length());

            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write(requestData);
            writer.flush();
            writer.close();

            int statusCode = connection.getResponseCode();
            if ((statusCode != HttpURLConnection.HTTP_OK)
                    && (statusCode != HttpURLConnection.HTTP_MOVED_TEMP)) {
                String responseText = Utils.getResposeText(connection);
                throw new StatusCodeException(statusCode, responseText);
            }
        } else {
            GoogleAuthTokenFactory factory = new GoogleAuthTokenFactory(GAE_SERVICE_NAME, "", null);
            // Obtain authentication token from Google Accounts
            String token = factory.getAuthToken(email, password, null, null, GAE_SERVICE_NAME, "");
            loginUrl = loginUrl + "/_ah/login?continue=" + URLEncoder.encode(serviceUrl, "UTF-8") + "&auth="
                    + token;
            URL url = new URL(loginUrl);

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setInstanceFollowRedirects(false);
            connection.setRequestMethod("GET");
            connection.connect();

            int statusCode = connection.getResponseCode();
            if ((statusCode != HttpURLConnection.HTTP_OK)
                    && (statusCode != HttpURLConnection.HTTP_MOVED_TEMP)) {
                String responseText = Utils.getResposeText(connection);
                throw new StatusCodeException(statusCode, responseText);
            }
        }

        return cookieManager;
    } finally {
        CookieHandler.setDefault(oldCookieHandler);
    }
}

From source file:com.gdevelop.gwt.syncrpc.LoginUtils.java

License:Apache License

public static CookieManager loginFormBasedJ2EE(String loginUrl, String username, String password)
        throws IOException, URISyntaxException {
    CookieHandler oldCookieHandler = CookieHandler.getDefault();
    try {/*  www.j av  a  2s .c o  m*/
        CookieManager cookieManager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
        CookieHandler.setDefault(cookieManager);

        // GET the form
        URL url = new URL(loginUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        int statusCode = connection.getResponseCode();
        if ((statusCode != HttpURLConnection.HTTP_OK) && (statusCode != HttpURLConnection.HTTP_MOVED_TEMP)) {
            String responseText = Utils.getResposeText(connection);
            throw new StatusCodeException(statusCode, responseText);
        }

        // Perform login
        loginUrl += "j_security_check";
        url = new URL(loginUrl);
        username = URLEncoder.encode(username, "UTF-8");
        password = URLEncoder.encode(password, "UTF-8");
        String requestData = "j_username=" + username + "&j_password=" + password;
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Length", "" + requestData.length());
        connection.connect();

        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(requestData);
        writer.flush();
        writer.close();

        statusCode = connection.getResponseCode();
        if ((statusCode != HttpURLConnection.HTTP_OK) && (statusCode != HttpURLConnection.HTTP_MOVED_TEMP)) {
            String responseText = Utils.getResposeText(connection);
            throw new StatusCodeException(statusCode, responseText);
        }

        return cookieManager;
    } finally {
        CookieHandler.setDefault(oldCookieHandler);
    }
}

From source file:com.gdevelop.gwt.syncrpc.RemoteServiceSyncProxy.java

License:Apache License

public Object doInvoke(RequestCallbackAdapter.ResponseReader responseReader, String requestData)
        throws Throwable {
    Map<String, String> headersCopy = new LinkedHashMap<String, String>();
    synchronized (RemoteServiceSyncProxy.class) {
        headersCopy.putAll(headers);/*from  w w w .j  a  va  2s  .  c o m*/
    }
    HttpURLConnection connection = null;
    InputStream is = null;
    int statusCode;
    // Send request
    try {
        URL url = new URL(remoteServiceURL);
        connection = connectionManager.openConnection(url);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty(RpcRequestBuilder.STRONG_NAME_HEADER, serializationPolicyName);
        connection.setRequestProperty("Content-Type", "text/x-gwt-rpc; charset=utf-8");
        connection.setRequestProperty("Content-Length", "" + requestData.getBytes("UTF-8").length);
        // Explicitly set these to override any system properties.
        connection.setReadTimeout(socketTimeout * 1000);
        connection.setConnectTimeout(socketTimeout * 1000);
        for (Entry<String, String> header : headersCopy.entrySet()) {
            connection.setRequestProperty(header.getKey(), header.getValue());
        }
        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(requestData);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        throw new InvocationException("IOException while sending RPC request", e);
    }
    // Receive and process response
    try {
        connectionManager.handleResponseHeaders(connection);
        statusCode = connection.getResponseCode();
        is = connection.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) > 0) {
            baos.write(buffer, 0, len);
        }
        String encodedResponse = baos.toString("UTF8");
        // System.out.println("Response payload (len = " +
        // encodedResponse.length() + "): " + encodedResponse);
        if (statusCode != HttpURLConnection.HTTP_OK) {
            throw new StatusCodeException(statusCode, encodedResponse);
        } else if (encodedResponse == null) {
            // This can happen if the XHR is interrupted by the server dying
            throw new InvocationException("No response payload");
        } else if (isReturnValue(encodedResponse)) {
            encodedResponse = encodedResponse.substring(4);
            return responseReader.read(createStreamReader(encodedResponse));
        } else if (isThrownException(encodedResponse)) {
            encodedResponse = encodedResponse.substring(4);
            Throwable throwable = (Throwable) createStreamReader(encodedResponse).readObject();
            throw throwable;
        } else {
            throw new InvocationException("Unknown response " + encodedResponse);
        }
    } catch (IOException e) {
        throw new InvocationException("IOException while receiving RPC response", e);
    } catch (SerializationException e) {
        throw new InvocationException("Error while deserialization response", e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ignore) {
            }
        }
        if (connection != null) {
            // connection.disconnect();
        }
    }
}

From source file:com.gdevelop.gwt.syncrpc.SyncProxy.java

License:Apache License

/**
 * //from  w w w. ja  va 2  s. co  m
 * @param loginUrl Should be http://localhost:8888 for local development mode 
 * or https://example.appspot.com for deployed app
 * @param serviceUrl Should be http://localhost:8888/yourApp.html 
 * or http[s]://example.appspot.com/yourApp.html
 * @param email
 * @param password
 * @throws IOException
 * @throws AuthenticationException
 */
public static void loginGAE(String loginUrl, String serviceUrl, String email, String password)
        throws IOException, AuthenticationException {
    boolean localDevMode = false;
    if (loginUrl.startsWith("http://localhost")) {
        localDevMode = true;
    }

    if (localDevMode) {
        loginUrl += "/_ah/login";
        URL url = new URL(loginUrl);
        email = URLEncoder.encode(email, "UTF-8");
        serviceUrl = URLEncoder.encode(serviceUrl, "UTF-8");
        String requestData = "email=" + email + "&continue=" + serviceUrl;

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Length", "" + requestData.length());
        cookieManager.setCookies(connection);

        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(requestData);
        writer.flush();
        writer.close();
        cookieManager.storeCookies(connection);
        int statusCode = connection.getResponseCode();

        if ((statusCode != HttpURLConnection.HTTP_OK) && (statusCode != HttpURLConnection.HTTP_MOVED_TEMP)) {
            String responseText = getResposeText(connection);
            throw new StatusCodeException(statusCode, responseText);
        }
    } else {
        GoogleAuthTokenFactory factory = new GoogleAuthTokenFactory(GAE_SERVICE_NAME, "", null);
        // Obtain authentication token from Google Accounts
        String token = factory.getAuthToken(email, password, null, null, GAE_SERVICE_NAME, "");
        loginUrl = loginUrl + "/_ah/login?continue=" + URLEncoder.encode(serviceUrl, "UTF-8") + "&auth="
                + token;
        URL url = new URL(loginUrl);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("GET");
        connection.connect();
        // Get cookie returned from login service
        cookieManager.storeCookies(connection);
        int statusCode = connection.getResponseCode();
        if ((statusCode != HttpURLConnection.HTTP_OK) && (statusCode != HttpURLConnection.HTTP_MOVED_TEMP)) {
            String responseText = getResposeText(connection);
            throw new StatusCodeException(statusCode, responseText);
        }
    }
}

From source file:com.seanchenxi.resteasy.autobean.client.BaseResponseHandler.java

License:Apache License

@Override
protected void handleResponse(Response response, Class<T> clazz, AsyncCallback<T> callback,
        String resourceName) {/*www  . j a  v  a  2s.co  m*/
    T result = null;
    Throwable caught = null;
    try {
        RESTResponse restResponse = REST.decodeResponse(response.getText());
        int statusCode = response.getStatusCode();
        if (statusCode != Response.SC_OK) {
            caught = new StatusCodeException(statusCode, response.getText());
        } else if (restResponse == null) {
            caught = new InvocationException(
                    "No response payload from " + uri + " of resource " + resourceName);
        } else if (REST.isReturnValue(restResponse)) {
            if (!Void.class.equals(clazz)) {
                Splittable data = StringQuoter.split(restResponse.getPayload());
                if (data != null)
                    result = (T) REST.decodeData(clazz, data);
            }
        } else if (REST.isThrowable(restResponse)) {
            caught = REST.decodeThrowable(restResponse.getPayload());
        } else {
            caught = new InvocationException(restResponse + " from " + uri + " of resource " + resourceName);
        }
    } catch (SerializationException e) {
        caught = new IncompatibleRemoteServiceException(
                "The response: \n{" + response.getText() + "}\n could not be deserialized", e);
    } catch (Throwable e) {
        caught = e;
    }

    if (caught != null) {
        callback.onFailure(caught);
    } else {
        callback.onSuccess(result);
    }
}

From source file:fr.putnami.pwt.core.widget.client.InputFile.java

License:Open Source License

private void handleError(String statusCode, String encodedResponse) {
    this.fileId = null;
    progressBar.setValue(0);/*from  www  . jav  a  2s. c o m*/
    StyleUtils.addStyle(this, STYLE_ERROR);
    throw new StatusCodeException(Integer.parseInt(statusCode), encodedResponse);
}

From source file:net.zschech.gwt.comet.client.impl.HTTPRequestCometTransport.java

License:Apache License

private void onReceiving(int statusCode, String responseText, boolean connected) {
    if (statusCode != Response.SC_OK) {
        if (!connected) {
            super.disconnect();
            listener.onError(new StatusCodeException(statusCode, responseText), connected);
        }//from w w  w. ja  v a2 s.  c o  m
    } else {
        int index = responseText.lastIndexOf(SEPARATOR);
        if (index > read) {
            List<Serializable> messages = new ArrayList<Serializable>();

            SplitResult data = separator.split(responseText.substring(read, index), index);
            int length = data.length();
            for (int i = 0; i < length; i++) {
                if (disconnecting) {
                    return;
                }

                String message = data.get(i);
                if (!message.isEmpty()) {
                    parse(message, messages);
                }
            }
            read = index + 1;
            if (!messages.isEmpty()) {
                listener.onMessage(messages);
            }
        }

        if (!connected) {
            super.disconnected();
        }
    }
}

From source file:net.zschech.gwt.comet.client.impl.IEHTMLFileCometTransport.java

License:Apache License

private void onError(int statusCode, String message) {
    listener.onError(new StatusCodeException(statusCode, message), false);
}

From source file:net.zschech.gwt.comet.client.impl.RawDataCometTransport.java

License:Apache License

protected void parse(String message, List<Serializable> messages) {
    if (expectingDisconnection) {
        listener.onError(new CometException("Expecting disconnection but received message: " + message), true);
    } else if (message.isEmpty()) {
        listener.onError(new CometException("Invalid empty message received"), true);
    } else {//from  w  ww. jav a2 s.  com
        char c = message.charAt(0);
        switch (c) {
        case '!':
            String heartbeatParameter = message.substring(1);
            try {
                listener.onConnected(Integer.parseInt(heartbeatParameter));
            } catch (NumberFormatException e) {
                listener.onError(new CometException("Unexpected heartbeat parameter: " + heartbeatParameter),
                        true);
            }
            break;
        case '?':
            // clean disconnection
            expectingDisconnection = true;
            break;
        case '#':
            listener.onHeartbeat();
            break;
        case '@':
            listener.onRefresh();
            break;
        case '*':
            // ignore padding
            break;
        case '|':
            messages.add(message.substring(1));
            break;
        case ']':
            messages.add(unescape(message.substring(1)));
            break;
        case '[':
        case 'R':
        case 'r':
        case 'f':
            CometSerializer serializer = client.getSerializer();
            if (serializer == null) {
                listener.onError(new SerializationException(
                        "Can not deserialize message with no serializer: " + message), true);
            } else {
                try {
                    messages.add(serializer.parse(message));
                } catch (SerializationException e) {
                    listener.onError(e, true);
                }
            }
            break;
        default:
            if (c >= '0' && c <= '9') {
                // error codes
                expectingDisconnection = true;
                try {
                    int statusCode;
                    String statusMessage;
                    int index = message.indexOf(' ');
                    if (index == -1) {
                        statusCode = Integer.parseInt(message);
                        statusMessage = null;
                    } else {
                        statusCode = Integer.parseInt(message.substring(0, index));
                        statusMessage = unescape(message.substring(index + 1));
                    }
                    listener.onError(new StatusCodeException(statusCode, statusMessage), false);
                } catch (NumberFormatException e) {
                    listener.onError(new CometException("Unexpected status code: " + message), false);
                }
                break;
            } else {
                listener.onError(new CometException("Invalid message received: " + message), true);
            }
        }
    }
}