Example usage for com.google.gson JsonElement getAsJsonPrimitive

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

Introduction

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

Prototype

public JsonPrimitive getAsJsonPrimitive() 

Source Link

Document

convenience method to get this element as a JsonPrimitive .

Usage

From source file:gov.nasa.jpf.jdart.summaries.json.VariableHandler.java

License:Open Source License

@Override
public Variable<?> deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
        throws JsonParseException {
    try {//from  ww  w  .  j a va2 s . c  o m
        Expression<Boolean> expr = ParserUtil.parseVariable(je.getAsJsonPrimitive().getAsString());
        return (Variable<?>) expr;
    } catch (RecognitionException ex) {
        throw new JsonParseException(ex);
    }
}

From source file:gsonlib.GsonTransfer.java

public static void transferJsonResponseParamMap(JsonObject inJson, JsonObject outJson,
        Map<String, String> ctxMap) {

    Set<Map.Entry<String, JsonElement>> inJsonEntrySet = inJson.entrySet();

    for (Map.Entry<String, JsonElement> inJsonEntry : inJsonEntrySet) {
        String inJsonEntryKey = inJsonEntry.getKey();
        JsonElement inJsonEntryValue = inJsonEntry.getValue();

        JsonElement outJsonEntryValue = outJson.get(inJsonEntryKey);

        if (outJsonEntryValue != null) {
            if (inJsonEntryValue.isJsonPrimitive() && outJsonEntryValue.isJsonPrimitive()) {
                JsonPrimitive inPrimitive = inJsonEntryValue.getAsJsonPrimitive();
                JsonPrimitive outPrimitive = outJsonEntryValue.getAsJsonPrimitive();
                ctxMap.put(inPrimitive.getAsString(), outPrimitive.getAsString());
            } else if (inJsonEntryValue.isJsonObject() && outJsonEntryValue.isJsonObject()) {
                JsonObject outJsonEntryValObj = outJsonEntryValue.getAsJsonObject();
                JsonObject inJsonEntryValObj = inJsonEntryValue.getAsJsonObject();
                transferJsonResponseParamMap(inJsonEntryValObj, outJsonEntryValObj, ctxMap);
            } else if (inJsonEntryValue.isJsonArray() && outJsonEntryValue.isJsonArray()) {
                JsonArray inJsonEntryValArr = inJsonEntryValue.getAsJsonArray();
                JsonArray outJsonEntryValArr = outJsonEntryValue.getAsJsonArray();
                int outSize = outJsonEntryValArr.size();
                for (int i = 0; i < inJsonEntryValArr.size(); i++) {
                    if (outSize > i) {
                        JsonElement inArrEle = inJsonEntryValArr.get(i);
                        JsonElement outArrEle = outJsonEntryValArr.get(i);
                        if (inArrEle.isJsonPrimitive() && outArrEle.isJsonPrimitive()) {
                            JsonPrimitive inPrimitive = inArrEle.getAsJsonPrimitive();
                            JsonPrimitive outPrimitive = outArrEle.getAsJsonPrimitive();
                            ctxMap.put(inPrimitive.getAsString(), outPrimitive.getAsString());
                        } else if (inArrEle.isJsonObject() && outArrEle.isJsonObject()) {
                            JsonObject outJsonEntryValObj = outArrEle.getAsJsonObject();
                            JsonObject inJsonEntryValObj = inArrEle.getAsJsonObject();
                            transferJsonResponseParamMap(inJsonEntryValObj, outJsonEntryValObj, ctxMap);
                        }// w w w  .jav a2s  .c o m
                    }
                }
            }
        }

    }

}

From source file:guru.qas.martini.report.column.ExceptionColumn.java

License:Apache License

@Override
public void addResult(State state, Cell cell, JsonObject o) {
    JsonArray array = o.getAsJsonArray(KEY_STEPS);
    int size = array.size();

    String value = null;/*from   w ww  . j av  a2  s. c o m*/
    for (int i = 0; null == value && i < size; i++) {
        JsonElement element = array.get(i);
        JsonObject step = element.getAsJsonObject();
        JsonElement keyElement = step.get(KEY_EXCEPTION);
        JsonPrimitive primitive = null != keyElement && keyElement.isJsonPrimitive()
                ? keyElement.getAsJsonPrimitive()
                : null;
        String stackTrace = null == primitive ? null : primitive.getAsString().trim();
        value = null != stackTrace && !stackTrace.isEmpty() ? stackTrace : null;
    }

    RichTextString richTextString = new XSSFRichTextString(value);
    cell.setCellValue(richTextString);
}

From source file:guru.qas.martini.report.column.TagColumn.java

License:Apache License

protected String getTag(JsonElement element) {
    JsonObject entry = element.getAsJsonObject();
    JsonElement nameElement = entry.get(KEY_NAME);
    String name = null == nameElement ? null : nameElement.getAsString();

    String tag = null;//from   ww  w.  j  a  v  a2s .  c o  m
    if (null != name) {
        JsonElement argumentElement = entry.get(KEY_ARGUMENT);
        JsonPrimitive primitive = null != argumentElement && argumentElement.isJsonPrimitive()
                ? argumentElement.getAsJsonPrimitive()
                : null;
        String argument = null == primitive ? "" : String.format("\"%s\"", primitive.getAsString());
        tag = String.format("@%s(%s)", name, argument);
    }
    return tag;
}

From source file:hdm.stuttgart.esell.router.GeneralObjectDeserializer.java

License:Apache License

public Object deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    if (json.isJsonNull()) {
        return null;
    } else if (json.isJsonPrimitive()) {
        JsonPrimitive primitive = json.getAsJsonPrimitive();
        if (primitive.isString()) {
            return primitive.getAsString();
        } else if (primitive.isNumber()) {
            return primitive.getAsNumber();
        } else if (primitive.isBoolean()) {
            return primitive.getAsBoolean();
        }//from  w  ww .j  ava 2  s .  c om
    } else if (json.isJsonArray()) {
        JsonArray array = json.getAsJsonArray();
        Object[] result = new Object[array.size()];
        int i = 0;
        for (JsonElement element : array) {
            result[i] = deserialize(element, null, context);
            ++i;
        }
        return result;
    } else if (json.isJsonObject()) {
        JsonObject object = json.getAsJsonObject();
        Map<String, Object> result = new HashMap<String, Object>();
        for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
            Object value = deserialize(entry.getValue(), null, context);
            result.put(entry.getKey(), value);
        }
        return result;
    } else {
        throw new JsonParseException("Unknown JSON type for JsonElement " + json.toString());
    }
    return null;
}

From source file:ilearn.orb.services.external.utils.UtilDateDeserializer.java

License:Open Source License

@Override
public java.util.Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    return new java.util.Date(json.getAsJsonPrimitive().getAsLong());
}

From source file:io.kodokojo.endpoint.ProjectSparkEndpoint.java

License:Open Source License

@Override
public void configure() {
    post(BASE_API + "/projectconfig", JSON_CONTENT_TYPE, (request, response) -> {
        String body = request.body();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Try to create project {}", body);
        }//  ww w .  ja va2  s.c o  m
        Gson gson = localGson.get();
        ProjectCreationDto dto = gson.fromJson(body, ProjectCreationDto.class);
        if (dto == null) {
            halt(400);
            return "";
        }
        User owner = userStore.getUserByIdentifier(dto.getOwnerIdentifier());
        String entityId = owner.getEntityIdentifier();
        if (StringUtils.isBlank(entityId)) {
            halt(400);
            return "";
        }

        Set<StackConfiguration> stackConfigurations = createDefaultStackConfiguration(dto.getName());
        if (CollectionUtils.isNotEmpty(dto.getStackConfigs())) {
            stackConfigurations = dto.getStackConfigs().stream().map(stack -> {
                Set<BrickConfiguration> brickConfigurations = stack.getBrickConfigs().stream().map(b -> {
                    Brick brick = brickFactory.createBrick(b.getName());
                    return new BrickConfiguration(brick);
                }).collect(Collectors.toSet());
                StackType stackType = StackType.valueOf(stack.getType());
                BootstrapStackData bootstrapStackData = projectManager.bootstrapStack(dto.getName(),
                        stack.getName(), stackType);
                return new StackConfiguration(stack.getName(), stackType, brickConfigurations,
                        bootstrapStackData.getLoadBalancerHost(), bootstrapStackData.getSshPort());
            }).collect(Collectors.toSet());
        }

        List<User> users = new ArrayList<>();
        users.add(owner);
        if (CollectionUtils.isNotEmpty(dto.getUserIdentifiers())) {
            for (String userId : dto.getUserIdentifiers()) {
                User user = userStore.getUserByIdentifier(userId);
                users.add(user);
            }
        }
        ProjectConfiguration projectConfiguration = new ProjectConfiguration(entityId, dto.getName(),
                Collections.singletonList(owner), stackConfigurations, users);
        String projectConfigIdentifier = projectStore.addProjectConfiguration(projectConfiguration);

        response.status(201);
        response.header("Location", "/projectconfig/" + projectConfigIdentifier);
        return projectConfigIdentifier;
    });

    get(BASE_API + "/projectconfig/:id", JSON_CONTENT_TYPE, (request, response) -> {
        String identifier = request.params(":id");
        ProjectConfiguration projectConfiguration = projectStore.getProjectConfigurationById(identifier);
        if (projectConfiguration == null) {
            halt(404);
            return "";
        }
        SimpleCredential credential = extractCredential(request);
        if (userStore.userIsAdminOfProjectConfiguration(credential.getUsername(), projectConfiguration)) {
            return new ProjectConfigDto(projectConfiguration);
        }
        halt(403);
        return "";
    }, jsonResponseTransformer);

    put(BASE_API + "/projectconfig/:id/user", JSON_CONTENT_TYPE, ((request, response) -> {
        SimpleCredential credential = extractCredential(request);

        String identifier = request.params(":id");
        ProjectConfiguration projectConfiguration = projectStore.getProjectConfigurationById(identifier);
        if (projectConfiguration == null) {
            halt(404);
            return "";
        }
        if (userStore.userIsAdminOfProjectConfiguration(credential.getUsername(), projectConfiguration)) {
            JsonParser parser = new JsonParser();
            JsonArray root = (JsonArray) parser.parse(request.body());
            List<User> users = IteratorUtils.toList(projectConfiguration.getUsers());
            List<User> usersToAdd = new ArrayList<>();
            for (JsonElement el : root) {
                String userToAddId = el.getAsJsonPrimitive().getAsString();
                User userToAdd = userStore.getUserByIdentifier(userToAddId);
                if (userToAdd != null && !users.contains(userToAdd)) {
                    users.add(userToAdd);
                    usersToAdd.add(userToAdd);
                }
            }

            projectConfiguration.setUsers(users);
            projectStore.updateProjectConfiguration(projectConfiguration);
            projectManager.addUsersToProject(projectConfiguration, usersToAdd);
        } else {
            halt(403, "You have not right to add user to project configuration id " + identifier + ".");
        }

        return "";
    }), jsonResponseTransformer);

    delete(BASE_API + "/projectconfig/:id/user", JSON_CONTENT_TYPE, ((request, response) -> {
        SimpleCredential credential = extractCredential(request);
        if (credential != null) {
            String identifier = request.params(":id");
            ProjectConfiguration projectConfiguration = projectStore.getProjectConfigurationById(identifier);
            if (projectConfiguration == null) {
                halt(404);
                return "";
            }
            if (userStore.userIsAdminOfProjectConfiguration(credential.getUsername(), projectConfiguration)) {
                JsonParser parser = new JsonParser();
                JsonArray root = (JsonArray) parser.parse(request.body());
                List<User> users = IteratorUtils.toList(projectConfiguration.getUsers());
                for (JsonElement el : root) {
                    String userToDeleteId = el.getAsJsonPrimitive().getAsString();
                    User userToDelete = userStore.getUserByIdentifier(userToDeleteId);
                    if (userToDelete != null) {
                        users.remove(userToDelete);
                    }
                }
                projectConfiguration.setUsers(users);
                projectStore.updateProjectConfiguration(projectConfiguration);
            } else {
                halt(403, "You have not right to delete user to project configuration id " + identifier + ".");
            }
        }
        return "";
    }), jsonResponseTransformer);

    //  -- Project

    //  Start project
    post(BASE_API + "/project/:id", JSON_CONTENT_TYPE, ((request, response) -> {
        SimpleCredential credential = extractCredential(request);
        if (credential != null) {
            User currentUser = userStore.getUserByUsername(credential.getUsername());
            String projectConfigurationId = request.params(":id");
            ProjectConfiguration projectConfiguration = projectStore
                    .getProjectConfigurationById(projectConfigurationId);
            if (projectConfiguration == null) {
                halt(404, "Project configuration not found.");
                return "";
            }
            if (userStore.userIsAdminOfProjectConfiguration(credential.getUsername(), projectConfiguration)) {
                String projectId = projectStore.getProjectIdByProjectConfigurationId(projectConfigurationId);
                if (StringUtils.isBlank(projectId)) {
                    //   projectManager.bootstrapStack(projectConfiguration.getName(), projectConfiguration.getDefaultStackConfiguration().getName(), projectConfiguration.getDefaultStackConfiguration().getType());
                    Project project = projectManager.start(projectConfiguration);
                    response.status(201);
                    String projectIdStarted = projectStore.addProject(project, projectConfigurationId);
                    return projectIdStarted;
                } else {
                    halt(409, "Project already exist.");
                }
            } else {
                halt(403,
                        "You have not right to start project configuration id " + projectConfigurationId + ".");
            }
        }
        return "";
    }));

    get(BASE_API + "/project/:id", JSON_CONTENT_TYPE, ((request, response) -> {
        SimpleCredential credential = extractCredential(request);
        if (credential != null) {
            User currentUser = userStore.getUserByUsername(credential.getUsername());
            String projectId = request.params(":id");
            Project project = projectStore.getProjectByIdentifier(projectId);
            if (project == null) {
                halt(404);
                return "";
            }
            ProjectConfiguration projectConfiguration = projectStore
                    .getProjectConfigurationById(project.getProjectConfigurationIdentifier());
            if (userStore.userIsAdminOfProjectConfiguration(currentUser.getUsername(), projectConfiguration)) {
                return new ProjectDto(project);
            } else {
                halt(403, "You have not right to lookup project id " + projectId + ".");
            }
        }
        return "";
    }), jsonResponseTransformer);
}

From source file:io.morea.handy.android.DateSerializer.java

License:Apache License

@Override
public Date deserialize(JsonElement jsonElement, Type type,
        JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
    try {//  ww w.j ava 2s  .  com
        return Util.dateFromIso8601(jsonElement.getAsJsonPrimitive().getAsString());
    } catch (ParseException e) {
        throw new JsonParseException(e);
    }
}

From source file:io.soliton.protobuf.json.JsonRpcRequest.java

License:Apache License

public static JsonRpcRequest fromJson(JsonElement root) throws JsonRpcError {
    if (!root.isJsonObject()) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "Received payload is not a JSON Object");
    }/* w w w  .ja  v a 2  s . c o  m*/

    JsonObject request = root.getAsJsonObject();
    JsonElement id = request.get(JsonRpcProtocol.ID);
    JsonElement methodNameElement = request.get(JsonRpcProtocol.METHOD);
    JsonElement paramsElement = request.get(JsonRpcProtocol.PARAMETERS);

    if (id == null) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "Malformed request, missing 'id' property");
    }

    if (methodNameElement == null) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "Malformed request, missing 'method' property");
    }

    if (paramsElement == null) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "Malformed request, missing 'params' property");
    }

    if (!methodNameElement.isJsonPrimitive()) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "Method name is not a JSON primitive");
    }

    JsonPrimitive methodName = methodNameElement.getAsJsonPrimitive();
    if (!methodName.isString()) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "Method name is not a string");
    }

    if (!paramsElement.isJsonArray()) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "'params' property is not an array");
    }

    JsonArray params = paramsElement.getAsJsonArray();
    if (params.size() != 1) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "'params' property is not an array");
    }

    JsonElement paramElement = params.get(0);
    if (!paramElement.isJsonObject()) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "Parameter is not an object");
    }

    JsonObject parameter = paramElement.getAsJsonObject();
    List<String> serviceAndMethod = Lists.newArrayList(DOT_SPLITTER.split(methodName.getAsString()));

    String methodNameString = methodName.getAsString();
    int dotIndex = methodNameString.lastIndexOf('.');

    if (dotIndex < 0) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "'method' property is not properly formatted");
    }

    if (dotIndex == methodNameString.length() - 1) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "'method' property is not properly formatted");
    }

    String service = methodNameString.substring(0, dotIndex);
    String method = methodNameString.substring(dotIndex + 1);

    if (service.isEmpty() || method.isEmpty()) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "'method' property is not properly formatted");
    }

    if (serviceAndMethod.size() < 2) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "'method' property is not properly formatted");
    }

    return new JsonRpcRequest(service, method, id, parameter);
}

From source file:io.thinger.thinger.DeviceResourceDescription.java

License:Open Source License

public DeviceResourceDescription(String resourceName, JsonElement resourceDescription) {
    this.resourceName = resourceName;
    this.resourceType = ResourceType.NONE;
    if (resourceDescription.isJsonObject()) {
        JsonObject object = resourceDescription.getAsJsonObject();
        if (object.has("fn")) {
            JsonElement function = object.get("fn");
            if (function.isJsonPrimitive()) {
                JsonPrimitive value = function.getAsJsonPrimitive();
                if (value.isNumber()) {
                    resourceType = ResourceType.get(value.getAsInt());
                }//from   w w w .j  av  a2s.c  o m
            }
        }
    }
}