Example usage for com.squareup.okhttp Response code

List of usage examples for com.squareup.okhttp Response code

Introduction

In this page you can find the example usage for com.squareup.okhttp Response code.

Prototype

int code

To view the source code for com.squareup.okhttp Response code.

Click Source Link

Usage

From source file:io.fabric8.elasticsearch.util.RequestUtils.java

License:Apache License

@SuppressWarnings("rawtypes")
public String assertUser(RestRequest request) throws Exception {
    String username = null;/*w  w  w .  ja va  2s.co m*/
    final String user = getUser(request);
    final String token = getBearerToken(request);
    ConfigBuilder builder = new ConfigBuilder().withOauthToken(token);
    try (DefaultOpenShiftClient osClient = new DefaultOpenShiftClient(builder.build())) {
        LOGGER.debug("Verifying user {} matches the given token.", user);
        Request okRequest = new Request.Builder().addHeader(AUTHORIZATION_HEADER, "Bearer " + token)
                .url(osClient.getMasterUrl() + "oapi/v1/users/~").build();
        Response response = null;
        try {
            response = osClient.getHttpClient().newCall(okRequest).execute();
            final String body = response.body().string();
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Response: code '{}' {}", response.code(), body);
            }
            if (response.code() != RestStatus.OK.getStatus()) {
                throw new ElasticsearchSecurityException("Could not authenticate with given token",
                        RestStatus.UNAUTHORIZED);
            }
            Map<String, Object> userResponse = XContentHelper.convertToMap(new BytesArray(body), false).v2();
            if (userResponse.containsKey("metadata")
                    && ((Map) userResponse.get("metadata")).containsKey("name")) {
                username = (String) ((Map) userResponse.get("metadata")).get("name");
            }
        } catch (Exception e) {
            LOGGER.debug("Exception trying to assertUser '{}'", e, user);
            throw e;
        }
        if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(user) && !user.equals(username)) {
            String message = String.format(
                    "The given username '%s' does not match the username '%s' associated with the token provided with the request.",
                    user, username);
            LOGGER.debug(message);
        }
    }
    if (null == username) {
        throw new ElasticsearchSecurityException("Could not determine username from token",
                RestStatus.UNAUTHORIZED);
    }
    return username;
}

From source file:io.fabric8.kubernetes.client.dsl.base.OperationSupport.java

License:Apache License

/**
 * Checks if the response status code is the expected and throws the appropriate KubernetesClientException if not.
 *
 * @param request            The {#link Request} object.
 * @param response           The {@link Response} object.
 * @param expectedStatusCode The expected status code.
 * @throws KubernetesClientException When the response code is not the expected.
 *//*from w w  w.ja v a  2  s .  c  o  m*/
protected void assertResponseCode(Request request, Response response, int expectedStatusCode) {
    int statusCode = response.code();
    String customMessage = config.getErrorMessages().get(statusCode);

    if (statusCode == expectedStatusCode) {
        return;
    } else if (customMessage != null) {
        throw requestFailure(request, createStatus(statusCode, customMessage));
    } else {
        throw requestFailure(request, createStatus(response));
    }
}

From source file:io.fabric8.kubernetes.client.dsl.base.OperationSupport.java

License:Apache License

public static Status createStatus(Response response) {
    int statusCode = response.code();
    String statusMessage = "";
    ResponseBody body = response != null ? response.body() : null;
    try {/*from  w ww  .j  a va2s .co m*/
        if (response == null) {
            statusMessage = "No response";
        } else if (body != null) {
            statusMessage = body.string();
        } else if (response.message() != null) {
            statusMessage = response.message();
        }
        return JSON_MAPPER.readValue(statusMessage, Status.class);
    } catch (JsonParseException e) {
        return createStatus(statusCode, statusMessage);
    } catch (IOException e) {
        return createStatus(statusCode, statusMessage);
    }
}

From source file:io.fabric8.openshift.client.internal.OpenShiftOAuthInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();

    //Build new request
    Request.Builder builder = request.newBuilder();
    builder.header("Accept", "application/json");

    String token = oauthToken.get();
    if (Utils.isNotNullOrEmpty(token)) {
        setAuthHeader(builder, token);//from  w w w .j  a va2  s  .  co  m
    }

    request = builder.build();
    Response response = chain.proceed(request);

    if ((response.code() == 401 || response.code() == 403) && Utils.isNotNullOrEmpty(config.getUsername())
            && Utils.isNotNullOrEmpty(config.getPassword())) {
        // Close the previous response to prevent leaked connections.
        response.body().close();

        synchronized (client) {
            token = authorize();
            if (token != null) {
                oauthToken.set(token);
                setAuthHeader(builder, token);
                request = builder.build();
                return chain.proceed(request); //repeat request with new token
            }
        }
    }
    return response;
}

From source file:io.gameup.android.GameUp.java

License:Apache License

/**
 * Ping the GameUp service to check it is reachable and ready to handle
 * requests./* w w w.jav  a  2s .c  o m*/
 *
 * Abstracted here to be used as shared code between the GameUp.ping() and
 * GameUpSession.ping() methods.
 *
 * @param apiKey The API key to use.
 * @param token The gamer token to use, may be an empty String but not null.
 * @return true if the service is reachable, responds correctly, and accepts
 *         the API key and token combination; false otherwise.
 * @throws IOException when a network or communication error occurs.
 */
static boolean ping(final @NonNull String apiKey, final @NonNull String token) throws IOException {
    final Request request = RequestFactory.head(new Uri.Builder().scheme(GameUp.SCHEME)
            .encodedAuthority(GameUp.API_SERVER).appendPath("v0").build(), apiKey, token);
    final Response response = OkHttpClientFactory.getClient().newCall(request).execute();
    return response.code() == HttpURLConnection.HTTP_OK;
}

From source file:io.gameup.android.GameUp.java

License:Apache License

/**
 * Retrieve GameUp global service and/or server instance data.
 *
 * @param apiKey The API key to use./* w w w. j a  v  a 2s.  com*/
 * @return A Server instance containing GameUp service and/or server
 *         instance information, for example current time.
 * @throws IOException when a network or communication error occurs.
 */
public static Server server(final @NonNull String apiKey) throws IOException {
    Reader in = null;
    try {
        final Request request = RequestFactory.get(new Uri.Builder().scheme(GameUp.SCHEME)
                .encodedAuthority(GameUp.API_SERVER).appendPath("v0").appendPath("server").build(), apiKey);
        final Response response = OkHttpClientFactory.getClient().newCall(request).execute();

        if (response.code() != HttpURLConnection.HTTP_OK) {
            throw new IOException("Operation returned HTTP " + response.code());
        }
        in = response.body().charStream();

        try {
            return GsonFactory.get().fromJson(in, Server.class);
        } catch (final JsonParseException e) {
            throw new IOException("Response data does not match expected entity");
        }
    } finally {
        Utils.closeQuietly(in);
    }
}

From source file:io.gameup.android.GameUp.java

License:Apache License

/**
 * Retrieve information about the game the given API key corresponds to, as
 * configured in the remote service./*  w w  w.j  a  va2  s  . co  m*/
 *
 * @param apiKey The API key to use.
 * @return An entity representing remotely configured data about the game.
 * @throws IOException when a network or communication error occurs.
 */
public static Game game(final @NonNull String apiKey) throws IOException {
    Reader in = null;
    try {
        final Request request = RequestFactory.get(new Uri.Builder().scheme(GameUp.SCHEME)
                .encodedAuthority(GameUp.API_SERVER).appendPath("v0").appendPath("game").build(), apiKey);
        final Response response = OkHttpClientFactory.getClient().newCall(request).execute();

        if (response.code() != HttpURLConnection.HTTP_OK) {
            throw new IOException("Operation returned HTTP " + response.code());
        }
        in = response.body().charStream();

        try {
            return GsonFactory.get().fromJson(in, Game.class);
        } catch (final JsonParseException e) {
            throw new IOException("Response data does not match expected entity");
        }
    } finally {
        Utils.closeQuietly(in);
    }
}

From source file:io.gameup.android.GameUp.java

License:Apache License

/**
 * Get a list of achievements available for the game, excluding any gamer
 * data such as progress or completed timestamps.
 *
 * @param apiKey The API key to use./*w w  w  .j  av  a2s . c  o m*/
 * @return An AchievementList, containing Achievement instances, may be
 *         empty if none are returned for the current game.
 * @throws IOException when a network or communication error occurs.
 */
public static AchievementList achievement(final @NonNull String apiKey) throws IOException {
    Reader in = null;
    try {
        final Request request = RequestFactory
                .get(new Uri.Builder().scheme(GameUp.SCHEME).encodedAuthority(GameUp.API_SERVER)
                        .appendPath("v0").appendPath("game").appendPath("achievement").build(), apiKey);
        final Response response = OkHttpClientFactory.getClient().newCall(request).execute();

        if (response.code() != HttpURLConnection.HTTP_OK) {
            throw new IOException("Operation returned HTTP " + response.code());
        }
        in = response.body().charStream();

        try {
            return GsonFactory.get().fromJson(in, AchievementList.class);
        } catch (final JsonParseException e) {
            throw new IOException("Response data does not match expected entity");
        }
    } finally {
        Utils.closeQuietly(in);
    }
}

From source file:io.gameup.android.GameUp.java

License:Apache License

/**
 * Request leaderboard metadata and the current top ranked gamers on a
 * specified leaderboard.//from   w ww .j  a  v a 2s.  c om
 *
 * @param apiKey The API key to use.
 * @param leaderboardId The private ID of the leaderboard to request.
 * @return A Leaderboard instance.
 * @throws IOException when a network or communication error occurs.
 */
public static Leaderboard leaderboard(final @NonNull String apiKey, final @NonNull String leaderboardId)
        throws IOException {
    Reader in = null;
    try {
        final Request request = RequestFactory.get(
                new Uri.Builder().scheme(GameUp.SCHEME).encodedAuthority(GameUp.API_SERVER).appendPath("v0")
                        .appendPath("game").appendPath("leaderboard").appendPath(leaderboardId).build(),
                apiKey);
        final Response response = OkHttpClientFactory.getClient().newCall(request).execute();

        if (response.code() != HttpURLConnection.HTTP_OK) {
            throw new IOException("Operation returned HTTP " + response.code());
        }
        in = response.body().charStream();

        try {
            return GsonFactory.get().fromJson(in, Leaderboard.class);
        } catch (final JsonParseException e) {
            throw new IOException("Response data does not match expected entity");
        }
    } finally {
        Utils.closeQuietly(in);
    }
}

From source file:io.gameup.android.GameUpSession.java

License:Apache License

/**
 * Get information about the gamer who owns this session.
 *
 * @param apiKey The API key to use.//w  ww.ja v  a 2 s.c o  m
 * @return An entity containing gamer information.
 * @throws IOException when a network or communication error occurs.
 */
public Gamer gamer(final @NonNull String apiKey) throws IOException {
    Reader in = null;
    try {
        final Request request = RequestFactory.get(new Uri.Builder().scheme(GameUp.SCHEME)
                .encodedAuthority(GameUp.API_SERVER).appendPath("v0").appendPath("gamer").build(), apiKey,
                token);
        final Response response = OkHttpClientFactory.getClient().newCall(request).execute();

        if (response.code() != HttpURLConnection.HTTP_OK) {
            throw new IOException("Operation returned HTTP " + response.code());
        }
        in = response.body().charStream();

        try {
            return GsonFactory.get().fromJson(in, Gamer.class);
        } catch (final JsonParseException e) {
            throw new IOException("Response data does not match expected entity");
        }
    } finally {
        Utils.closeQuietly(in);
    }
}