Example usage for com.google.gson JsonObject getAsJsonPrimitive

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

Introduction

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

Prototype

public JsonPrimitive getAsJsonPrimitive(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonPrimitive element.

Usage

From source file:com.builtbroken.builder.html.data.ImageData.java

public void parseJsonImageEnergy(String key, JsonObject linkEntryObject) {
    String path = linkEntryObject.getAsJsonPrimitive("path").getAsString();
    String alt = linkEntryObject.getAsJsonPrimitive("alt").getAsString();
    if (linkEntryObject.has("url")) {
        add(key, path, alt, linkEntryObject.getAsJsonPrimitive("url").getAsString());
    } else {//from  w  w w .  j a  v  a2  s.  c  o  m
        add(key, path, alt);
    }
}

From source file:com.builtbroken.builder.html.data.LinkData.java

public void parseJsonLinkEnergy(String key, JsonObject linkEntryObject) {
    String text = linkEntryObject.getAsJsonPrimitive("text").getAsString();
    String url = linkEntryObject.getAsJsonPrimitive("url").getAsString();
    add(key, text, url);/*from  ww  w  .j  av a 2  s  .  c  om*/
}

From source file:com.builtbroken.builder.html.page.PageData.java

/**
 * Called to load the page from json/* w w  w  .j a  va  2  s  .  c  om*/
 */
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//from  w w w  . j  a v  a2 s  .  c  om
 */
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 v  a 2 s.  c o m
        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  w w  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");
                        }/*  w  w  w  .  ja  v a  2 s . co  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.canoo.dolphin.impl.codec.CreatePresentationModelEncoder.java

License:Apache License

@Override
public CreatePresentationModelCommand decode(JsonObject jsonObject) {
    Assert.requireNonNull(jsonObject, "jsonObject");

    try {//from  w w  w  . j  a  v  a  2 s .  c om
        final CreatePresentationModelCommand command = new CreatePresentationModelCommand();

        command.setPmId(jsonObject.getAsJsonPrimitive(PM_ID).getAsString());
        command.setPmType(jsonObject.getAsJsonPrimitive(PM_TYPE).getAsString());
        command.setClientSideOnly(false);

        final JsonArray jsonArray = jsonObject.getAsJsonArray(PM_ATTRIBUTES);
        final List<Map<String, Object>> attributes = new ArrayList<>();
        for (final JsonElement jsonElement : jsonArray) {
            final JsonObject attribute = jsonElement.getAsJsonObject();
            final HashMap<String, Object> map = new HashMap<>();
            map.put("propertyName", attribute.getAsJsonPrimitive(ATTRIBUTE_NAME).getAsString());
            map.put("id", attribute.getAsJsonPrimitive(ATTRIBUTE_ID).getAsString());
            final Object value = attribute.has(ATTRIBUTE_VALUE) ? decodeValue(attribute.get(ATTRIBUTE_VALUE))
                    : null;
            map.put("value", value);
            map.put("baseValue", value);
            map.put("qualifier", null);
            attributes.add(map);
        }
        command.setAttributes(attributes);

        return command;
    } catch (IllegalStateException | ClassCastException | NullPointerException ex) {
        throw new JsonParseException("Illegal JSON detected", ex);
    }
}

From source file:com.canoo.dolphin.impl.codec.OptimizedJsonCodec.java

License:Apache License

@Override
public List<Command> decode(String transmitted) {
    Assert.requireNonNull(transmitted, "transmitted");
    LOG.trace("Decoding message: {}", transmitted);
    try {/*from   w  w  w . j av a2  s.co m*/
        final List<Command> commands = new ArrayList<>();
        final JsonArray array = (JsonArray) new JsonParser().parse(transmitted);

        for (final JsonElement jsonElement : array) {
            final JsonObject command = (JsonObject) jsonElement;
            JsonPrimitive idPrimitive = command.getAsJsonPrimitive("id");

            String id = null;
            if (idPrimitive != null) {
                id = idPrimitive.getAsString();
            }
            LOG.trace("Decoding command: {}", id);
            CommandEncoder<?> encoder = null;
            if (id != null) {
                encoder = DECODERS.get(id);
            }
            if (encoder != null) {
                commands.add(encoder.decode(command));
            } else {
                commands.addAll(fallBack.decode("[" + command.toString() + "]"));
            }
        }
        LOG.trace("Decoded command list with {} commands", commands.size());
        return commands;
    } catch (ClassCastException | NullPointerException ex) {
        throw new JsonParseException("Illegal JSON detected", ex);
    }
}

From source file:com.cloudant.http.interceptors.CookieInterceptor.java

License:Open Source License

@Override
public HttpConnectionInterceptorContext interceptResponse(HttpConnectionInterceptorContext context) {
    HttpURLConnection connection = context.connection.getConnection();
    try {//from w  w  w  .  jav  a  2 s  .  c o  m
        boolean renewCookie = false;
        int statusCode = connection.getResponseCode();
        switch (statusCode) {
        case HttpURLConnection.HTTP_FORBIDDEN: //403
            //check if it was an expiry case
            InputStream errorStream = connection.getErrorStream();
            String errorString = new String(IOUtils.toString(errorStream, "UTF-8"));
            try {
                JsonObject errorResponse = new Gson().fromJson(errorString, JsonObject.class);
                String error = errorResponse.getAsJsonPrimitive("error").getAsString();
                String reason = errorResponse.getAsJsonPrimitive("reason").getAsString();
                if (!"credentials_expired".equals(error)) {
                    //wasn't a credentials expired, throw exception
                    throw new HttpConnectionInterceptorException(error, reason);
                } else {
                    // Was expired - set boolean to renew cookie
                    renewCookie = true;
                }
            } catch (JsonParseException e) {
                //wasn't JSON throw an exception
                throw new HttpConnectionInterceptorException(errorString);
            } finally {
                errorStream.close();
            }
            break;
        case HttpURLConnection.HTTP_UNAUTHORIZED: //401
            // We need to get a new cookie
            renewCookie = true;
            break;
        default:
            break;
        }
        if (renewCookie) {
            cookie = getCookie(connection.getURL(), context);
            // Don't resend request, failed to get cookie
            if (cookie != null) {
                context.replayRequest = true;
            } else {
                context.replayRequest = false;
            }
        }
    } catch (IOException e) {
        logger.log(Level.SEVERE, "Failed to get response code from request", e);
    }
    return context;

}