Example usage for com.google.gson JsonObject getAsJsonObject

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

Introduction

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

Prototype

public JsonObject getAsJsonObject(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonObject.

Usage

From source file:com.dangdang.ddframe.job.cloud.scheduler.mesos.MesosSlaveService.java

License:Apache License

private JsonObject buildSlave(final JsonObject rootObject) {
    JsonObject result = new JsonObject();
    result.addProperty("id", rootObject.get("id").getAsString());
    result.addProperty("hostname", rootObject.get("hostname").getAsString());
    result.addProperty("registered_time", rootObject.get("registered_time").getAsDouble());
    if (rootObject.get("reregistered_time") != null) {
        result.addProperty("reregistered_time", rootObject.get("reregistered_time").getAsDouble());
    }/*from ww w . jav a 2 s  . c  om*/
    result.add("resources", buildSummaryResource(rootObject.getAsJsonObject("resources")));
    result.add("use_resources", buildSummaryResource(rootObject.getAsJsonObject("used_resources")));
    result.add("offered_resources", buildSummaryResource(rootObject.getAsJsonObject("offered_resources")));
    result.add("roles", buildRoles(rootObject));
    return result;
}

From source file:com.dangdang.ddframe.job.cloud.scheduler.mesos.MesosSlaveService.java

License:Apache License

private JsonArray buildRoles(final JsonObject rootObject) {
    final Map<String, JsonObject> roleMap = new HashMap<>();
    fillReservedResources(roleMap, rootObject.getAsJsonObject("reserved_resources_full"));
    fillUsedResources(roleMap, rootObject.getAsJsonArray("used_resources_full"));
    fillOfferedResources(roleMap, rootObject.getAsJsonArray("offered_resources_full"));
    JsonArray result = new JsonArray();
    for (JsonObject each : roleMap.values()) {
        result.add(each);/*w w w  .  j a  v a2 s.  c o  m*/
    }
    return result;
}

From source file:com.dangdang.ddframe.job.cloud.scheduler.mesos.MesosSlaveService.java

License:Apache License

private JsonObject buildResource(final JsonObject resourceObject) {
    JsonObject result = new JsonObject();
    result.addProperty("name", resourceObject.get("name").getAsString());
    result.addProperty("type", resourceObject.get("type").getAsString());
    result.addProperty("role_name", resourceObject.get("role").getAsString());
    if ("SCALAR".equals(result.get("type").getAsString())) {
        result.addProperty("value", resourceObject.getAsJsonObject("scalar").get("value").getAsDouble());
    } else if ("RANGES".equals(result.get("type").getAsString())) {
        result.addProperty("begin", resourceObject.getAsJsonObject("ranges").getAsJsonArray("range").get(0)
                .getAsJsonObject().get("begin").getAsInt());
        result.addProperty("end", resourceObject.getAsJsonObject("ranges").getAsJsonArray("range").get(0)
                .getAsJsonObject().get("end").getAsInt());
    }/* www  .j a  v a2  s.co  m*/
    return result;
}

From source file:com.davis.bluefolder.BlueEndpoint.java

@GET
@Path("/getAllUsers")
public Response getAllUsers(@Context UriInfo requestUriInfo) throws Exception {
    String url = "https://app.bluefolder.com/api/1.0/users/list.aspx";
    String result = blueRestService.getResponseString(url,
            "<request>" + "<userList>" + "<listType>full</listType>" + "</userList>" + "</request>");
    String jsonString = BlueUtils.convertXmlToJson(result);
    JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
    JsonArray jsonArray = jsonObject.getAsJsonObject("response").getAsJsonArray("user");
    BFUser[] userList = gson.fromJson(jsonArray, BFUser[].class);
    Response response = null;/*from ww w.j  a  va2 s .com*/
    try {
        response = generateResponseFromObject(userList);
    } catch (EndpointException e) {
        return generateErrorResponse(500, "Server Error", "There was a error handling the request.");

    }

    return response;
}

From source file:com.davis.bluefolder.BlueEndpoint.java

@GET
@Path("/isUserValid")
public Response isUserValid(@Context UriInfo requestUriInfo, @QueryParam("user") String userID)
        throws Exception {

    if (userID == null || userID.trim().equalsIgnoreCase("")) {
        return generateErrorResponse(400, "No User Supplied", "No user ID was supplied to the endpoint.");

    }/*from  w w w.  ja  va 2  s.  com*/

    String url = "https://app.bluefolder.com/api/1.0/users/list.aspx";
    String result = null;
    try {
        result = blueRestService.getResponseString(url,
                "<request>" + "<userList>" + "<listType>full</listType>" + "</userList>" + "</request>");
    } catch (Exception e) {
        logger.error("isUserValid request failed {}", e.getMessage());
    }
    String jsonString = BlueUtils.convertXmlToJson(result);
    JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
    JsonArray jsonArray = jsonObject.getAsJsonObject("response").getAsJsonArray("user");
    BFUser[] userList = gson.fromJson(jsonArray, BFUser[].class);
    BFUser targetUser = null;
    for (BFUser bfUser : userList) {
        if (bfUser.getUserName().equalsIgnoreCase(userID)) {
            targetUser = bfUser;
        }
    }
    if (targetUser == null) {
        return generateErrorResponse(204, "No User", "The user is not within the Blue Folder database");

    }
    Response response = null;
    try {
        response = generateResponseFromObject(targetUser);
    } catch (EndpointException e) {
        return generateErrorResponse(500, "Server Error", "There was a error handling the request.");

    }

    return response;

}

From source file:com.denimgroup.threadfix.cli.util.JsonTestUtils.java

License:Mozilla Public License

public static <T> void assertHasObjectWithFields(RestResponse<T> restResponse, String objectKey,
        String... fields) {/*from w ww  .  j  a va 2 s .  c o  m*/

    assert getJsonObject(restResponse) != null : "Failed to parse RestResponse from data: "
            + restResponse.getOriginalJson();

    JsonObject jsonObject = getJsonObject(restResponse).getAsJsonObject("object");

    jsonObject = jsonObject.getAsJsonObject(objectKey);

    innerValidate(jsonObject, fields);
}

From source file:com.devicehive.websockets.handlers.CommandHandlers.java

License:Apache License

@PreAuthorize("isAuthenticated() and hasPermission(null, 'CREATE_DEVICE_COMMAND')")
public WebSocketResponse processCommandInsert(JsonObject request, WebSocketSession session) {
    HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication()
            .getPrincipal();//from   w ww  .  j ava  2s. c  o  m
    final String deviceGuid = Optional.ofNullable(request.get(Constants.DEVICE_GUID))
            .map(JsonElement::getAsString).orElse(null);
    final DeviceCommandWrapper deviceCommand = gson.fromJson(request.getAsJsonObject(COMMAND),
            DeviceCommandWrapper.class);

    logger.debug("command/insert action for {}, Session ", deviceGuid, session.getId());

    Set<DeviceVO> devices = new HashSet<>();
    if (deviceGuid == null) {
        for (String guid : principal.getDeviceGuids()) {
            devices.add(deviceService.findByGuidWithPermissionsCheck(guid, principal));
        }
    } else {
        devices.add(deviceService.findByGuidWithPermissionsCheck(deviceGuid, principal));
    }

    if (devices.isEmpty()) {
        throw new HiveException(String.format(Messages.DEVICE_NOT_FOUND, deviceGuid), SC_NOT_FOUND);
    }
    if (deviceCommand == null) {
        throw new HiveException(Messages.EMPTY_COMMAND, SC_BAD_REQUEST);
    }
    final UserVO user = principal.getUser();

    WebSocketResponse response = new WebSocketResponse();
    for (DeviceVO device : devices) {
        commandService.insert(deviceCommand, device, user).thenApply(cmd -> {
            commandUpdateSubscribeAction(cmd.getId(), device.getGuid(), session);
            response.addValue(COMMAND, new InsertCommand(cmd.getId(), cmd.getTimestamp(), cmd.getUserId()),
                    COMMAND_TO_CLIENT);
            return response;
        }).exceptionally(ex -> {
            logger.warn("Unable to insert notification.", ex);
            throw new HiveException(Messages.INTERNAL_SERVER_ERROR, SC_INTERNAL_SERVER_ERROR);
        }).join();
    }

    return response;
}

From source file:com.devicehive.websockets.handlers.CommandHandlers.java

License:Apache License

@PreAuthorize("isAuthenticated() and hasPermission(null, 'UPDATE_DEVICE_COMMAND')")
public WebSocketResponse processCommandUpdate(JsonObject request, WebSocketSession session) {
    HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication()
            .getPrincipal();/*from  www  . ja  va 2  s  .c om*/
    String guid = request.get(DEVICE_GUID).getAsString();
    final Long id = Long.valueOf(request.get(COMMAND_ID).getAsString()); // TODO: nullable long?
    final DeviceCommandWrapper commandUpdate = gson.fromJson(request.getAsJsonObject(COMMAND),
            DeviceCommandWrapper.class);

    logger.debug("command/update requested for session: {}. Device guid: {}. Command id: {}", session, guid,
            id);
    /*todo - is check really redundant now?
    if (guid == null) {
    logger.debug("command/update canceled for session: {}. Guid is not provided", session);
    throw new HiveException(Messages.DEVICE_GUID_REQUIRED, SC_BAD_REQUEST);
    }*/
    if (id == null) {
        logger.debug("command/update canceled for session: {}. Command id is not provided", session);
        throw new HiveException(Messages.COMMAND_ID_REQUIRED, SC_BAD_REQUEST);
    }

    Set<DeviceVO> devices = new HashSet<>();
    if (guid == null) {
        for (String deviceGuid : principal.getDeviceGuids()) {
            devices.add(deviceService.findByGuidWithPermissionsCheck(deviceGuid, principal));
        }
    } else {
        devices.add(deviceService.findByGuidWithPermissionsCheck(guid, principal));
    }

    if (devices.isEmpty()) {
        throw new HiveException(String.format(Messages.DEVICE_NOT_FOUND, id), SC_NOT_FOUND);
    }

    Optional<DeviceCommand> savedCommand = Optional.empty();
    for (DeviceVO device : devices) {
        savedCommand = commandService.findOne(id, device.getGuid()).join();
        if (savedCommand.isPresent()) {
            commandService.update(savedCommand.get(), commandUpdate);
        }
    }

    if (!savedCommand.isPresent()) {
        throw new HiveException(String.format(Messages.COMMAND_NOT_FOUND, id), SC_NOT_FOUND);
    }

    logger.debug("command/update proceed successfully for session: {}. Device guid: {}. Command id: {}",
            session, guid, id);
    return new WebSocketResponse();
}

From source file:com.devonfw.module.i18n.common.util.BundleMapSerializer.java

License:Apache License

private static JsonObject getJsonIfExists(final JsonObject parent, final String key) {

    if (parent == null) {
        LOG.warn("Parent json parameter is null!");
        return null;
    }//w  w w.  j  a  va2s  .c  om

    if (parent.get(key) != null && !(parent.get(key) instanceof JsonObject)) {
        throw new IllegalArgumentException("Invalid key \'" + key + "\' for parent: " + parent
                + "\nKey can not be JSON object and property or array at a time");
    }

    if (parent.getAsJsonObject(key) != null) {
        return parent.getAsJsonObject(key);
    } else {
        return new JsonObject();
    }
}

From source file:com.elevenpaths.latch.sdk.impl.LatchSDKImpl.java

License:Open Source License

/**
 * Returns the status of the latch identified by the provided
 * account id and, if not null, the provided operation id.
 * <p>/* w w w  .j  ava 2  s.  co m*/
 * If something has gone wrong trying to get the latch status an
 * special <code>LatchSDKStatus</code> value will be returned (
 * <code>UNKNOWN</code>), so the application can choose what to
 * do.
 * <p>
 * If the backend returns a JSON with an error, this error is
 * returned as a <code>LatchErrorException</code>. It's also
 * responsibility of the application using this method to choose
 * what to do.
 * 
 * @param accountId
 *        The account id that identifies the latch being checked.
 * @param operationId
 *        The operation id that identifies the latch being
 *        checked. If the application has no operations, it should
 *        be null.
 * 
 * @return The status of the latch.
 * 
 * @throws LatchErrorException
 *         If the backend returns a JSON with an error.
 */
public LatchSDKStatus parsedStatus(String accountId, String operationId) throws LatchErrorException {

    Utils.checkMethodRequiredParameter(LOG, "accountId", accountId);

    /* The default status is UNKNOWN */

    LatchSDKStatus rv = LatchSDKStatus.UNKNOWN;

    /* Connect to the server and get the JSON response to the status request */

    LatchResponse latchResponse = null;

    try {

        if (operationId == null) {
            latchResponse = status(accountId);
        } else {
            latchResponse = operationStatus(accountId, operationId);
        }

    } catch (Exception e) {
        LOG.error("And exception has been thrown when communicating with Latch backend", e);
        return rv;
    }

    /* Check if a response has been received and parsed correctly */

    if (latchResponse != null) {

        if (latchResponse.getData() != null) {

            /* The backend has responded with data */

            JsonObject jsonObject = (JsonObject) latchResponse.getData();

            if (jsonObject.has("operations")) {

                JsonObject operations = jsonObject.getAsJsonObject("operations");
                JsonObject latch = null;

                if (operationId == null) {
                    if (operations.has(applicationId)) {
                        latch = operations.getAsJsonObject(applicationId);
                    }
                } else {
                    if (operations.has(operationId)) {
                        latch = operations.getAsJsonObject(operationId);
                    }
                }

                if (latch != null && latch.has("status")) {
                    if ("off".equals(latch.get("status").getAsString())) {
                        rv = LatchSDKStatus.LOCKED;
                    } else if ("on".equals(latch.get("status").getAsString())) {
                        rv = LatchSDKStatus.UNLOCKED;
                    }
                }

            }

        } else if (latchResponse.getError() != null) {

            /* The backend has responded with an application error message */

            LOG.error(
                    "The backend has responded with an application error message: " + latchResponse.getError());
            throw new LatchErrorException(latchResponse.getError());

        }

    }

    return rv;

}