Example usage for com.squareup.okhttp OkHttpClient OkHttpClient

List of usage examples for com.squareup.okhttp OkHttpClient OkHttpClient

Introduction

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

Prototype

public OkHttpClient() 

Source Link

Usage

From source file:org.apache.nifi.minifi.bootstrap.configuration.notifiers.TestRestChangeNotifierSSL.java

License:Apache License

@BeforeClass
public static void setUpHttps() throws CertificateException, NoSuchAlgorithmException, KeyStoreException,
        IOException, UnrecoverableKeyException, KeyManagementException, InterruptedException {
    Properties properties = new Properties();
    properties.setProperty(RestChangeNotifier.TRUSTSTORE_LOCATION_KEY, "./src/test/resources/localhost-ts.jks");
    properties.setProperty(RestChangeNotifier.TRUSTSTORE_PASSWORD_KEY, "localtest");
    properties.setProperty(RestChangeNotifier.TRUSTSTORE_TYPE_KEY, "JKS");
    properties.setProperty(RestChangeNotifier.KEYSTORE_LOCATION_KEY, "./src/test/resources/localhost-ks.jks");
    properties.setProperty(RestChangeNotifier.KEYSTORE_PASSWORD_KEY, "localtest");
    properties.setProperty(RestChangeNotifier.KEYSTORE_TYPE_KEY, "JKS");
    properties.setProperty(RestChangeNotifier.NEED_CLIENT_AUTH_KEY, "true");
    restChangeNotifier = new RestChangeNotifier();
    restChangeNotifier.initialize(properties);
    restChangeNotifier.registerListener(mockChangeListener);
    restChangeNotifier.start();//from   w w  w  . j av  a  2  s  .  c om

    client = new OkHttpClient();

    SSLContext sslContext = SSLContext.getInstance("TLS");
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(readKeyStore("./src/test/resources/localhost-ts.jks"));

    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(readKeyStore("./src/test/resources/localhost-ks.jks"), "localtest".toCharArray());

    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
            new SecureRandom());
    client.setSslSocketFactory(sslContext.getSocketFactory());

    url = restChangeNotifier.getURI().toURL().toString();
    Thread.sleep(1000);
}

From source file:org.apache.nifi.processors.att.m2x.AbstractM2XProcessor.java

License:Apache License

@OnScheduled
public void onScheduled(final ProcessContext context) {
    httpClientRef.set(new OkHttpClient());
}

From source file:org.apache.nifi.processors.standard.InvokeHTTP.java

License:Apache License

@OnScheduled
public void setUpClient(final ProcessContext context) throws IOException {
    okHttpClientAtomicReference.set(null);

    OkHttpClient okHttpClient = new OkHttpClient();

    // Add a proxy if set
    final String proxyHost = context.getProperty(PROP_PROXY_HOST).getValue();
    final Integer proxyPort = context.getProperty(PROP_PROXY_PORT).asInteger();
    if (proxyHost != null && proxyPort != null) {
        final Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
        okHttpClient.setProxy(proxy);//  w  ww. j a v a 2 s. com
    }

    // Set timeouts
    okHttpClient.setConnectTimeout(
            (context.getProperty(PROP_CONNECT_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()),
            TimeUnit.MILLISECONDS);
    okHttpClient.setReadTimeout(
            context.getProperty(PROP_READ_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue(),
            TimeUnit.MILLISECONDS);

    // Set whether to follow redirects
    okHttpClient.setFollowRedirects(context.getProperty(PROP_FOLLOW_REDIRECTS).asBoolean());

    final SSLContextService sslService = context.getProperty(PROP_SSL_CONTEXT_SERVICE)
            .asControllerService(SSLContextService.class);
    final SSLContext sslContext = sslService == null ? null : sslService.createSSLContext(ClientAuth.NONE);

    // check if the ssl context is set and add the factory if so
    if (sslContext != null) {
        okHttpClient.setSslSocketFactory(sslContext.getSocketFactory());
    }

    // check the trusted hostname property and override the HostnameVerifier
    String trustedHostname = trimToEmpty(context.getProperty(PROP_TRUSTED_HOSTNAME).getValue());
    if (!trustedHostname.isEmpty()) {
        okHttpClient.setHostnameVerifier(
                new OverrideHostnameVerifier(trustedHostname, okHttpClient.getHostnameVerifier()));
    }

    setAuthenticator(okHttpClient, context);

    useChunked = context.getProperty(PROP_USE_CHUNKED_ENCODING).asBoolean();

    okHttpClientAtomicReference.set(okHttpClient);
}

From source file:org.bitcoinj.core.PeerGroup.java

License:Apache License

/**
 * <p>Creates a PeerGroup that accesses the network via the Tor network. The provided TorClient is used so you can
 * preconfigure it beforehand. It should not have been already started. You can just use "new TorClient()" if
 * you don't have any particular configuration requirements.</p>
 *
 * <p>If running on the Oracle JDK the unlimited strength jurisdiction checks will also be overridden,
 * as they no longer apply anyway and can cause startup failures due to the requirement for AES-256.</p>
 *
 * <p>The user does not need any additional software for this: it's all pure Java. As of April 2014 <b>this mode
 * is experimental</b>.</p>// w w w.  j ava  2 s . c  o m
 *
 * @params doDiscovery if true, DNS or HTTP peer discovery will be performed via Tor: this is almost always what you want.
 * @throws java.util.concurrent.TimeoutException if Tor fails to start within 20 seconds.
 */
public static PeerGroup newWithTor(Context context, @Nullable AbstractBlockChain chain, TorClient torClient,
        boolean doDiscovery) throws TimeoutException {
    checkNotNull(torClient);
    DRMWorkaround.maybeDisableExportControls();
    BlockingClientManager manager = new BlockingClientManager(torClient.getSocketFactory());
    final int CONNECT_TIMEOUT_MSEC = TOR_TIMEOUT_SECONDS * 1000;
    manager.setConnectTimeoutMillis(CONNECT_TIMEOUT_MSEC);
    PeerGroup result = new PeerGroup(context, chain, manager, torClient);
    result.setConnectTimeoutMillis(CONNECT_TIMEOUT_MSEC);

    if (doDiscovery) {
        NetworkParameters params = context.getParams();
        HttpDiscovery.Details[] httpSeeds = params.getHttpSeeds();
        if (httpSeeds.length > 0) {
            // Use HTTP discovery when Tor is active and there is a Cartographer seed, for a much needed speed boost.
            OkHttpClient client = new OkHttpClient();
            client.setSocketFactory(torClient.getSocketFactory());
            result.addPeerDiscovery(new HttpDiscovery(params, httpSeeds[0], client));
        } else {
            result.addPeerDiscovery(new TorDiscovery(params, torClient));
        }
    }
    return result;
}

From source file:org.bitcoinj_extra.core.PeerGroup.java

License:Apache License

/**
 * <p>Creates a PeerGroup that accesses the network via the Tor network. The provided TorClient is used so you can
 * preconfigure it beforehand. It should not have been already started. You can just use "new TorClient()" if
 * you don't have any particular configuration requirements.</p>
 *
 * <p>If running on the Oracle JDK the unlimited strength jurisdiction checks will also be overridden,
 * as they no longer apply anyway and can cause startup failures due to the requirement for AES-256.</p>
 *
 * <p>The user does not need any additional software for this: it's all pure Java. As of April 2014 <b>this mode
 * is experimental</b>.</p>/*from   w ww. j  av  a  2  s  .c o  m*/
 *
 * @param doDiscovery if true, DNS or HTTP peer discovery will be performed via Tor: this is almost always what you want.
 * @throws java.util.concurrent.TimeoutException if Tor fails to start within 20 seconds.
 */
public static PeerGroup newWithTor(Context context, @Nullable AbstractBlockChain chain, TorClient torClient,
        boolean doDiscovery) throws TimeoutException {
    checkNotNull(torClient);
    DRMWorkaround.maybeDisableExportControls();
    BlockingClientManager manager = new BlockingClientManager(torClient.getSocketFactory());
    final int CONNECT_TIMEOUT_MSEC = TOR_TIMEOUT_SECONDS * 1000;
    manager.setConnectTimeoutMillis(CONNECT_TIMEOUT_MSEC);
    PeerGroup result = new PeerGroup(context, chain, manager, torClient);
    result.setConnectTimeoutMillis(CONNECT_TIMEOUT_MSEC);

    if (doDiscovery) {
        NetworkParameters params = context.getParams();
        HttpDiscovery.Details[] httpSeeds = params.getHttpSeeds();
        if (httpSeeds.length > 0) {
            // Use HTTP discovery when Tor is active and there is a Cartographer seed, for a much needed speed boost.
            OkHttpClient httpClient = new OkHttpClient();
            httpClient.setSocketFactory(torClient.getSocketFactory());
            List<PeerDiscovery> discoveries = Lists.newArrayList();
            for (HttpDiscovery.Details httpSeed : httpSeeds)
                discoveries.add(new HttpDiscovery(params, httpSeed, httpClient));
            result.addPeerDiscovery(new MultiplexingDiscovery(params, discoveries));
        } else {
            result.addPeerDiscovery(new TorDiscovery(params, torClient));
        }
    }
    return result;
}

From source file:org.bitcoinj_extra.net.discovery.HttpDiscovery.java

License:Apache License

/**
 * Constructs a discovery object that will read data from the given HTTP[S] URI and, if a public key is provided,
 * will check the signature using that key.
 *///w  w w. j  av a 2  s .c o m
public HttpDiscovery(NetworkParameters params, Details details) {
    this(params, details, new OkHttpClient());
}

From source file:org.bitcoinj_extra.net.discovery.MultiplexingDiscovery.java

License:Apache License

/**
 * Builds a suitable set of peer discoveries. Will query them in parallel before producing a merged response.
 * If specific services are required, DNS is not used as the protocol can't handle it.
 * @param params Network to use.// w w  w . j  a va  2s  . c  o m
 * @param services Required services as a bitmask, e.g. {@link VersionMessage#NODE_NETWORK}.
 */
public static MultiplexingDiscovery forServices(NetworkParameters params, long services) {
    List<PeerDiscovery> discoveries = Lists.newArrayList();
    HttpDiscovery.Details[] httpSeeds = params.getHttpSeeds();
    if (httpSeeds != null) {
        OkHttpClient httpClient = new OkHttpClient();
        for (HttpDiscovery.Details httpSeed : httpSeeds)
            discoveries.add(new HttpDiscovery(params, httpSeed, httpClient));
    }
    // Also use DNS seeds if there is no specific service requirement
    if (services == 0) {
        String[] dnsSeeds = params.getDnsSeeds();
        if (dnsSeeds != null)
            for (String dnsSeed : dnsSeeds)
                discoveries.add(new DnsSeedDiscovery(params, dnsSeed));
    }
    return new MultiplexingDiscovery(params, discoveries);
}

From source file:org.catnut.support.OkHttpStack.java

License:Open Source License

public static OkHttpClient getOkHttpClient() {
    if (okHttpClient == null) {
        okHttpClient = new OkHttpClient();
    }/* ww w  .j  a v  a  2s . c  o m*/
    return okHttpClient;
}

From source file:org.catrobat.catroid.web.ConnectionWrapper.java

License:Open Source License

public String doHttpsPostFileUpload(String urlString, HashMap<String, String> postValues, String fileTag,
        String filePath, ResultReceiver receiver, Integer notificationId)
        throws IOException, WebconnectionException {

    String answer = "";
    String fileName = postValues.get(TAG_PROJECT_TITLE);

    if (filePath != null) {
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setTransports(Arrays.asList("http/1.1"));
        HttpRequest.setConnectionFactory(new OkConnectionFactory(okHttpClient));
        HttpRequest uploadRequest = HttpRequest.post(urlString).chunk(0);

        for (HashMap.Entry<String, String> entry : postValues.entrySet()) {
            uploadRequest.part(entry.getKey(), entry.getValue());
        }//from   w ww.j a va  2s  . c  o  m
        File file = new File(filePath);
        uploadRequest.part(fileTag, fileName, file);

        try {
            int responseCode = uploadRequest.code();
            if (!(responseCode == 200 || responseCode == 201)) {
                throw new WebconnectionException(responseCode, "Error response code should be 200 or 201!");
            }
            if (!uploadRequest.ok()) {
                Log.v(TAG, "Upload not successful");
                StatusBarNotificationManager.getInstance().cancelNotification(notificationId);
            } else {
                StatusBarNotificationManager.getInstance().showOrUpdateNotification(notificationId, 100);
            }

            answer = uploadRequest.body();
            Log.v(TAG, "Upload response is: " + answer);
        } catch (HttpRequest.HttpRequestException exception) {
            Log.e(TAG, "OkHttpError", exception);
            throw new WebconnectionException(WebconnectionException.ERROR_NETWORK, "OkHttp threw an exception");
        }
    }
    return answer;
}

From source file:org.catrobat.catroid.web.ServerCalls.java

License:Open Source License

private ServerCalls() {
    okHttpClient = new OkHttpClient();
    okHttpClient.setConnectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS));
    gson = new Gson();
}