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:com.navercorp.pinpoint.plugin.okhttp.v2.interceptor.HttpEngineReadResponseMethodInterceptor.java

License:Apache License

@Override
public void after(Object target, Object[] args, Object result, Throwable throwable) {
    if (isDebug) {
        logger.afterInterceptor(target, args);
    }// w  w w . j a v a 2s  .co  m

    final Trace trace = traceContext.currentTraceObject();
    if (trace == null) {
        return;
    }

    if (!validate(target)) {
        return;
    }

    try {
        final SpanEventRecorder recorder = trace.currentSpanEventRecorder();
        recorder.recordApi(methodDescriptor);
        recorder.recordException(throwable);

        if (statusCode) {
            // type check validate();
            final Response response = ((UserResponseGetter) target)._$PINPOINT$_getUserResponse();
            if (response != null) {
                recorder.recordAttribute(AnnotationKey.HTTP_STATUS_CODE, response.code());
            }
        }
    } finally {
        trace.traceBlockEnd();
    }
}

From source file:com.netflix.spinnaker.clouddriver.artifacts.maven.MavenArtifactCredentials.java

License:Apache License

@Override
public InputStream download(Artifact artifact) {
    try {//w ww.j  ava  2  s.  co  m
        DefaultArtifact requestedArtifact = new DefaultArtifact(artifact.getReference());
        String artifactPath = resolveVersion(requestedArtifact)
                .map(version -> repositoryLayout.getLocation(withVersion(requestedArtifact, version), false))
                .map(URI::getPath)
                .orElseThrow(() -> new IllegalStateException("No versions matching constraint '"
                        + artifact.getVersion() + "' for '" + artifact.getReference() + "'"));

        Request artifactRequest = new Request.Builder().url(account.getRepositoryUrl() + "/" + artifactPath)
                .get().build();

        Response artifactResponse = okHttpClient.newCall(artifactRequest).execute();
        if (artifactResponse.isSuccessful()) {
            return artifactResponse.body().byteStream();
        }
        throw new IllegalStateException("Unable to download artifact with reference '" + artifact.getReference()
                + "'. HTTP " + artifactResponse.code());
    } catch (IOException | ArtifactDownloadException e) {
        throw new IllegalStateException(
                "Unable to download artifact with reference '" + artifact.getReference() + "'", e);
    }
}

From source file:com.netflix.spinnaker.clouddriver.artifacts.maven.MavenArtifactCredentials.java

License:Apache License

private Optional<String> resolveVersion(org.eclipse.aether.artifact.Artifact artifact) {
    try {//from  ww  w  .  ja v  a2  s.c o m
        String metadataPath = metadataUri(artifact).getPath();
        Request metadataRequest = new Request.Builder().url(account.getRepositoryUrl() + "/" + metadataPath)
                .get().build();
        Response response = okHttpClient.newCall(metadataRequest).execute();

        if (response.isSuccessful()) {
            VersionScheme versionScheme = new GenericVersionScheme();
            VersionConstraint versionConstraint = versionScheme.parseVersionConstraint(artifact.getVersion());
            Versioning versioning = new MetadataXpp3Reader().read(response.body().byteStream(), false)
                    .getVersioning();

            if (isRelease(artifact)) {
                return Optional.ofNullable(versioning.getRelease());
            } else if (isLatestSnapshot(artifact)) {
                return resolveVersion(withVersion(artifact, versioning.getLatest()));
            } else if (isLatest(artifact)) {
                String latestVersion = versioning.getLatest();
                return latestVersion != null && latestVersion.endsWith("-SNAPSHOT")
                        ? resolveVersion(withVersion(artifact, latestVersion))
                        : Optional.ofNullable(latestVersion);
            } else if (artifact.getVersion().endsWith("-SNAPSHOT")) {
                String requestedClassifier = artifact.getClassifier() == null ? "" : artifact.getClassifier();
                return versioning.getSnapshotVersions().stream()
                        .filter(v -> v.getClassifier().equals(requestedClassifier))
                        .map(SnapshotVersion::getVersion).findFirst();
            } else {
                return versioning.getVersions().stream().map(v -> {
                    try {
                        return versionScheme.parseVersion(v);
                    } catch (InvalidVersionSpecificationException e) {
                        throw new ArtifactDownloadException(e);
                    }
                }).filter(versionConstraint::containsVersion).max(Version::compareTo).map(Version::toString);
            }
        } else {
            throw new IOException("Unsuccessful response retrieving maven-metadata.xml " + response.code());
        }
    } catch (IOException | XmlPullParserException | InvalidVersionSpecificationException e) {
        throw new ArtifactDownloadException(e);
    }
}

From source file:com.netflix.spinnaker.clouddriver.cloudfoundry.client.HttpCloudFoundryClient.java

License:Apache License

Response createRetryInterceptor(Interceptor.Chain chain) {
    Retry retry = Retry.of("cf.api.call",
            RetryConfig.custom().retryExceptions(RetryableApiException.class).build());

    AtomicReference<Response> lastResponse = new AtomicReference<>();
    try {//  w  ww  .j  a va  2  s  .c o m
        return retry.executeCallable(() -> {
            Response response = chain.proceed(chain.request());
            lastResponse.set(response);

            switch (response.code()) {
            case 401:
                BufferedSource source = response.body().source();
                source.request(Long.MAX_VALUE); // request the entire body
                Buffer buffer = source.buffer();
                String body = buffer.clone().readString(Charset.forName("UTF-8"));
                if (!body.contains("Bad credentials")) {
                    refreshToken();
                    response = chain.proceed(chain.request().newBuilder()
                            .header("Authorization", "bearer " + token.getAccessToken()).build());
                    lastResponse.set(response);
                }
                break;
            case 502:
            case 503:
            case 504:
                // after retries fail, the response body for these status codes will get wrapped up into a CloudFoundryApiException
                throw new RetryableApiException();
            }

            return response;
        });
    } catch (Exception e) {
        return lastResponse.get();
    }
}

From source file:com.netflix.spinnaker.igor.concourse.client.OkHttpClientBuilder.java

License:Apache License

private static Response createRetryInterceptor(Interceptor.Chain chain, Supplier<Token> refreshToken) {
    Retry retry = Retry.of("concourse.api.call",
            RetryConfig.custom().retryExceptions(RetryableApiException.class).build());

    AtomicReference<Response> lastResponse = new AtomicReference<>();
    try {//from w ww  .j a v  a  2s  .  c  om
        return retry.executeCallable(() -> {
            Response response = chain.proceed(chain.request());
            lastResponse.set(response);

            switch (response.code()) {
            case 401:
                String body = null;
                if (response.body() != null) {
                    BufferedSource source = response.body().source();
                    source.request(Long.MAX_VALUE); // request the entire body
                    Buffer buffer = source.buffer();
                    body = buffer.clone().readString(Charset.forName("UTF-8"));
                }
                if (body == null || !body.contains("Bad credentials")) {
                    response = chain.proceed(chain.request().newBuilder()
                            .header("Authorization", "bearer " + refreshToken.get().getAccessToken()).build());
                    lastResponse.set(response);
                }
                break;
            case 502:
            case 503:
            case 504:
                // after retries fail, the response body for these status codes will get wrapped up
                // into a ConcourseApiException
                throw new RetryableApiException();
            }

            return response;
        });
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } catch (Exception e) {
        return lastResponse.get();
    }
}

From source file:com.netflix.spinnaker.igor.concourse.client.OkHttpClientBuilder.java

License:Apache License

private static okhttp3.Response createRetryInterceptor3(okhttp3.Interceptor.Chain chain,
        Supplier<Token> refreshToken) {
    Retry retry = Retry.of("concourse.api.call",
            RetryConfig.custom().retryExceptions(RetryableApiException.class).build());

    AtomicReference<okhttp3.Response> lastResponse = new AtomicReference<>();
    try {//from w  w  w  .  j av a2 s  .co  m
        return retry.executeCallable(() -> {
            okhttp3.Response response = chain.proceed(chain.request());
            lastResponse.set(response);

            switch (response.code()) {
            case 401:
                String body = null;
                if (response.body() != null) {
                    BufferedSource source = response.body().source();
                    source.request(Long.MAX_VALUE); // request the entire body
                    Buffer buffer = source.buffer();
                    body = buffer.clone().readString(Charset.forName("UTF-8"));
                }
                if (body == null || !body.contains("Bad credentials")) {
                    response = chain.proceed(chain.request().newBuilder()
                            .header("Authorization", "bearer " + refreshToken.get().getAccessToken()).build());
                    lastResponse.set(response);
                }
                break;
            case 502:
            case 503:
            case 504:
                // after retries fail, the response body for these status codes will get wrapped up
                // into a ConcourseApiException
                throw new RetryableApiException();
            }

            return response;
        });
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } catch (Exception e) {
        return lastResponse.get();
    }
}

From source file:com.netflix.spinnaker.okhttp.OkHttpMetricsInterceptor.java

License:Apache License

@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
    long start = System.nanoTime();
    boolean wasSuccessful = false;
    int statusCode = -1;

    Request request = chain.request();

    try {//from w w  w .j a va 2  s  .c  o m
        Response response = chain.proceed(request);
        wasSuccessful = true;
        statusCode = response.code();

        return response;
    } finally {
        recordTimer(registry, request.url(), System.nanoTime() - start, statusCode, wasSuccessful);
    }
}

From source file:com.northernwall.hadrian.details.simple.SimpleHostDetailsHelper.java

License:Apache License

private void getDetailsFromUrl(Host host, String url, List<GetPairData> pairs) {
    Request httpRequest = new Request.Builder().url(url).build();
    try {/*from w  w w  . ja v  a  2s .c  o m*/
        Response resp = client.newCall(httpRequest).execute();
        try (Reader reader = new InputStreamReader(resp.body().byteStream())) {
            if (resp.isSuccessful()) {
                JsonElement jsonElement = parser.parse(reader);
                if (jsonElement.isJsonObject()) {
                    JsonObject jsonObject = jsonElement.getAsJsonObject();
                    for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
                        processAttribute(null, entry, pairs);
                    }
                }
            } else {
                logger.warn("Call to {} failed with code {}", url, resp.code());
            }
        }
    } catch (Exception ex) {
        logger.warn("Error while getting secondary host details for {}, error {}", host.getHostName(),
                ex.getMessage());
    }
}

From source file:com.northernwall.hadrian.service.DocumentGetHandler.java

License:Apache License

@Override
public void handle(String target, Request request, HttpServletRequest httpRequest, HttpServletResponse response)
        throws IOException, ServletException {
    Service service = getService(request);

    for (Document doc : service.getDocuments()) {
        if (doc.getDocId().equals(request.getParameter("docId"))) {
            com.squareup.okhttp.Request docRequest = new com.squareup.okhttp.Request.Builder()
                    .url(addToken(doc.getLink())).build();
            try {
                com.squareup.okhttp.Response resp = client.newCall(docRequest).execute();
                if (resp.isSuccessful()) {
                    try (InputStream inputStream = resp.body().byteStream()) {
                        byte[] buffer = new byte[50 * 1024];
                        int len = inputStream.read(buffer);
                        while (len != -1) {
                            response.getOutputStream().write(buffer, 0, len);
                            len = inputStream.read(buffer);
                        }// ww w.j av  a2  s  .  co m
                        response.getOutputStream().flush();
                    }
                    response.setStatus(200);
                    request.setHandled(true);
                    return;
                } else {
                    throw new Http400BadRequestException("Could not get document " + doc.getTitle() + " at "
                            + doc.getLink() + " status " + resp.code());
                }
            } catch (UnknownHostException ex) {
                throw new Http400BadRequestException("Error: Unknown host!");
            } catch (ConnectException | SocketTimeoutException ex) {
                throw new Http400BadRequestException("Error: Time out!");
            }
        }
    }

    throw new Http400BadRequestException("Could not find document");
}

From source file:com.northernwall.hadrian.workItem.simple.SimpleWorkItemSender.java

License:Apache License

@Override
public Result sendWorkItem(WorkItem workItem) throws IOException {
    RequestBody body = RequestBody.create(Const.JSON_MEDIA_TYPE, gson.toJson(workItem));
    Request request = new Request.Builder().url(url).addHeader("X-Request-Id", workItem.getId()).post(body)
            .build();/*from  w ww.j  ava 2  s  .  co m*/
    Response response = client.newCall(request).execute();
    logger.info("Sent workitem {} and got response {}", workItem.getId(), response.code());
    if (response.isSuccessful()) {
        return Result.wip;
    }
    return Result.error;
}