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:com.stackmob.sdk.model.StackMobModel.java

License:Apache License

protected void fillFieldFromJson(String jsonName, JsonElement json) throws StackMobException {
    try {//  www  . ja v a2  s .co m
        if (jsonName.equals(getIDFieldName())) {
            // The id field is special, its name doesn't match the field
            setID(json.getAsJsonPrimitive().getAsString());
        } else {
            // undo the toLowerCase we do when sending out the json
            String fieldName = getFieldName(jsonName);
            if (fieldName != null) {
                Field field = getField(fieldName);
                field.setAccessible(true);
                if (getMetadata(fieldName) == MODEL) {
                    // Delegate any expanded relations to the appropriate object
                    StackMobModel relatedModel = (StackMobModel) field.get(this);
                    // If there's a model with the same id, keep it. Otherwise create a new one
                    if (relatedModel == null || !relatedModel.hasSameID(json)) {
                        relatedModel = (StackMobModel) field.getType().newInstance();
                    }
                    relatedModel.fillFromJson(json);
                    field.set(this, relatedModel);
                } else if (getMetadata(fieldName) == MODEL_ARRAY) {
                    Class<? extends StackMobModel> actualModelClass = (Class<? extends StackMobModel>) SerializationMetadata
                            .getComponentClass(field);
                    Collection<StackMobModel> existingModels = getFieldAsCollection(field);
                    List<StackMobModel> newModels = updateModelListFromJson(json.getAsJsonArray(),
                            existingModels, actualModelClass);
                    setFieldFromList(field, newModels, actualModelClass);
                } else {
                    // Let gson do its thing
                    field.set(this, gson.fromJson(json, field.getType()));
                }
            }
        }
    } catch (NoSuchFieldException ignore) {
    } catch (IllegalAccessException e) {
        throw new StackMobException(e.getMessage());
    } catch (InstantiationException e) {
        throw new StackMobException(e.getMessage());
    }
}

From source file:com.stackmob.sdk.model.StackMobModel.java

License:Apache License

protected void fillFromJson(JsonElement json, List<String> selection) throws StackMobException {
    if (json.isJsonPrimitive()) {
        //This ought to be an unexpanded relation then
        setID(json.getAsJsonPrimitive().getAsString());
    } else {//from ww w  .  j av  a  2 s . com
        for (Map.Entry<String, JsonElement> jsonField : json.getAsJsonObject().entrySet()) {
            if (selection == null || selection.contains(jsonField.getKey())) {
                fillFieldFromJson(jsonField.getKey(), jsonField.getValue());
            }
        }
        hasData = true;
    }
}

From source file:com.stackmob.sdk.model.StackMobModel.java

License:Apache License

/**
 * Checks if the current object has the same id as this json
 * @param json/*from   w ww  . ja  va 2  s  .c  om*/
 * @return
 */
protected boolean hasSameID(JsonElement json) {
    if (getID() == null)
        return false;
    if (json.isJsonPrimitive()) {
        return getID().equals(json.getAsJsonPrimitive().getAsString());
    }
    JsonElement idFromJson = json.getAsJsonObject().get(getIDFieldName());
    return idFromJson != null && getID().equals(idFromJson.getAsString());
}

From source file:com.stackmob.sdk.model.StackMobModel.java

License:Apache License

protected void setID(JsonElement json) {
    if (json.isJsonPrimitive()) {
        setID(json.getAsJsonPrimitive().getAsString());
    } else {//from   w ww .j a  v a 2 s.  co m
        setID(json.getAsJsonObject().get(getIDFieldName()).getAsString());
    }
}

From source file:com.stackmob.sdk.request.StackMobAccessTokenRequest.java

License:Apache License

private static StackMobRawCallback getIntermediaryCallback(final StackMobSession session,
        final StackMobRawCallback callback) {
    return new StackMobRawCallback() {
        @Override/*from w  ww .j a v a 2  s  .  c o  m*/
        public void unsent(StackMobException e) {
            callback.unsent(e);
        }

        @Override
        public void temporaryPasswordResetRequired(StackMobException e) {
            callback.temporaryPasswordResetRequired(e);
        }

        @Override
        public void done(HttpVerb requestVerb, String requestURL,
                List<Map.Entry<String, String>> requestHeaders, String requestBody, Integer responseStatusCode,
                List<Map.Entry<String, String>> responseHeaders, byte[] responseBody) {
            JsonElement responseElt = new JsonParser().parse(new String(responseBody));
            byte[] finalResponseBody = responseBody;
            if (responseElt.isJsonObject()) {
                // Parse out the token and expiration
                JsonElement tokenElt = responseElt.getAsJsonObject().get("access_token");
                JsonElement macKeyElt = responseElt.getAsJsonObject().get("mac_key");
                JsonElement expirationElt = responseElt.getAsJsonObject().get("expires_in");
                JsonElement refreshTokenElt = responseElt.getAsJsonObject().get("refresh_token");
                if (tokenElt != null && tokenElt.isJsonPrimitive() && tokenElt.getAsJsonPrimitive().isString()
                        && macKeyElt != null && macKeyElt.isJsonPrimitive()
                        && macKeyElt.getAsJsonPrimitive().isString() && expirationElt != null
                        && expirationElt.isJsonPrimitive() && expirationElt.getAsJsonPrimitive().isNumber()
                        && refreshTokenElt != null && refreshTokenElt.isJsonPrimitive()
                        && refreshTokenElt.getAsJsonPrimitive().isString()) {
                    session.setOAuth2TokensAndExpiration(tokenElt.getAsString(), macKeyElt.getAsString(),
                            refreshTokenElt.getAsString(), expirationElt.getAsInt());

                }
                JsonElement stackmobElt = responseElt.getAsJsonObject().get("stackmob");
                if (stackmobElt != null && stackmobElt.isJsonObject()) {
                    // Return only the user to be compatible with the old login
                    JsonElement userElt = stackmobElt.getAsJsonObject().get("user");
                    session.setLastUserLoginName(
                            userElt.getAsJsonObject().get(session.getUserIdName()).getAsString());
                    finalResponseBody = userElt.toString().getBytes();
                }
            }
            callback.setDone(requestVerb, requestURL, requestHeaders, requestBody, responseStatusCode,
                    responseHeaders, finalResponseBody);
        }

        @Override
        public void circularRedirect(String originalUrl, Map<String, String> redirectHeaders,
                String redirectBody, String newURL) {
            callback.circularRedirect(originalUrl, redirectHeaders, redirectBody, newURL);
        }
    };
}

From source file:com.strategicgains.restexpress.serialization.json.GsonDateSerializer.java

License:Apache License

@Override
public Date deserialize(JsonElement json, Type typeOf, JsonDeserializationContext context)
        throws JsonParseException {
    try {//from ww w.j av a  2s.  co m
        return adapter.parse(json.getAsJsonPrimitive().getAsString());
    } catch (ParseException e) {
        throw new JsonParseException(e);
    }
}

From source file:com.synflow.cx.internal.instantiation.properties.InstancePropertiesChecker.java

License:Open Source License

/**
 * Validates the given clocks object.//  w w w .  java 2  s  .co  m
 * 
 * @param clocks
 *            a clocks object
 * @param parentClocks
 *            a list of parent clocks
 * @param entityClocks
 *            a list of entity clocks
 */
private void validateClocks(JsonObject clocks, JsonArray parentClocks, JsonArray entityClocks) {
    int size = entityClocks.size();
    int got = 0;

    Iterator<JsonElement> it = entityClocks.iterator();
    for (Entry<String, JsonElement> pair : clocks.entrySet()) {
        String clockName = pair.getKey();
        if (NO_CLOCK.equals(clockName)) {
            // no more clocks after this one => mismatch in number of clocks
            got = clocks.entrySet().size();
            break;
        }

        if (!it.hasNext()) {
            // no more entity clocks => mismatch in number of clocks
            break;
        }

        // check we use a valid entity clock name
        String expected = it.next().getAsString();
        if (!clockName.equals(expected)) {
            handler.addError(clocks,
                    "given clock name '" + clockName + "' does not match entity's clock '" + expected + "'");
        }

        // check value
        JsonElement value = pair.getValue();
        if (value.isJsonPrimitive() && value.getAsJsonPrimitive().isString()) {
            got++;
            if (!Iterables.contains(parentClocks, value)) {
                handler.addError(value, "given clock name '" + value.getAsString()
                        + "' does not appear in parent's clocks " + parentClocks);
            }
        } else {
            handler.addError(value, "invalid clock value: " + value.toString());
        }
    }

    if (got < size) {
        String msg = "not enough clocks given, expected " + size + " clocks, got " + got;
        handler.addError(clocks, msg);
    } else if (got > size) {
        String msg = "too many clocks given, expected " + size + " clocks, got " + got;
        handler.addError(clocks, msg);
    }
}

From source file:com.synflow.cx.internal.instantiation.properties.PropertiesChecker.java

License:Open Source License

/**
 * If the given properties define {clock: 'name'}, and no 'clocks' property, transform to
 * {clocks: ['name']}./*w ww . j  av  a  2 s.c o  m*/
 * 
 * @param properties
 */
protected final void applyClockShortcut(JsonObject properties) {
    JsonElement clock = properties.get(PROP_CLOCK);
    if (clock == null) {
        // no clock property, return
        return;
    }

    if (properties.has(PROP_CLOCKS)) {
        // both 'clock' and 'clocks' exist, show error and ignore 'clock'
        handler.addError(clock, "'clock' and 'clocks' are mutually exclusive");
        return;
    }

    if (clock.isJsonNull()) {
        // {clock: null} becomes {clocks: []}
        properties.add(PROP_CLOCKS, new JsonArray());
    } else if (clock.isJsonPrimitive() && clock.getAsJsonPrimitive().isString()) {
        // clock is valid, {clock: name} becomes {clocks: [name]}
        JsonArray clocksArray = new JsonArray();
        clocksArray.add(clock);
        properties.add(PROP_CLOCKS, clocksArray);
    } else {
        // clock not valid, ignore
        handler.addError(clock, "'clock' must be a valid clock name");
    }
}

From source file:com.synflow.cx.internal.instantiation.properties.PropertiesChecker.java

License:Open Source License

/**
 * Check the 'clocks 'array./* w w  w .  j ava  2 s  .c  o  m*/
 * 
 * @param clocks
 *            an array of clock names
 * @return <code>true</code> if it is valid
 */
protected boolean checkClockArray(JsonElement clocks) {
    boolean isValid;
    if (clocks.isJsonArray()) {
        isValid = true;
        JsonArray clocksArray = clocks.getAsJsonArray();
        for (JsonElement clock : clocksArray) {
            if (!clock.isJsonPrimitive() || !clock.getAsJsonPrimitive().isString()) {
                isValid = false;
                break;
            }
        }
    } else {
        isValid = false;
    }

    if (!isValid) {
        handler.addError(clocks, "'clocks' must be an array of clock names");
    }
    return isValid;
}

From source file:com.synflow.cx.internal.instantiation.properties.Specializer.java

License:Open Source License

/**
 * Returns an IR expression from the given JSON element.
 * //from   w  w w  .jav  a2 s. c  om
 * @param json
 *            a JSON element (should be a primitive)
 * @return an expression, or <code>null</code>
 */
public Expression transformJson(JsonElement json) {
    if (json.isJsonPrimitive()) {
        JsonPrimitive primitive = json.getAsJsonPrimitive();
        if (primitive.isBoolean()) {
            return eINSTANCE.createExprBool(primitive.getAsBoolean());
        } else if (primitive.isNumber()) {
            return eINSTANCE.createExprInt(primitive.getAsBigInteger());
        } else if (primitive.isString()) {
            return eINSTANCE.createExprString(primitive.getAsString());
        }
    }
    return null;
}