Example usage for com.google.gson JsonObject entrySet

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

Introduction

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

Prototype

public Set<Map.Entry<String, JsonElement>> entrySet() 

Source Link

Document

Returns a set of members of this object.

Usage

From source file:com.bizosys.dataservice.dao.WriteToXls.java

License:Apache License

public static void main(String[] args) throws Exception {

    String json = " { \"values\" : [ { \"name\" : \"ravi\" , \"id\" : \"334\" }, { \"name\" : \"kumar\" , \"id\" : \"335\" } ] }";
    JsonParser parser = new JsonParser();
    JsonObject o = (JsonObject) parser.parse(json);

    JsonArray values = o.getAsJsonArray("values");

    Set<Map.Entry<String, JsonElement>> entrySet = null;

    List<Object[]> records = new ArrayList<Object[]>();
    List<Object> cols = new ArrayList<Object>();

    List<String> labels = new ArrayList<String>();
    boolean isFirst = true;
    for (JsonElement elem : values) {
        JsonObject obj = elem.getAsJsonObject();
        entrySet = obj.entrySet();
        cols.clear();/*w  ww . java 2s  .c o m*/
        if (isFirst) {
            for (Map.Entry<String, JsonElement> entry : entrySet) {
                labels.add(entry.getKey());
            }
            isFirst = false;
        }

        for (String aLabel : labels) {
            cols.add(obj.get(aLabel).getAsString());
        }
        records.add(cols.toArray());
    }

    OutputStream out = null;
    out = new FileOutputStream(new File("/tmp/test.xlsx"));
    WriteToXls writerXls = new WriteToXls(out, 0, 0);
    writerXls.write(records);
}

From source file:com.blackducksoftware.integration.hub.detect.detector.npm.NpmCliParser.java

License:Apache License

private void populateChildren(final MutableDependencyGraph graph, final Dependency parentDependency,
        final JsonObject parentNodeChildren, final Boolean root) {
    if (parentNodeChildren == null) {
        return;//from  w  w  w .ja va 2  s.  c  om
    }
    final Set<Entry<String, JsonElement>> elements = parentNodeChildren.entrySet();
    elements.forEach(it -> {
        if (it.getValue() != null && it.getValue().isJsonObject()) {

        }
        final JsonObject element = it.getValue().getAsJsonObject();
        final String name = it.getKey();
        String version = null;
        final JsonPrimitive versionPrimitive = element.getAsJsonPrimitive(JSON_VERSION);
        if (versionPrimitive != null && versionPrimitive.isString()) {
            version = versionPrimitive.getAsString();
        }
        final JsonObject children = element.getAsJsonObject(JSON_DEPENDENCIES);

        if (name != null && version != null) {
            final ExternalId externalId = externalIdFactory.createNameVersionExternalId(Forge.NPM, name,
                    version);
            final Dependency child = new Dependency(name, version, externalId);

            populateChildren(graph, child, children, false);
            if (root) {
                graph.addChildToRoot(child);
            } else {
                graph.addParentWithChild(parentDependency, child);
            }
        }
    });
}

From source file:com.blackducksoftware.integration.hub.detect.detector.packagist.PackagistParser.java

License:Apache License

private List<NameVersion> parseDependenciesFromRequire(final JsonObject requireObject) {
    final List<NameVersion> dependencies = new ArrayList<>();
    requireObject.entrySet().forEach(it -> {
        if (!it.getKey().equalsIgnoreCase("php")) {
            final NameVersion nameVersion = new NameVersion(it.getKey().toString(), it.getValue().toString());
            dependencies.add(nameVersion);
        }//from   w  w  w . j  av a2 s . c  om
    });
    return dependencies;
}

From source file:com.braindrainpain.docker.DockerRepository.java

License:Open Source License

private DockerTag getLatestTag(final JsonObject tags, final String tagName) {
    DockerTag result = null;//from www  . j  a va  2  s .  co m
    for (Map.Entry<String, JsonElement> entry : tags.entrySet()) {
        if (tagName.equals(entry.getKey())) {
            result = new DockerTag(entry.getKey(), entry.getValue().getAsString());
            LOG.info("Found tag: " + result);
            break;
        }
    }
    return result;
}

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

/**
 * Parses the json object as an array of links
 * <p>// w  w  w  .  j  a va  2  s  .c o  m
 * If the object doesn't contain a list of links it will be ignored with no warning
 *
 * @param linkObject - json object
 */
public void parseJsonImageArray(JsonObject linkObject) {
    if (linkObject.has("images")) {
        Set<Map.Entry<String, JsonElement>> linkEntrySet = linkObject.entrySet();
        for (Map.Entry<String, JsonElement> entry : linkEntrySet) {
            JsonObject linkEntryObject = entry.getValue().getAsJsonObject();
            parseJsonImageEnergy(entry.getKey(), linkEntryObject);
        }
    }
}

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

/**
 * Parses the json object as an array of links
 * <p>//from  www. j  a  v a2 s. c om
 * If the object doesn't contain a list of links it will be ignored with no warning
 *
 * @param linkObject - json object
 */
public void parseJsonLinkArray(JsonObject linkObject) {
    if (linkObject.has("links")) {
        Set<Map.Entry<String, JsonElement>> linkEntrySet = linkObject.entrySet();
        for (Map.Entry<String, JsonElement> entry : linkEntrySet) {
            JsonObject linkEntryObject = entry.getValue().getAsJsonObject();
            parseJsonLinkEnergy(entry.getKey(), linkEntryObject);
        }
    }
}

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

/**
 * Converts json data into html data/*from   w w w .  jav a 2  s .  c  om*/
 *
 * @param object - json content object
 * @return HTML as string
 */
public String toHTML(final JsonObject object) {
    String html = "";
    //Convert content into HTML
    Set<Map.Entry<String, JsonElement>> entrySet = object.entrySet();
    for (Map.Entry<String, JsonElement> entry : entrySet) {
        html += JsonProcessorHTML.process(entry.getKey(), entry.getValue());
    }
    return html;
}

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   www . j  av  a2  s  . 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

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));
        }/*  w w  w.  j av a2 s.  c  om*/
        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.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 {/*from w  w  w. ja v a 2  s. c  o 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;
}