List of usage examples for com.squareup.okhttp Credentials basic
public static String basic(String userName, String password)
From source file:abtlibrary.utils.as24ApiClient.auth.HttpBasicAuth.java
License:Apache License
@Override public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) { if (username == null && password == null) { return;//from w w w . j av a 2 s.c om } headerParams.put("Authorization", Credentials.basic(username == null ? "" : username, password == null ? "" : password)); }
From source file:alfio.manager.system.MailgunMailer.java
License:Open Source License
@Override public void send(Event event, String to, String subject, String text, Optional<String> html, Attachment... attachment) {/*from w w w .ja va 2s . c o m*/ String apiKey = configurationManager .getRequiredValue(Configuration.from(event.getOrganizationId(), event.getId(), MAILGUN_KEY)); String domain = configurationManager .getRequiredValue(Configuration.from(event.getOrganizationId(), event.getId(), MAILGUN_DOMAIN)); try { RequestBody formBody = prepareBody(event, to, subject, text, html, attachment); Request request = new Request.Builder().url("https://api.mailgun.net/v2/" + domain + "/messages") .header("Authorization", Credentials.basic("api", apiKey)).post(formBody).build(); Response resp = client.newCall(request).execute(); if (!resp.isSuccessful()) { log.warn("sending email was not successful:" + resp); } } catch (IOException e) { log.warn("error while sending email", e); } }
From source file:alfio.manager.system.MailjetMailer.java
License:Open Source License
@Override public void send(Event event, String to, String subject, String text, Optional<String> html, Attachment... attachment) {/*from w w w .j a v a 2 s. c o m*/ String apiKeyPublic = configurationManager.getRequiredValue(Configuration.from(event.getOrganizationId(), event.getId(), ConfigurationKeys.MAILJET_APIKEY_PUBLIC)); String apiKeyPrivate = configurationManager.getRequiredValue(Configuration.from(event.getOrganizationId(), event.getId(), ConfigurationKeys.MAILJET_APIKEY_PRIVATE)); String fromEmail = configurationManager.getRequiredValue( Configuration.from(event.getOrganizationId(), event.getId(), ConfigurationKeys.MAILJET_FROM)); //https://dev.mailjet.com/guides/?shell#sending-with-attached-files Map<String, Object> mailPayload = new HashMap<>(); mailPayload.put("FromEmail", fromEmail); mailPayload.put("FromName", event.getDisplayName()); mailPayload.put("Subject", subject); mailPayload.put("Text-part", text); html.ifPresent(h -> mailPayload.put("Html-part", h)); mailPayload.put("Recipients", Collections.singletonList(Collections.singletonMap("Email", to))); String replyTo = configurationManager.getStringConfigValue( Configuration.from(event.getOrganizationId(), event.getId(), ConfigurationKeys.MAIL_REPLY_TO), ""); if (StringUtils.isNotBlank(replyTo)) { mailPayload.put("Headers", Collections.singletonMap("Reply-To", replyTo)); } if (attachment != null && attachment.length > 0) { mailPayload.put("Attachments", Arrays.stream(attachment).map(MailjetMailer::fromAttachment).collect(Collectors.toList())); } try { RequestBody body = RequestBody.create(MediaType.parse("application/json"), Json.GSON.toJson(mailPayload)); Request request = new Request.Builder().url("https://api.mailjet.com/v3/send") .header("Authorization", Credentials.basic(apiKeyPublic, apiKeyPrivate)).post(body).build(); Response resp = client.newCall(request).execute(); if (!resp.isSuccessful()) { log.warn("sending email was not successful:" + resp); } } catch (IOException e) { log.warn("error while sending email", e); } }
From source file:alfio.plugin.mailchimp.MailChimpPlugin.java
License:Open Source License
private boolean send(int eventId, String address, String apiKey, String email, CustomerName name, String language, String eventKey) { Map<String, Object> content = new HashMap<>(); content.put("email_address", email); content.put("status", "subscribed"); Map<String, String> mergeFields = new HashMap<>(); mergeFields.put("FNAME", name.isHasFirstAndLastName() ? name.getFirstName() : name.getFullName()); mergeFields.put(ALFIO_EVENT_KEY, eventKey); content.put("merge_fields", mergeFields); content.put("language", language); Request request = new Request.Builder().url(address) .header("Authorization", Credentials.basic("alfio", apiKey)) .put(RequestBody.create(MediaType.parse(APPLICATION_JSON), Json.GSON.toJson(content, Map.class))) .build();/* w ww.j a va2 s .co m*/ try { Response response = httpClient.newCall(request).execute(); if (response.isSuccessful()) { pluginDataStorage.registerSuccess(String.format("user %s has been subscribed to list", email), eventId); return true; } String responseBody = response.body().string(); if (response.code() != 400 || responseBody.contains("\"errors\"")) { pluginDataStorage.registerFailure(String.format(FAILURE_MSG, email, name, language, responseBody), eventId); return false; } else { pluginDataStorage.registerWarning(String.format(FAILURE_MSG, email, name, language, responseBody), eventId); } return true; } catch (IOException e) { pluginDataStorage.registerFailure(String.format(FAILURE_MSG, email, name, language, e.toString()), eventId); return false; } }
From source file:alfio.plugin.mailchimp.MailChimpPlugin.java
License:Open Source License
private void createMergeFieldIfNotPresent(String listAddress, String apiKey, int eventId, String eventKey) { Request request = new Request.Builder().url(listAddress + MERGE_FIELDS) .header("Authorization", Credentials.basic("alfio", apiKey)).get().build(); try {// w ww . j a v a 2 s.c o m Response response = httpClient.newCall(request).execute(); String responseBody = response.body().string(); if (!responseBody.contains(ALFIO_EVENT_KEY)) { log.debug("can't find ALFIO_EKEY for event " + eventKey); createMergeField(listAddress, apiKey, eventKey, eventId); } } catch (IOException e) { pluginDataStorage.registerFailure( String.format("Cannot get merge fields for %s, got: %s", eventKey, e.getMessage()), eventId); log.warn("exception while reading merge fields for event id " + eventId, e); } }
From source file:alfio.plugin.mailchimp.MailChimpPlugin.java
License:Open Source License
private void createMergeField(String listAddress, String apiKey, String eventKey, int eventId) { Map<String, Object> mergeField = new HashMap<>(); mergeField.put("tag", ALFIO_EVENT_KEY); mergeField.put("name", "Alfio's event key"); mergeField.put("type", "text"); mergeField.put("required", false); mergeField.put("public", false); Request request = new Request.Builder().url(listAddress + MERGE_FIELDS) .header("Authorization", Credentials.basic("alfio", apiKey)).post(RequestBody .create(MediaType.parse(APPLICATION_JSON), Json.GSON.toJson(mergeField, Map.class))) .build();//from w ww . ja v a2 s . c o m try { Response response = httpClient.newCall(request).execute(); if (!response.isSuccessful()) { log.debug("can't create {} merge field. Got: {}", ALFIO_EVENT_KEY, response.body().string()); } } catch (IOException e) { pluginDataStorage.registerFailure( String.format("Cannot create merge field for %s, got: %s", eventKey, e.getMessage()), eventId); log.warn("exception while creating ALFIO_EKEY for event id " + eventId, e); } }
From source file:at.bitfire.dav4android.BasicDigestAuthenticator.java
License:Open Source License
@Override public Request authenticate(Proxy proxy, Response response) throws IOException { Request request = response.request(); if (host != null && !request.httpUrl().host().equalsIgnoreCase(host)) { Constants.log.warn("Not authenticating against " + host + " for security reasons!"); return null; }// w ww . ja va 2 s . c o m // check whether this is the first authentication try with our credentials Response priorResponse = response.priorResponse(); boolean triedBefore = priorResponse != null ? priorResponse.request().header(HEADER_AUTHORIZATION) != null : false; HttpUtils.AuthScheme basicAuth = null, digestAuth = null; for (HttpUtils.AuthScheme scheme : HttpUtils .parseWwwAuthenticate(response.headers(HEADER_AUTHENTICATE).toArray(new String[0]))) if ("Basic".equalsIgnoreCase(scheme.name)) basicAuth = scheme; else if ("Digest".equalsIgnoreCase(scheme.name)) digestAuth = scheme; // we MUST prefer Digest auth [https://tools.ietf.org/html/rfc2617#section-4.6] if (digestAuth != null) { // Digest auth if (triedBefore && !"true".equalsIgnoreCase(digestAuth.params.get("stale"))) // credentials didn't work last time, and they won't work now -> stop here return null; return authorizationRequest(request, digestAuth); } else if (basicAuth != null) { // Basic auth if (triedBefore) // credentials didn't work last time, and they won't work now -> stop here return null; return request.newBuilder().header(HEADER_AUTHORIZATION, Credentials.basic(username, password)).build(); } // no supported auth scheme return null; }
From source file:co.paralleluniverse.fibers.okhttp.CallTest.java
License:Open Source License
private void postBodyRetransmittedAfterAuthorizationFail(String body) throws Exception { server.enqueue(new MockResponse().setResponseCode(401)); server.enqueue(new MockResponse()); Request request = new Request.Builder().url(server.getUrl("/")) .method("POST", RequestBody.create(null, body)).build(); String credential = Credentials.basic("jesse", "secret"); client.setAuthenticator(new RecordingOkAuthenticator(credential)); Response response = FiberOkHttpTestUtil.executeInFiberRecorded(client, request).response; assertEquals(200, response.code());//from w w w . java 2s . c om RecordedRequest recordedRequest1 = server.takeRequest(); assertEquals("POST", recordedRequest1.getMethod()); assertEquals(body, recordedRequest1.getBody().readUtf8()); assertNull(recordedRequest1.getHeader("Authorization")); RecordedRequest recordedRequest2 = server.takeRequest(); assertEquals("POST", recordedRequest2.getMethod()); assertEquals(body, recordedRequest2.getBody().readUtf8()); assertEquals(credential, recordedRequest2.getHeader("Authorization")); }
From source file:co.paralleluniverse.fibers.okhttp.CallTest.java
License:Open Source License
@Test public void attemptAuthorization20Times() throws Exception { for (int i = 0; i < 20; i++) { server.enqueue(new MockResponse().setResponseCode(401)); }//from w w w .j a v a 2 s. co m server.enqueue(new MockResponse().setBody("Success!")); String credential = Credentials.basic("jesse", "secret"); client.setAuthenticator(new RecordingOkAuthenticator(credential)); Request request = new Request.Builder().url(server.getUrl("/")).build(); FiberOkHttpTestUtil.executeInFiberRecorded(client, request).assertCode(200).assertBody("Success!"); }
From source file:co.paralleluniverse.fibers.okhttp.CallTest.java
License:Open Source License
@Test public void doesNotAttemptAuthorization21Times() throws Exception { for (int i = 0; i < 21; i++) { server.enqueue(new MockResponse().setResponseCode(401)); }// w w w .j a v a2s . c om String credential = Credentials.basic("jesse", "secret"); client.setAuthenticator(new RecordingOkAuthenticator(credential)); try { FiberOkHttpUtil.executeInFiber(client, new Request.Builder().url(server.getUrl("/0")).build()); fail(); } catch (IOException expected) { assertEquals("Too many follow-up requests: 21", expected.getMessage()); } }