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:de.ebf.GetTranslationsOneSkyAppMojo.java

License:Apache License

private void getTranslations() throws MojoExecutionException {
    try {/*from   www . j  a  v a  2s  .c om*/
        for (String sourceFileName : sourceFileNames) {
            for (String locale : locales) {
                System.out
                        .println(String.format("Downloading %1s translations for %2s", locale, sourceFileName));

                OkHttpClient okHttpClient = new OkHttpClient();
                final String url = String.format(
                        API_ENDPOINT + "projects/%1$s/translations?locale=%2$s&source_file_name=%3$s&%4$s",
                        projectId, locale, sourceFileName, getAuthParams());
                final Request request = new Request.Builder().get().url(url).build();
                final Response response = okHttpClient.newCall(request).execute();

                if (response.code() == 200) {
                    if (!outputDir.exists()) {
                        outputDir.mkdirs();
                    }
                    //even though the OneSkyApp API documentation states that the file name should be sourceFileName_locale.sourceFileNameExtension, it is just locale.sourceFileNameExtension)
                    //https://github.com/onesky/api-documentation-platform/blob/master/resources/translation.md

                    String targetFileName = sourceFileName + "_" + locale;
                    int index = sourceFileName.lastIndexOf(".");
                    if (index > 0) {
                        targetFileName = sourceFileName.substring(0, index) + "_" + locale + "."
                                + sourceFileName.substring(index + 1);
                    }
                    File outputFile = new File(outputDir, targetFileName);
                    outputFile.createNewFile();
                    final InputStream inputStream = response.body().byteStream();
                    FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
                    IOUtils.copy(inputStream, fileOutputStream);
                    System.out.println(String.format("Successfully downloaded %1s translation for %2s to %3s",
                            locale, sourceFileName, outputFile.getName()));
                } else {
                    throw new MojoExecutionException(String.format("OneSkyApp API returned %1$s: %2s",
                            response.code(), response.message()));
                }
            }
        }
    } catch (IOException | MojoExecutionException ex) {
        if (failOnError == null || failOnError) {
            throw new MojoExecutionException(ex.getMessage(), ex);
        } else {
            System.out.println("Caught exception: " + ex.getMessage());
        }
    }
}

From source file:de.ebf.UploadFileOneSkyAppMojo.java

License:Apache License

private void uploadFiles() throws MojoExecutionException {
    try {/*from   ww  w . j  av  a 2 s . c o  m*/
        for (File file : files) {
            System.out.println(String.format("Uploading %1$s", file.getName()));
            OkHttpClient okHttpClient = new OkHttpClient();
            final String url = String.format(
                    API_ENDPOINT + "projects/%1$s/files?file_format=%2$s&locale=%3$s&%4$s", projectId,
                    fileFormat, locale, getAuthParams());

            RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
                    .addPart(
                            Headers.of("Content-Disposition",
                                    "form-data; name=\"file\"; filename=\"" + file.getName() + "\""),
                            RequestBody.create(MediaType.parse("text/plain"), file))
                    .build();

            final Request request = new Request.Builder().post(requestBody).url(url).build();
            final Response response = okHttpClient.newCall(request).execute();

            if (response.code() == 201) {
                System.out.println(String.format("Successfully uploaded %1$s", file.getName()));
            } else {
                throw new MojoExecutionException(String.format("OneSkyApp API returned %1$s: %2s, %3$s",
                        response.code(), response.message(), response.body().string()));
            }
        }
    } catch (IOException | MojoExecutionException ex) {
        if (failOnError == null || failOnError) {
            throw new MojoExecutionException(ex.getMessage(), ex);
        } else {
            System.out.println("Caught exception: " + ex.getMessage());
        }
    }
}

From source file:de.schildbach.wallet.data.DynamicFeeLoader.java

License:Open Source License

private static void fetchDynamicFees(final HttpUrl url, final File tempFile, final File targetFile,
        final String userAgent) {
    final Stopwatch watch = Stopwatch.createStarted();

    final Request.Builder request = new Request.Builder();
    request.url(url);//from   w w w  .j  a  v  a 2s  .co m
    request.header("User-Agent", userAgent);
    if (targetFile.exists())
        request.header("If-Modified-Since", HttpDate.format(new Date(targetFile.lastModified())));

    final OkHttpClient httpClient = Constants.HTTP_CLIENT.clone();
    httpClient.setConnectTimeout(5, TimeUnit.SECONDS);
    httpClient.setWriteTimeout(5, TimeUnit.SECONDS);
    httpClient.setReadTimeout(5, TimeUnit.SECONDS);
    final Call call = httpClient.newCall(request.build());
    try {
        final Response response = call.execute();
        final int status = response.code();
        if (status == HttpURLConnection.HTTP_NOT_MODIFIED) {
            log.info("Dynamic fees not modified at {}, took {}", url, watch);
        } else if (status == HttpURLConnection.HTTP_OK) {
            final ResponseBody body = response.body();
            final FileOutputStream os = new FileOutputStream(tempFile);
            Io.copy(body.byteStream(), os);
            os.close();
            final Date lastModified = response.headers().getDate("Last-Modified");
            if (lastModified != null)
                tempFile.setLastModified(lastModified.getTime());
            body.close();
            if (!tempFile.renameTo(targetFile))
                throw new IllegalStateException("Cannot rename " + tempFile + " to " + targetFile);
            watch.stop();
            log.info("Dynamic fees fetched from {}, took {}", url, watch);
        } else {
            log.warn("HTTP status {} when fetching dynamic fees from {}", response.code(), url);
        }
    } catch (final Exception x) {
        log.warn("Problem when fetching dynamic fees rates from " + url, x);
    }
}

From source file:de.schildbach.wallet.data.ExchangeRatesProvider.java

License:Open Source License

private Map<String, ExchangeRate> requestExchangeRates() {
    final Stopwatch watch = Stopwatch.createStarted();

    final Request.Builder request = new Request.Builder();
    request.url(BITCOINAVERAGE_URL);
    request.header("User-Agent", userAgent);

    final Call call = Constants.HTTP_CLIENT.newCall(request.build());
    try {/*from w w w  .  j  av a  2  s.c o  m*/
        final Response response = call.execute();
        if (response.isSuccessful()) {
            final String content = response.body().string();
            final JSONObject head = new JSONObject(content);
            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                if (currencyCode.startsWith("BTC")) {
                    final String fiatCurrencyCode = currencyCode.substring(3);
                    if (!fiatCurrencyCode.equals(MonetaryFormat.CODE_BTC)
                            && !fiatCurrencyCode.equals(MonetaryFormat.CODE_MBTC)
                            && !fiatCurrencyCode.equals(MonetaryFormat.CODE_UBTC)) {
                        final JSONObject exchangeRate = head.getJSONObject(currencyCode);
                        final JSONObject averages = exchangeRate.getJSONObject("averages");
                        try {
                            final Fiat rate = parseFiatInexact(fiatCurrencyCode, averages.getString("day"));
                            if (rate.signum() > 0)
                                rates.put(fiatCurrencyCode, new ExchangeRate(
                                        new org.bitcoinj.utils.ExchangeRate(rate), BITCOINAVERAGE_SOURCE));
                        } catch (final IllegalArgumentException x) {
                            log.warn("problem fetching {} exchange rate from {}: {}", currencyCode,
                                    BITCOINAVERAGE_URL, x.getMessage());
                        }
                    }
                }
            }

            watch.stop();
            log.info("fetched exchange rates from {}, {} chars, took {}", BITCOINAVERAGE_URL, content.length(),
                    watch);

            return rates;
        } else {
            log.warn("http status {} when fetching exchange rates from {}", response.code(),
                    BITCOINAVERAGE_URL);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + BITCOINAVERAGE_URL, x);
    }

    return null;
}

From source file:de.schildbach.wallet.ExchangeRatesProvider.java

License:Open Source License

private static Map<String, ExchangeRate> requestExchangeRates(final URL url, final String userAgent,
        final String source, final String... fields) {
    final Stopwatch watch = Stopwatch.createStarted();

    final Request.Builder request = new Request.Builder();
    request.url(url);/*from   w  w w.ja va 2  s  . c o m*/
    request.header("User-Agent", userAgent);

    final Call call = Constants.HTTP_CLIENT.newCall(request.build());
    try {
        final Response response = call.execute();
        if (response.isSuccessful()) {
            final String content = response.body().string();

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            final JSONObject head = new JSONObject(content);
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = Strings.emptyToNull(i.next());
                if (currencyCode != null && !"timestamp".equals(currencyCode)
                        && !MonetaryFormat.CODE_BTC.equals(currencyCode)
                        && !MonetaryFormat.CODE_MBTC.equals(currencyCode)
                        && !MonetaryFormat.CODE_UBTC.equals(currencyCode)) {
                    final JSONObject o = head.getJSONObject(currencyCode);

                    for (final String field : fields) {
                        final String rateStr = o.optString(field, null);

                        if (rateStr != null) {
                            try {
                                final Fiat rate = Fiat.parseFiat(currencyCode, rateStr);

                                if (rate.signum() > 0) {
                                    rates.put(currencyCode, new ExchangeRate(
                                            new org.bitcoinj.utils.ExchangeRate(rate), source));
                                    break;
                                }
                            } catch (final NumberFormatException x) {
                                log.warn("problem fetching {} exchange rate from {}: {}", currencyCode, url,
                                        x.getMessage());
                            }
                        }
                    }
                }
            }

            watch.stop();
            log.info("fetched exchange rates from {}, {} chars, took {}", url, content.length(), watch);

            return rates;
        } else {
            log.warn("http status {} when fetching exchange rates from {}", response.code(), url);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + url, x);
    }

    return null;
}

From source file:de.schildbach.wallet.ui.send.RequestWalletBalanceTask.java

License:Open Source License

public void requestWalletBalance(final Address... addresses) {
    backgroundHandler.post(new Runnable() {
        @Override/*w  w  w  . ja v a 2  s .  co  m*/
        public void run() {
            org.bitcoinj.core.Context.propagate(Constants.CONTEXT);

            final HttpUrl.Builder url = HttpUrl.parse(Constants.BITEASY_API_URL).newBuilder();
            url.addPathSegment("outputs");
            url.addQueryParameter("per_page", "MAX");
            url.addQueryParameter("operator", "AND");
            url.addQueryParameter("spent_state", "UNSPENT");
            for (final Address address : addresses)
                url.addQueryParameter("address[]", address.toBase58());

            log.debug("trying to request wallet balance from {}", url.build());

            final Request.Builder request = new Request.Builder();
            request.url(url.build());
            request.cacheControl(new CacheControl.Builder().noCache().build());
            request.header("Accept-Charset", "utf-8");
            if (userAgent != null)
                request.header("User-Agent", userAgent);

            final Call call = Constants.HTTP_CLIENT.newCall(request.build());
            try {
                final Response response = call.execute();
                if (response.isSuccessful()) {
                    final String content = response.body().string();
                    final JSONObject json = new JSONObject(content);

                    final int status = json.getInt("status");
                    if (status != 200)
                        throw new IOException("api status " + status + " when fetching unspent outputs");

                    final JSONObject jsonData = json.getJSONObject("data");

                    final JSONObject jsonPagination = jsonData.getJSONObject("pagination");

                    if (!"false".equals(jsonPagination.getString("next_page")))
                        throw new IOException("result set too big");

                    final JSONArray jsonOutputs = jsonData.getJSONArray("outputs");

                    final Map<Sha256Hash, Transaction> transactions = new HashMap<Sha256Hash, Transaction>(
                            jsonOutputs.length());

                    for (int i = 0; i < jsonOutputs.length(); i++) {
                        final JSONObject jsonOutput = jsonOutputs.getJSONObject(i);

                        final Sha256Hash uxtoHash = Sha256Hash.wrap(jsonOutput.getString("transaction_hash"));
                        final int uxtoIndex = jsonOutput.getInt("transaction_index");
                        final byte[] uxtoScriptBytes = Constants.HEX
                                .decode(jsonOutput.getString("script_pub_key"));
                        final Coin uxtoValue = Coin.valueOf(Long.parseLong(jsonOutput.getString("value")));

                        Transaction tx = transactions.get(uxtoHash);
                        if (tx == null) {
                            tx = new FakeTransaction(Constants.NETWORK_PARAMETERS, uxtoHash);
                            tx.getConfidence().setConfidenceType(ConfidenceType.BUILDING);
                            transactions.put(uxtoHash, tx);
                        }

                        final TransactionOutput output = new TransactionOutput(Constants.NETWORK_PARAMETERS, tx,
                                uxtoValue, uxtoScriptBytes);

                        if (tx.getOutputs().size() > uxtoIndex) {
                            // Work around not being able to replace outputs on transactions
                            final List<TransactionOutput> outputs = new ArrayList<TransactionOutput>(
                                    tx.getOutputs());
                            final TransactionOutput dummy = outputs.set(uxtoIndex, output);
                            checkState(dummy.getValue().equals(Coin.NEGATIVE_SATOSHI),
                                    "Index %s must be dummy output", uxtoIndex);
                            // Remove and re-add all outputs
                            tx.clearOutputs();
                            for (final TransactionOutput o : outputs)
                                tx.addOutput(o);
                        } else {
                            // Fill with dummies as needed
                            while (tx.getOutputs().size() < uxtoIndex)
                                tx.addOutput(new TransactionOutput(Constants.NETWORK_PARAMETERS, tx,
                                        Coin.NEGATIVE_SATOSHI, new byte[] {}));

                            // Add the real output
                            tx.addOutput(output);
                        }
                    }

                    log.info("fetched unspent outputs from {}", url);

                    onResult(transactions.values());
                } else {
                    final int responseCode = response.code();
                    final String responseMessage = response.message();

                    log.info("got http error '{}: {}' from {}", responseCode, responseMessage, url);
                    onFail(R.string.error_http, responseCode, responseMessage);
                }
            } catch (final JSONException x) {
                log.info("problem parsing json from " + url, x);

                onFail(R.string.error_parse, x.getMessage());
            } catch (final IOException x) {
                log.info("problem querying unspent outputs from " + url, x);

                onFail(R.string.error_io, x.getMessage());
            }
        }
    });
}

From source file:feign.okhttp.OkHttpClient.java

License:Apache License

private static feign.Response toFeignResponse(Response input) {
    return feign.Response.create(input.code(), input.message(), toMap(input.headers()), toBody(input.body()));
}

From source file:io.apiman.common.net.hawkular.HawkularMetricsClient.java

License:Apache License

/**
 * Creates a new tenant.//from   w w  w.  j  a v  a 2  s. co m
 * @param tenantId
 */
public void createTenant(String tenantId) {
    TenantBean tenant = new TenantBean(tenantId);
    try {
        URL endpoint = serverUrl.toURI().resolve("tenants").toURL(); //$NON-NLS-1$
        Request request = new Request.Builder().url(endpoint).post(toBody(tenant))
                .header("Hawkular-Tenant", tenantId) //$NON-NLS-1$
                .build();
        Response response = httpClient.newCall(request).execute();
        if (response.code() >= 400) {
            throw hawkularMetricsError(response);
        }
    } catch (URISyntaxException | IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:io.apiman.common.net.hawkular.HawkularMetricsClient.java

License:Apache License

/**
 * Get a list of all counter metrics for a given tenant.
 * @param tenantId/*from  w ww .j  av  a2  s. co m*/
 */
public List<MetricBean> listCounterMetrics(String tenantId) {
    try {
        URL endpoint = serverUrl.toURI().resolve("counters").toURL(); //$NON-NLS-1$
        Request request = new Request.Builder().url(endpoint).header("Accept", "application/json") //$NON-NLS-1$ //$NON-NLS-2$
                .header("Hawkular-Tenant", tenantId) //$NON-NLS-1$
                .build();
        Response response = httpClient.newCall(request).execute();
        if (response.code() >= 400) {
            throw hawkularMetricsError(response);
        }
        if (response.code() == 204) {
            return Collections.EMPTY_LIST;
        }
        String responseBody = response.body().string();
        return readMapper.reader(new TypeReference<List<MetricBean>>() {
        }).readValue(responseBody);
    } catch (URISyntaxException | IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:io.apiman.common.net.hawkular.HawkularMetricsClient.java

License:Apache License

/**
 * Adds multiple data points to a counter.
 * @param tenantId//  w w  w  .j  ava 2 s.c  o m
 * @param counterId
 * @param dataPoints
 */
public void addCounterDataPoints(String tenantId, String counterId, List<DataPointLongBean> dataPoints) {
    try {
        URL endpoint = serverUrl.toURI().resolve("counters/" + counterId + "/raw").toURL(); //$NON-NLS-1$ //$NON-NLS-2$
        Request request = new Request.Builder().url(endpoint).post(toBody(dataPoints))
                .header("Hawkular-Tenant", tenantId) //$NON-NLS-1$
                .build();
        Response response = httpClient.newCall(request).execute();
        if (response.code() >= 400) {
            throw hawkularMetricsError(response);
        }
    } catch (URISyntaxException | IOException e) {
        throw new RuntimeException(e);
    }
}