static SphereClientFactory of() { ServiceLoader<SphereHttpClientFactory> loader = ServiceLoader.load(SphereHttpClientFactory.class,SphereClientFactory.class.getClassLoader()); SphereHttpClientFactory httpClientFactory = loader.iterator().next(); if(httpClientFactory == null){ throw new SphereException(new NoClassDefFoundError(SphereHttpClientFactory.class.getCanonicalName())); } return of(httpClientFactory::getClient); } }
static SphereClientFactory of() { ServiceLoader<SphereHttpClientFactory> loader = ServiceLoader.load(SphereHttpClientFactory.class,SphereClientFactory.class.getClassLoader()); SphereHttpClientFactory httpClientFactory = loader.iterator().next(); if(httpClientFactory == null){ throw new SphereException(new NoClassDefFoundError(SphereHttpClientFactory.class.getCanonicalName())); } return of(httpClientFactory::getClient); } }
/** * Fetches a new access token using the client credentials flow. * * {@include.example io.sphere.sdk.client.TokensFacadeIntegrationTest#fetchAccessToken()} * * @param authConfig the commercetools project which the token should belong to * @return token */ public static CompletionStage<Tokens> fetchTokens(final SphereAuthConfig authConfig) { return TokensSupplier.of(authConfig, SphereClientFactory.of().createHttpClient(), true).get(); }
@Override public HttpRequestResult sendHttpGetRequest(String url) { HttpRequest request = HttpRequest.of(HttpMethod.GET, url); try(HttpClient client = SphereClientFactory.of().createHttpClient()) { HttpResponse response = client.execute(request).toCompletableFuture().get(10000, TimeUnit.MILLISECONDS); return HttpRequestResult.of(request, response, null); } catch (InterruptedException | ExecutionException | TimeoutException e) { return HttpRequestResult.of(request, null, e); } } }
/** * Shows the initialization of a {@link SphereClient} with a custom {@link HttpClient} provider. */ private void demoCreateClient() { final SphereClient sphereClient = SphereClientFactory.of(CustomClientConfigDemoIntegrationTest::createCustomHttpClient) .createClient("your projectKey", "your clientId", "your clientSecret"); }
/** * Fetches a new access token using the client credentials flow. * * {@include.example io.sphere.sdk.client.TokensFacadeIntegrationTest#fetchAccessToken()} * * @param authConfig the commercetools project which the token should belong to * @return token */ public static CompletionStage<Tokens> fetchTokens(final SphereAuthConfig authConfig) { return TokensSupplier.of(authConfig, SphereClientFactory.of().createHttpClient(), true).get(); }
public void instantiate() { final SphereClientFactory factory = SphereClientFactory.of(); final SphereClient client = factory.createClient( "jvm-sdk-dev-1", //replace with your project key "ELqF0rykXD2fyS8s-IhIPKfQ", //replace with your client id "222222222222222222222222222222226"); //replace with your client secret } }
/** * Fetches a new access token using the customer password flow. * * {@include.example io.sphere.sdk.client.TokensFacadeIntegrationTest#passwordFlowDemo()} * * @param authConfig authConfig * @param email email * @param password password * @return token */ public static CompletionStage<Tokens> fetchCustomerPasswordFlowTokens(final SphereAuthConfig authConfig, final String email, final String password) { return TokensSupplier.ofCustomerPasswordFlowTokens(authConfig, email, password, SphereClientFactory.of().createHttpClient(), true).get(); } }
private BlockingSphereClient createSphereClient() { final SphereClientFactory factory = SphereClientFactory.of(); final SphereClient asyncSphereClient = factory.createClient( "jvm-sdk-dev-1", //replace with your project key "ELqF0rykXD2fyS8s-IhIPKfQ", //replace with your client id "222222222222222222222222222222226"); //replace with your client secret return BlockingSphereClient.of(asyncSphereClient, 20, TimeUnit.SECONDS); } }
@Test public void autoLoadHttpClientWithoutExplicitSpecification() { if (!"false".equals(System.getenv("JVM_SDK_IT_SSL_VALIDATION"))) { final SphereClientFactory sphereClientFactory = SphereClientFactory.of(); final SphereClient client = sphereClientFactory.createClient(getSphereClientConfig()); final PagedQueryResult<Category> queryResult = client.execute(CategoryQuery.of()).toCompletableFuture().join(); assertThat(queryResult).isNotNull(); client.close(); } }
@Override public CompletionStage<Payment> requestHandling(String paymentId) { try (final HttpClient httpClient = SphereClientFactory.of().createHttpClient()) { return httpClient.execute(HttpRequest.of(HttpMethod.GET, buildUrl(paymentId))) .thenCompose(response -> { if(response.getStatusCode().equals(HttpStatusCode.OK_200)) { return sphereClient.execute(PaymentByIdGet.of(paymentId)); } return null; }); } }
@Test public void clientAlreadyClosed() throws Exception { if (!"false".equals(System.getenv("JVM_SDK_IT_SSL_VALIDATION"))) { try (final SphereClient client = SphereClientFactory.of().createClient(getSphereClientConfig())) { client.close(); assertThatThrownBy(() -> client.execute(ProjectGet.of())) .isInstanceOf(IllegalStateException.class); } } }
@Override @Nonnull public CompletionStage<HttpRequestResult> sendHttpGetRequest(String url) { HttpRequest request = HttpRequest.of(HttpMethod.GET, url); HttpClient client = SphereClientFactory.of().createHttpClient(); return client.execute(request) .thenApplyAsync(response -> HttpRequestResult.of(request, response, null)) .exceptionally(throwable -> HttpRequestResult.of(request, null, throwable)) .whenCompleteAsync((response, throwable) -> client.close()); } }
@Test public void create() { //we cannot check this in TeamCity with sphere CI, but with travis if (!"false".equals(System.getenv("JVM_SDK_IT_SSL_VALIDATION"))) { final SphereClientFactory clientFactory = SphereClientFactory.of(); try (final SphereClient client = clientFactory.createClient("empty-for-test", "empty", "empty")) { final Throwable throwable = catchThrowable(() -> doRequest(client)); assertThat(throwable) .as("if the client works then we know that the credentials are wrong") .isInstanceOf(CompletionException.class) .hasCauseInstanceOf(InvalidClientCredentialsException.class); } } }
@Test public void useToken() { if (!"false".equals(System.getenv("JVM_SDK_IT_SSL_VALIDATION"))) { final SphereClientFactory sphereClientFactory = SphereClientFactory.of(); final SphereApiConfig sphereClientConfig = getSphereClientConfig(); try(final SphereClient client = sphereClientFactory.createClientOfApiConfigAndAccessToken(sphereClientConfig, accessToken())){ final Project project = client.execute(ProjectGet.of()).toCompletableFuture().join(); assertThat(project.getKey()).isEqualTo(getSphereClientConfig().getProjectKey()); } } }
@Test public void userAgent() throws Exception { try (final FakeHttpClient httpClient = new FakeHttpClient()) { try (final SphereClient client = SphereClientFactory.of(() -> httpClient).createClient(getSphereClientConfig())) { client.execute(ProjectGet.of()).toCompletableFuture().join(); assertThat(httpClient.getLastUserAgent()) .startsWith("commercetools-jvm-sdk") .contains("JVM-SDK-integration-tests") .contains(BuildInfo.version()); } } }
@Test public void misconfiguredApiUrl() throws Exception { if (!"false".equals(System.getenv("JVM_SDK_IT_SSL_VALIDATION"))) { final String invalidApiUrl = "http://sdfjifdsjifdsjfdsjdfsjidsfjidfs.de"; final SphereClientConfig config = getSphereClientConfig().withApiUrl(invalidApiUrl); try (final SphereClient client = SphereClientFactory.of().createClient(config)) { final Throwable throwable = catchThrowable(() -> blockingWait(client.execute(ProjectGet.of()), Duration.ofMillis(1000))); assertThat(throwable).isInstanceOf(HttpException.class).hasCauseInstanceOf(UnknownHostException.class); assertThat(client).isNot(closed()); } } }
@Test public void misconfiguredAuthUrl() throws Exception { if (!"false".equals(System.getenv("JVM_SDK_IT_SSL_VALIDATION"))) { final String invalidAuthUrl = "http://sdfjifdsjifdsjfdsjdfsjidsfjidfs.de"; final SphereClientConfig config = getSphereClientConfig().withAuthUrl(invalidAuthUrl); try (final SphereClient client = SphereClientFactory.of().createClient(config)) { final Throwable throwable = catchThrowable(() -> blockingWait(client.execute(ProjectGet.of()), Duration.ofMillis(1000))); assertThat(throwable).isInstanceOf(HttpException.class).hasCauseInstanceOf(UnknownHostException.class); assertThat(client).isNot(closed()); } } }
protected synchronized static TestClient client() { if (client == null) { final SphereClientFactory factory = SphereClientFactory.of(); final SphereClientConfig config = SphereClientConfig.of(projectKey(), clientId(), clientSecret(), authUrl(), apiUrl()); final SphereAccessTokenSupplier tokenSupplier = SphereAccessTokenSupplierFactory.of().createSupplierOfOneTimeFetchingToken(config); final SphereClient underlying = factory.createClient(config, tokenSupplier); final SphereClient underlyingWithDeprecationExceptions = DeprecationExceptionSphereClientDecorator.of(underlying); client = new TestClient(underlyingWithDeprecationExceptions); } return client; }
@Test public void integrationTest() { final HttpClient httpClient = AsyncHttpClientAdapter.of(new AsyncHttpClient()); final SphereClientConfig sphereClientConfig = IntegrationTest.getSphereClientConfig(); final SphereClientFactory factory = SphereClientFactory.of(() -> httpClient); try (final BlockingSphereClient sphereClient = BlockingSphereClient.of(factory.createClient(sphereClientConfig), 10, TimeUnit.SECONDS)) { final Project project = sphereClient.executeBlocking(ProjectGet.of()); assertThat(project.getKey()).isEqualTo(sphereClientConfig.getProjectKey()); } } }