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.builtbroken.builder.html.PageBuilder.java

/**
 * Called to parse the settings file// www . java2 s  .co  m
 */
public void parseSettings() {
    logger.info("Loading settings for wiki building form " + settingsFile);
    if (!outputDirectory.exists()) {
        outputDirectory.mkdirs();
    }
    if (settingsFile.exists() && settingsFile.isFile()) {
        JsonElement element = Utils.toJsonElement(settingsFile);

        if (element.isJsonObject()) {
            JsonObject object = element.getAsJsonObject();
            if (object.has("vars")) {
                logger.info("Vars:");
                Gson gson = new Gson();
                Map<String, String> map = new HashMap();
                map = (Map<String, String>) gson.fromJson(object.get("vars"), map.getClass());
                vars = new HashMap();
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    logger.info("\t" + entry.getKey() + " = " + entry.getValue());
                    vars.put(entry.getKey(), entry.getValue());
                }
            }
            if (object.has("images")) {
                String value = object.getAsJsonPrimitive("images").getAsString();
                imageDirectory = Utils.getFile(workingDirectory, value);
                vars.put("imagePath", value);
                logger.info("Image Path: " + imageDirectory);
            } else {
                throw new RuntimeException("Missing image folder location from " + settingsFile);
            }
            if (object.has("categories")) {
                logger.info("Categories:");
                categoryData = new HashMap();
                final Set<Map.Entry<String, JsonElement>> entrySet = object.get("categories").getAsJsonObject()
                        .entrySet();
                for (Map.Entry<String, JsonElement> entry : entrySet) {
                    final JsonObject catEntry = entry.getValue().getAsJsonObject();
                    this.categoryData.put(entry.getKey().toLowerCase(),
                            CategoryData.parse(entry.getKey(), catEntry));
                }
                logger.info("");
            } else {
                throw new RuntimeException("Missing categories data from " + settingsFile);
            }
            if (object.has("pages")) {
                String value = object.getAsJsonPrimitive("pages").getAsString();
                pageDirectory = Utils.getFile(workingDirectory, value);
                logger.info("Pages folder: " + pageDirectory);
            } else {
                throw new RuntimeException("Missing pages location data from " + settingsFile);
            }
            if (pageTheme == null) {
                if (object.has("theme")) {
                    File file = Utils.getFile(workingDirectory,
                            object.getAsJsonPrimitive("theme").getAsString());
                    if (file.isDirectory()) {
                        file = new File(file, "theme.json");
                    }
                    pageTheme = new PageTheme(file);
                    logger.info("Theme : " + pageTheme.themeFile);
                } else {
                    throw new RuntimeException("Missing theme data from " + settingsFile);
                }
            }
        } else {
            throw new RuntimeException("File does not contain a json object [" + settingsFile + "]");
        }
    } else {
        throw new RuntimeException("File is invalid for reading or missing [" + settingsFile + "]");
    }
}

From source file:com.builtbroken.builder.html.parts.HTMLPartHeader.java

@Override
public String process(JsonElement value) {
    try {//ww  w . ja v a  2 s. c om
        if (value.isJsonObject() && !value.isJsonPrimitive()) {
            JsonObject h = value.getAsJsonObject();
            String text = h.getAsJsonPrimitive("text").getAsString();
            int size = 2;
            if (h.has("size")) {
                JsonPrimitive p = h.getAsJsonPrimitive("size");
                if (p.isString()) {
                    String s = p.getAsString().toLowerCase();
                    if (s.equals("small")) {
                        size = 3;
                    } else if (s.equals("medium")) {
                        size = 2;
                    } else if (s.equals("large")) {
                        size = 1;
                    }
                } else {
                    size = p.getAsInt();
                }
            }
            if (h.has("link")) {
                String link = h.getAsJsonPrimitive("link").getAsString();
                if (link.startsWith("url")) {
                    return "<h" + size + "><a href=\"" + link + "\">" + text + "</a></h" + size + ">";
                } else if (link.endsWith(".json")) {
                    return "<h" + size + "><a href=\"#PageRef:" + link + "#\">" + text + "</a></h" + size + ">";
                } else {
                    return "<h" + size + "><a href=\"#" + link + "#\">" + text + "</a></h" + size + ">";
                }
            }
            return "<h" + size + ">" + text + "</h" + size + ">";
        }
        return "<h2>" + value.getAsString() + "</h2>";
    } catch (Exception e) {
        throw new RuntimeException("Unexpected error while parsing header tag " + value, e);
    }
}

From source file:com.builtbroken.builder.html.theme.PageTheme.java

/**
 * Called to load the theme data from file. Does
 * not actually load the theme pages. To load
 * the pages call {@link #loadTemplates()} after
 * calling this./*from www  .  jav a  2  s  .c  o  m*/
 */
public void load() {
    //Parse settings file
    if (themeFile.exists() && themeFile.isFile()) {
        final JsonElement element = Utils.toJsonElement(themeFile);
        if (element.isJsonObject()) {
            final JsonObject object = element.getAsJsonObject();
            if (object.has("templates")) {
                Gson gson = new Gson();
                //PageName or injection key, Page disk location
                Map<String, String> map = new HashMap();
                map = (Map<String, String>) gson.fromJson(object.get("templates"), map.getClass());

                for (Map.Entry<String, String> entry : map.entrySet()) {
                    String key = entry.getKey().toLowerCase();
                    templates.put(key, new PageTemplate(key, entry.getValue()));
                }
            } else {
                throw new RuntimeException("File does not define any templates to load [" + themeFile + "]");
            }
            if (object.has("pageDirectory")) {
                String value = object.getAsJsonPrimitive("pageDirectory").getAsString();
                pageDirectory = Utils.getFile(themeFile.getParentFile(), value);
            } else {
                throw new RuntimeException(
                        "File does not define a directory to load template pages from [" + themeFile + "]");
            }
            if (object.has("name")) {
                name = object.getAsJsonPrimitive("name").getAsString();
            } else {
                throw new RuntimeException("File does not define the theme's name [" + themeFile + "]");
            }
            if (templates.containsKey("main_template")) {
                mainTemplate = templates.get("main_template");
            } else {
                throw new RuntimeException(
                        "File does not define a main template for the theme [" + themeFile + "]");
            }
            if (templates.containsKey("category_template")) {
                categoryTemplate = templates.get("category_template");
            } else {
                throw new RuntimeException(
                        "File does not define a category template for the theme [" + themeFile + "]");
            }
            if (templates.containsKey("category_entry")) {
                categoryEntryTemplate = templates.get("category_entry");
            } else {
                throw new RuntimeException(
                        "File does not define a category entry template for the theme [" + themeFile + "]");
            }
            if (templates.containsKey("category_item")) {
                categoryItemTemplate = templates.get("category_item");
            } else {
                throw new RuntimeException(
                        "File does not define a category item template for the theme [" + themeFile + "]");
            }
            if (templates.containsKey("category_child")) {
                categoryChildTemplate = templates.get("category_child");
            } else {
                throw new RuntimeException(
                        "File does not define a category child template for the theme [" + themeFile + "]");
            }
            if (templates.containsKey("category_parent")) {
                categoryParentTemplate = templates.get("category_parent");
            } else {
                throw new RuntimeException(
                        "File does not define a category parent template for the theme [" + themeFile + "]");
            }
        } else {
            throw new RuntimeException("File does not contain a json object [" + themeFile + "]");
        }
    } else {
        throw new RuntimeException("File is invalid for reading [" + themeFile + "]");
    }
}

From source file:com.builtbroken.builder.WikiBuilder.java

public static void main(String... args) {
    Logger logger = LogManager.getRootLogger();

    logger.info("Wiki-Builder has been started...");
    logger.info("Parsing arguments...");

    //TODO implement GUI
    //Load arguments
    HashMap<String, String> launchSettings = loadArgs(args);

    if (launchSettings.containsKey("batchFile")) {
        File batchFile = Utils.getFile(new File("."), launchSettings.get("batchFile"));
        if (batchFile.exists() && batchFile.isFile()) {
            JsonElement element = Utils.toJsonElement(batchFile);
            if (element.isJsonObject()) {
                JsonObject object = element.getAsJsonObject();
                if (object.has("jobs")) {
                    ImageData imageData = new ImageData();
                    LinkData linkData = new LinkData();
                    List<PageBuilder> builders = new ArrayList();

                    PageTheme pageTheme = null;
                    if (launchSettings.containsKey("theme")) {
                        File file = Utils.getFile(batchFile.getParentFile(), launchSettings.get("theme"));
                        if (file.isDirectory()) {
                            file = new File(file, "theme.json");
                        }/*from  w  w  w .ja v  a2  s .  c  om*/
                        pageTheme = new PageTheme(file);
                        logger.info(
                                "Theme is being set by program arguments! Theme in settings file will not be used.");
                        logger.info("Theme : " + pageTheme.themeFile);
                    }

                    Set<Map.Entry<String, JsonElement>> entrySet = object.entrySet();

                    if (!entrySet.isEmpty()) {
                        for (Map.Entry<String, JsonElement> entry : entrySet) {
                            if (element.isJsonObject()) {
                                object = element.getAsJsonObject();
                                HashMap<String, String> settings = new HashMap();
                                //Limit settings as some are not valid for batch
                                if (launchSettings.containsKey("outputDirectory")) {
                                    settings.put("outputDirectory", launchSettings.get("outputDirectory"));
                                }

                                File workingDirectory;
                                File settingsFile;

                                //TODO add data files to batch file so program arguments can be reduced

                                if (object.has("directory")) {
                                    workingDirectory = Utils.getFile(batchFile.getParentFile(),
                                            object.getAsJsonPrimitive("directory").getAsString());
                                } else {
                                    throw new RuntimeException(
                                            "Batch job '" + entry.getKey() + "' is missing the directory tag");
                                }
                                if (object.has("settingsFile")) {
                                    settingsFile = Utils.getFile(batchFile.getParentFile(),
                                            object.getAsJsonPrimitive("settingsFile").getAsString());
                                } else {
                                    settingsFile = Utils.getFile(batchFile.getParentFile(), "./settings.json");
                                }

                                builders.add(new PageBuilder(logger, workingDirectory, settingsFile, settings,
                                        pageTheme, imageData, linkData));
                            } else {
                                throw new RuntimeException("Batch job '" + entry.getKey()
                                        + "' format is invalid and should be a json object");
                            }
                        }

                        if (launchSettings.containsKey("linkDataFile")) {
                            String value = launchSettings.get("linkDataFile");
                            if (value.contains(",")) {
                                String[] split = value.split(",");
                                for (String s : split) {
                                    linkData.loadDataFromFile(Utils.getFile(batchFile.getParentFile(), s));
                                }
                            } else {
                                linkData.loadDataFromFile(Utils.getFile(batchFile.getParentFile(), value));
                            }
                        }
                        if (launchSettings.containsKey("imageDataFile")) {
                            String value = launchSettings.get("imageDataFile");
                            if (value.contains(",")) {
                                String[] split = value.split(",");
                                for (String s : split) {
                                    imageData.loadDataFromFile(Utils.getFile(batchFile.getParentFile(), s));
                                }
                            } else {
                                imageData.loadDataFromFile(Utils.getFile(batchFile.getParentFile(), value));
                            }
                        }

                        //Run each wiki build one phase at a time to allow data to be shared correctly
                        builders.forEach(PageBuilder::parseSettings);

                        //If changed update page build html load process
                        logger.info("\tLoading theme");
                        pageTheme.load();
                        pageTheme.loadTemplates();
                        logger.info("\tDone");

                        builders.forEach(PageBuilder::parseSettings);
                        builders.forEach(PageBuilder::loadWikiData);
                        builders.forEach(PageBuilder::parseWikiData);
                        builders.forEach(PageBuilder::buildWikiData);
                        builders.forEach(PageBuilder::buildPages);
                    } else {
                        throw new RuntimeException("Batch file's job list is empty");
                    }
                } else {
                    throw new RuntimeException("Batch file does not contain the 'jobs' tag");
                }
            } else {
                throw new RuntimeException("Batch file is not a valid json object");
            }
        } else {
            throw new RuntimeException("Batch file is missing or invalid.");
        }
    } else {
        //Vars
        File workingDirector = null;
        File settingsFile = null;

        //Get our working folder
        if (launchSettings.containsKey("workingFolder")) {
            workingDirector = Utils.getFile(new File("."), launchSettings.get("workingFolder"));
        }
        if (workingDirector == null) {
            workingDirector = new File(".");
        }
        if (!workingDirector.exists()) {
            workingDirector.mkdirs();
        }

        //Get our settings file
        if (launchSettings.containsKey("settingsFile")) {
            settingsFile = Utils.getFile(workingDirector, launchSettings.get("settingsFile"));
        }
        if (settingsFile == null) {
            settingsFile = new File(workingDirector, SETTINGS_FILE_NAME);
        }
        if (!settingsFile.getParentFile().exists()) {
            settingsFile.getParentFile().mkdirs();
        }
        if (!settingsFile.exists()) {
            throw new RuntimeException("Settings file does not exist at location: " + settingsFile);
        }

        //Output settings
        logger.info("Working folder :" + workingDirector);
        logger.info("Settings file  :" + settingsFile);

        //Start process
        PageTheme pageTheme = null;
        if (launchSettings.containsKey("theme")) {
            File file = Utils.getFile(workingDirector, launchSettings.get("theme"));
            if (file.isDirectory()) {
                file = new File(file, "theme.json");
            }
            pageTheme = new PageTheme(file);
            logger.info("Theme is being set by program arguments! Theme in settings file will not be used.");
            logger.info("Theme : " + pageTheme.themeFile);
        }
        PageBuilder builder = new PageBuilder(logger, workingDirector, settingsFile, launchSettings, pageTheme,
                new ImageData(), new LinkData());
        builder.run();
    }

    //End of program pause
    if (!launchSettings.containsKey("noConfirm")) {
        logger.info("Press 'any' key to continue...");
        try {
            System.in.read();
        } catch (IOException e) {
        }
    }
    System.exit(0);
}

From source file:com.bzcentre.dapiPush.MeetingPayload.java

License:Open Source License

private Object extractAps(JsonElement in) {
    if (in == null || in.isJsonNull())
        return null;

    if (in.isJsonArray()) {
        List<Object> list = new ArrayList<>();
        JsonArray arr = in.getAsJsonArray();
        for (JsonElement anArr : arr) {
            list.add(extractAps(anArr));
        }/*from   w w w.  j  a  va2 s . c  o m*/
        return list;
    } else if (in.isJsonObject()) {
        Map<String, Object> map = new LinkedTreeMap<>();
        JsonObject obj = in.getAsJsonObject();
        Set<Map.Entry<String, JsonElement>> entitySet = obj.entrySet();
        for (Map.Entry<String, JsonElement> entry : entitySet) {
            map.put(entry.getKey(), extractAps(entry.getValue()));
            NginxClojureRT.log.debug(TAG + entry.getKey() + "=>" + map.get(entry.getKey()) + "=>"
                    + map.get(entry.getKey()).getClass().getTypeName());
            switch (entry.getKey()) {
            case "dapi":
                this.setDapi(map.get(entry.getKey()));
                break;
            case "acme1":
                this.setAcme1(map.get(entry.getKey()));
                break;
            case "acme2":
                this.setAcme2(map.get(entry.getKey()));
                break;
            case "acme3":
                this.setAcme3(map.get(entry.getKey()));
                break;
            case "acme4":
                this.setAcme4(map.get(entry.getKey()));
                break;
            case "acme5":
                this.setAcme5(map.get(entry.getKey()));
                break;
            case "acme6":
                this.setAcme6(map.get(entry.getKey()));
                break;
            case "acme7":
                this.setAcme7(map.get(entry.getKey()));
                break;
            case "acme8":
                this.setAcme8(map.get(entry.getKey()));
                break;
            case "aps":
                NginxClojureRT.log.debug(TAG + "aps initialized");
                break;
            case "badge":
                this.getAps().setBadge(map.get(entry.getKey()));
                break;
            case "sound":
                this.getAps().setSound(map.get(entry.getKey()));
                break;
            case "alert":
                NginxClojureRT.log.debug(TAG + "alert initialized");
                break;
            case "title":
                this.getAps().getAlert().setTitle(map.get(entry.getKey()));
                break;
            case "body":
                this.getAps().getAlert().setBody(map.get(entry.getKey()));
                break;
            case "action-loc-key":
                this.getAps().getAlert().setActionLocKey(map.get(entry.getKey()));
                break;
            default:
                NginxClojureRT.log.info(TAG + "Unhandled field : " + entry.getKey());
                break;
            }
        }
        return map;
    } else if (in.isJsonPrimitive()) {
        JsonPrimitive prim = in.getAsJsonPrimitive();
        if (prim.isBoolean()) {
            return prim.getAsBoolean();
        } else if (prim.isString()) {
            return prim.getAsString();
        } else if (prim.isNumber()) {
            Number num = prim.getAsNumber();
            // here you can handle double int/long values
            // and return any type you want
            // this solution will transform 3.0 float to long values
            if (Math.ceil(num.doubleValue()) == num.longValue()) {
                return num.longValue();
            } else {
                return num.doubleValue();
            }
        }
    }
    NginxClojureRT.log.info("Handling json null");
    return null;
}

From source file:com.ca.dvs.utilities.raml.RamlUtil.java

License:Open Source License

/**
 * @param jsonString//from www. j  av a 2  s  .c  o m
 * @return the appropriate JsonElement object from the parsed jsonString
 */
private static Object getJsonElementValue(String jsonString) {

    JsonParser jsonParser = new JsonParser();
    JsonElement jsonElement = jsonParser.parse(jsonString);

    if (jsonElement.isJsonObject()) {

        return jsonElement.getAsJsonObject();

    } else if (jsonElement.isJsonArray()) {

        return jsonElement.getAsJsonArray();

    } else if (jsonElement.isJsonNull()) {

        return jsonElement.getAsJsonNull();

    } else if (jsonElement.isJsonPrimitive()) {

        return jsonElement.getAsJsonPrimitive();

    } else {

        return null;

    }
}

From source file:com.ccc.crest.core.cache.crest.schema.endpoint.EndpointCollection.java

License:Open Source License

@Override
public EndpointCollection deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject topObj = (JsonObject) json;
    Set<Entry<String, JsonElement>> topSet = topObj.entrySet();
    Iterator<Entry<String, JsonElement>> topIter = topSet.iterator();
    do {//w  w  w.ja  v a2  s  . co  m
        if (!topIter.hasNext())
            break;
        Entry<String, JsonElement> topEntry = topIter.next();
        String topKey = topEntry.getKey();
        JsonElement topElement = topEntry.getValue();
        if (topKey.equals(UserCountKey)) {
            userCount = Long.parseLong(topElement.getAsString());
            continue;
        }
        if (topKey.equals(UserCountStrKey))
            continue;
        if (topKey.equals(ServerVersionKey)) {
            serverVersion = topElement.getAsString();
            continue;
        }
        if (topKey.equals(ServerNameKey)) {
            serverName = topElement.getAsString();
            continue;
        }
        if (topKey.equals(ServerStatusKey)) {
            serviceStatus = topElement.getAsString();
            continue;
        }
        // if its not a top object level known variable from above list, it must be a group object
        if (topElement.isJsonPrimitive()) {
            log.warn("unexpected key: " + topKey + " = " + topObj.toString());
            continue;
        }
        if (!topElement.isJsonObject()) {
            log.warn("expected an object: " + topKey + " = " + topObj.toString());
            continue;
        }
        // first pass you should have a group in the topElement
        String groupName = topKey;
        EndpointGroup endpointGroup = new EndpointGroup(groupName);
        callGroups.add(endpointGroup);
        Set<Entry<String, JsonElement>> groupSet = topElement.getAsJsonObject().entrySet();
        Iterator<Entry<String, JsonElement>> groupIter = groupSet.iterator();
        do {
            if (!groupIter.hasNext())
                break;
            Entry<String, JsonElement> groupEntry = groupIter.next();
            // expecting a primitive href here
            String endpointName = groupEntry.getKey();
            JsonElement hrefElement = groupEntry.getValue();
            if (hrefElement.isJsonObject()) {
                JsonObject groupChildObj = (JsonObject) hrefElement;
                Set<Entry<String, JsonElement>> groupChildSet = groupChildObj.entrySet();
                Iterator<Entry<String, JsonElement>> groupChildIter = groupChildSet.iterator();
                if (!groupChildIter.hasNext())
                    break;
                Entry<String, JsonElement> groupChildEntry = groupChildIter.next();
                String groupChildKey = groupChildEntry.getKey();
                JsonElement groupChildElement = groupChildEntry.getValue();
                endpointGroup.addEndpoint(new CrestEndpoint(endpointName, groupChildElement.getAsString()));
                continue;
            }
            // expect an object with href in it
            if (!hrefElement.isJsonPrimitive()) {
                log.warn("expected a primitive after group: " + groupName + " = " + hrefElement.toString());
                continue;
            }
            endpointGroup.addEndpoint(new CrestEndpoint(endpointName, hrefElement.getAsString()));
            break;
        } while (true);
    } while (true);
    return this;
}

From source file:com.ccreanga.bitbucket.rest.client.http.responseparsers.CommentAnchorParser.java

License:Apache License

@Override
public CommentAnchor apply(JsonElement jsonElement) {
    if (jsonElement == null || !jsonElement.isJsonObject()) {
        return null;
    }//w  ww  .j a v  a  2s  . c  o  m

    JsonObject json = jsonElement.getAsJsonObject();
    return new CommentAnchor(optionalJsonString(json, "fromHash"), json.get("toHash").getAsString(),
            optionalJsonLong(json, "line"),
            json.has("lineType") ? LineType.valueOf(json.get("lineType").getAsString()) : null,
            json.has("fileType") ? FileType.valueOf(json.get("fileType").getAsString()) : null,
            json.get("path").getAsString(), optionalJsonString(json, "srcPath"),
            json.get("orphaned").getAsBoolean());
}

From source file:com.ccreanga.bitbucket.rest.client.http.responseparsers.CommentParser.java

License:Apache License

@Override
public Comment apply(JsonElement jsonElement) {
    if (jsonElement == null || !jsonElement.isJsonObject()) {
        return null;
    }/*from   ww  w . java 2  s .  co  m*/
    JsonObject json = jsonElement.getAsJsonObject();
    return new Comment(json.get("id").getAsLong(), json.get("version").getAsLong(),
            json.get("text").getAsString(), userParser().apply(json.getAsJsonObject("author")),
            new Date(json.get("createdDate").getAsLong()), new Date(json.get("updatedDate").getAsLong()),
            listParser(commentParser()).apply(json.get("comments")),
            permittedOperationsParser().apply(json.getAsJsonObject("permittedOperations")));

}

From source file:com.ccreanga.bitbucket.rest.client.http.responseparsers.CommitParser.java

License:Apache License

@Override
public Commit apply(JsonElement jsonElement) {

    if (jsonElement == null || !jsonElement.isJsonObject()) {
        return null;
    }//from w w w. j ava  2s .  c o  m
    JsonObject json = jsonElement.getAsJsonObject();

    return new Commit(json.get("id").getAsString(), json.get("displayId").getAsString(),
            json.get("author").getAsJsonObject().get("name").getAsString(),
            json.get("author").getAsJsonObject().get("emailAddress").getAsString(),
            json.get("authorTimestamp").getAsLong(), json.get("message").getAsString(),
            listParser(minimalCommitParser()).apply(json.get("parents")));
}