Example usage for com.squareup.okhttp OkHttpClient OkHttpClient

List of usage examples for com.squareup.okhttp OkHttpClient OkHttpClient

Introduction

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

Prototype

public OkHttpClient() 

Source Link

Usage

From source file:io.jawg.osmcontributor.flickr.util.FlickrUploadUtils.java

License:Open Source License

public static RestAdapter getRestAdapter(final Map<String, String> oAuthParams) {
    if (adapter == null) {
        OkHttpClient okHttpClient = new OkHttpClient();
        try {/*w w  w. j  a  v a  2 s .co m*/
            SSLSocketFactory NoSSLv3Factory = new NoSSLv3SocketFactory(
                    new URL("https://up.flickr.com/services"));
            okHttpClient.setSslSocketFactory(NoSSLv3Factory);
            adapter = new RestAdapter.Builder().setConverter(new StringConverter())
                    .setEndpoint("https://up.flickr.com/services").setClient(new OkClient(okHttpClient))
                    .setRequestInterceptor(new RequestInterceptor() {
                        @Override
                        public void intercept(RequestFacade request) {
                            request.addHeader("Authorization",
                                    FlickrSecurityUtils.getAuthorizationHeader(oAuthParams));
                        }
                    }).build();
        } catch (MalformedURLException e) {

        } catch (IOException e) {

        }
    }
    return adapter;
}

From source file:io.jawg.osmcontributor.rest.CommonSyncModule.java

License:Open Source License

@Provides
OkHttpClient getOkHttpClient(AuthenticationRequestInterceptor interceptor) {
    final OkHttpClient client = new OkHttpClient();
    client.setAuthenticator(interceptor);
    return client;
}

From source file:io.kodokojo.bdd.MarathonIsPresent.java

License:Open Source License

public MarathonIsPresent() {
    LinkedList<PropertyValueProvider> valueproviders = new LinkedList<>();
    valueproviders.add(new SystemEnvValueProvider());
    valueproviders.add(new SystemPropertyValueProvider());
    PropertyValueProvider valueProvider = new OrderedMergedValueProvider(valueproviders);
    PropertyResolver resolver = new PropertyResolver(valueProvider);
    marathonConfig = resolver.createProxy(MarathonConfig.class);
    httpClient = new OkHttpClient();
}

From source file:io.kodokojo.bdd.stage.AccessRestWhen.java

License:Open Source License

public SELF try_to_access_to_list_of_brick_available() {
    UserInfo currentUser = currentUsers.get(currentUserLogin);
    OkHttpClient httpClient = new OkHttpClient();
    Request.Builder builder = new Request.Builder().url(getBaseUrl() + "/api/v1/brick").get();
    builder = HttpUserSupport.addBasicAuthentification(currentUser, builder);
    Response response = null;//from   w w w  . j  a  va  2s .c  om

    try {
        response = httpClient.newCall(builder.build()).execute();
        Gson gson = new GsonBuilder().create();
        JsonParser parser = new JsonParser();
        String payload = response.body().string();
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace(payload);
        }
        JsonArray root = (JsonArray) parser.parse(payload);
        for (JsonElement el : root) {
            brickAvailable.add(gson.fromJson(el, BrickConfigDto.class));
        }
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        if (response != null) {
            IOUtils.closeQuietly(response.body());
        }
    }

    return self();
}

From source file:io.kodokojo.bdd.stage.ApplicationGiven.java

License:Open Source License

public SELF kodokojo_restEntrypoint_is_available_on_port_$(int port) {
    try {/*from w ww .  j  a  v  a2 s.c om*/
        KeyGenerator generator = KeyGenerator.getInstance("AES");
        generator.init(128);
        SecretKey aesKey = generator.generateKey();
        userStore = new RedisUserStore(aesKey, redisHost, redisPort);
        DefaultBrickFactory brickFactory = new DefaultBrickFactory();
        projectStore = new RedisProjectStore(aesKey, redisHost, redisPort, brickFactory);
        entityStore = new RedisEntityStore(aesKey, redisHost, redisPort);
        UserAuthenticator<SimpleCredential> userAuthenticator = new SimpleUserAuthenticator(userStore);
        projectManager = mock(ProjectManager.class);
        Launcher.INJECTOR = Guice.createInjector(new UserEndpointModule(), new ProjectEndpointModule(),
                new BrickEndpointModule(), new EmailSenderModule(), new AbstractModule() {
                    @Override
                    protected void configure() {
                        bind(UserStore.class).toInstance(userStore);
                        bind(ProjectStore.class).toInstance(projectStore);
                        bind(ProjectManager.class).toInstance(projectManager);
                        bind(EntityStore.class).toInstance(entityStore);
                        bind(Key.get(new TypeLiteral<UserAuthenticator<SimpleCredential>>() {
                        })).toInstance(userAuthenticator);
                        bind(BrickFactory.class).toInstance(brickFactory);
                        bind(ApplicationConfig.class).toInstance(new ApplicationConfig() {
                            @Override
                            public int port() {
                                return 80;
                            }

                            @Override
                            public String domain() {
                                return "kodokojo.dev";
                            }

                            @Override
                            public String loadbalancerHost() {
                                return dockerTestSupport.getServerIp();
                            }

                            @Override
                            public int initialSshPort() {
                                return 1022;
                            }

                            @Override
                            public long sslCaDuration() {
                                return -1;
                            }
                        });
                        bind(BrickUrlFactory.class).toInstance(new DefaultBrickUrlFactory("kodokojo.dev"));
                        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;
                            }

                        });
                    }
                });
        Set<SparkEndpoint> sparkEndpoints = Launcher.INJECTOR
                .getInstance(Key.get(new TypeLiteral<Set<SparkEndpoint>>() {
                }));
        httpEndpoint = new HttpEndpoint(port, new SimpleUserAuthenticator(userStore), sparkEndpoints);
        httpUserSupport = new HttpUserSupport(new OkHttpClient(), "localhost:" + port);
        httpEndpoint.start();
        restEntryPointPort = port;
        restEntryPointHost = "localhost";
    } catch (NoSuchAlgorithmException e) {
        fail(e.getMessage(), e);
    }
    return self();
}

From source file:io.kodokojo.bdd.stage.ApplicationThen.java

License:Open Source License

public SELF add_user_$_to_project_configuration_as_user_$_will_fail(@Quoted String usernameToAdd,
        @Quoted String usernameOwner) {
    UserInfo currentUser = currentUsers.get(usernameOwner);
    UserInfo userToAdd = currentUsers.get(usernameToAdd);

    String json = "[\n" + "    \"" + userToAdd.getIdentifier() + "\"\n" + "  ]";

    OkHttpClient httpClient = new OkHttpClient();

    RequestBody body = RequestBody.create(com.squareup.okhttp.MediaType.parse("application/json"),
            json.getBytes());// w  w  w .ja  v a 2s .  c o m
    Request.Builder builder = new Request.Builder()
            .url(getApiBaseUrl() + "/projectconfig/" + projectConfigurationId + "/user").put(body);
    Request request = HttpUserSupport.addBasicAuthentification(currentUser, builder).build();
    Response response = null;
    try {
        response = httpClient.newCall(request).execute();
        assertThat(response.code()).isEqualTo(403);
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        if (response != null) {
            IOUtils.closeQuietly(response.body());
        }
    }
    return self();
}

From source file:io.kodokojo.bdd.stage.ApplicationThen.java

License:Open Source License

private void getUserDetails(String username, boolean complete) {
    OkHttpClient httpClient = new OkHttpClient();
    UserInfo requesterUserInfo = currentUsers.get(currentUserLogin);
    UserInfo targetUserInfo = currentUsers.get(username);
    String url = getApiBaseUrl() + "/user";
    if (!requesterUserInfo.getIdentifier().equals(targetUserInfo.getIdentifier())) {
        url += "/" + targetUserInfo.getIdentifier();
    }/* w  ww .java  2s  .  c  o m*/
    Request.Builder builder = new Request.Builder().get().url(url);
    Request request = HttpUserSupport.addBasicAuthentification(requesterUserInfo, builder).build();
    Response response = null;
    try {
        response = httpClient.newCall(request).execute();
        assertThat(response.code()).isEqualTo(200);

        JsonParser parser = new JsonParser();
        String body = response.body().string();
        JsonObject json = (JsonObject) parser.parse(body);

        assertThat(json.getAsJsonPrimitive("name").getAsString()).isNotEmpty();
        if (complete) {
            assertThat(json.getAsJsonPrimitive("password").getAsString()).isNotEmpty();
            assertThat(json.getAsJsonPrimitive("email").getAsString()).isNotEmpty();
            assertThat(json.getAsJsonPrimitive("sshPublicKey").getAsString()).isNotEmpty();

        } else {
            assertThat(json.getAsJsonPrimitive("password").getAsString()).isEmpty();
        }
        if (StringUtils.isNotBlank(projectConfigurationId)) {
            assertThat(json.has("projectConfigurationIds"));
            JsonArray projectConfigurationIds = json.getAsJsonArray("projectConfigurationIds");
            assertThat(projectConfigurationIds).isNotEmpty();
            boolean foundCurrentProjectConfigurationId = false;
            Iterator<JsonElement> projectConfigIt = projectConfigurationIds.iterator();

            while (projectConfigIt.hasNext()) {
                JsonObject projectConfig = (JsonObject) projectConfigIt.next();
                assertThat(projectConfig.has("projectConfigurationId"));
                foundCurrentProjectConfigurationId = projectConfigurationId
                        .equals(projectConfig.getAsJsonPrimitive("projectConfigurationId").getAsString());
            }
            assertThat(foundCurrentProjectConfigurationId).isTrue();
        }
    } catch (IOException e) {
        fail("Unable to get User details on Url " + url, e);
    } finally {
        if (response != null) {
            try {
                response.body().close();
            } catch (IOException e) {
                fail("Fail to close Http response.", e);
            }
        }
    }
}

From source file:io.kodokojo.bdd.stage.ApplicationThen.java

License:Open Source License

private ProjectConfigDto getProjectConfigurationFromCurrentProjectConfigId() {
    OkHttpClient httpClient = new OkHttpClient();
    UserInfo requesterUserInfo = currentUsers.get(currentUserLogin);
    Request.Builder builder = new Request.Builder()
            .url(getApiBaseUrl() + "/projectconfig/" + projectConfigurationId).get();
    Request request = HttpUserSupport.addBasicAuthentification(requesterUserInfo, builder).build();
    Response response = null;//from w ww. ja v  a  2s.  c om
    try {
        response = httpClient.newCall(request).execute();
        assertThat(response.code()).isEqualTo(200);
        String bodyResponse = response.body().string();
        Gson gson = new GsonBuilder().create();
        ProjectConfigDto projectConfigDto = gson.fromJson(bodyResponse, ProjectConfigDto.class);
        assertThat(projectConfigDto).isNotNull();
        assertThat(projectConfigDto.getAdmins().get(0).getUsername())
                .isEqualTo(requesterUserInfo.getUsername());
        assertThat(projectConfigDto.getUsers()).isNotEmpty();
        assertThat(projectConfigDto.getStackConfigs()).isNotEmpty();

        JsonParser parser = new JsonParser();
        JsonObject json = (JsonObject) parser.parse(bodyResponse);
        assertThat(json.has("name")).isTrue();
        assertThat(json.has("identifier")).isTrue();
        assertThat(json.has("admins")).isTrue();
        JsonArray admins = json.getAsJsonArray("admins");
        assertThat(admins).isNotEmpty();
        jsonUserAreValid(admins.iterator());
        JsonArray users = json.getAsJsonArray("users");
        jsonUserAreValid(users.iterator());
        assertThat(users).isNotEmpty();
        JsonArray stackConfigs = json.getAsJsonArray("stackConfigs");
        assertThat(stackConfigs).isNotEmpty();
        Iterator<JsonElement> stackConfigurationIt = stackConfigs.iterator();
        while (stackConfigurationIt.hasNext()) {
            JsonObject stackConf = (JsonObject) stackConfigurationIt.next();
            jsonStackConfigIsValid(stackConf);
        }

        return projectConfigDto;
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        if (response != null) {
            closeQuietly(response.body());
        }
    }
    return null;
}

From source file:io.kodokojo.bdd.stage.ApplicationWhen.java

License:Open Source License

public SELF retrive_a_new_id() {
    OkHttpClient httpClient = new OkHttpClient();
    RequestBody emptyBody = RequestBody.create(null, new byte[0]);
    String baseUrl = getBaseUrl();
    Request request = new Request.Builder().post(emptyBody).url(baseUrl + "/api/v1/user").build();
    Response response = null;// ww  w . j  a v  a 2s. c  om
    try {
        response = httpClient.newCall(request).execute();
        if (response.code() != 200) {
            fail("Invalid HTTP code status " + response.code() + " expected 200");
        }
        newUserId = response.body().string();

    } catch (IOException e) {
        fail(e.getMessage(), e);
    } finally {
        if (response != null) {
            IOUtils.closeQuietly(response.body());
        }
    }
    return self();
}

From source file:io.kodokojo.bdd.stage.ApplicationWhen.java

License:Open Source License

private SELF create_user(String email, boolean success) {
    if (isBlank(email)) {
        throw new IllegalArgumentException("email must be defined.");
    }/*from  w  w  w  . j a  v a2s  .c  o m*/
    if (success && StringUtils.isBlank(newUserId)) {
        retrive_a_new_id();
    }

    OkHttpClient httpClient = new OkHttpClient();
    RequestBody body = RequestBody.create(MediaType.parse("application/json"),
            ("{\"email\": \"" + email + "\"}").getBytes());
    String baseUrl = getBaseUrl();

    Request.Builder builder = new Request.Builder().post(body)
            .url(baseUrl + "/api/v1/user" + (newUserId != null ? "/" + newUserId : ""));
    if (isNotBlank(currentUserLogin)) {
        UserInfo currentUser = currentUsers.get(currentUserLogin);
        if (currentUser != null) {
            builder = HttpUserSupport.addBasicAuthentification(currentUser, builder);
        }
    }
    Request request = builder.build();
    Response response = null;
    try {
        response = httpClient.newCall(request).execute();
        if (success) {
            assertThat(response.code()).isEqualTo(201);
            JsonParser parser = new JsonParser();
            String bodyResponse = response.body().string();
            JsonObject json = (JsonObject) parser.parse(bodyResponse);
            String currentUsername = json.getAsJsonPrimitive("username").getAsString();
            String currentUserPassword = json.getAsJsonPrimitive("password").getAsString();
            String currentUserEmail = json.getAsJsonPrimitive("email").getAsString();
            String currentUserIdentifier = json.getAsJsonPrimitive("identifier").getAsString();
            String currentUserEntityIdentifier = json.getAsJsonPrimitive("entityIdentifier").getAsString();
            currentUsers.put(currentUsername, new UserInfo(currentUsername, currentUserIdentifier,
                    currentUserEntityIdentifier, currentUserPassword, currentUserEmail));
            if (isBlank(currentUserLogin)) {
                currentUserLogin = currentUsername;
            }
            Attachment privateKey = Attachment.plainText(bodyResponse).withTitle(currentUsername + " response");
            currentStep.addAttachment(privateKey);
        } else {
            assertThat(response.code()).isNotEqualTo(201);
        }
        response.body().close();
    } catch (IOException e) {
        if (success) {
            fail(e.getMessage(), e);
        }
    } finally {
        if (response != null) {
            IOUtils.closeQuietly(response.body());
        }
    }
    return self();
}