Example usage for com.google.gson JsonObject getAsJsonPrimitive

List of usage examples for com.google.gson JsonObject getAsJsonPrimitive

Introduction

In this page you can find the example usage for com.google.gson JsonObject getAsJsonPrimitive.

Prototype

public JsonPrimitive getAsJsonPrimitive(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonPrimitive element.

Usage

From source file:io.hypertrack.sendeta.util.LocationDeserializer.java

License:Open Source License

public Location deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) {
    JsonObject jsonObject = je.getAsJsonObject();
    Location location = new Location(jsonObject.getAsJsonPrimitive("mProvider").getAsString());
    location.setAccuracy(jsonObject.getAsJsonPrimitive("mAccuracy").getAsFloat());
    location.setLatitude(jsonObject.getAsJsonPrimitive("mLatitude").getAsDouble());
    location.setLongitude(jsonObject.getAsJsonPrimitive("mLongitude").getAsDouble());
    location.setTime(jsonObject.getAsJsonPrimitive("mTime").getAsLong());
    location.setSpeed(jsonObject.getAsJsonPrimitive("mSpeed").getAsFloat());
    location.setBearing(jsonObject.getAsJsonPrimitive("mBearing").getAsFloat());
    return location;
}

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();
    }// ww  w . j av a2  s . 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.ApplicationWhen.java

License:Open Source License

private SELF create_user(String email, boolean success) {
    if (isBlank(email)) {
        throw new IllegalArgumentException("email must be defined.");
    }/*ww w  .ja v  a 2  s  .  c  om*/
    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();
}

From source file:io.kodokojo.bdd.stage.cluster.ClusterApplicationGiven.java

License:Open Source License

private void killAllAppInMarathon(String marathonUrl) {
    OkHttpClient httpClient = new OkHttpClient();
    Request.Builder builder = new Request.Builder().url(marathonUrl + "/v2/apps").get();
    Response response = null;/*from   w w  w . ja  va 2  s  .co  m*/
    Set<String> appIds = new HashSet<>();

    try {
        response = httpClient.newCall(builder.build()).execute();
        String body = response.body().string();
        JsonParser parser = new JsonParser();
        JsonObject json = (JsonObject) parser.parse(body);
        JsonArray apps = json.getAsJsonArray("apps");
        for (JsonElement appEl : apps) {
            JsonObject app = (JsonObject) appEl;
            appIds.add(app.getAsJsonPrimitive("id").getAsString());
        }
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        if (response != null) {
            IOUtils.closeQuietly(response.body());
        }
    }
    appIds.stream().forEach(id -> {
        Request.Builder rmBuilder = new Request.Builder().url(marathonUrl + "/v2/apps/" + id).delete();
        Response responseRm = null;
        try {
            LOGGER.debug("Delete Marathon application id {}.", id);
            responseRm = httpClient.newCall(rmBuilder.build()).execute();
        } catch (IOException e) {
            fail(e.getMessage());
        } finally {
            if (responseRm != null) {
                IOUtils.closeQuietly(responseRm.body());
            }
        }
    });

}

From source file:io.kodokojo.bdd.stage.cluster.ClusterApplicationWhen.java

License:Open Source License

public SELF i_start_the_project() {

    OkHttpClient httpClient = new OkHttpClient();

    String url = "http://" + restEntryPointHost + ":" + restEntryPointPort + "/api/v1/project/"
            + projectConfiguration.getIdentifier();
    RequestBody body = RequestBody.create(null, new byte[0]);
    Request.Builder builder = new Request.Builder().url(url).post(body);
    builder = HttpUserSupport.addBasicAuthentification(currentUser, builder);
    Response response = null;/*from   www  . ja  va 2  s .  c o m*/

    try {
        response = httpClient.newCall(builder.build()).execute();
        assertThat(response.code()).isEqualTo(201);
        LOGGER.trace("Starting project");

        Map<String, Boolean> brickRunning = new HashMap<>();
        projectConfiguration.getDefaultBrickConfigurations().forEachRemaining(b -> {
            brickRunning.put(b.getName(), Boolean.FALSE);
        });

        JsonParser parser = new JsonParser();
        boolean allBrickStarted = true;

        long now = System.currentTimeMillis();
        long end = now + 180000;

        do {
            Iterator<String> messageReceive = webSocketEventsListener.getMessages().iterator();
            while (messageReceive.hasNext()) {
                String message = messageReceive.next();
                JsonObject root = (JsonObject) parser.parse(message);
                if ("updateState".equals(root.getAsJsonPrimitive("action").getAsString())) {
                    JsonObject data = root.getAsJsonObject("data");
                    String brickName = data.getAsJsonPrimitive("brickName").getAsString();
                    String brickState = data.getAsJsonPrimitive("state").getAsString();
                    if ("RUNNING".equals(brickState)) {
                        brickRunning.put(brickName, Boolean.TRUE);
                    }
                }
            }
            Iterator<Boolean> iterator = brickRunning.values().iterator();
            allBrickStarted = true;
            while (allBrickStarted && iterator.hasNext()) {
                allBrickStarted = iterator.next();
            }
            if (!allBrickStarted) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
            now = System.currentTimeMillis();
        } while (!allBrickStarted && now < end);
        assertThat(allBrickStarted).isTrue();
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        if (response != null) {
            IOUtils.closeQuietly(response.body());
        }
    }

    return self();
}

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

License:Open Source License

public UserInfo createUser(UserInfo currentUser, String email) {

    RequestBody emptyBody = RequestBody.create(null, new byte[0]);
    Request.Builder builder = new Request.Builder().post(emptyBody).url(getApiBaseUrl() + "/user");
    if (currentUser != null) {
        builder = addBasicAuthentification(currentUser, builder);
    }//from w w w. ja v  a2  s  . co m
    Request request = builder.build();
    Response response = null;
    String identifier = null;
    try {
        response = httpClient.newCall(request).execute();
        identifier = response.body().string();
        assertThat(identifier).isNotEmpty();
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        if (response != null) {
            IOUtils.closeQuietly(response.body());
        }
    }

    RequestBody body = RequestBody.create(MediaType.parse("application/json"),
            ("{\"email\": \"" + email + "\"}").getBytes());
    builder = new Request.Builder().post(body).url(getApiBaseUrl() + "/user/" + identifier);
    if (currentUser != null) {
        builder = addBasicAuthentification(currentUser, builder);
    }
    request = builder.build();
    response = null;
    try {
        response = httpClient.newCall(request).execute();
        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();
        UserInfo res = new UserInfo(currentUsername, currentUserIdentifier, currentUserEntityIdentifier,
                currentUserPassword, currentUserEmail);
        return res;

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

From source file:io.kodokojo.brick.gitlab.GitlabConfigurer.java

License:Open Source License

private boolean createUser(GitlabRest gitlabRest, String privateToken, User user) {
    Response response = null;/*  w  w w .jav  a 2 s . c o m*/
    int id = -1;
    try {
        JsonObject jsonObject = gitlabRest.createUser(privateToken, user.getUsername(), user.getPassword(),
                user.getEmail(), user.getName(), "false");
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace(jsonObject.toString());
        }

        id = jsonObject.getAsJsonPrimitive("id").getAsInt();
    } catch (RetrofitError e) {
        LOGGER.error("unable to complete creation of user : ", e);
    }

    if (id != -1) {
        try {
            try {
                Thread.sleep(500); // We encount some cases where Gitlab throw a 500 internal error while post the SSH key. Test if let some time to Gitlab to add user will resolv this issue ?
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            response = gitlabRest.addSshKey(privateToken, Integer.toString(id), "SSH Key",
                    user.getSshPublicKey());
            return true;
            //return response.code() >= 200 && response.code() < 300; return a non 20X HTTP code when success to push the SSH key...
            //  Have a look on the HAproxy timeout ?

        } catch (RetrofitError e) {
            LOGGER.error("unable to add SSH keys creation of user : ", e);
        } finally {
            if (response != null) {
                IOUtils.closeQuietly(response.body());
            }
        }
    }
    return false;
}

From source file:io.kodokojo.commons.utils.properties.provider.kv.ConsulKvPropertyValueProvider.java

License:Open Source License

@Override
protected String provideValue(String key) {
    if (isBlank(key)) {
        throw new IllegalArgumentException("key must be defined.");
    }/*from  w w w. j ava2s.c o m*/
    try {
        JsonArray values = consulKvRest.getValueResult(key);
        JsonObject json = values.get(0).getAsJsonObject();

        String res = null;
        if (json != null) {
            JsonPrimitive primitive = json.getAsJsonPrimitive("Value");
            if (primitive != null) {
                String value = primitive.getAsString();
                res = new String(Base64.getDecoder().decode(value));
            }
        }
        return res;
    } catch (RetrofitError e) {
        if ("404 Not Found".equals(e.getMessage())) {
            return null;
        }
        throw e;
    }
}

From source file:io.kodokojo.commons.utils.servicelocator.marathon.MarathonServiceLocator.java

License:Open Source License

@Override
public Set<Service> getService(String type, String name) {
    Set<String> appIds = new HashSet<>();
    JsonObject json = marathonRestApi.getAllApplications();
    JsonArray apps = json.getAsJsonArray("apps");
    for (int i = 0; i < apps.size(); i++) {
        JsonObject app = (JsonObject) apps.get(i);
        String id = app.getAsJsonPrimitive("id").getAsString();
        JsonObject labels = app.getAsJsonObject("labels");
        if (labels.has("project")) {
            String project = labels.getAsJsonPrimitive("project").getAsString();
            String apptype = labels.getAsJsonPrimitive("componentType").getAsString();
            if (type.equals(apptype) && name.equals(project)) {
                appIds.add(id);//from www.  j  a v a 2s .c o m
            }
        }
    }
    Set<Service> res = new HashSet<>();
    for (String appId : appIds) {
        JsonObject applicationConfiguration = marathonRestApi.getApplicationConfiguration(appId);
        res.addAll(convertToService(name + "-" + type, applicationConfiguration));
    }

    return res;
}

From source file:io.kodokojo.commons.utils.servicelocator.marathon.MarathonServiceLocator.java

License:Open Source License

private static Set<Service> convertToService(String name, JsonObject json) {
    Set<Service> res = new HashSet<>();
    JsonObject app = json.getAsJsonObject("app");
    JsonObject container = app.getAsJsonObject("container");
    String containerType = container.getAsJsonPrimitive("type").getAsString();
    if ("DOCKER".equals(containerType)) {
        List<String> ports = new ArrayList<>();
        JsonObject docker = container.getAsJsonObject("docker");
        JsonArray portMappings = docker.getAsJsonArray("portMappings");
        for (int i = 0; i < portMappings.size(); i++) {
            JsonObject portMapping = (JsonObject) portMappings.get(i);
            ports.add(portMapping.getAsJsonPrimitive("containerPort").getAsString());
        }//from   w  ww .  j a v a  2s .co m
        JsonArray tasks = app.getAsJsonArray("tasks");
        for (int i = 0; i < tasks.size(); i++) {
            JsonObject task = (JsonObject) tasks.get(i);
            String host = task.getAsJsonPrimitive("host").getAsString();
            boolean alive = false;
            if (task.has("healthCheckResults")) {
                JsonArray healthCheckResults = task.getAsJsonArray("healthCheckResults");
                for (int j = 0; j < healthCheckResults.size() && !alive; j++) {
                    JsonObject healthCheck = (JsonObject) healthCheckResults.get(j);
                    alive = healthCheck.getAsJsonPrimitive("alive").getAsBoolean();
                }
            }
            if (alive) {
                JsonArray jsonPorts = task.getAsJsonArray("ports");
                for (int j = 0; j < jsonPorts.size(); j++) {
                    JsonPrimitive jsonPort = (JsonPrimitive) jsonPorts.get(j);
                    String portName = ports.get(j);
                    res.add(new Service(name + "-" + portName, host, jsonPort.getAsInt()));
                }
            }
        }
    }
    return res;
}