Example usage for com.google.gson JsonElement isJsonArray

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

Introduction

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

Prototype

public boolean isJsonArray() 

Source Link

Document

provides check for verifying if this element is an array or not.

Usage

From source file:com.googlesource.gerrit.plugins.oauth.CasOAuthService.java

License:Apache License

@Override
public OAuthUserInfo getUserInfo(OAuthToken token) throws IOException {
    final String protectedResourceUrl = String.format(PROTECTED_RESOURCE_URL, rootUrl);
    OAuthRequest request = new OAuthRequest(Verb.GET, protectedResourceUrl);
    Token t = new Token(token.getToken(), token.getSecret(), token.getRaw());
    service.signRequest(t, request);//from w  w w. ja v a2s. c o  m

    Response response = request.send();
    if (response.getCode() != HttpServletResponse.SC_OK) {
        throw new IOException(String.format("Status %s (%s) for request %s", response.getCode(),
                response.getBody(), request.getUrl()));
    }

    if (log.isDebugEnabled()) {
        log.debug("User info response: {}", response.getBody());
    }

    JsonElement userJson = JSON.newGson().fromJson(response.getBody(), JsonElement.class);
    if (!userJson.isJsonObject()) {
        throw new IOException(String.format("Invalid JSON '%s': not a JSON Object", userJson));
    }
    JsonObject jsonObject = userJson.getAsJsonObject();

    JsonElement id = jsonObject.get("id");
    if (id == null || id.isJsonNull()) {
        throw new IOException(String.format("CAS response missing id: %s", response.getBody()));
    }

    JsonElement attrListJson = jsonObject.get("attributes");
    if (attrListJson == null) {
        throw new IOException(String.format("CAS response missing attributes: %s", response.getBody()));
    }

    String email = null, name = null, login = null;

    if (attrListJson.isJsonArray()) {
        // It is possible for CAS to be configured to not return any attributes (email, name, login),
        // in which case,
        // CAS returns an empty JSON object "attributes":{}, rather than "null" or an empty JSON array
        // "attributes": []

        JsonArray attrJson = attrListJson.getAsJsonArray();
        for (JsonElement elem : attrJson) {
            if (elem == null || !elem.isJsonObject()) {
                throw new IOException(String.format("Invalid JSON '%s': not a JSON Object", elem));
            }
            JsonObject obj = elem.getAsJsonObject();

            String property = getStringElement(obj, "email");
            if (property != null)
                email = property;
            property = getStringElement(obj, "name");
            if (property != null)
                name = property;
            property = getStringElement(obj, "login");
            if (property != null)
                login = property;
        }
    }

    return new OAuthUserInfo(CAS_PROVIDER_PREFIX + id.getAsString(), login, email, name,
            fixLegacyUserId ? id.getAsString() : null);
}

From source file:com.gst.batch.service.ResolutionHelper.java

License:Apache License

private JsonElement resolveDependentVariables(final Entry<String, JsonElement> entryElement,
        final JsonModel responseJsonModel) {
    JsonElement value = null;/* w ww.  j a  va 2 s .  c  om*/

    final JsonElement element = entryElement.getValue();

    if (element.isJsonObject()) {
        final JsonObject jsObject = element.getAsJsonObject();
        value = processJsonObject(jsObject, responseJsonModel);
    } else if (element.isJsonArray()) {
        final JsonArray jsElementArray = element.getAsJsonArray();
        value = processJsonArray(jsElementArray, responseJsonModel);
    } else {
        value = resolveDependentVariable(element, responseJsonModel);
    }
    return value;
}

From source file:com.haulmont.cuba.core.app.importexport.EntityImportViewBuilder.java

License:Apache License

protected EntityImportView buildFromJsonObject(JsonObject jsonObject, MetaClass metaClass) {
    EntityImportView view = new EntityImportView(metaClass.getJavaClass());

    for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
        String propertyName = entry.getKey();
        MetaProperty metaProperty = metaClass.getProperty(propertyName);
        if (metaProperty != null) {
            Range propertyRange = metaProperty.getRange();
            Class<?> propertyType = metaProperty.getJavaType();
            if (propertyRange.isDatatype() || propertyRange.isEnum()) {
                if (security.isEntityAttrUpdatePermitted(metaClass, propertyName))
                    view.addLocalProperty(propertyName);
            } else if (propertyRange.isClass()) {
                if (Entity.class.isAssignableFrom(propertyType)) {
                    if (metadataTools.isEmbedded(metaProperty)) {
                        MetaClass propertyMetaClass = metadata.getClass(propertyType);
                        JsonElement propertyJsonObject = entry.getValue();
                        if (!propertyJsonObject.isJsonObject()) {
                            throw new RuntimeException("JsonObject was expected for property " + propertyName);
                        }/*  ww w .j  av a 2 s  . c  o  m*/
                        if (security.isEntityAttrUpdatePermitted(metaClass, propertyName)) {
                            EntityImportView propertyImportView = buildFromJsonObject(
                                    propertyJsonObject.getAsJsonObject(), propertyMetaClass);
                            view.addEmbeddedProperty(propertyName, propertyImportView);
                        }
                    } else {
                        MetaClass propertyMetaClass = metadata.getClass(propertyType);
                        if (metaProperty.getType() == MetaProperty.Type.COMPOSITION) {
                            JsonElement propertyJsonObject = entry.getValue();
                            if (security.isEntityAttrUpdatePermitted(metaClass, propertyName)) {
                                if (propertyJsonObject.isJsonNull()) {
                                    //in case of null we must add such import behavior to update the reference with null value later
                                    if (metaProperty.getRange()
                                            .getCardinality() == Range.Cardinality.MANY_TO_ONE) {
                                        view.addManyToOneProperty(propertyName,
                                                ReferenceImportBehaviour.IGNORE_MISSING);
                                    } else {
                                        view.addOneToOneProperty(propertyName,
                                                ReferenceImportBehaviour.IGNORE_MISSING);
                                    }
                                } else {
                                    if (!propertyJsonObject.isJsonObject()) {
                                        throw new RuntimeException(
                                                "JsonObject was expected for property " + propertyName);
                                    }
                                    EntityImportView propertyImportView = buildFromJsonObject(
                                            propertyJsonObject.getAsJsonObject(), propertyMetaClass);
                                    if (metaProperty.getRange()
                                            .getCardinality() == Range.Cardinality.MANY_TO_ONE) {
                                        view.addManyToOneProperty(propertyName, propertyImportView);
                                    } else {
                                        view.addOneToOneProperty(propertyName, propertyImportView);
                                    }
                                }
                            }
                        } else {
                            if (security.isEntityAttrUpdatePermitted(metaClass, propertyName))
                                if (metaProperty.getRange().getCardinality() == Range.Cardinality.MANY_TO_ONE) {
                                    view.addManyToOneProperty(propertyName,
                                            ReferenceImportBehaviour.ERROR_ON_MISSING);
                                } else {
                                    view.addOneToOneProperty(propertyName,
                                            ReferenceImportBehaviour.ERROR_ON_MISSING);
                                }
                        }
                    }
                } else if (Collection.class.isAssignableFrom(propertyType)) {
                    MetaClass propertyMetaClass = metaProperty.getRange().asClass();
                    switch (metaProperty.getRange().getCardinality()) {
                    case MANY_TO_MANY:
                        if (security.isEntityAttrUpdatePermitted(metaClass, propertyName))
                            view.addManyToManyProperty(propertyName, ReferenceImportBehaviour.ERROR_ON_MISSING,
                                    CollectionImportPolicy.REMOVE_ABSENT_ITEMS);
                        break;
                    case ONE_TO_MANY:
                        if (metaProperty.getType() == MetaProperty.Type.COMPOSITION) {
                            JsonElement compositionJsonArray = entry.getValue();
                            if (!compositionJsonArray.isJsonArray()) {
                                throw new RuntimeException(
                                        "JsonArray was expected for property " + propertyName);
                            }
                            EntityImportView propertyImportView = buildFromJsonArray(
                                    compositionJsonArray.getAsJsonArray(), propertyMetaClass);
                            if (security.isEntityAttrUpdatePermitted(metaClass, propertyName))
                                view.addOneToManyProperty(propertyName, propertyImportView,
                                        CollectionImportPolicy.REMOVE_ABSENT_ITEMS);
                        }
                        break;
                    }
                }
            }
        }
    }

    return view;
}

From source file:com.haulmont.restapi.service.filter.RestFilterParser.java

License:Apache License

protected RestFilterPropertyCondition parsePropertyCondition(JsonObject conditionJsonObject,
        MetaClass metaClass) throws RestFilterParseException {
    RestFilterPropertyCondition condition = new RestFilterPropertyCondition();

    JsonElement propertyJsonElem = conditionJsonObject.get("property");
    if (propertyJsonElem == null) {
        throw new RestFilterParseException("Field 'property' is not defined for filter condition");
    }// w w  w . j  a va  2  s.  c  o  m
    String propertyName = propertyJsonElem.getAsString();

    JsonElement operatorJsonElem = conditionJsonObject.get("operator");
    if (operatorJsonElem == null) {
        throw new RestFilterParseException("Field 'operator' is not defined for filter condition");
    }
    String operator = operatorJsonElem.getAsString();
    Op op = findOperator(operator);

    boolean isValueRequired = op != Op.NOT_EMPTY;
    JsonElement valueJsonElem = conditionJsonObject.get("value");
    if (valueJsonElem == null && isValueRequired) {
        throw new RestFilterParseException("Field 'value' is not defined for filter condition");
    }

    MetaPropertyPath propertyPath = metaClass.getPropertyPath(propertyName);
    if (propertyPath == null) {
        throw new RestFilterParseException(
                "Property for " + metaClass.getName() + " not found: " + propertyName);
    }
    MetaProperty metaProperty = propertyPath.getMetaProperty();

    EnumSet<Op> opsAvailableForJavaType = opManager.availableOps(metaProperty.getJavaType());
    if (!opsAvailableForJavaType.contains(op)) {
        throw new RestFilterParseException("Operator " + operator + " is not available for java type "
                + metaProperty.getJavaType().getCanonicalName());
    }

    if (metaProperty.getRange().isClass()) {
        if (Entity.class.isAssignableFrom(metaProperty.getJavaType())) {
            MetaClass _metaClass = metadata.getClass(metaProperty.getJavaType());
            MetaProperty primaryKeyProperty = metadata.getTools().getPrimaryKeyProperty(_metaClass);
            String pkName = primaryKeyProperty.getName();
            propertyName += "." + pkName;
            propertyPath = metaClass.getPropertyPath(propertyName);
            if (propertyPath == null) {
                throw new RestFilterParseException(
                        "Property " + propertyName + " for " + metaClass.getName() + " not found");
            }
            metaProperty = propertyPath.getMetaProperty();
        }
    }

    if (isValueRequired) {
        Object value = null;
        if (op == Op.IN || op == Op.NOT_IN) {
            if (!valueJsonElem.isJsonArray()) {
                throw new RestFilterParseException(
                        "JSON array was expected as a value for condition with operator " + operator);
            }
            List<Object> parsedArrayValues = new ArrayList<>();
            for (JsonElement arrayItemElem : valueJsonElem.getAsJsonArray()) {
                parsedArrayValues.add(parseValue(metaProperty, arrayItemElem.getAsString()));
            }
            value = parsedArrayValues;
        } else {
            value = parseValue(metaProperty, valueJsonElem.getAsString());
        }
        condition.setValue(transformValue(value, op));
        condition.setQueryParamName(generateQueryParamName());
    }

    condition.setPropertyName(propertyName);
    condition.setOperator(op);

    return condition;
}

From source file:com.hbm.devices.jet.JetPeer.java

License:Open Source License

@Override
public void update(Observable observable, Object obj) {
    try {/*from   w w w  .j  ava2s  . c o m*/
        JsonElement element = parser.parse((String) obj);
        if (element == null) {
            return;
        }

        if (element.isJsonObject()) {
            handleSingleJsonMessage((JsonObject) element);
        } else if (element.isJsonArray()) {
            JsonArray array = (JsonArray) element;
            for (int i = 0; i < array.size(); i++) {
                JsonElement e = array.get(i);
                if (e.isJsonObject()) {
                    handleSingleJsonMessage((JsonObject) e);
                }
            }
        }
    } catch (JsonSyntaxException e) {
        /*
         * There is no error handling necessary in this case. If somebody sends us invalid JSON,
         * we just ignore the packet and go ahead.
         */
        LOGGER.log(Level.SEVERE, "Can't parse JSON!", e);
    }
}

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  . j a v  a 2 s  .  c  o  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.heliosapm.shorthand.instrumentor.shorthand.ShorthandJSONScript.java

License:Open Source License

/**
 * Parses a shorthand json script and returns an array of script objects
 * @param scriptText The json script/*  ww w  .  ja v a  2  s.  c  om*/
 * @return an array of script objects
 */
public static ShorthandJSONScript[] parse(String scriptText) {
    JsonElement element = new JsonParser().parse(scriptText);
    if (element.isJsonArray()) {
        return GsonProvider.getInstance().getGson().fromJson(scriptText, ShorthandJSONScript[].class);
    }
    return new ShorthandJSONScript[] {
            GsonProvider.getInstance().getGson().fromJson(scriptText, ShorthandJSONScript.class) };
}

From source file:com.hkm.disqus.api.gson.ApplicationsUsageDeserializer.java

License:Apache License

@Override
public Usage deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    // JSON element should be an array
    if (json.isJsonArray()) {
        // Create usage
        Usage usage = new Usage();

        // Iterate the array
        for (JsonElement element : json.getAsJsonArray()) {
            // Each element should be an array containing a date and int
            if (element.isJsonArray() && element.getAsJsonArray().size() == 2) {
                JsonArray jsonArray = element.getAsJsonArray();
                Date date = context.deserialize(jsonArray.get(0), Date.class);
                int count = jsonArray.get(1).getAsInt();
                usage.put(date, count);/*w ww  .j a  va2s  .  com*/
            }
        }
        return usage;
    }
    return null;
}

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  av  a 2  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());
            }/* w w w  . j a v a2 s .  c  om*/

            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);
}