Example usage for com.google.gson JsonElement isJsonObject

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

Introduction

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

Prototype

public boolean isJsonObject() 

Source Link

Document

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

Usage

From source file:com.google.code.stackexchange.client.query.impl.BaseStackOverflowApiQuery.java

License:Apache License

protected <A> A unmarshallObject(Class<A> clazz, InputStream jsonContent) {
    if (clazz.equals(Error.class)) {
        try {/*from  www .j  a  v  a 2 s.  com*/
            JsonElement response = parser.parse(new InputStreamReader(jsonContent, UTF_8_CHAR_SET));
            if (response.isJsonObject()) {
                JsonObject adaptee = response.getAsJsonObject();
                Gson gson = getGsonBuilder().create();
                return gson.fromJson(adaptee.get("error"), clazz);
            }
        } catch (Exception e) {
            throw new StackExchangeApiException(e);
        }
    }
    return null;
}

From source file:com.google.code.stackexchange.client.query.impl.BaseStackOverflowApiQuery.java

License:Apache License

protected <A> PagedList<A> unmarshallList(Class<A> clazz, InputStream jsonContent) {
    try {/*from w ww. j  a  v a 2 s.  c o m*/
        JsonElement response = parser.parse(new InputStreamReader(jsonContent, UTF_8_CHAR_SET));
        if (response.isJsonObject()) {
            JsonObject adaptee = response.getAsJsonObject();
            return unmarshallList(clazz, adaptee);
        }
        throw new StackExchangeApiException("Unknown content found in response:" + response.toString());
    } catch (Exception e) {
        throw new StackExchangeApiException(e);
    }
}

From source file:com.google.debugging.sourcemap.SourceMapConsumerFactory.java

License:Apache License

/**
 * @param contents The string representing the source map file contents.
 * @param supplier A supplier for any referenced maps.
 * @return The parsed source map.//from w  w w . j a  va 2 s  . c o m
 * @throws SourceMapParseException
 */
public static SourceMapping parse(String contents, SourceMapSupplier supplier) throws SourceMapParseException {
    // Version 1, starts with a magic string
    if (contents.startsWith("/** Begin line maps. **/")) {
        throw new SourceMapParseException("This appears to be a V1 SourceMap, which is not supported.");
    } else if (contents.startsWith("{")) {
        try {
            // Revision 2 and 3, are JSON Objects
            JsonElement jsonElement = PARSER.parse(contents);
            if (!jsonElement.isJsonObject()) {
                throw new SourceMapParseException("Expected a JSON Object.");
            }
            JsonObject sourceMapRoot = jsonElement.getAsJsonObject();

            // Check basic assertions about the format.
            int version = sourceMapRoot.get("version").getAsInt();
            switch (version) {
            case 3: {
                SourceMapConsumerV3 consumer = new SourceMapConsumerV3();
                consumer.parse(sourceMapRoot, supplier);
                return consumer;
            }
            default:
                throw new SourceMapParseException("Unknown source map version:" + version);
            }
        } catch (JsonParseException ex) {
            throw new SourceMapParseException("JSON parse exception: " + ex);
        }
    }

    throw new SourceMapParseException("unable to detect source map format");
}

From source file:com.google.devtools.kythe.platform.shared.KytheMetadataLoader.java

License:Open Source License

@Override
public Metadata parseFile(String fileName, byte[] data) {
    if (!fileName.endsWith(META_SUFFIX)) {
        return null;
    }/*from   w w  w . j a va2  s  .  co m*/
    JsonElement root = null;
    try (ByteArrayInputStream stream = new ByteArrayInputStream(data);
            InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
        root = PARSER.parse(reader);
    } catch (IOException ex) {
        emitWarning(ex.getMessage(), fileName);
        return null;
    }
    if (root == null || !root.isJsonObject()) {
        emitWarning("Missing root.", fileName);
        return null;
    }
    JsonObject rootObject = root.getAsJsonObject();
    JsonPrimitive rootType = rootObject.getAsJsonPrimitive(TYPE);
    if (rootType == null || !rootType.getAsString().equals(KYTHE_FORMAT_0)) {
        emitWarning("Root missing type.", fileName);
        return null;
    }
    JsonArray rules = rootObject.getAsJsonArray(META);
    if (rules == null) {
        emitWarning("Root missing meta array.", fileName);
        return null;
    }
    Metadata metadata = new Metadata();
    for (JsonElement rule : rules) {
        RuleXorError ruleXorError = parseRule(rule.getAsJsonObject());
        if (ruleXorError != null) { // skip nulls
            Metadata.Rule metadataRule = ruleXorError.rule();
            if (metadataRule != null) {
                metadata.addRule(metadataRule);
            } else {
                emitWarning(ruleXorError.error(), fileName);
            }
        }
    }
    return metadata;
}

From source file:com.google.gerrit.httpd.restapi.ParameterParser.java

License:Apache License

@VisibleForTesting
static JsonObject formToJson(Map<String, String[]> map, Set<String> query) throws BadRequestException {
    JsonObject inputObject = new JsonObject();
    for (Map.Entry<String, String[]> ent : map.entrySet()) {
        String key = ent.getKey();
        String[] values = ent.getValue();

        if (query.contains(key) || values.length == 0) {
            // Disallow processing query parameters as input body fields.
            // Implementations of views should avoid duplicate naming.
            continue;
        }//  ww w.  j  a va2s.  c  om

        JsonObject obj = inputObject;
        int dot = key.indexOf('.');
        if (0 <= dot) {
            String property = key.substring(0, dot);
            JsonElement e = inputObject.get(property);
            if (e == null) {
                obj = new JsonObject();
                inputObject.add(property, obj);
            } else if (e.isJsonObject()) {
                obj = e.getAsJsonObject();
            } else {
                throw new BadRequestException(String.format("key %s conflicts with %s", key, property));
            }
            key = key.substring(dot + 1);
        }

        if (obj.get(key) != null) {
            // This error should never happen. If all form values are handled
            // together in a single pass properties are set only once. Setting
            // again indicates something has gone very wrong.
            throw new BadRequestException("invalid form input, use JSON instead");
        } else if (values.length == 1) {
            obj.addProperty(key, values[0]);
        } else {
            JsonArray list = new JsonArray();
            for (String v : values) {
                list.add(new JsonPrimitive(v));
            }
            obj.add(key, list);
        }
    }
    return inputObject;
}

From source file:com.google.gerrit.httpd.TokenVerifiedRestApiServlet.java

License:Apache License

private static ParsedBody parseJson(HttpServletRequest req, HttpServletResponse res) throws IOException {
    try {// w w w.j av a 2 s  .  c  o m
        JsonElement element = new JsonParser().parse(req.getReader());
        if (!element.isJsonObject()) {
            sendError(res, SC_BAD_REQUEST, "Expected JSON object in request body");
            return null;
        }

        ParsedBody body = new ParsedBody();
        body.req = req;
        body.json = (JsonObject) element;
        JsonElement authKey = body.json.remove(AUTHKEY_NAME);
        if (authKey != null && authKey.isJsonPrimitive() && authKey.getAsJsonPrimitive().isString()) {
            body._authkey = authKey.getAsString();
        }
        return body;
    } catch (JsonParseException e) {
        sendError(res, SC_BAD_REQUEST, "Invalid JSON object in request body");
        return null;
    }
}

From source file:com.google.gerrit.server.events.EventDeserializer.java

License:Apache License

@Override
public Event deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    if (!json.isJsonObject()) {
        throw new JsonParseException("Not an object");
    }/*from   w  ww  .j  av  a 2  s.com*/
    JsonElement typeJson = json.getAsJsonObject().get("type");
    if (typeJson == null || !typeJson.isJsonPrimitive() || !typeJson.getAsJsonPrimitive().isString()) {
        throw new JsonParseException("Type is not a string: " + typeJson);
    }
    String type = typeJson.getAsJsonPrimitive().getAsString();
    Class<?> cls = EventTypes.getClass(type);
    if (cls == null) {
        throw new JsonParseException("Unknown event type: " + type);
    }
    return context.deserialize(json, cls);
}

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

License:Apache License

@TaskAction
public void action() throws IOException {
    if (!quickstartFile.isFile()) {
        getLogger().warn("File " + quickstartFile.getName() + " is missing from module root folder."
                + " The Google Quickstart Plugin cannot function without it.");

        // Skip the rest of the actions because it would not make sense if `quickstartFile` is missing.
        return;// w  w w.  j  a  v a2s  . c  o  m
    }

    // delete content of outputdir.
    deleteFolder(intermediateDir);
    if (!intermediateDir.mkdirs()) {
        throw new GradleException("Failed to create folder: " + intermediateDir);
    }

    JsonElement root = new JsonParser().parse(Files.newReader(quickstartFile, Charsets.UTF_8));

    if (!root.isJsonObject()) {
        throw new GradleException("Malformed root json");
    }

    JsonObject rootObject = root.getAsJsonObject();

    Map<String, String> resValues = new TreeMap<String, String>();

    handleProjectNumber(rootObject, resValues);

    JsonObject clientObject = getClientForPackageName(rootObject);

    if (clientObject != null) {
        handleAnalytics(clientObject, resValues);
        handleAdsService(clientObject, resValues);
    } else {
        getLogger().warn("No matching client found for package name '" + packageName + "'");
    }

    // write the values file.
    File values = new File(intermediateDir, "values");
    if (!values.exists() && !values.mkdirs()) {
        throw new GradleException("Failed to create folder: " + values);
    }

    Files.write(getValuesContent(resValues), new File(values, "values.xml"), Charsets.UTF_8);
}

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

License:Apache License

/**
 * find an item in the "client" array that match the package name of the app
 * @param jsonObject the root json object.
 * @return a JsonObject representing the client entry or null if no match is found.
 *//*from www.  j av a 2  s . c  o  m*/
private JsonObject getClientForPackageName(JsonObject jsonObject) {
    JsonArray array = jsonObject.getAsJsonArray("client");
    if (array != null) {
        final int count = array.size();
        for (int i = 0; i < count; i++) {
            JsonElement clientElement = array.get(i);
            if (clientElement == null || !clientElement.isJsonObject()) {
                continue;
            }

            JsonObject clientObject = clientElement.getAsJsonObject();

            JsonObject clientInfo = clientObject.getAsJsonObject("client_info");
            if (clientInfo == null)
                continue;

            JsonObject androidClientInfo = clientInfo.getAsJsonObject("android_client_info");
            if (androidClientInfo == null)
                continue;

            JsonPrimitive clientPackageName = androidClientInfo.getAsJsonPrimitive("package_name");
            if (clientPackageName == null)
                continue;

            if (packageName.equals(clientPackageName.getAsString())) {
                return clientObject;
            }
        }
    }

    return null;
}

From source file:com.google.gwtjsonrpc.server.CallDeserializer.java

License:Apache License

public CallType deserialize(final JsonElement json, final Type typeOfT,
        final JsonDeserializationContext context) throws JsonParseException, NoSuchRemoteMethodException {
    if (!json.isJsonObject()) {
        throw new JsonParseException("Expected object");
    }//from  w  w  w. j a  va 2 s . com

    final JsonObject in = json.getAsJsonObject();
    req.id = in.get("id");

    final JsonElement jsonrpc = in.get("jsonrpc");
    final JsonElement version = in.get("version");
    if (isString(jsonrpc) && version == null) {
        final String v = jsonrpc.getAsString();
        if ("2.0".equals(v)) {
            req.versionName = "jsonrpc";
            req.versionValue = jsonrpc;
        } else {
            throw new JsonParseException("Expected jsonrpc=2.0");
        }

    } else if (isString(version) && jsonrpc == null) {
        final String v = version.getAsString();
        if ("1.1".equals(v)) {
            req.versionName = "version";
            req.versionValue = version;
        } else {
            throw new JsonParseException("Expected version=1.1");
        }
    } else {
        throw new JsonParseException("Expected version=1.1 or jsonrpc=2.0");
    }

    final JsonElement method = in.get("method");
    if (!isString(method)) {
        throw new JsonParseException("Expected method name as string");
    }

    req.method = server.lookupMethod(method.getAsString());
    if (req.method == null) {
        throw new NoSuchRemoteMethodException();
    }

    final JsonElement callback = in.get("callback");
    if (callback != null) {
        if (!isString(callback)) {
            throw new JsonParseException("Expected callback as string");
        }
        req.callback = callback.getAsString();
    }

    final JsonElement xsrfKey = in.get("xsrfKey");
    if (xsrfKey != null) {
        if (!isString(xsrfKey)) {
            throw new JsonParseException("Expected xsrfKey as string");
        }
        req.xsrfKeyIn = xsrfKey.getAsString();
    }

    final Type[] paramTypes = req.method.getParamTypes();
    final JsonElement params = in.get("params");
    if (params != null) {
        if (!params.isJsonArray()) {
            throw new JsonParseException("Expected params array");
        }

        final JsonArray paramsArray = params.getAsJsonArray();
        if (paramsArray.size() != paramTypes.length) {
            throw new JsonParseException("Expected " + paramTypes.length + " parameter values in params array");
        }

        final Object[] r = new Object[paramTypes.length];
        for (int i = 0; i < r.length; i++) {
            final JsonElement v = paramsArray.get(i);
            if (v != null) {
                r[i] = context.deserialize(v, paramTypes[i]);
            }
        }
        req.params = r;
    } else {
        if (paramTypes.length != 0) {
            throw new JsonParseException("Expected params array");
        }
        req.params = JsonServlet.NO_PARAMS;
    }

    return req;
}