List of usage examples for com.squareup.okhttp Credentials basic
public static String basic(String userName, String password)
From source file:com.xebialabs.xlt.ci.server.XLTestServerImpl.java
License:Open Source License
private String createCredentials() { return Credentials.basic(credentials.getUsername(), credentials.getPassword()); }
From source file:es.bsc.vmmclient.rest.VmmRestClient.java
License:Open Source License
public VmmRestClient(String url, long timeout, final String username, final String password) { if (url.startsWith("https://")) { // TODO: add the option to accept only Trusted HTTPS connections okHttpClient = getUnsafeOkHttpClient(); } else {/*from ww w . j a v a 2 s . co m*/ okHttpClient = new OkHttpClient(); } // Define our own okHttpClient to increase the timeout okHttpClient.setReadTimeout(timeout, TimeUnit.SECONDS); if (username != null && password != null) { okHttpClient.setAuthenticator(new Authenticator() { @Override public Request authenticate(Proxy proxy, Response response) throws IOException { String credential = Credentials.basic(username, password); return response.request().newBuilder().header("Authorization", credential).build(); } @Override public Request authenticateProxy(Proxy proxy, Response response) throws IOException { return null; } }); } RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(url).setClient(new OkClient(okHttpClient)) .build(); service = restAdapter.create(VmmService.class); }
From source file:info.curtbinder.reefangel.service.ControllerTask.java
License:Creative Commons License
public void run() { // Communicate with controller // clear out the error code on run rapp.clearErrorCode();/* ww w . j a va 2 s . c om*/ Response response = null; boolean fInterrupted = false; broadcastUpdateStatus(R.string.statusStart); try { URL url = new URL(host.toString()); OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(host.getConnectTimeout(), TimeUnit.MILLISECONDS); client.setReadTimeout(host.getReadTimeout(), TimeUnit.MILLISECONDS); Request.Builder builder = new Request.Builder(); builder.url(url); if (host.isDeviceAuthenticationEnabled()) { String creds = Credentials.basic(host.getWifiUsername(), host.getWifiPassword()); builder.header("Authorization", creds); } Request req = builder.build(); broadcastUpdateStatus(R.string.statusConnect); response = client.newCall(req).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); if (Thread.interrupted()) throw new InterruptedException(); } catch (MalformedURLException e) { rapp.error(1, e, "MalformedURLException"); } catch (SocketTimeoutException e) { rapp.error(5, e, "SocketTimeoutException"); } catch (ConnectException e) { rapp.error(3, e, "ConnectException"); } catch (UnknownHostException e) { String msg = "Unknown Host: " + host.toString(); UnknownHostException ue = new UnknownHostException(msg); rapp.error(4, ue, "UnknownHostException"); } catch (EOFException e) { EOFException eof = new EOFException(rapp.getString(R.string.errorAuthentication)); rapp.error(3, eof, "EOFException"); } catch (IOException e) { rapp.error(3, e, "IOException"); } catch (InterruptedException e) { fInterrupted = true; } processResponse(response, fInterrupted); }
From source file:io.fabric8.devops.connector.DevOpsConnector.java
License:Apache License
protected void createGerritRepo(String repoName, String gerritUser, String gerritPwd, String gerritGitInitialCommit, String gerritGitRepoDescription) throws Exception { // lets add defaults if not env vars final String username = Strings.isNullOrBlank(gerritUser) ? "admin" : gerritUser; final String password = Strings.isNullOrBlank(gerritPwd) ? "secret" : gerritPwd; log.info("A Gerrit git repo will be created for this name : " + repoName); String gerritAddress = KubernetesHelper.getServiceURL(kubernetes, ServiceNames.GERRIT, namespace, "http", true);/*w w w . j a v a 2 s .c o m*/ log.info("Found gerrit address: " + gerritAddress + " for namespace: " + namespace + " on Kubernetes address: " + kubernetes.getMasterUrl()); if (Strings.isNullOrBlank(gerritAddress)) { throw new Exception("No address for service " + ServiceNames.GERRIT + " in namespace: " + namespace + " on Kubernetes address: " + kubernetes.getMasterUrl()); } String GERRIT_URL = gerritAddress + "/a/projects/" + repoName; OkHttpClient client = new OkHttpClient(); if (isNotNullOrEmpty(gerritUser) && isNotNullOrEmpty(gerritPwd)) { client.setAuthenticator(new Authenticator() { @Override public Request authenticate(Proxy proxy, Response response) throws IOException { List<Challenge> challenges = response.challenges(); Request request = response.request(); for (int i = 0, size = challenges.size(); i < size; i++) { Challenge challenge = challenges.get(i); if (!"Basic".equalsIgnoreCase(challenge.getScheme())) continue; String credential = Credentials.basic(username, password); return request.newBuilder().header("Authorization", credential).build(); } return null; } @Override public Request authenticateProxy(Proxy proxy, Response response) throws IOException { return null; } }); } System.out.println("Requesting : " + GERRIT_URL); try { CreateRepositoryDTO createRepoDTO = new CreateRepositoryDTO(); createRepoDTO.setDescription(gerritGitRepoDescription); createRepoDTO.setName(repoName); createRepoDTO.setCreate_empty_commit(Boolean.valueOf(gerritGitInitialCommit)); RequestBody body = RequestBody.create(JSON, MAPPER.writeValueAsString(createRepoDTO)); Request request = new Request.Builder().post(body).url(GERRIT_URL).build(); Response response = client.newCall(request).execute(); System.out.println("responseBody : " + response.body().string()); } catch (Throwable t) { throw new RuntimeException(t); } finally { if (client != null && client.getConnectionPool() != null) { client.getConnectionPool().evictAll(); } } }
From source file:io.fabric8.docker.client.utils.HttpClientUtils.java
License:Apache License
public static OkHttpClient createHttpClient(final Config config) { try {//from w ww .j av a2 s. c om OkHttpClient httpClient = new OkHttpClient(); httpClient.setConnectionPool(ConnectionPool.getDefault()); // Follow any redirects httpClient.setFollowRedirects(true); httpClient.setFollowSslRedirects(true); if (config.isTrustCerts()) { httpClient.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }); } if (usesUnixSocket(config)) { URL masterURL = new URL(config.getDockerUrl().replaceFirst(UNIX_SCHEME, FILE_SCHEME)); httpClient.setSocketFactory(new UnixSocketFactory(masterURL.getFile())); config.setDockerUrl(UNIX_FAKE_URL); } TrustManager[] trustManagers = SSLUtils.trustManagers(config); KeyManager[] keyManagers = SSLUtils.keyManagers(config); if (keyManagers != null || trustManagers != null || config.isTrustCerts()) { try { SSLContext sslContext = SSLUtils.sslContext(keyManagers, trustManagers, config.isTrustCerts()); httpClient.setSslSocketFactory(sslContext.getSocketFactory()); } catch (GeneralSecurityException e) { throw new AssertionError(); // The system has no TLS. Just give up. } } if (isNotNullOrEmpty(config.getUsername()) && isNotNullOrEmpty(config.getPassword())) { httpClient.setAuthenticator(new Authenticator() { @Override public Request authenticate(Proxy proxy, Response response) throws IOException { List<Challenge> challenges = response.challenges(); Request request = response.request(); HttpUrl url = request.httpUrl(); for (int i = 0, size = challenges.size(); i < size; i++) { Challenge challenge = challenges.get(i); if (!"Basic".equalsIgnoreCase(challenge.getScheme())) continue; String credential = Credentials.basic(config.getUsername(), config.getPassword()); return request.newBuilder().header("Authorization", credential).build(); } return null; } @Override public Request authenticateProxy(Proxy proxy, Response response) throws IOException { return null; } }); } else if (config.getOauthToken() != null) { httpClient.interceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request authReq = chain.request().newBuilder() .addHeader("Authorization", "Bearer " + config.getOauthToken()).build(); return chain.proceed(authReq); } }); } Logger reqLogger = LoggerFactory.getLogger(HttpLoggingInterceptor.class); if (reqLogger.isTraceEnabled()) { HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); httpClient.networkInterceptors().add(loggingInterceptor); } if (config.getConnectionTimeout() > 0) { httpClient.setConnectTimeout(config.getConnectionTimeout(), TimeUnit.MILLISECONDS); } if (config.getRequestTimeout() > 0) { httpClient.setReadTimeout(config.getRequestTimeout(), TimeUnit.MILLISECONDS); } // Only check proxy if it's a full URL with protocol if (config.getDockerUrl().toLowerCase().startsWith(Config.HTTP_PROTOCOL_PREFIX) || config.getDockerUrl().startsWith(Config.HTTPS_PROTOCOL_PREFIX)) { try { URL proxyUrl = getProxyUrl(config); if (proxyUrl != null) { httpClient.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyUrl.getHost(), proxyUrl.getPort()))); } } catch (MalformedURLException e) { throw new DockerClientException("Invalid proxy server configuration", e); } } return httpClient; } catch (Exception e) { throw DockerClientException.launderThrowable(e); } }
From source file:io.fabric8.kubernetes.client.utils.HttpClientUtils.java
License:Apache License
public static OkHttpClient createHttpClient(final Config config) { try {/*from www . java 2 s. com*/ OkHttpClient httpClient = new OkHttpClient(); // Follow any redirects httpClient.setFollowRedirects(true); httpClient.setFollowSslRedirects(true); if (config.isTrustCerts()) { httpClient.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }); } TrustManager[] trustManagers = SSLUtils.trustManagers(config); KeyManager[] keyManagers = SSLUtils.keyManagers(config); if (keyManagers != null || trustManagers != null || config.isTrustCerts()) { try { SSLContext sslContext = SSLUtils.sslContext(keyManagers, trustManagers, config.isTrustCerts()); httpClient.setSslSocketFactory(sslContext.getSocketFactory()); } catch (GeneralSecurityException e) { throw new AssertionError(); // The system has no TLS. Just give up. } } if (isNotNullOrEmpty(config.getUsername()) && isNotNullOrEmpty(config.getPassword())) { httpClient.setAuthenticator(new Authenticator() { @Override public Request authenticate(Proxy proxy, Response response) throws IOException { List<Challenge> challenges = response.challenges(); Request request = response.request(); HttpUrl url = request.httpUrl(); for (int i = 0, size = challenges.size(); i < size; i++) { Challenge challenge = challenges.get(i); if (!"Basic".equalsIgnoreCase(challenge.getScheme())) continue; String credential = Credentials.basic(config.getUsername(), config.getPassword()); return request.newBuilder().header("Authorization", credential).build(); } return null; } @Override public Request authenticateProxy(Proxy proxy, Response response) throws IOException { return null; } }); } else if (config.getOauthToken() != null) { httpClient.interceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request authReq = chain.request().newBuilder() .addHeader("Authorization", "Bearer " + config.getOauthToken()).build(); return chain.proceed(authReq); } }); } Logger reqLogger = LoggerFactory.getLogger(HttpLoggingInterceptor.class); if (reqLogger.isTraceEnabled()) { HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); httpClient.networkInterceptors().add(loggingInterceptor); } if (config.getConnectionTimeout() > 0) { httpClient.setConnectTimeout(config.getConnectionTimeout(), TimeUnit.MILLISECONDS); } if (config.getRequestTimeout() > 0) { httpClient.setReadTimeout(config.getRequestTimeout(), TimeUnit.MILLISECONDS); } // Only check proxy if it's a full URL with protocol if (config.getMasterUrl().toLowerCase().startsWith(Config.HTTP_PROTOCOL_PREFIX) || config.getMasterUrl().startsWith(Config.HTTPS_PROTOCOL_PREFIX)) { try { URL proxyUrl = getProxyUrl(config); if (proxyUrl != null) { httpClient.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyUrl.getHost(), proxyUrl.getPort()))); } } catch (MalformedURLException e) { throw new KubernetesClientException("Invalid proxy server configuration", e); } } if (config.getUserAgent() != null && !config.getUserAgent().isEmpty()) { httpClient.networkInterceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request agent = chain.request().newBuilder().header("User-Agent", config.getUserAgent()) .build(); return chain.proceed(agent); } }); } return httpClient; } catch (Exception e) { throw KubernetesClientException.launderThrowable(e); } }
From source file:io.fabric8.openshift.client.internal.OpenShiftOAuthInterceptor.java
License:Apache License
private String authorize() { try {//from w w w. j a va 2s . co m OkHttpClient clone = client.clone(); clone.interceptors().remove(this); String credential = Credentials.basic(config.getUsername(), new String(config.getPassword())); URL url = new URL(URLUtils.join(config.getMasterUrl(), AUTHORIZE_PATH)); Response response = clone .newCall(new Request.Builder().get().url(url).header(AUTHORIZATION, credential).build()) .execute(); response.body().close(); String token = response.priorResponse().networkResponse().header(LOCATION); token = token.substring(token.indexOf(BEFORE_TOKEN) + BEFORE_TOKEN.length()); token = token.substring(0, token.indexOf(AFTER_TOKEN)); return token; } catch (Exception e) { throw KubernetesClientException.launderThrowable(e); } }
From source file:io.macgyver.neorx.rest.NeoRxClient.java
License:Apache License
protected ObjectNode execRawCypher(String cypher, ObjectNode params) { try {//from w ww . j a v a 2s .co m ObjectNode payload = formatPayload(cypher, params); String payloadString = payload.toString(); OkHttpClient c = getClient(); checkNotNull(c); String requestId = newRequestId(); if (logger.isDebugEnabled()) { logger.debug(String.format("request[%s]: %s", requestId, payloadString)); } Builder builder = injectCredentials(new Request.Builder()) .addHeader("X-Stream", Boolean.toString(streamResponse)).addHeader("Accept", "application/json") .url(getUrl() + "/db/data/transaction/commit") .post(RequestBody.create(MediaType.parse("application/json"), payloadString)); if (!GuavaStrings.isNullOrEmpty(username) && !GuavaStrings.isNullOrEmpty(password)) { builder = builder.addHeader("Authorization", Credentials.basic(username, password)); } com.squareup.okhttp.Response r = c.newCall(builder.build()).execute(); ObjectNode jsonResponse = (ObjectNode) mapper.readTree(r.body().charStream()); if (logger.isDebugEnabled()) { logger.debug(String.format("response[%s]: %s", requestId, jsonResponse.toString())); } ObjectNode n = jsonResponse; JsonNode error = n.path("errors").path(0); if (error instanceof ObjectNode) { throw new NeoRxException(((ObjectNode) error)); } return n; } catch (IOException e) { throw new NeoRxException(e); } }
From source file:io.macgyver.neorx.rest.NeoRxClient.java
License:Apache License
protected Request.Builder injectCredentials(Request.Builder builder) { if (!GuavaStrings.isNullOrEmpty(username) && !GuavaStrings.isNullOrEmpty(password)) { return builder.addHeader("Authorization", Credentials.basic(username, password)); } else {//w w w . ja v a 2s . c om return builder; } }
From source file:io.macgyver.test.MockWebServerTest.java
License:Apache License
@Test public void testIt() throws IOException, InterruptedException { // set up mock response mockServer.enqueue(/*from w w w .j av a 2 s .c o m*/ new MockResponse().setBody("{\"name\":\"Rob\"}").addHeader("Content-type", "application/json")); // set up client and request OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(mockServer.getUrl("/test").toString()) .post(RequestBody.create(MediaType.parse("application/json"), "{}")) .header("Authorization", Credentials.basic("scott", "tiger")).build(); // make the call Response response = client.newCall(request).execute(); // check the response assertThat(response.code()).isEqualTo(200); assertThat(response.header("content-type")).isEqualTo("application/json"); // check the response body JsonNode n = new ObjectMapper().readTree(response.body().string()); assertThat(n.path("name").asText()).isEqualTo("Rob"); // now make sure that the request was as we exepected it to be RecordedRequest recordedRequest = mockServer.takeRequest(); assertThat(recordedRequest.getPath()).isEqualTo("/test"); assertThat(recordedRequest.getHeader("Authorization")).isEqualTo("Basic c2NvdHQ6dGlnZXI="); }