Example usage for com.squareup.okhttp Response isSuccessful

List of usage examples for com.squareup.okhttp Response isSuccessful

Introduction

In this page you can find the example usage for com.squareup.okhttp Response isSuccessful.

Prototype

public boolean isSuccessful() 

Source Link

Document

Returns true if the code is in [200..300), which means the request was successfully received, understood, and accepted.

Usage

From source file:FunctionalTest.java

License:Apache License

public static void presignedGetObject_test1() throws Exception {
    println("Test: presignedGetObject(String bucketName, String objectName)");
    String fileName = createFile(3 * MB);
    client.putObject(bucketName, fileName, fileName);

    String urlString = client.presignedGetObject(bucketName, fileName);
    Request.Builder requestBuilder = new Request.Builder();
    Request request = requestBuilder.url(HttpUrl.parse(urlString)).method("GET", null).build();
    OkHttpClient transport = new OkHttpClient();
    Response response = transport.newCall(request).execute();

    if (response != null) {
        if (response.isSuccessful()) {
            OutputStream os = Files.newOutputStream(Paths.get(fileName + ".downloaded"),
                    StandardOpenOption.CREATE);
            ByteStreams.copy(response.body().byteStream(), os);
            response.body().close();//from w w  w  .  j ava 2  s.co  m
            os.close();
        } else {
            String errorXml = "";

            // read entire body stream to string.
            Scanner scanner = new java.util.Scanner(response.body().charStream()).useDelimiter("\\A");
            if (scanner.hasNext()) {
                errorXml = scanner.next();
            }

            println("FAILED", response, errorXml);
        }
    } else {
        println("NO RESPONSE");
    }

    if (!Arrays.equals(Files.readAllBytes(Paths.get(fileName)),
            Files.readAllBytes(Paths.get(fileName + ".downloaded")))) {
        println("CONTENT DIFFERS");
    }

    Files.delete(Paths.get(fileName));
    Files.delete(Paths.get(fileName + ".downloaded"));
    client.removeObject(bucketName, fileName);
}

From source file:FunctionalTest.java

License:Apache License

public static void presignedGetObject_test2() throws Exception {
    println("Test: presignedGetObject(String bucketName, String objectName, Integer expires)");
    String fileName = createFile(3 * MB);
    client.putObject(bucketName, fileName, fileName);

    String urlString = client.presignedGetObject(bucketName, fileName, 3600);
    Request.Builder requestBuilder = new Request.Builder();
    Request request = requestBuilder.url(HttpUrl.parse(urlString)).method("GET", null).build();
    OkHttpClient transport = new OkHttpClient();
    Response response = transport.newCall(request).execute();

    if (response != null) {
        if (response.isSuccessful()) {
            OutputStream os = Files.newOutputStream(Paths.get(fileName + ".downloaded"),
                    StandardOpenOption.CREATE);
            ByteStreams.copy(response.body().byteStream(), os);
            response.body().close();/*www . j av a 2 s  .com*/
            os.close();
        } else {
            String errorXml = "";

            // read entire body stream to string.
            Scanner scanner = new java.util.Scanner(response.body().charStream()).useDelimiter("\\A");
            if (scanner.hasNext()) {
                errorXml = scanner.next();
            }

            println("FAILED", response, errorXml);
        }
    } else {
        println("NO RESPONSE");
    }

    if (!Arrays.equals(Files.readAllBytes(Paths.get(fileName)),
            Files.readAllBytes(Paths.get(fileName + ".downloaded")))) {
        println("CONTENT DIFFERS");
    }

    Files.delete(Paths.get(fileName));
    Files.delete(Paths.get(fileName + ".downloaded"));
    client.removeObject(bucketName, fileName);
}

From source file:FunctionalTest.java

License:Apache License

public static void presignedPutObject_test1() throws Exception {
    println("Test: presignedPutObject(String bucketName, String objectName)");
    String fileName = createFile(3 * MB);
    String urlString = client.presignedPutObject(bucketName, fileName);

    Request.Builder requestBuilder = new Request.Builder();
    Request request = requestBuilder.url(HttpUrl.parse(urlString))
            .method("PUT", RequestBody.create(null, Files.readAllBytes(Paths.get(fileName)))).build();
    OkHttpClient transport = new OkHttpClient();
    Response response = transport.newCall(request).execute();

    if (response != null) {
        if (!response.isSuccessful()) {
            String errorXml = "";

            // read entire body stream to string.
            Scanner scanner = new java.util.Scanner(response.body().charStream()).useDelimiter("\\A");
            if (scanner.hasNext()) {
                errorXml = scanner.next();
            }// w ww .j  a  v a 2  s  .c om

            println("FAILED", response, errorXml);
        }
    } else {
        println("NO RESPONSE");
    }

    Files.delete(Paths.get(fileName));
    client.removeObject(bucketName, fileName);
}

From source file:FunctionalTest.java

License:Apache License

public static void presignedPutObject_test2() throws Exception {
    println("Test: presignedPutObject(String bucketName, String objectName, Integer expires)");
    String fileName = createFile(3 * MB);
    String urlString = client.presignedPutObject(bucketName, fileName, 3600);

    Request.Builder requestBuilder = new Request.Builder();
    Request request = requestBuilder.url(HttpUrl.parse(urlString))
            .method("PUT", RequestBody.create(null, Files.readAllBytes(Paths.get(fileName)))).build();
    OkHttpClient transport = new OkHttpClient();
    Response response = transport.newCall(request).execute();

    if (response != null) {
        if (!response.isSuccessful()) {
            String errorXml = "";

            // read entire body stream to string.
            Scanner scanner = new java.util.Scanner(response.body().charStream()).useDelimiter("\\A");
            if (scanner.hasNext()) {
                errorXml = scanner.next();
            }//from  w w w.  jav  a 2  s. c  o m

            println("FAILED", response, errorXml);
        }
    } else {
        println("NO RESPONSE");
    }

    Files.delete(Paths.get(fileName));
    client.removeObject(bucketName, fileName);
}

From source file:FunctionalTest.java

License:Apache License

public static void presignedPostPolicy_test() throws Exception {
    println("Test: presignedPostPolicy(PostPolicy policy)");
    String fileName = createFile(3 * MB);
    PostPolicy policy = new PostPolicy(bucketName, fileName, DateTime.now().plusDays(7));
    policy.setContentRange(1 * MB, 4 * MB);
    Map<String, String> formData = client.presignedPostPolicy(policy);

    MultipartBuilder multipartBuilder = new MultipartBuilder();
    multipartBuilder.type(MultipartBuilder.FORM);
    for (Map.Entry<String, String> entry : formData.entrySet()) {
        multipartBuilder.addFormDataPart(entry.getKey(), entry.getValue());
    }//from  ww  w  . ja  v a 2s . c  o m
    multipartBuilder.addFormDataPart("file", fileName, RequestBody.create(null, new File(fileName)));

    Request.Builder requestBuilder = new Request.Builder();
    Request request = requestBuilder.url(endpoint + "/" + bucketName).post(multipartBuilder.build()).build();
    OkHttpClient transport = new OkHttpClient();
    Response response = transport.newCall(request).execute();

    if (response != null) {
        if (!response.isSuccessful()) {
            String errorXml = "";

            // read entire body stream to string.
            Scanner scanner = new java.util.Scanner(response.body().charStream()).useDelimiter("\\A");
            if (scanner.hasNext()) {
                errorXml = scanner.next();
            }

            println("FAILED", response, errorXml);
        }
    } else {
        println("NO RESPONSE");
    }

    Files.delete(Paths.get(fileName));
    client.removeObject(bucketName, fileName);
}

From source file:abtlibrary.utils.as24ApiClient.ApiClient.java

License:Apache License

/**
 * Handle the given response, return the deserialized object when the response is successful.
 *
 * @param <T> Type// w  w w.j ava  2s  .c o  m
 * @param response Response
 * @param returnType Return type
 * @throws ApiException If the response has a unsuccessful status code or
 *   fail to deserialize the response body
 * @return Type
 */
public <T> T handleResponse(Response response, Type returnType) throws ApiException {
    if (response.isSuccessful()) {
        if (returnType == null || response.code() == 204) {
            // returning null if the returnType is not defined,
            // or the status code is 204 (No Content)
            return null;
        } else {
            return deserialize(response, returnType);
        }
    } else {
        String respBody = null;
        if (response.body() != null) {
            try {
                respBody = response.body().string();
            } catch (IOException e) {
                throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap());
            }
        }
        throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody);
    }
}

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) {// www.  ja  v  a2 s  .com

    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  va2s .  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();//from ww w. jav 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 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 www.  ja v a  2  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);
    }
}