Example usage for com.squareup.okhttp Request.Builder Request.Builder

List of usage examples for com.squareup.okhttp Request.Builder Request.Builder

Introduction

In this page you can find the example usage for com.squareup.okhttp Request.Builder Request.Builder.

Prototype

Request.Builder

Source Link

Usage

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) {/* ww  w  .  j av a 2 s .  c om*/

    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) {/*w  w  w .j a v a  2s. co 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();//from ww  w. j  a  v a  2 s  . c o 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 {/*from   w  w  w.  j a  va 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();/*  w  w  w  . ja  va  2s.  co  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:co.paralleluniverse.fibers.okhttp.test.InterceptorTest.java

License:Apache License

@Test
public void applicationInterceptorsCanShortCircuitResponses() throws Exception {
    server.shutdown(); // Accept no connections.

    Request request = new Request.Builder().url("https://localhost:1/").build();

    final Response interceptorResponse = new Response.Builder().request(request).protocol(Protocol.HTTP_1_1)
            .code(200).message("Intercepted!")
            .body(ResponseBody.create(MediaType.parse("text/plain; charset=utf-8"), "abc")).build();

    client.interceptors().add(new Interceptor() {
        @Override//w w  w  . jav  a 2s  .co m
        public Response intercept(Chain chain) throws IOException {
            return interceptorResponse;
        }
    });

    Response response = client.newCall(request).execute();
    assertSame(interceptorResponse, response);
}

From source file:co.paralleluniverse.fibers.okhttp.test.InterceptorTest.java

License:Apache License

@Ignore
@Test//ww w.j  av  a2s .  c om
public void networkInterceptorsCannotShortCircuitResponses() throws Exception {
    server.enqueue(new MockResponse().setResponseCode(500));

    Interceptor interceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            return new Response.Builder().request(chain.request()).protocol(Protocol.HTTP_1_1).code(200)
                    .message("Intercepted!")
                    .body(ResponseBody.create(MediaType.parse("text/plain; charset=utf-8"), "abc")).build();
        }
    };
    client.networkInterceptors().add(interceptor);

    Request request = new Request.Builder().url(server.url("/")).build();

    try {
        client.newCall(request).execute();
        fail();
    } catch (IllegalStateException expected) {
        assertEquals("network interceptor " + interceptor + " must call proceed() exactly once",
                expected.getMessage());
    }
}

From source file:co.paralleluniverse.fibers.okhttp.test.InterceptorTest.java

License:Apache License

@Ignore
@Test/* w w w. j  a  v a2 s.com*/
public void networkInterceptorsCannotCallProceedMultipleTimes() throws Exception {
    server.enqueue(new MockResponse());
    server.enqueue(new MockResponse());

    Interceptor interceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            chain.proceed(chain.request());
            return chain.proceed(chain.request());
        }
    };
    client.networkInterceptors().add(interceptor);

    Request request = new Request.Builder().url(server.url("/")).build();

    try {
        client.newCall(request).execute();
        fail();
    } catch (IllegalStateException expected) {
        assertEquals("network interceptor " + interceptor + " must call proceed() exactly once",
                expected.getMessage());
    }
}

From source file:co.paralleluniverse.fibers.okhttp.test.InterceptorTest.java

License:Apache License

@Ignore
@Test/*  w  w  w . j a va 2  s  . c om*/
public void networkInterceptorsCannotChangeServerAddress() throws Exception {
    server.enqueue(new MockResponse().setResponseCode(500));

    Interceptor interceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Address address = chain.connection().getRoute().getAddress();
            String sameHost = address.getUriHost();
            int differentPort = address.getUriPort() + 1;
            return chain.proceed(chain.request().newBuilder()
                    .url(HttpUrl.parse("http://" + sameHost + ":" + differentPort + "/")).build());
        }
    };
    client.networkInterceptors().add(interceptor);

    Request request = new Request.Builder().url(server.url("/")).build();

    try {
        client.newCall(request).execute();
        fail();
    } catch (IllegalStateException expected) {
        assertEquals("network interceptor " + interceptor + " must retain the same host and port",
                expected.getMessage());
    }
}

From source file:co.paralleluniverse.fibers.okhttp.test.InterceptorTest.java

License:Apache License

@Test
public void networkInterceptorsHaveConnectionAccess() throws Exception {
    server.enqueue(new MockResponse());

    client.networkInterceptors().add(new Interceptor() {
        @Override//from  w w  w . j  a va  2s  .c o  m
        public Response intercept(Chain chain) throws IOException {
            Connection connection = chain.connection();
            assertNotNull(connection);
            return chain.proceed(chain.request());
        }
    });

    Request request = new Request.Builder().url(server.url("/")).build();
    client.newCall(request).execute();
}