List of usage examples for com.squareup.okhttp OkHttpClient OkHttpClient
public OkHttpClient()
From source file:io.kodokojo.bdd.stage.ApplicationWhen.java
License:Open Source License
private String getProjectConfiguration(String username, String projectConfigurationId) { UserInfo userInfo = currentUsers.get(username); Request.Builder builder = new Request.Builder().get() .url(getApiBaseUrl() + "/projectconfig/" + projectConfigurationId); Request request = HttpUserSupport.addBasicAuthentification(userInfo, builder).build(); Response response = null;/*from w w w .j av a 2 s.com*/ try { OkHttpClient httpClient = new OkHttpClient(); response = httpClient.newCall(request).execute(); assertThat(response.code()).isEqualTo(200); String body = response.body().string(); return body; } catch (IOException e) { fail(e.getMessage()); } finally { if (response != null) { IOUtils.closeQuietly(response.body()); } } return null; }
From source file:io.kodokojo.bdd.stage.brickauthenticator.JenkinsUserAuthenticator.java
License:Open Source License
@Override public boolean authenticate(String url, UserInfo userInfo) { OkHttpClient httpClient = new OkHttpClient(); return authenticate(httpClient, url, userInfo); }
From source file:io.kodokojo.bdd.stage.BrickConfigurerGiven.java
License:Open Source License
private boolean waitBrickStarted(String brickUrl, int timeout) { boolean started = false; long now = System.currentTimeMillis(); long end = now + (timeout * 1000); OkHttpClient httpClient = new OkHttpClient(); Request request = new Request.Builder().get().url(brickUrl).build(); while (!started && (end - System.currentTimeMillis()) > 0) { Response response = null; try {/*from w w w . j av a 2 s. c o m*/ response = httpClient.newCall(request).execute(); int httpStatusCode = response.code(); started = httpStatusCode >= 200 && httpStatusCode < 300; } catch (IOException e) { // Silently ignore, service maybe not available started = false; } finally { if (response != null) { IOUtils.closeQuietly(response.body()); } } if (!started) { try { Thread.sleep(500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } try { Thread.sleep(5000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return started; }
From source file:io.kodokojo.bdd.stage.BrickStateNotificationGiven.java
License:Open Source License
public SELF kodokojo_is_started(@Hidden DockerTestSupport dockerTestSupport) { if (this.dockerTestSupport != null) { this.dockerTestSupport.stopAndRemoveContainer(); }/*from w w w . j a va 2s. c o m*/ this.dockerTestSupport = dockerTestSupport; LOGGER.info("Pulling docker image redis:latest"); this.dockerTestSupport.pullImage("redis:latest"); Service service = StageUtils.startDockerRedis(this.dockerTestSupport); brickManager = mock(BrickManager.class); bootstrapProvider = mock(BootstrapConfigurationProvider.class); dnsManager = mock(DnsManager.class); configurationStore = mock(ConfigurationStore.class); Mockito.when(bootstrapProvider.provideLoadBalancerHost(anyString(), anyString())) .thenReturn("192.168.22.3"); Mockito.when(bootstrapProvider.provideSshPortEntrypoint(anyString(), anyString())).thenReturn(10022); SecretKey tmpKey = null; try { KeyGenerator kg = KeyGenerator.getInstance("AES"); tmpKey = kg.generateKey(); } catch (NoSuchAlgorithmException e) { fail(e.getMessage()); } final SecretKey secreteKey = tmpKey; int port = TestUtils.getEphemeralPort(); RedisUserStore redisUserManager = new RedisUserStore(secreteKey, service.getHost(), service.getPort()); RedisProjectStore redisProjectStore = new RedisProjectStore(secreteKey, service.getHost(), service.getPort(), new DefaultBrickFactory()); RedisEntityStore redisEntityStore = new RedisEntityStore(secreteKey, service.getHost(), service.getPort()); KeyPair keyPair = null; try { keyPair = RSAUtils.generateRsaKeyPair(); } catch (NoSuchAlgorithmException e) { fail(e.getMessage()); } SSLKeyPair caKey = SSLUtils.createSelfSignedSSLKeyPair("Fake CA", (RSAPrivateKey) keyPair.getPrivate(), (RSAPublicKey) keyPair.getPublic()); Injector injector = Guice.createInjector(new EmailSenderModule(), new UserEndpointModule(), new ProjectEndpointModule(), new ActorModule(), new AbstractModule() { @Override protected void configure() { bind(UserStore.class).toInstance(redisUserManager); bind(ProjectStore.class).toInstance(redisProjectStore); bind(EntityStore.class).toInstance(redisEntityStore); bind(BrickStateMsgDispatcher.class).toInstance(new BrickStateMsgDispatcher()); bind(BrickManager.class).toInstance(brickManager); bind(DnsManager.class).toInstance(dnsManager); bind(ConfigurationStore.class).toInstance(configurationStore); bind(BrickFactory.class).toInstance(new DefaultBrickFactory()); bind(Key.get(new TypeLiteral<UserAuthenticator<SimpleCredential>>() { })).toInstance(new SimpleUserAuthenticator(redisUserManager)); DefaultBrickUrlFactory brickUrlFactory = new DefaultBrickUrlFactory("kodokojo.dev"); bind(BrickConfigurerProvider.class) .toInstance(new DefaultBrickConfigurerProvider(brickUrlFactory)); bind(ApplicationConfig.class).toInstance(new ApplicationConfig() { @Override public int port() { return port; } @Override public String domain() { return "kodokojo.dev"; } @Override public String loadbalancerHost() { return "192.168.22.3"; } @Override public int initialSshPort() { return 10022; } @Override public long sslCaDuration() { return -1; } }); bind(EmailConfig.class).toInstance(new EmailConfig() { @Override public String smtpHost() { return null; } @Override public int smtpPort() { return 0; } @Override public String smtpUsername() { return null; } @Override public String smtpPassword() { return null; } @Override public String smtpFrom() { return null; } }); bind(SSLCertificatProvider.class).toInstance(new WildcardSSLCertificatProvider(caKey)); bind(BrickUrlFactory.class).toInstance(brickUrlFactory); } @Provides @Singleton ProjectManager provideProjectManager(BrickConfigurationStarter brickConfigurationStarter, BrickConfigurerProvider brickConfigurerProvider, BrickUrlFactory brickUrlFactory) { return new DefaultProjectManager("kodokojo.dev", configurationStore, redisProjectStore, bootstrapProvider, dnsManager, brickConfigurerProvider, brickConfigurationStarter, brickUrlFactory); } }); // DefaultProjectManager projectManager = new DefaultProjectManager(caKey, "kodokojo.dev", configurationStore, redisProjectStore, bootstrapProvider, dnsManager, injector.getInstance(BrickConfigurerProvider.class), injector.getInstance(BrickConfigurationStarter.class), new DefaultBrickUrlFactory("kodokojo.dev"), 10000000); Launcher.INJECTOR = injector; entryPointUrl = "localhost:" + port; Set<SparkEndpoint> sparkEndpoints = Launcher.INJECTOR .getInstance(Key.get(new TypeLiteral<Set<SparkEndpoint>>() { })); httpEndpoint = new HttpEndpoint(port, new SimpleUserAuthenticator(redisUserManager), sparkEndpoints); httpUserSupport = new HttpUserSupport(new OkHttpClient(), entryPointUrl); httpEndpoint.start(); return self(); }
From source file:io.kodokojo.bdd.stage.cluster.ClusterApplicationGiven.java
License:Open Source License
private void killApp(String appId) { OkHttpClient httpClient = new OkHttpClient(); Request request = new Request.Builder().delete().url(marathonUrl + "/v2/apps/" + appId).build(); try {//from w w w. jav a 2 s . c om Response response = httpClient.newCall(request).execute(); assertThat(response.code()).isEqualTo(200); } catch (IOException e) { LOGGER.error("Unable to kill app {}.", appId, e); } }
From source file:io.kodokojo.bdd.stage.cluster.ClusterApplicationGiven.java
License:Open Source License
private void startKodokojo() { String keystorePath = System.getProperty("javax.net.ssl.keyStore", null); if (StringUtils.isBlank(keystorePath)) { String keystorePathDefined = new File("").getAbsolutePath() + "/src/test/resources/keystore/mykeystore.jks"; System.out.println(keystorePathDefined); System.setProperty("javax.net.ssl.keyStore", keystorePathDefined); }/*from ww w. j av a2s . com*/ BrickUrlFactory brickUrlFactory = new MarathonBrickUrlFactory(marathonUrl); System.setProperty("javax.net.ssl.keyStorePassword", "password"); System.setProperty("security.ssl.rootCa.ks.alias", "rootcafake"); System.setProperty("security.ssl.rootCa.ks.password", "password"); System.setProperty("application.dns.domain", "kodokojo.io"); System.setProperty("redis.host", redisService.getHost()); System.setProperty("redis.port", "" + redisService.getPort()); System.setProperty("marathon.url", "http://" + dockerTestSupport.getServerIp() + ":8080"); System.setProperty("lb.defaultIp", dockerTestSupport.getServerIp()); System.setProperty("application.dns.domain", "kodokojo.dev"); LOGGER.debug("redis.port: {}", System.getProperty("redis.port")); injector = Guice.createInjector(new PropertyModule(new String[] {}), new RedisModule(), new SecurityModule(), new ServiceModule(), new ActorModule(), new AwsModule(), new EmailSenderModule(), new UserEndpointModule(), new ProjectEndpointModule(), new AbstractModule() { @Override protected void configure() { } @Provides @Singleton ServiceLocator provideServiceLocator(MarathonConfig marathonConfig) { return new MarathonServiceLocator(marathonConfig.url()); } @Provides @Singleton ConfigurationStore provideConfigurationStore(MarathonConfig marathonConfig) { return new MarathonConfigurationStore(marathonConfig.url()); } @Provides @Singleton BrickManager provideBrickManager(MarathonConfig marathonConfig, BrickConfigurerProvider brickConfigurerProvider, ProjectStore projectStore, ApplicationConfig applicationConfig, BrickUrlFactory brickUrlFactory) { MarathonServiceLocator marathonServiceLocator = new MarathonServiceLocator( marathonConfig.url()); return new MarathonBrickManager(marathonConfig.url(), marathonServiceLocator, brickConfigurerProvider, projectStore, false, applicationConfig.domain(), brickUrlFactory); } }); Launcher.INJECTOR = injector; userStore = injector.getInstance(UserStore.class); projectStore = injector.getInstance(ProjectStore.class); entityStore = injector.getInstance(EntityStore.class); //BrickFactory brickFactory = injector.getInstance(BrickFactory.class); restEntryPointHost = "localhost"; restEntryPointPort = TestUtils.getEphemeralPort(); projectManager = new DefaultProjectManager(domain, injector.getInstance(ConfigurationStore.class), projectStore, injector.getInstance(BootstrapConfigurationProvider.class), new NoOpDnsManager(), new DefaultBrickConfigurerProvider(brickUrlFactory), injector.getInstance(BrickConfigurationStarter.class), brickUrlFactory); httpUserSupport = new HttpUserSupport(new OkHttpClient(), restEntryPointHost + ":" + restEntryPointPort); Set<SparkEndpoint> sparkEndpoints = new HashSet<>( injector.getInstance(Key.get(new TypeLiteral<Set<SparkEndpoint>>() { }))); Key<UserAuthenticator<SimpleCredential>> authenticatorKey = Key .get(new TypeLiteral<UserAuthenticator<SimpleCredential>>() { }); UserAuthenticator<SimpleCredential> userAuthenticator = injector.getInstance(authenticatorKey); sparkEndpoints.add(new ProjectSparkEndpoint(userAuthenticator, userStore, projectStore, projectManager, injector.getInstance(BrickFactory.class))); httpEndpoint = new HttpEndpoint(restEntryPointPort, new SimpleUserAuthenticator(userStore), sparkEndpoints); Semaphore semaphore = new Semaphore(1); try { semaphore.acquire(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } Thread t = new Thread(() -> { httpEndpoint.start(); semaphore.release(); }); t.start(); try { semaphore.acquire(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
From source file:io.kodokojo.bdd.stage.cluster.ClusterApplicationGiven.java
License:Open Source License
private void killAllAppInMarathon(String marathonUrl) { OkHttpClient httpClient = new OkHttpClient(); Request.Builder builder = new Request.Builder().url(marathonUrl + "/v2/apps").get(); Response response = null;/*from ww w . ja v a2s . co m*/ Set<String> appIds = new HashSet<>(); try { response = httpClient.newCall(builder.build()).execute(); String body = response.body().string(); JsonParser parser = new JsonParser(); JsonObject json = (JsonObject) parser.parse(body); JsonArray apps = json.getAsJsonArray("apps"); for (JsonElement appEl : apps) { JsonObject app = (JsonObject) appEl; appIds.add(app.getAsJsonPrimitive("id").getAsString()); } } catch (IOException e) { fail(e.getMessage()); } finally { if (response != null) { IOUtils.closeQuietly(response.body()); } } appIds.stream().forEach(id -> { Request.Builder rmBuilder = new Request.Builder().url(marathonUrl + "/v2/apps/" + id).delete(); Response responseRm = null; try { LOGGER.debug("Delete Marathon application id {}.", id); responseRm = httpClient.newCall(rmBuilder.build()).execute(); } catch (IOException e) { fail(e.getMessage()); } finally { if (responseRm != null) { IOUtils.closeQuietly(responseRm.body()); } } }); }
From source file:io.kodokojo.bdd.stage.cluster.ClusterApplicationThen.java
License:Open Source License
private OkHttpClient provideDefaultOkHttpClient() { OkHttpClient httpClient = new OkHttpClient(); final TrustManager[] certs = new TrustManager[] { new X509TrustManager() { @Override/*from w w w . j a v a 2 s . c om*/ public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkServerTrusted(final X509Certificate[] chain, final String authType) throws CertificateException { } @Override public void checkClientTrusted(final X509Certificate[] chain, final String authType) throws CertificateException { } } }; SSLContext ctx = null; try { ctx = SSLContext.getInstance("TLS"); ctx.init(null, certs, new SecureRandom()); } catch (final java.security.GeneralSecurityException ex) { } httpClient.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }); httpClient.setSslSocketFactory(ctx.getSocketFactory()); return httpClient; }
From source file:io.kodokojo.bdd.stage.cluster.ClusterApplicationWhen.java
License:Open Source License
public SELF i_start_the_project() { OkHttpClient httpClient = new OkHttpClient(); String url = "http://" + restEntryPointHost + ":" + restEntryPointPort + "/api/v1/project/" + projectConfiguration.getIdentifier(); RequestBody body = RequestBody.create(null, new byte[0]); Request.Builder builder = new Request.Builder().url(url).post(body); builder = HttpUserSupport.addBasicAuthentification(currentUser, builder); Response response = null;/* w w w. j a va2 s . co m*/ try { response = httpClient.newCall(builder.build()).execute(); assertThat(response.code()).isEqualTo(201); LOGGER.trace("Starting project"); Map<String, Boolean> brickRunning = new HashMap<>(); projectConfiguration.getDefaultBrickConfigurations().forEachRemaining(b -> { brickRunning.put(b.getName(), Boolean.FALSE); }); JsonParser parser = new JsonParser(); boolean allBrickStarted = true; long now = System.currentTimeMillis(); long end = now + 180000; do { Iterator<String> messageReceive = webSocketEventsListener.getMessages().iterator(); while (messageReceive.hasNext()) { String message = messageReceive.next(); JsonObject root = (JsonObject) parser.parse(message); if ("updateState".equals(root.getAsJsonPrimitive("action").getAsString())) { JsonObject data = root.getAsJsonObject("data"); String brickName = data.getAsJsonPrimitive("brickName").getAsString(); String brickState = data.getAsJsonPrimitive("state").getAsString(); if ("RUNNING".equals(brickState)) { brickRunning.put(brickName, Boolean.TRUE); } } } Iterator<Boolean> iterator = brickRunning.values().iterator(); allBrickStarted = true; while (allBrickStarted && iterator.hasNext()) { allBrickStarted = iterator.next(); } if (!allBrickStarted) { try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } now = System.currentTimeMillis(); } while (!allBrickStarted && now < end); assertThat(allBrickStarted).isTrue(); } catch (IOException e) { fail(e.getMessage()); } finally { if (response != null) { IOUtils.closeQuietly(response.body()); } } return self(); }
From source file:io.kodokojo.bdd.stage.HttpUserSupport.java
License:Open Source License
public HttpUserSupport(String endpoint) { this(new OkHttpClient(), endpoint); }