Example usage for com.google.gson JsonElement isJsonPrimitive

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

Introduction

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

Prototype

public boolean isJsonPrimitive() 

Source Link

Document

provides check for verifying if this element is a primitive or not.

Usage

From source file:com.google.samples.apps.iosched.server.schedule.model.DataExtractor.java

License:Open Source License

public JsonArray extractSessions(JsonDataSources sources) {
    if (videoSessionsById == null) {
        throw new IllegalStateException(
                "You need to extract video sessions before attempting to extract sessions");
    }//from  ww w .  j  a  v  a 2s  . c om
    if (categoryToTagMap == null) {
        throw new IllegalStateException("You need to extract tags before attempting to extract sessions");
    }

    JsonArray result = new JsonArray();
    JsonDataSource source = sources.getSource(InputJsonKeys.VendorAPISource.MainTypes.topics.name());
    if (source != null) {
        for (JsonObject origin : source) {
            if (isVideoSession(origin)) {
                // Sessions with the Video tag are processed as video library content
                continue;
            }
            if (isHiddenSession(origin)) {
                // Sessions with a "Hidden from schedule" flag should be ignored
                continue;
            }
            JsonElement title = get(origin, InputJsonKeys.VendorAPISource.Topics.title);
            // Since the CMS returns an empty keynote as a session, we need to ignore it
            if (title != null && title.isJsonPrimitive() && "keynote".equalsIgnoreCase(title.getAsString())) {
                continue;
            }
            JsonObject dest = new JsonObject();

            // Some sessions require a special ID, so we replace it here...
            if (title != null && title.isJsonPrimitive()
                    && "after hours".equalsIgnoreCase(title.getAsString())) {
                set(new JsonPrimitive("__afterhours__"), dest, OutputJsonKeys.Sessions.id);
            } else {
                set(origin, InputJsonKeys.VendorAPISource.Topics.id, dest, OutputJsonKeys.Sessions.id);
            }
            set(origin, InputJsonKeys.VendorAPISource.Topics.id, dest, OutputJsonKeys.Sessions.url,
                    Converters.SESSION_URL);
            set(origin, InputJsonKeys.VendorAPISource.Topics.title, dest, OutputJsonKeys.Sessions.title,
                    obfuscate ? Converters.OBFUSCATE : null);
            set(origin, InputJsonKeys.VendorAPISource.Topics.description, dest,
                    OutputJsonKeys.Sessions.description, obfuscate ? Converters.OBFUSCATE : null);
            set(origin, InputJsonKeys.VendorAPISource.Topics.start, dest,
                    OutputJsonKeys.Sessions.startTimestamp, Converters.DATETIME);
            set(origin, InputJsonKeys.VendorAPISource.Topics.finish, dest, OutputJsonKeys.Sessions.endTimestamp,
                    Converters.DATETIME);
            set(new JsonPrimitive(isFeatured(origin)), dest, OutputJsonKeys.Sessions.isFeatured);

            JsonElement documents = get(origin, InputJsonKeys.VendorAPISource.Topics.documents);
            if (documents != null && documents.isJsonArray() && documents.getAsJsonArray().size() > 0) {
                // Note that the input for SessionPhotoURL is the entity ID. We simply ignore the original
                // photo URL, because that will be processed by an offline cron script, resizing the
                // photos and saving them to a known location with the entity ID as its base name.
                set(origin, InputJsonKeys.VendorAPISource.Topics.id, dest, OutputJsonKeys.Sessions.photoUrl,
                        Converters.SESSION_PHOTO_URL);
            }

            setVideoPropertiesInSession(origin, dest);
            setRelatedContent(origin, dest);

            JsonElement mainTag = null;
            JsonElement hashtag = null;
            JsonElement mainTagColor = null;
            JsonArray categories = origin
                    .getAsJsonArray(InputJsonKeys.VendorAPISource.Topics.categoryids.name());
            JsonArray tags = new JsonArray();
            for (JsonElement category : categories) {
                JsonObject tag = categoryToTagMap.get(category.getAsString());
                if (tag != null) {
                    JsonElement tagName = get(tag, OutputJsonKeys.Tags.tag);
                    tags.add(tagName);
                    usedTags.add(tagName.getAsString());

                    if (mainTag == null) {
                        // check if the tag is from a "default" category. For example, if THEME is the default
                        // category, all sessions will have a "mainTag" property set to the first tag of type THEME
                        JsonElement tagCategory = get(tag, OutputJsonKeys.Tags.category); // THEME, TYPE or TOPIC
                        if (tagCategory.equals(mainCategory)) {
                            mainTag = tagName;
                            mainTagColor = get(tag, OutputJsonKeys.Tags.color);
                        }
                        if (hashtag == null && isHashtag(tag)) {
                            hashtag = get(tag, OutputJsonKeys.Tags.hashtag);
                            if (hashtag == null || hashtag.getAsString() == null
                                    || hashtag.getAsString().isEmpty()) {
                                // If no hashtag set in the tagsconf file, we will convert the tagname to find one:
                                hashtag = new JsonPrimitive(
                                        get(tag, OutputJsonKeys.Tags.name, Converters.TAG_NAME).getAsString()
                                                .toLowerCase());
                            }
                        }
                    }
                }
            }
            set(tags, dest, OutputJsonKeys.Sessions.tags);
            if (mainTag != null) {
                set(mainTag, dest, OutputJsonKeys.Sessions.mainTag);
            }
            if (mainTagColor != null) {
                set(mainTagColor, dest, OutputJsonKeys.Sessions.color);
            }
            if (hashtag != null) {
                set(hashtag, dest, OutputJsonKeys.Sessions.hashtag);
            }

            JsonArray speakers = getAsArray(origin, InputJsonKeys.VendorAPISource.Topics.speakerids);
            if (speakers != null)
                for (JsonElement speaker : speakers) {
                    String speakerId = speaker.getAsString();
                    usedSpeakers.add(speakerId);
                }
            set(speakers, dest, OutputJsonKeys.Sessions.speakers);

            JsonArray sessions = origin.getAsJsonArray(InputJsonKeys.VendorAPISource.Topics.sessions.name());
            if (sessions != null && sessions.size() > 0) {
                String roomId = get(sessions.get(0).getAsJsonObject(),
                        InputJsonKeys.VendorAPISource.Sessions.roomid).getAsString();
                roomId = Config.ROOM_MAPPING.getRoomId(roomId);
                set(new JsonPrimitive(roomId), dest, OutputJsonKeys.Sessions.room);

                // captions URL is set based on the session room, so keep it here.
                String captionsURL = Config.ROOM_MAPPING.getCaptions(roomId);
                if (captionsURL != null) {
                    set(new JsonPrimitive(captionsURL), dest, OutputJsonKeys.Sessions.captionsUrl);
                }
            }

            if (Config.DEBUG_FIX_DATA) {
                DebugDataExtractorHelper.changeSession(dest, usedTags);
            }
            result.add(dest);
        }
    }
    return result;
}

From source file:com.haulmont.restapi.common.RestParseUtils.java

License:Apache License

public Map<String, String> parseParamsJson(String paramsJson) {
    Map<String, String> result = new LinkedHashMap<>();
    if (Strings.isNullOrEmpty(paramsJson))
        return result;

    JsonParser jsonParser = new JsonParser();
    JsonObject jsonObject = jsonParser.parse(paramsJson).getAsJsonObject();

    for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
        String paramName = entry.getKey();
        JsonElement paramValue = entry.getValue();
        if (paramValue.isJsonNull()) {
            result.put(paramName, null);
        } else if (paramValue.isJsonPrimitive()) {
            result.put(paramName, paramValue.getAsString());
        } else {//ww  w.java  2  s .  c  om
            result.put(paramName, paramValue.toString());
        }
    }

    return result;
}

From source file:com.haulmont.restapi.service.QueriesControllerManager.java

License:Apache License

protected Object toObject(Class clazz, String value) throws ParseException {
    if (clazz.isArray()) {
        Class componentType = clazz.getComponentType();
        JsonParser jsonParser = new JsonParser();
        JsonArray jsonArray = jsonParser.parse(value).getAsJsonArray();
        List result = new ArrayList();
        for (JsonElement jsonElement : jsonArray) {
            String stringValue = (jsonElement.isJsonPrimitive() && jsonElement.getAsJsonPrimitive().isString())
                    ? jsonElement.getAsJsonPrimitive().getAsString()
                    : jsonElement.toString();
            Object arrayElementValue = toObject(componentType, stringValue);
            result.add(arrayElementValue);
        }/* w  ww .j  a va2  s.c  om*/
        return result;
    }
    if (String.class == clazz)
        return value;
    if (Integer.class == clazz || Integer.TYPE == clazz || Byte.class == clazz || Byte.TYPE == clazz
            || Short.class == clazz || Short.TYPE == clazz)
        return Datatypes.getNN(Integer.class).parse(value);
    if (Date.class == clazz) {
        try {
            return Datatypes.getNN(Date.class).parse(value);
        } catch (ParseException e) {
            try {
                return Datatypes.getNN(java.sql.Date.class).parse(value);
            } catch (ParseException e1) {
                return Datatypes.getNN(Time.class).parse(value);
            }
        }
    }
    if (BigDecimal.class == clazz)
        return Datatypes.getNN(BigDecimal.class).parse(value);
    if (Boolean.class == clazz || Boolean.TYPE == clazz)
        return Datatypes.getNN(Boolean.class).parse(value);
    if (Long.class == clazz || Long.TYPE == clazz)
        return Datatypes.getNN(Long.class).parse(value);
    if (Double.class == clazz || Double.TYPE == clazz || Float.class == clazz || Float.TYPE == clazz)
        return Datatypes.getNN(Double.class).parse(value);
    if (UUID.class == clazz)
        return UUID.fromString(value);
    throw new IllegalArgumentException("Parameters of type " + clazz.getName() + " are not supported");
}

From source file:com.haulmont.restapi.service.RestServiceInvoker.java

License:Apache License

private void parseParamsJson(String paramsJson, List<String> paramValuesStr, List<Class> paramTypes) {
    if (Strings.isNullOrEmpty(paramsJson))
        return;//from  w  w  w  . j  a va  2  s.co  m
    JsonParser jsonParser = new JsonParser();
    JsonObject jsonObject = jsonParser.parse(paramsJson).getAsJsonObject();
    int idx = 0;
    while (true) {
        JsonElement nthParam = jsonObject.get("param" + idx);
        if (nthParam == null)
            break;
        if (nthParam.isJsonPrimitive()) {
            paramValuesStr.add(nthParam.getAsString());
        } else {
            paramValuesStr.add(nthParam.toString());
        }

        JsonElement nthParamType = jsonObject.get("param" + idx + "_type");
        if (nthParamType != null) {
            try {
                paramTypes.add(ClassUtils.forName(nthParamType.getAsString(), null));
            } catch (ClassNotFoundException e) {
                throw new RestAPIException("Error on evaluating parameter type", e.getMessage(),
                        HttpStatus.BAD_REQUEST, e);
            }
        }
        idx++;
    }
}

From source file:com.helion3.prism.util.DataUtil.java

License:MIT License

/**
 * Attempts to convert a JsonElement to an a known type.
 *
 * @param element JsonElement/*  w  w w. ja  va  2 s  . co  m*/
 * @return Optional<Object>
 */
private static Optional<Object> jsonElementToObject(JsonElement element) {
    Object result = null;

    if (element.isJsonObject()) {
        result = dataViewFromJson(element.getAsJsonObject());
    } else if (element.isJsonPrimitive()) {
        JsonPrimitive prim = element.getAsJsonPrimitive();

        if (prim.isBoolean()) {
            result = prim.getAsBoolean();
        } else if (prim.isNumber()) {
            result = prim.getAsNumber().intValue();
        } else if (prim.isString()) {
            result = prim.getAsString();
        }
    } else if (element.isJsonArray()) {
        List<Object> list = new ArrayList<Object>();
        JsonArray arr = element.getAsJsonArray();
        arr.forEach(new Consumer<JsonElement>() {
            @Override
            public void accept(JsonElement t) {
                Optional<Object> translated = jsonElementToObject(t);
                if (translated.isPresent()) {
                    list.add(translated.get());
                }
            }
        });

        result = list;
    }

    return Optional.ofNullable(result);
}

From source file:com.hp.ov.sdk.adaptors.PortTelemetrySerializationAdapter.java

License:Apache License

@Override
public PortTelemetry deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    if (json.isJsonPrimitive()) {
        return PortTelemetry.valueOf(json.getAsString());
    } else if (json.isJsonArray()) {
        for (JsonElement element : json.getAsJsonArray()) {
            String elementAsString = element.getAsString();

            if (PortTelemetry.contains(elementAsString)) {
                return PortTelemetry.valueOf(elementAsString);
            }//  ww  w.  j a v  a2  s  .c om
        }
    }
    throw new JsonParseException("Unknown port telemetry value type. "
            + "Expected value types are String or String[] (String array)");
}

From source file:com.hp.ov.sdk.adaptors.StorageCapabilitiesDeserializer.java

License:Apache License

@Override
public StorageCapabilities deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    if (json.isJsonArray()) {
        StorageCapabilities storageCapabilities = new StorageCapabilities();

        storageCapabilities.setControllerModes(Lists.newArrayList(ControllerMode.RAID));
        storageCapabilities.setDriveTechnologies(new ArrayList<DriveTechnology>());
        storageCapabilities.setRaidLevels(new ArrayList<RaidLevel>());

        Iterator<JsonElement> iterator = json.getAsJsonArray().iterator();

        while (iterator.hasNext()) {
            JsonElement element = iterator.next();

            if (!element.isJsonPrimitive()) {
                throw new JsonParseException(
                        "Expected a primitive (String) value but found " + element.toString());
            }/*  ww  w . j  av a2  s . c  o  m*/

            try {
                storageCapabilities.getRaidLevels().add(RaidLevel.valueOf(element.getAsString()));
            } catch (IllegalArgumentException e) {
                throw new JsonParseException("Unknown RAID Level", e);
            }
        }
        return storageCapabilities;
    }
    return new Gson().fromJson(json, StorageCapabilities.class);
}

From source file:com.hp.ov.sdk.adaptors.StoragePoolSerializationAdapter.java

License:Apache License

@Override
public StoragePool deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    Gson gson = new Gson();
    JsonElement allocatedCapacity = json.getAsJsonObject().remove(StoragePool.ALLOCATED_CAPACITY_FIELD);
    StoragePool storagePool = gson.fromJson(json, StoragePool.class);

    if (allocatedCapacity.isJsonPrimitive()) {
        storagePool.setAllocatedCapacity(allocatedCapacity.getAsString());
    } else {/*from ww  w . j a v a2 s.  com*/
        storagePool.setAllocatedCapacityDetails(gson.fromJson(allocatedCapacity, AllocatedCapacity.class));
    }
    return storagePool;
}

From source file:com.hybris.datahub.service.impl.DefaultJsonService.java

License:Open Source License

private String convertJsonValue(final JsonElement jsonElement) {
    if (jsonElement.isJsonPrimitive()) {
        return jsonElement.getAsString();
    } else if (jsonElement.isJsonNull()) {
        return "";
    } else {//from w ww  . j  av  a2 s.c om
        return jsonElement.toString();
    }
}

From source file:com.hybris.mobile.lib.http.converter.JsonDataConverter.java

License:Open Source License

/**
 * @param data     String of character to be parsed
 * @param property Attributes to be parse
 * @param element  JSON element to get data from
 * @return List of String//w ww  .ja v a  2  s.  co m
 */
protected List<String> getValuesFromPropertyElement(String data, String property, String element,
        boolean recursive) {
    List<String> listToReturn = new ArrayList<>();

    if (data == null) {
        throw new IllegalArgumentException();
    }

    JsonParser parser = new JsonParser();

    JsonArray jsonArray;
    JsonElement jsonElement;

    try {
        if (StringUtils.isNotBlank(property)) {
            jsonElement = parser.parse(data).getAsJsonObject().get(property);
        } else {
            jsonElement = parser.parse(data);
        }

        if (jsonElement != null) {
            if (jsonElement.isJsonArray()) {
                jsonArray = jsonElement.getAsJsonArray();
            } else {
                jsonArray = new JsonArray();
                jsonArray.add(jsonElement);
            }

            if (jsonArray != null) {

                for (JsonElement currentJsonElement : jsonArray) {

                    if (StringUtils.isNotBlank(element)) {
                        if (recursive) {
                            try {
                                listToReturn.addAll(getValuesFromPropertyElement(currentJsonElement.toString(),
                                        property, element, recursive));
                            } catch (NoSuchElementException e) {
                                Log.d(TAG, "End of getting the recursive property " + property + ".");
                            }
                        }

                        currentJsonElement = currentJsonElement.getAsJsonObject().get(element);
                    }

                    if (currentJsonElement != null) {
                        if (currentJsonElement.isJsonPrimitive()) {
                            listToReturn.add(currentJsonElement.getAsString());
                        } else {
                            listToReturn.add(currentJsonElement.toString());
                        }
                    } else {
                        Log.d(TAG, "No data found for element " + element + ".");
                    }

                }

            }

        } else {
            Log.d(TAG, "No data found on " + data + " for property " + property + ".");
        }
    } catch (Exception e) {
        Log.e(TAG, "Error parsing the data " + data + " for property " + property + " and element " + element
                + ".");
        throw new NoSuchElementException("Error parsing the data " + data + " for property " + property
                + " and element " + element + ".");
    }

    return listToReturn;

}