Example usage for com.google.gson JsonNull INSTANCE

List of usage examples for com.google.gson JsonNull INSTANCE

Introduction

In this page you can find the example usage for com.google.gson JsonNull INSTANCE.

Prototype

JsonNull INSTANCE

To view the source code for com.google.gson JsonNull INSTANCE.

Click Source Link

Document

singleton for JsonNull

Usage

From source file:monasca.common.middleware.FilterUtils.java

License:Apache License

private static void wrapRequestFromHttpV3Response(ServletRequest req, String data) {
    StringBuilder tenants = new StringBuilder();
    StringBuilder nonTenants = new StringBuilder();
    JsonParser jp = new JsonParser();
    JsonObject token = jp.parse(data).getAsJsonObject().get("token").getAsJsonObject();
    // Domain Scoped Token
    if (token.get("domain") != null) {
        JsonObject domain = token.get("domain").getAsJsonObject();
        req.setAttribute(AUTH_DOMAIN_ID, domain.get("id").getAsString());
        if (domain.get("name") != null) {
            req.setAttribute(AUTH_DOMAIN_NAME, domain.get("name").getAsString());
        }//from   www  .j  a  va2 s .  com
    }
    // Project Scoped Token
    if (token.get("project") != null) {
        JsonObject project = token.get("project").getAsJsonObject();
        req.setAttribute(AUTH_PROJECT_ID, project.get("id").getAsString());
        req.setAttribute(AUTH_PROJECT_NAME, project.get("name").getAsString());

        JsonObject projectDomain = project.get("domain").getAsJsonObject();
        // special case where the value of id is null and the
        // projectDomain.get("id") != null
        if (!projectDomain.get("id").equals(JsonNull.INSTANCE)) {
            req.setAttribute(AUTH_PROJECT_DOMAIN_ID, projectDomain.get("id").getAsString());
        }
        if (projectDomain.get("name") != null) {
            req.setAttribute(AUTH_PROJECT_DOMAIN_NAME, projectDomain.get("name"));
        }
    }
    // User info
    if (token.get("user") != null) {
        JsonObject user = token.get("user").getAsJsonObject();
        req.setAttribute(AUTH_USER_ID, user.get("id").getAsString());
        req.setAttribute(AUTH_USER_NAME, user.get("name").getAsString());

        JsonObject userDomain = user.get("domain").getAsJsonObject();
        if (userDomain.get("id") != null) {
            req.setAttribute(AUTH_USER_DOMAIN_ID, userDomain.get("id").getAsString());
        }
        if (userDomain.get("name") != null) {
            req.setAttribute(AUTH_USER_DOMAIN_NAME, userDomain.get("name").getAsString());
        }

    }
    // Roles
    JsonArray roles = token.getAsJsonArray("roles");
    if (roles != null) {
        Iterator<JsonElement> it = roles.iterator();
        StringBuilder roleBuilder = new StringBuilder();
        while (it.hasNext()) {

            //Changed to meet my purposes
            JsonObject role = it.next().getAsJsonObject();
            String currentRole = role.get("name").getAsString();
            roleBuilder.append(currentRole).append(",");
        }
        //My changes to meet my needs
        req.setAttribute(AUTH_ROLES, roleBuilder.toString());
    }
    String tenantRoles = (tenants.length() > 0) ? tenants.substring(1) : tenants.toString();
    String nonTenantRoles = (nonTenants.length() > 0) ? nonTenants.substring(1) : nonTenants.toString();
    if (!tenantRoles.equals("")) {
        req.setAttribute(AUTH_ROLES, tenantRoles);
    }
    if (!nonTenantRoles.equals("")) {
        req.setAttribute(AUTH_HP_IDM_ROLES, nonTenantRoles);
    }
    // Catalog
    if (token.get("catalog") != null && appConfig.isIncludeCatalog()) {
        JsonArray catalog = token.get("catalog").getAsJsonArray();
        req.setAttribute(AUTH_SERVICE_CATALOG, catalog.toString());
    }
}

From source file:net.javacrumbs.jsonunit.core.internal.GsonNodeFactory.java

License:Apache License

@Override
protected Node nullNode() {
    return newNode(JsonNull.INSTANCE);
}

From source file:net.karlmartens.platform.datatable.DataTableCell.java

License:Apache License

private static JsonElement creasteJsonElement(Object o) {
    if (o == null)
        return JsonNull.INSTANCE;

    if (o instanceof String)
        return new JsonPrimitive((String) o);

    if (o instanceof Boolean)
        return new JsonPrimitive((Boolean) o);

    if (o instanceof Number)
        return new JsonPrimitive((Number) o);

    if (o instanceof BaseLocal) {
        final BaseLocal date = (BaseLocal) o;
        final JsonObject json = new JsonObject();
        json.add("year", createJsonElement(DateTimeFieldType.year(), date));
        json.add("month", createJsonElement(DateTimeFieldType.monthOfYear(), date));
        json.add("day", createJsonElement(DateTimeFieldType.dayOfMonth(), date));
        json.add("hour", createJsonElement(DateTimeFieldType.hourOfDay(), date));
        json.add("minute", createJsonElement(DateTimeFieldType.minuteOfHour(), date));
        json.add("second", createJsonElement(DateTimeFieldType.secondOfMinute(), date));
        json.add("millis", createJsonElement(DateTimeFieldType.millisOfSecond(), date));
        return json;
    }//  www .ja  v  a 2 s.co  m

    throw new UnsupportedOperationException();
}

From source file:net.karlmartens.platform.datatable.DataTableCell.java

License:Apache License

private static JsonElement createJsonElement(DateTimeFieldType field, BaseLocal local) {
    if (!local.isSupported(field))
        return JsonNull.INSTANCE;

    return new JsonPrimitive(local.get(field));
}

From source file:net.karlmartens.platform.datatable.DataTableColumn.java

License:Apache License

public JsonElement toJson() {
    final JsonObject json = new JsonObject();
    json.addProperty("id", _id);
    json.addProperty("label", _label);
    json.addProperty("pattern", _pattern);
    json.add("role", _role == null ? JsonNull.INSTANCE : _role.toJson());
    json.add("type", _type == null ? JsonNull.INSTANCE : _type.toJson());
    return json;//  w  ww  .  j av a 2 s . c om
}

From source file:nl.talsmasoftware.enumerables.support.json.gson.EnumerableSerializer.java

License:Apache License

private static JsonElement jsonString(String object) {
    return object != null ? new JsonPrimitive(object) : JsonNull.INSTANCE;
}

From source file:nl.talsmasoftware.enumerables.support.json.gson.EnumerableSerializer.java

License:Apache License

protected JsonElement serialize(Object value) {
    if (value == null)
        return JsonNull.INSTANCE;
    else if (value instanceof CharSequence)
        return new JsonPrimitive(value.toString());
    else if (value instanceof Number)
        return new JsonPrimitive((Number) value);
    else if (value instanceof Character)
        return new JsonPrimitive((Character) value);
    else if (value instanceof Boolean)
        return new JsonPrimitive((Boolean) value);
    // Otherwise, reflect the value
    JsonObject result = new JsonObject();
    for (Map.Entry<String, Object> property : getPropertyValues(value).entrySet()) {
        if (!"class".equals(property.getKey()))
            result.add(property.getKey(), serialize(property.getValue()));
    }//  w  w w  .j  a  v  a  2  s  . c  o m
    return result;
}

From source file:org.apache.edgent.runtime.jsoncontrol.JsonControlService.java

License:Apache License

/**
 * Handle a JSON control request./*from ww  w . j a  v a2 s .com*/
 * 
 * The control action is executed directly
 * using the calling thread.
 * 
 * @param request the request
 * @return JSON response, JSON null if the request was not recognized.
 * @throws Exception on failure
 */
public JsonElement controlRequest(JsonObject request) throws Exception {
    if (request.has(OP_KEY))
        return controlOperation(request);

    return JsonNull.INSTANCE;
}

From source file:org.apache.gobblin.converter.avro.JsonRecordAvroSchemaToAvroConverter.java

License:Apache License

public static GenericRecord convertNestedRecord(Schema outputSchema, JsonObject inputRecord,
        WorkUnitState workUnit, List<String> ignoreFields) throws DataConversionException {
    GenericRecord avroRecord = new GenericData.Record(outputSchema);
    JsonElementConversionWithAvroSchemaFactory.JsonElementConverter converter;
    for (Schema.Field field : outputSchema.getFields()) {

        if (ignoreFields.contains(field.name())) {
            continue;
        }//from ww  w . j av  a 2  s .  c o m

        Schema.Type type = field.schema().getType();
        boolean nullable = false;
        Schema schema = field.schema();

        if (type.equals(Schema.Type.UNION)) {
            nullable = true;
            List<Schema> types = field.schema().getTypes();
            if (types.size() != 2) {
                throw new DataConversionException("Unions must be size 2, and contain one null");
            }
            if (field.schema().getTypes().get(0).getType().equals(Schema.Type.NULL)) {
                schema = field.schema().getTypes().get(1);
                type = schema.getType();
            } else if (field.schema().getTypes().get(1).getType().equals(Schema.Type.NULL)) {
                schema = field.schema().getTypes().get(0);
                type = schema.getType();
            } else {
                throw new DataConversionException("Unions must be size 2, and contain one null");
            }

            if (inputRecord.get(field.name()) == null) {
                inputRecord.add(field.name(), JsonNull.INSTANCE);
            }
        }

        if (inputRecord.get(field.name()) == null) {
            throw new DataConversionException("Field missing from record: " + field.name());
        }

        if (type.equals(Schema.Type.RECORD)) {
            if (nullable && inputRecord.get(field.name()).isJsonNull()) {
                avroRecord.put(field.name(), null);
            } else {
                avroRecord.put(field.name(), convertNestedRecord(schema,
                        inputRecord.get(field.name()).getAsJsonObject(), workUnit, ignoreFields));
            }
        } else {
            try {
                converter = JsonElementConversionWithAvroSchemaFactory.getConvertor(field.name(),
                        type.getName(), schema, workUnit, nullable, ignoreFields);
                avroRecord.put(field.name(), converter.convert(inputRecord.get(field.name())));
            } catch (Exception e) {
                throw new DataConversionException("Could not convert field " + field.name(), e);
            }
        }
    }
    return avroRecord;
}

From source file:org.apache.gobblin.converter.csv.CsvToJsonConverter.java

License:Apache License

/**
 * Takes in a record with format String and splits the data based on SOURCE_SCHEMA_DELIMITER
 * Uses the inputSchema and the split record to convert the record to a JsonObject
 * @return a JsonObject representing the record
 * @throws DataConversionException//from ww w .  ja v a2  s .c  om
 */
@Override
public Iterable<JsonObject> convertRecord(JsonArray outputSchema, String inputRecord, WorkUnitState workUnit)
        throws DataConversionException {
    try {
        String strDelimiter = workUnit.getProp(ConfigurationKeys.CONVERTER_CSV_TO_JSON_DELIMITER);
        if (Strings.isNullOrEmpty(strDelimiter)) {
            throw new IllegalArgumentException("Delimiter cannot be empty");
        }
        InputStreamCSVReader reader = new InputStreamCSVReader(inputRecord, strDelimiter.charAt(0),
                workUnit.getProp(ConfigurationKeys.CONVERTER_CSV_TO_JSON_ENCLOSEDCHAR,
                        ConfigurationKeys.DEFAULT_CONVERTER_CSV_TO_JSON_ENCLOSEDCHAR).charAt(0));
        List<String> recordSplit;
        recordSplit = Lists.newArrayList(reader.splitRecord());
        JsonObject outputRecord = new JsonObject();

        for (int i = 0; i < outputSchema.size(); i++) {
            if (i < recordSplit.size()) {
                if (recordSplit.get(i) == null) {
                    outputRecord.add(outputSchema.get(i).getAsJsonObject().get("columnName").getAsString(),
                            JsonNull.INSTANCE);
                } else if (recordSplit.get(i).isEmpty() || recordSplit.get(i).toLowerCase().equals(NULL)) {
                    outputRecord.add(outputSchema.get(i).getAsJsonObject().get("columnName").getAsString(),
                            JsonNull.INSTANCE);
                } else {
                    outputRecord.addProperty(
                            outputSchema.get(i).getAsJsonObject().get("columnName").getAsString(),
                            recordSplit.get(i));
                }
            } else {
                outputRecord.add(outputSchema.get(i).getAsJsonObject().get("columnName").getAsString(),
                        JsonNull.INSTANCE);
            }
        }

        return new SingleRecordIterable<>(outputRecord);
    } catch (Exception e) {
        throw new DataConversionException(e);
    }
}