Example usage for com.squareup.okhttp HttpUrl parse

List of usage examples for com.squareup.okhttp HttpUrl parse

Introduction

In this page you can find the example usage for com.squareup.okhttp HttpUrl parse.

Prototype

public static HttpUrl parse(String url) 

Source Link

Document

Returns a new HttpUrl representing url if it is a well-formed HTTP or HTTPS URL, or null if it isn't.

Usage

From source file:com.netflix.spinnaker.clouddriver.artifacts.jenkins.JenkinsArtifactCredentials.java

License:Apache License

@Override
protected HttpUrl getDownloadUrl(Artifact artifact) {
    String formattedJenkinsAddress = jenkinsArtifactAccount.getAddress().endsWith("/")
            ? jenkinsArtifactAccount.getAddress()
            : jenkinsArtifactAccount.getAddress() + "/";
    String formattedReference = artifact.getReference().startsWith("/") ? artifact.getReference()
            : "/" + artifact.getReference();
    String buildUrl = formattedJenkinsAddress + "job/" + artifact.getName() + "/" + artifact.getVersion()
            + "/artifact" + formattedReference;
    HttpUrl url = HttpUrl.parse(buildUrl);
    if (url == null) {
        throw new IllegalArgumentException("Malformed content URL in reference: " + buildUrl
                + ". Read more here https://www.spinnaker.io/reference/artifacts/types/");
    }/* www.ja v  a  2  s  .c  o m*/
    return url;
}

From source file:com.piusvelte.okoauth.Helper.java

License:Apache License

public String getTokenAuthorizationUrl(@NonNull OkHttpClient client) {
    getTokenSecret(client);/*from w  w  w. ja  v a  2 s  .  c o m*/
    HttpUrl.Builder builder = HttpUrl.parse(mAuthorizationUrl).newBuilder()
            .addQueryParameter(RequestBuilder.OAuthParameter.oauth_token.name(), mToken);

    if (!mIsOAuth10a) {
        builder.addQueryParameter(RequestBuilder.OAuthParameter.oauth_callback.name(), mCallbackUrl);
    }

    return builder.build().toString();
}

From source file:com.quarterfull.newsAndroid.reader.HttpJsonRequest.java

License:Open Source License

public void setCredentials(final String username, final String password, final String oc_root_path) {
    if (username != null)
        credentials = Credentials.basic(username, password);
    else//from   w  w w .  j av  a 2  s .c om
        credentials = null;

    if (oc_root_path != null) {
        // Add empty path segment to ensure trailing slash
        oc_root_url = HttpUrl.parse(oc_root_path).newBuilder().addPathSegment("").build();
    }
}

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

License:Open Source License

public DynamicFeeLoader(final Context context) {
    super(context);
    final PackageInfo packageInfo = WalletApplication.packageInfoFromContext(context);
    final int versionNameSplit = packageInfo.versionName.indexOf('-');
    this.dynamicFeesUrl = HttpUrl.parse(Constants.DYNAMIC_FEES_URL
            + (versionNameSplit >= 0 ? packageInfo.versionName.substring(versionNameSplit) : ""));
    this.userAgent = WalletApplication.httpUserAgent(packageInfo.versionName);
    this.assets = context.getAssets();
}

From source file:de.schildbach.wallet.ui.AlertDialogsFragment.java

License:Open Source License

@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    backgroundThread = new HandlerThread("backgroundThread", Process.THREAD_PRIORITY_BACKGROUND);
    backgroundThread.start();/*from w  w  w.  ja va  2 s  . c om*/
    backgroundHandler = new Handler(backgroundThread.getLooper());

    final PackageInfo packageInfo = application.packageInfo();
    final int versionNameSplit = packageInfo.versionName.indexOf('-');
    final HttpUrl.Builder url = HttpUrl
            .parse(Constants.VERSION_URL
                    + (versionNameSplit >= 0 ? packageInfo.versionName.substring(versionNameSplit) : ""))
            .newBuilder();
    url.addEncodedQueryParameter("package", packageInfo.packageName);
    url.addQueryParameter("current", Integer.toString(packageInfo.versionCode));
    versionUrl = url.build();
}

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/*  www  . j  a va2 s  . c  o  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:de.schildbach.wallet.ui.WalletActivity.java

License:Open Source License

private void checkAlerts() {
    final PackageInfo packageInfo = getWalletApplication().packageInfo();
    final int versionNameSplit = packageInfo.versionName.indexOf('-');
    final HttpUrl.Builder url = HttpUrl
            .parse(Constants.VERSION_URL
                    + (versionNameSplit >= 0 ? packageInfo.versionName.substring(versionNameSplit) : ""))
            .newBuilder();//from   ww  w .  j a v  a  2 s.  c om
    url.addEncodedQueryParameter("package", packageInfo.packageName);
    url.addQueryParameter("current", Integer.toString(packageInfo.versionCode));

    new HttpGetThread(url.build(), application.httpUserAgent()) {
        @Override
        protected void handleLine(final String line, final long serverTime) {
            final int serverVersionCode = Integer.parseInt(line.split("\\s+")[0]);

            log.info("according to \"" + url + "\", strongly recommended minimum app version is "
                    + serverVersionCode);

            if (serverTime > 0) {
                final long diffMinutes = Math
                        .abs((System.currentTimeMillis() - serverTime) / DateUtils.MINUTE_IN_MILLIS);

                if (diffMinutes >= 60) {
                    log.info(
                            "according to \"" + url + "\", system clock is off by " + diffMinutes + " minutes");

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (!isFinishing())
                                return;
                            final Bundle args = new Bundle();
                            args.putLong("diff_minutes", diffMinutes);
                            showDialog(DIALOG_TIMESKEW_ALERT, args);
                        }
                    });

                    return;
                }
            }

            if (serverVersionCode > packageInfo.versionCode) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (isFinishing())
                            return;
                        showDialog(DIALOG_VERSION_ALERT);
                    }
                });

                return;
            }
        }

        @Override
        protected void handleException(final Exception x) {
            if (x instanceof UnknownHostException || x instanceof SocketException
                    || x instanceof SocketTimeoutException) {
                // swallow
                log.debug("problem reading", x);
            } else {
                CrashReporter.saveBackgroundTrace(new RuntimeException(url.toString(), x), packageInfo);
            }
        }
    }.start();

    if (CrashReporter.hasSavedCrashTrace()) {
        final StringBuilder stackTrace = new StringBuilder();

        try {
            CrashReporter.appendSavedCrashTrace(stackTrace);
        } catch (final IOException x) {
            log.info("problem appending crash info", x);
        }

        final ReportIssueDialogBuilder dialog = new ReportIssueDialogBuilder(this,
                R.string.report_issue_dialog_title_crash, R.string.report_issue_dialog_message_crash) {
            @Override
            protected CharSequence subject() {
                return Constants.REPORT_SUBJECT_CRASH + " " + packageInfo.versionName;
            }

            @Override
            protected CharSequence collectApplicationInfo() throws IOException {
                final StringBuilder applicationInfo = new StringBuilder();
                CrashReporter.appendApplicationInfo(applicationInfo, application);
                return applicationInfo;
            }

            @Override
            protected CharSequence collectStackTrace() throws IOException {
                if (stackTrace.length() > 0)
                    return stackTrace;
                else
                    return null;
            }

            @Override
            protected CharSequence collectDeviceInfo() throws IOException {
                final StringBuilder deviceInfo = new StringBuilder();
                CrashReporter.appendDeviceInfo(deviceInfo, WalletActivity.this);
                return deviceInfo;
            }

            @Override
            protected CharSequence collectWalletDump() {
                return wallet.toString(false, true, true, null);
            }
        };

        dialog.show();
    }
}

From source file:io.github.hidroh.materialistic.accounts.UserServicesClient.java

License:Apache License

@Override
public void login(final String username, final String password, boolean createAccount,
        final Callback callback) {
    FormEncodingBuilder formBuilder = new FormEncodingBuilder().add(LOGIN_PARAM_ACCT, username)
            .add(LOGIN_PARAM_PW, password).add(LOGIN_PARAM_GOTO, DEFAULT_REDIRECT);
    if (createAccount) {
        formBuilder.add(LOGIN_PARAM_CREATING, CREATING_TRUE);
    }//from   ww  w.ja  v  a 2 s  . c o  m
    mClient.newCall(new Request.Builder()
            .url(HttpUrl.parse(BASE_WEB_URL).newBuilder().addPathSegment(LOGIN_PATH).build())
            .post(formBuilder.build()).build()).enqueue(wrap(callback));
}

From source file:io.github.hidroh.materialistic.accounts.UserServicesClient.java

License:Apache License

@Override
public void voteUp(Context context, String itemId, final Callback callback) {
    Pair<String, String> credentials = AppUtils.getCredentials(context);
    if (credentials == null) {
        callback.onDone(false);//from  www .j av a  2  s.c  o  m
        return;
    }
    Toast.makeText(context, R.string.sending, Toast.LENGTH_SHORT).show();
    mClient.newCall(new Request.Builder()
            .url(HttpUrl.parse(BASE_WEB_URL).newBuilder().addPathSegment(VOTE_PATH).build())
            .post(new FormEncodingBuilder().add(LOGIN_PARAM_ACCT, credentials.first)
                    .add(LOGIN_PARAM_PW, credentials.second).add(VOTE_PARAM_FOR, itemId)
                    .add(VOTE_PARAM_DIR, VOTE_DIR_UP).add(VOTE_PARAM_WHENCE, DEFAULT_REDIRECT).build())
            .build()).enqueue(wrap(callback));
}

From source file:io.github.hidroh.materialistic.accounts.UserServicesClient.java

License:Apache License

@Override
public void reply(Context context, String parentId, String text, Callback callback) {
    Pair<String, String> credentials = AppUtils.getCredentials(context);
    if (credentials == null) {
        callback.onDone(false);/*  w w  w. j  a v a2 s . co  m*/
        return;
    }
    mClient.newCall(new Request.Builder()
            .url(HttpUrl.parse(BASE_WEB_URL).newBuilder().addPathSegment(COMMENT_PATH).build())
            .post(new FormEncodingBuilder().add(LOGIN_PARAM_ACCT, credentials.first)
                    .add(LOGIN_PARAM_PW, credentials.second).add(COMMENT_PARAM_PARENT, parentId)
                    .add(COMMENT_PARAM_TEXT, text).build())
            .build()).enqueue(wrap(callback));
}