List of usage examples for com.google.gson JsonElement getAsJsonObject
public JsonObject getAsJsonObject()
From source file:com.builtbroken.builder.html.data.LinkData.java
/** * Loads a file from disk as a json file * then parses the file looking for an array * of links formatted as {"key":{"text":"String","url":"String"}} * * @param file - file to load, throws an exception if the file is invalid *///from w w w . j a v a 2s. c o m public void loadDataFromFile(File file) { if (file.exists()) { if (file.isFile()) { JsonElement linkJson = Utils.toJsonElement(file); if (linkJson.isJsonObject()) { parseJsonLinkArray(linkJson.getAsJsonObject()); } else { throw new IllegalArgumentException("Link data file is not a valid json object. File = " + file); } } else { throw new IllegalArgumentException("Link data file is not a valid file. File = " + file); } } else { throw new IllegalArgumentException("Link data file is missing. File = " + file); } }
From source file:com.builtbroken.builder.html.page.PageData.java
/** * Called to load the page from json//from w w w.j a va2s .co m */ public void load(PageBuilder builder) { imgReplaceKeys = new HashMap(); linkReplaceKeys = new HashMap(); //TODO format nano time outputs on debugger debug("Loading new Page Data"); long startTime = System.nanoTime(); debug("\tLoading file from disk"); JsonElement element = Utils.toJsonElement(file); startTime = System.nanoTime() - startTime; debug("\tDone..." + startTime + "ns"); if (element.isJsonObject()) { debug("\tParsing json"); startTime = System.nanoTime(); JsonObject object = element.getAsJsonObject(); if (object.has("pageName")) { pageName = object.getAsJsonPrimitive("pageName").getAsString(); debug("\tDisplay Name: " + pageName); } if (object.has("fileName")) { fileNameOverride = object.getAsJsonPrimitive("fileName").getAsString(); debug("\tFile Name: " + fileNameOverride); } if (object.has("fileExtension")) { fileExtension = object.getAsJsonPrimitive("fileExtension").getAsString(); debug("\tFile Extension: " + fileExtension); } if (object.has("type")) { type = object.getAsJsonPrimitive("type").getAsString().toLowerCase(); debug("\tType: " + type); if (type.equalsIgnoreCase("ignore")) { return; } } if (object.has("category_display_name")) { categoryDisplayName = object.getAsJsonPrimitive("category_display_name").getAsString(); debug("\tCategory Display Name: " + type); } if (object.has("category_display_order")) { categoryDisplayOrder = object.getAsJsonPrimitive("category_display_order").getAsString(); debug("\tCategory Display Order: " + type); } if (object.has("category")) { category = object.getAsJsonPrimitive("category").getAsString().toLowerCase(); debug("\tCategory: " + category); } if (object.has("replaceKeys")) { Gson gson = new Gson(); Map<String, String> map = new HashMap(); map = (Map<String, String>) gson.fromJson(object.get("replaceKeys"), map.getClass()); linkReplaceKeys.putAll(map); debug("\tLinks Keys: " + linkReplaceKeys.size()); } if (object.has("imageKeys")) { Gson gson = new Gson(); Map<String, String> map = new HashMap(); map = (Map<String, String>) gson.fromJson(object.get("imageKeys"), map.getClass()); imgReplaceKeys.putAll(map); debug("\tImage Keys: " + imgReplaceKeys.size()); } if (object.has("content")) { debug("\tLoading Page Content"); long time = System.nanoTime(); //Split HTML into segments for injection process(toHTML(object.getAsJsonObject("content"))); time = System.nanoTime() - time; debug("\tDone..." + time + "ns"); } } else { throw new RuntimeException( "File " + file + " is not a valid json object so can not be parsed into a wiki page."); } debug("\tProcessing reference data..."); //Loop all contained link replace keys for (Map.Entry<String, String> entry : linkReplaceKeys.entrySet()) { final String key = entry.getKey().toLowerCase(); if (!builder.linkData.linkReplaceKeys.containsKey(key)) { String html = "<a href=\"" + getOutput(builder.vars.get("outputPath")) + "\">" + entry.getValue() + "</a>"; builder.linkData.linkReplaceKeys.put(key, html); debug("\t\tKey: " + key + " --> " + html); } else { throw new RuntimeException("Duplicate link key[" + entry.getKey() + "] was found for page [" + pageName + "] key is linked to " + builder.linkData.linkReplaceKeys.get(key)); } } //Loop all image replace keys for (Map.Entry<String, String> entry : imgReplaceKeys.entrySet()) { final String key = entry.getKey().toLowerCase(); if (!builder.imageData.imageReplaceKeys.containsKey(key)) { String path = builder.vars.get("imagePath") + entry.getValue(); String html = "<img src=\"" + entry.getValue() + "\">"; builder.imageData.imageReplaceKeys.put(key, html); builder.imageData.images.put(key, path); debug("\t\tKey: " + key + " --> " + html); } else { throw new RuntimeException("Duplicate image key[" + entry.getKey() + "] was found for page [" + pageName + "] key is linked to " + builder.imageData.imageReplaceKeys.get(key)); } } //Debug startTime = System.nanoTime() - startTime; debug("Done..." + startTime + "ns"); }
From source file:com.builtbroken.builder.html.PageBuilder.java
/** * Called to parse the settings file//ww w.j a v a 2s .com */ 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 {//from w w w . j a va 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 ww w. j a v 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"); }// ww w .j a v a 2s . c o m 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
public MeetingPayload deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { NginxClojureRT.log/*from w w w. ja v a 2 s . co m*/ .debug(TAG + "Deserialize json to type:" + typeOfT.getTypeName() + "=>" + json.toString()); JsonObject jsonObject = json.getAsJsonObject(); extractAps(jsonObject); return this; }
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)); }//ww w. j a v a 2 s . com 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 w ww. j a va 2 s .c om*/ * @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.canoo.cog.sonar.JsonToModelConverter.java
License:Apache License
private void fillModel(JsonArray msr, ModelImpl model) { for (JsonElement jsonElement : msr) { String key = jsonElement.getAsJsonObject().get("key").getAsString(); String val = jsonElement.getAsJsonObject().get("val").getAsString(); switch (key) { case SonarConstants.CLASSES: model.setClasses(val); break; case SonarConstants.CLASS_COMPLEXITY: model.setClassComplexity(val); break; case SonarConstants.COMMENT_LINES: model.setCommentLines(val); break; case SonarConstants.COMMENT_LINES_DENSITY: model.setCommentLineDensity(val); break; case SonarConstants.COMPLEXITY: model.setComplexity(val); break; case SonarConstants.COVERAGE: model.setCoverage(val); break; case SonarConstants.DIRECTORIES: model.setDirectories(val); break; case SonarConstants.FILE_COMPLEXITY: model.setFileComplexity(val); break; case SonarConstants.FILES: model.setFiles(val); break; case SonarConstants.FUNCTION_COMPLEXITY: model.setFunctionComplexity(val); break; case SonarConstants.FUNCTIONS: model.setFunctions(val); break; case SonarConstants.LINES_OF_CODE: model.setLinesOfCode(val); break; case SonarConstants.PUBLIC_API: model.setPublicApi(val); break; case SonarConstants.TESTS: model.setTests(val); break; case SonarConstants.STATEMENTS: model.setStatements(val); break; case SonarConstants.SQALE_INDEX: model.setSqaleIndex(val); break; }//from w w w .ja v a 2 s. co m } }