Search in sources :

Example 11 with OkHttpClient

use of com.github.mjeanroy.junit.servers.client.impl.okhttp3.OkHttpClient in project spring-cloud-kubernetes by spring-cloud.

the class KubernetesClientEventBasedSecretsChangeDetectorTests method watch.

@Test
void watch() {
    GsonBuilder builder = new GsonBuilder();
    builder.excludeFieldsWithModifiers(Modifier.STATIC, Modifier.TRANSIENT, Modifier.VOLATILE).registerTypeAdapter(OffsetDateTime.class, new GsonOffsetDateTimeAdapter());
    Gson gson = builder.create();
    V1Secret dbPassword = new V1Secret().kind("Secret").metadata(new V1ObjectMeta().name("db-password")).putStringDataItem("password", Base64.getEncoder().encodeToString("p455w0rd".getBytes())).putStringDataItem("username", Base64.getEncoder().encodeToString("user".getBytes()));
    V1Secret dbPasswordUpdated = new V1Secret().kind("Secret").metadata(new V1ObjectMeta().name("db-password")).putStringDataItem("password", Base64.getEncoder().encodeToString("p455w0rd2".getBytes())).putStringDataItem("username", Base64.getEncoder().encodeToString("user".getBytes()));
    V1SecretList secretList = new V1SecretList().kind("SecretList").metadata(new V1ListMeta().resourceVersion("0")).items(Arrays.asList(dbPassword));
    stubFor(get(urlMatching("^/api/v1/namespaces/default/secrets.*")).inScenario("watch").whenScenarioStateIs(STARTED).withQueryParam("watch", equalTo("false")).willReturn(aResponse().withStatus(200).withBody(gson.toJson(secretList))).willSetStateTo("update"));
    Watch.Response<V1Secret> watchResponse = new Watch.Response<>(EventType.MODIFIED.name(), dbPasswordUpdated);
    stubFor(get(urlMatching("/api/v1/namespaces/default/secrets.*")).inScenario("watch").whenScenarioStateIs("update").withQueryParam("watch", equalTo("true")).willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(watchResponse))).willSetStateTo("add"));
    stubFor(get(urlMatching("/api/v1/namespaces/default/secrets.*")).inScenario("watch").whenScenarioStateIs("add").withQueryParam("watch", equalTo("true")).willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(new Watch.Response<>(EventType.ADDED.name(), new V1Secret().kind("Secret").metadata(new V1ObjectMeta().name("rabbit-password")).putDataItem("rabbit-pw", Base64.getEncoder().encode("password".getBytes())))))).willSetStateTo("delete"));
    stubFor(get(urlMatching("/api/v1/namespaces/default/secrets.*")).inScenario("watch").whenScenarioStateIs("delete").withQueryParam("watch", equalTo("true")).willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(new Watch.Response<>(EventType.DELETED.name(), new V1Secret().kind("Secret").metadata(new V1ObjectMeta().name("rabbit-password")).putDataItem("rabbit-pw", Base64.getEncoder().encode("password".getBytes())))))).willSetStateTo("done"));
    stubFor(get(urlMatching("/api/v1/namespaces/default/secrets.*")).inScenario("watch").whenScenarioStateIs("done").withQueryParam("watch", equalTo("true")).willReturn(aResponse().withStatus(200)));
    ApiClient apiClient = new ClientBuilder().setBasePath("http://localhost:" + wireMockServer.port()).build();
    OkHttpClient httpClient = apiClient.getHttpClient().newBuilder().readTimeout(0, TimeUnit.SECONDS).build();
    apiClient.setHttpClient(httpClient);
    CoreV1Api coreV1Api = new CoreV1Api(apiClient);
    ConfigurationUpdateStrategy strategy = mock(ConfigurationUpdateStrategy.class);
    when(strategy.getName()).thenReturn("strategy");
    KubernetesMockEnvironment environment = new KubernetesMockEnvironment(mock(KubernetesClientSecretsPropertySource.class)).withProperty("db-password", "p455w0rd");
    KubernetesClientSecretsPropertySourceLocator locator = mock(KubernetesClientSecretsPropertySourceLocator.class);
    when(locator.locate(environment)).thenAnswer(ignoreMe -> new MockPropertySource().withProperty("db-password", "p455w0rd2"));
    ConfigReloadProperties properties = new ConfigReloadProperties();
    properties.setMonitoringSecrets(true);
    KubernetesNamespaceProvider kubernetesNamespaceProvider = mock(KubernetesNamespaceProvider.class);
    when(kubernetesNamespaceProvider.getNamespace()).thenReturn("default");
    KubernetesClientEventBasedSecretsChangeDetector changeDetector = new KubernetesClientEventBasedSecretsChangeDetector(coreV1Api, environment, properties, strategy, locator, kubernetesNamespaceProvider);
    Thread controllerThread = new Thread(changeDetector::watch);
    controllerThread.setDaemon(true);
    controllerThread.start();
    await().timeout(Duration.ofSeconds(300)).until(() -> Mockito.mockingDetails(strategy).getInvocations().size() > 4);
    verify(strategy, atLeast(3)).reload();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) KubernetesClientSecretsPropertySourceLocator(org.springframework.cloud.kubernetes.client.config.KubernetesClientSecretsPropertySourceLocator) V1ObjectMeta(io.kubernetes.client.openapi.models.V1ObjectMeta) Gson(com.google.gson.Gson) JSON(io.kubernetes.client.openapi.JSON) ConfigurationUpdateStrategy(org.springframework.cloud.kubernetes.commons.config.reload.ConfigurationUpdateStrategy) V1SecretList(io.kubernetes.client.openapi.models.V1SecretList) Watch(io.kubernetes.client.util.Watch) KubernetesNamespaceProvider(org.springframework.cloud.kubernetes.commons.KubernetesNamespaceProvider) CoreV1Api(io.kubernetes.client.openapi.apis.CoreV1Api) ClientBuilder(io.kubernetes.client.util.ClientBuilder) GsonBuilder(com.google.gson.GsonBuilder) ApiClient(io.kubernetes.client.openapi.ApiClient) V1ListMeta(io.kubernetes.client.openapi.models.V1ListMeta) WireMock.aResponse(com.github.tomakehurst.wiremock.client.WireMock.aResponse) ConfigReloadProperties(org.springframework.cloud.kubernetes.commons.config.reload.ConfigReloadProperties) MockPropertySource(org.springframework.mock.env.MockPropertySource) V1Secret(io.kubernetes.client.openapi.models.V1Secret) Test(org.junit.jupiter.api.Test)

Example 12 with OkHttpClient

use of com.github.mjeanroy.junit.servers.client.impl.okhttp3.OkHttpClient in project bttv by bttv-android.

the class UpdaterActivity method startDownload.

private void startDownload(final String url, final ProgressBar bar) {
    final String filename = "bttv.apk";
    final ProgressListener progListener = getProgressListener(bar);
    final OkHttpClient client = getClient(progListener);
    final Request request = new Request.Builder().url(url).build();
    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                Response response = client.newCall(request).execute();
                if (!response.isSuccessful())
                    throw new IOException("Unexpected code " + response);
                Log.d("LBTTVUpdaterActivity", "sucessful");
                File downloadedFile = new File(UpdaterActivity.this.getCacheDir(), filename);
                FileOutputStream os = new FileOutputStream(downloadedFile);
                BufferedSink sink = Okio.buffer(Okio.sink(os));
                sink.writeAll(response.body().source());
                sink.close();
                Intent intent = new Intent("android.intent.action.INSTALL_PACKAGE");
                Uri uri = FileProvider.getUriForFile(UpdaterActivity.this, "tv.twitch.bttvandroid.app.provider", downloadedFile);
                intent.setDataAndType(uri, "application/vnd.android.package-archive");
                intent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_GRANT_READ_URI_PERMISSION);
                startActivity(intent);
            } catch (Exception e) {
                Log.e("LBTTVUpdaterActivity", "Update failed", e);
                UpdaterActivity.this.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        Util.showError(UpdaterActivity.this, e);
                    }
                });
            }
        }
    }).start();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) BufferedSink(okio.BufferedSink) Intent(android.content.Intent) IOException(java.io.IOException) Uri(android.net.Uri) IOException(java.io.IOException) Response(okhttp3.Response) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 13 with OkHttpClient

use of com.github.mjeanroy.junit.servers.client.impl.okhttp3.OkHttpClient in project bttv by bttv-android.

the class Network method get.

public static void get(String url, Callback cb) {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(url).addHeader("User-Agent", "bttv-android").build();
    client.newCall(request).enqueue(cb);
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request)

Example 14 with OkHttpClient

use of com.github.mjeanroy.junit.servers.client.impl.okhttp3.OkHttpClient in project ergo-appkit by ergoplatform.

the class BlockchainContextBuilderImpl method build.

@Override
public BlockchainContext build() throws ErgoClientException {
    _ok = _client.getOkBuilder().build();
    _retrofit = _client.getAdapterBuilder().client(_ok).build();
    if (_explorer != null) {
        OkHttpClient okExplorer = _explorer.getOkBuilder().build();
        _retrofitExplorer = _explorer.getAdapterBuilder().client(okExplorer).build();
    }
    _nodeInfo = ErgoNodeFacade.getNodeInfo(_retrofit);
    _headers = ErgoNodeFacade.getLastHeaders(_retrofit, BigDecimal.valueOf(NUM_LAST_HEADERS));
    Collections.reverse(_headers);
    return new BlockchainContextImpl(_client, _retrofit, _explorer, _retrofitExplorer, _networkType, _nodeInfo, _headers);
}
Also used : OkHttpClient(okhttp3.OkHttpClient)

Example 15 with OkHttpClient

use of com.github.mjeanroy.junit.servers.client.impl.okhttp3.OkHttpClient in project bitcoinj by bitcoinj.

the class MultiplexingDiscovery method forServices.

/**
 * Builds a suitable set of peer discoveries.
 * @param params Network to use.
 * @param services Required services as a bitmask, e.g. {@link VersionMessage#NODE_NETWORK}.
 * @param parallelQueries When true, seeds are queried in parallel
 * @param shufflePeers When true, queried peers are shuffled
 */
public static MultiplexingDiscovery forServices(NetworkParameters params, long services, boolean parallelQueries, boolean shufflePeers) {
    List<PeerDiscovery> discoveries = new ArrayList<>();
    HttpDiscovery.Details[] httpSeeds = params.getHttpSeeds();
    if (httpSeeds != null) {
        OkHttpClient httpClient = new OkHttpClient();
        for (HttpDiscovery.Details httpSeed : httpSeeds) discoveries.add(new HttpDiscovery(params, httpSeed, httpClient));
    }
    String[] dnsSeeds = params.getDnsSeeds();
    if (dnsSeeds != null)
        for (String dnsSeed : dnsSeeds) discoveries.add(new DnsSeedDiscovery(params, dnsSeed));
    return new MultiplexingDiscovery(params, discoveries, parallelQueries, shufflePeers);
}
Also used : OkHttpClient(okhttp3.OkHttpClient) ArrayList(java.util.ArrayList) DnsSeedDiscovery(org.bitcoinj.net.discovery.DnsDiscovery.DnsSeedDiscovery)

Aggregations

OkHttpClient (okhttp3.OkHttpClient)1944 Request (okhttp3.Request)1024 Response (okhttp3.Response)880 IOException (java.io.IOException)567 Test (org.junit.Test)365 Call (okhttp3.Call)290 RequestBody (okhttp3.RequestBody)222 Test (org.junit.jupiter.api.Test)145 Retrofit (retrofit2.Retrofit)138 File (java.io.File)132 HttpUrl (okhttp3.HttpUrl)131 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)128 Callback (okhttp3.Callback)117 JSONObject (org.json.JSONObject)110 ArrayList (java.util.ArrayList)106 ResponseBody (okhttp3.ResponseBody)105 Gson (com.google.gson.Gson)98 MediaType (okhttp3.MediaType)98 List (java.util.List)92 Map (java.util.Map)85