Example usage for com.google.gson JsonObject getAsJsonObject

List of usage examples for com.google.gson JsonObject getAsJsonObject

Introduction

In this page you can find the example usage for com.google.gson JsonObject getAsJsonObject.

Prototype

public JsonObject getAsJsonObject(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonObject.

Usage

From source file:com.google.gms.googleservices.GoogleServicesTask.java

License:Apache License

/**
 * Finds a service by name in the client object. Returns null if the service is not found
 * or if the service is disabled.//from   ww  w.j  av a 2  s .  co m
 *
 * @param clientObject the json object that represents the client.
 * @param serviceName the service name
 * @return the service if found.
 */
private JsonObject getServiceByName(JsonObject clientObject, String serviceName) {
    JsonObject services = clientObject.getAsJsonObject("services");
    if (services == null)
        return null;

    JsonObject service = services.getAsJsonObject(serviceName);
    if (service == null)
        return null;

    JsonPrimitive status = service.getAsJsonPrimitive("status");
    if (status == null)
        return null;

    String statusStr = status.getAsString();

    if (STATUS_DISABLED.equals(statusStr))
        return null;
    if (!STATUS_ENABLED.equals(statusStr)) {
        getLogger().warn(String.format("Status with value '%1$s' for service '%2$s' is unknown", statusStr,
                serviceName));
        return null;
    }

    return service;
}

From source file:com.google.identitytoolkit.RpcHelper.java

License:Open Source License

@VisibleForTesting
JsonObject checkGitkitException(String response) throws GitkitClientException, GitkitServerException {
    JsonElement resultElement = new JsonParser().parse(response);
    if (!resultElement.isJsonObject()) {
        throw new GitkitServerException("null error code from Gitkit server");
    }/* www .  j  a va  2  s  . c o m*/
    JsonObject result = resultElement.getAsJsonObject();
    if (!result.has("error")) {
        return result;
    }
    // Error handling
    JsonObject error = result.getAsJsonObject("error");
    JsonElement codeElement = error.get("code");
    if (codeElement != null) {
        JsonElement messageElement = error.get("message");
        String message = (messageElement == null) ? "" : messageElement.getAsString();
        if (codeElement.getAsString().startsWith("4")) {
            // 4xx means client input error
            throw new GitkitClientException(message);
        } else {
            throw new GitkitServerException(message);
        }
    }
    throw new GitkitServerException("null error code from Gitkit server");
}

From source file:com.google.paymentexpress.jwt.MaskedWalletResponse.java

License:Apache License

/**
 * Constructor that takes a the decoded JWT body to convert
 * /*from w  w  w .j  a va 2  s  .  c o m*/
 * @param jwt JSON Web Token body 
 */
public MaskedWalletResponse(JsonToken jwt) {
    this.iat = jwt.getIssuedAt().getMillis();
    this.iss = jwt.getIssuer();
    this.aud = jwt.getAudience();
    this.typ = jwt.getParamAsPrimitive("typ").getAsString();
    this.google_transaction_id = jwt.getParamAsPrimitive("google_transaction_id").getAsString();
    if (jwt.getParamAsPrimitive("transaction_id") != null)
        this.transaction_id = jwt.getParamAsPrimitive("transaction_id").getAsString();
    this.email = jwt.getParamAsPrimitive("email").getAsString();
    JsonObject payload = jwt.getPayloadAsJsonObject();
    JsonObject selection = payload.getAsJsonObject(SELECTION);
    Gson gson = GsonHelper.getGson();
    this.selection = gson.fromJson(selection, Selectors.class);
}

From source file:com.google.research.ic.ferret.uiserver.RESTHandler.java

License:Open Source License

@POST
@Path("getFilteredResults")
@Produces(MediaType.APPLICATION_JSON)//  w ww  .  java 2  s .co m
public String getFilteredResults(@FormParam("filterParams") String filterParams) {

    Debug.log("filterParams: " + filterParams);

    JsonParser parser = new JsonParser();
    JsonObject rootObj = parser.parse(filterParams).getAsJsonObject();
    String attrName = rootObj.get("attrName").getAsString();
    String values = rootObj.get("values").getAsString();

    JsonObject rSummObj = rootObj.getAsJsonObject("rSummary");
    FilteredResultSummary rSummary = getGson().fromJson(rSummObj, FilteredResultSummary.class);
    FilterSpec fSpec = null;
    Attribute attr = rSummary.getAttributes().get(attrName);

    Debug.log("values: " + values);
    Debug.log("attrType: " + attr.getType());

    if (attr.getType().equals(CategoricalAttribute.TYPE)) {
        String operator = FilterSpec.EQUALS;
        fSpec = new FilterSpec(rSummary.getMinDist(), rSummary.getMaxDist(), 20, attrName, operator, values);
    } else if (attr.getType().equals(NumericalAttribute.TYPE)) {
        if (values.contains("-")) {
            String min = values.split("-")[0];
            String max = values.split("-")[1];
            String operator = FilterSpec.BETWEEN;
            fSpec = new FilterSpec(rSummary.getMinDist(), rSummary.getMaxDist(), 20, attrName, operator,
                    Double.parseDouble(min), Double.parseDouble(max));
        } else {
            // assume a single value
            String operator = FilterSpec.EQUALS;
            fSpec = new FilterSpec(rSummary.getMinDist(), rSummary.getMaxDist(), 20, attrName, operator,
                    Double.parseDouble(values));
        }
    } else if (attr.getType().equals(DateTimeAttribute.TYPE)) {
        if (values.contains("-")) {
            String min = values.split("-")[0];
            String max = values.split("-")[1];
            String operator = FilterSpec.BETWEEN;

            Debug.log("Creating FilterSpec to return " + operator + " " + min + " and " + max);
            fSpec = new FilterSpec(rSummary.getMinDist(), rSummary.getMaxDist(), 20, attrName, operator,
                    new Date(Long.parseLong(min)), new Date(Long.parseLong(max)));
        } else {
            // assume a single value
            String operator = FilterSpec.EQUALS;
            fSpec = new FilterSpec(rSummary.getMinDist(), rSummary.getMaxDist(), 20, attrName, operator,
                    new Date(Long.parseLong(values)));
        }
    }

    ResultSet currentResults = Session.getCurrentSession().getCurrentResultSet().getStrongMatches();
    if (currentResults != null) {
        FilteredResultSet filteredResults = currentResults.filter(fSpec);
        String jsonString = getGson().toJson(filteredResults);
        //Debug.log("*** Returning Filtered Results: " + jsonString);
        return jsonString;
    } else {
        return null;
    }
}

From source file:com.google.wave.api.impl.OperationRequestGsonAdaptor.java

License:Apache License

@Override
public OperationRequest deserialize(JsonElement json, Type type, JsonDeserializationContext ctx)
        throws JsonParseException {
    JsonObject jsonObject = json.getAsJsonObject();
    JsonObject parameters = jsonObject.getAsJsonObject(RequestProperty.PARAMS.key());

    OperationRequest request = new OperationRequest(jsonObject.get(RequestProperty.METHOD.key()).getAsString(),
            jsonObject.get(RequestProperty.ID.key()).getAsString(),
            getPropertyAsStringThenRemove(parameters, ParamsProperty.WAVE_ID),
            getPropertyAsStringThenRemove(parameters, ParamsProperty.WAVELET_ID),
            getPropertyAsStringThenRemove(parameters, ParamsProperty.BLIP_ID));

    for (Entry<String, JsonElement> parameter : parameters.entrySet()) {
        ParamsProperty parameterType = ParamsProperty.fromKey(parameter.getKey());
        if (parameterType != null) {
            Object object;/*w w  w  .ja va 2 s  .c o m*/
            if (parameterType == ParamsProperty.RAW_DELTAS) {
                object = ctx.deserialize(parameter.getValue(), GsonFactory.RAW_DELTAS_TYPE);
            } else {
                object = ctx.deserialize(parameter.getValue(), parameterType.clazz());
            }
            request.addParameter(Parameter.of(parameterType, object));
        }
    }

    return request;
}

From source file:com.google.wave.api.v2.ElementGsonAdaptorV2.java

License:Apache License

@Override
public Element deserialize(JsonElement jsonElement, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject json = jsonElement.getAsJsonObject();
    String type = json.get(TYPE_TAG).getAsString();

    if (ElementType.IMAGE.name().equals(type)) {
        JsonObject properties = json.getAsJsonObject(PROPERTIES_TAG);
        if (!properties.has(Image.URL)) {
            json.addProperty(TYPE_TAG, ElementType.ATTACHMENT.name());
        }/*from w w w. j a  va 2 s  .  c  o  m*/
    }
    return super.deserialize(json, typeOfT, context);
}

From source file:com.google.wave.splash.data.serialize.JsonSerializer.java

License:Apache License

/**
 * Parses a string of json from a wave.robot.search rpc into a search result
 * with a set of digests.//from  w  w  w  . j a  v  a  2  s . c o m
 *
 * @param query the query used to get the search results.
 * @param json the json to parse.
 * @return a result object, which may not contain results.
 */
public SearchResult parseSearchResult(String query, String json) {
    JsonObject dataObject = getDataObject(json);
    SearchResult result = new SearchResult(query);
    if (dataObject == null) {
        LOG.warning("Search returned empty result: " + query);
        return result;
    }
    if (dataObject != null) {
        JsonArray digestElements = dataObject.getAsJsonObject("searchResults").getAsJsonArray("digests");
        List<Digest> digests = gson.fromJson(digestElements, DIGEST_LIST_TYPE);
        for (Digest digest : digests) {
            result.addDigest(digest);
        }
    }
    return result;
}

From source file:com.google.wave.splash.data.serialize.JsonSerializer.java

License:Apache License

/**
 * Parses a string of json from a wave.robot.fetchWave into a result.
 *
 * @param json the json to parse./*from w  w  w .  ja  va 2s  .c om*/
 * @return the result object, which may not contain a wavelet.
 */
@Timed
public FetchWaveletResult parseFetchWaveletResult(String json) {
    JsonObject dataObject = getDataObject(json);
    if (dataObject == null || !dataObject.has("waveletData")) {
        LOG.warning("Fetch returned empty result.");
        return FetchWaveletResult.emptyResult();
    }

    JsonObject waveletDataJson = dataObject.getAsJsonObject("waveletData");
    OperationQueue operationQueue = new OperationQueue();
    WaveletData waveletData = gson.fromJson(waveletDataJson, WaveletData.class);

    Map<String, Blip> blips = Maps.newHashMap();
    HashMap<String, BlipThread> threads = Maps.newHashMap();
    Wavelet wavelet = Wavelet.deserialize(operationQueue, blips, threads, waveletData);

    JsonObject threadMap = dataObject.getAsJsonObject("threads");
    if (null != threadMap) {
        for (Map.Entry<String, JsonElement> entries : threadMap.entrySet()) {
            JsonObject threadElement = entries.getValue().getAsJsonObject();
            int location = threadElement.get("location").getAsInt();

            List<String> blipIds = Lists.newArrayList();
            for (JsonElement blipId : threadElement.get("blipIds").getAsJsonArray()) {
                blipIds.add(blipId.getAsString());
            }

            BlipThread thread = new BlipThread(entries.getKey(), location, blipIds, blips);
            threads.put(thread.getId(), thread);
        }
    }

    JsonObject blipMap = dataObject.getAsJsonObject("blips");
    for (Map.Entry<String, JsonElement> entries : blipMap.entrySet()) {
        BlipData blipData = gson.fromJson(entries.getValue(), BlipData.class);
        Blip blip = Blip.deserialize(operationQueue, wavelet, blipData);
        blips.put(blipData.getBlipId(), blip);
    }

    return new FetchWaveletResult(wavelet);
}

From source file:com.googlesource.gerrit.plugins.hooks.rtc.api.AbstractDeserializer.java

License:Apache License

protected final String extractRdfResourceUrl(JsonObject json, String memberName) {
    JsonObject rdf = json.getAsJsonObject(memberName);
    return rdf.get("rdf:resource").getAsString();
}

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

License:Apache License

@Override
public OAuthUserInfo getUserInfo(OAuthToken token) throws IOException {
    OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
    Token t = new Token(token.getToken(), token.getSecret(), token.getRaw());
    service.signRequest(t, request);/*w  w w .  j  a v  a  2 s  . co  m*/
    Response response = request.send();
    if (response.getCode() != SC_OK) {
        throw new IOException(String.format("Status %s (%s) for request %s", response.getCode(),
                response.getBody(), request.getUrl()));
    }
    JsonElement userJson = JSON.newGson().fromJson(response.getBody(), JsonElement.class);
    if (log.isDebugEnabled()) {
        log.debug("User info response: {}", response.getBody());
    }
    if (userJson.isJsonObject()) {
        JsonObject jsonObject = userJson.getAsJsonObject();
        JsonObject userObject = jsonObject.getAsJsonObject("user");
        if (userObject == null || userObject.isJsonNull()) {
            throw new IOException("Response doesn't contain 'user' field");
        }
        JsonElement usernameElement = userObject.get("username");
        String username = usernameElement.getAsString();

        JsonElement displayName = jsonObject.get("display_name");
        return new OAuthUserInfo(username, username, null,
                displayName == null || displayName.isJsonNull() ? null : displayName.getAsString(), null);
    } else {
        throw new IOException(String.format("Invalid JSON '%s': not a JSON Object", userJson));
    }
}