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:at.tugraz.kmi.medokyservice.fca.util.ImportExport.java

License:Open Source License

private Map<Long, LearningObject> json2LearningObjects(JsonObject json, Map<Long, User> users) {
    HashMap<Long, LearningObject> learningObjects = new HashMap<Long, LearningObject>();
    JsonObject block = json.get(SECTION_LO).getAsJsonObject();

    Set<Entry<String, JsonElement>> entries = block.entrySet();
    for (Entry<String, JsonElement> lo : entries) {
        JsonObject jsLo = lo.getValue().getAsJsonObject();
        User owner;//ww  w .j a va 2 s  . c  om
        try {
            owner = users.get(Long.parseLong(jsLo.get(OWNER).getAsString()));
        } catch (Exception e) {
            owner = null;
        }
        LearningObject learningObject = new LearningObject(jsLo.get(NAME).getAsString(),
                jsLo.get(DESCRIPTION).getAsString(), jsLo.get(DATA).getAsString(), owner);
        learningObjects.put(Long.parseLong(lo.getKey()), learningObject);
    }
    return learningObjects;
}

From source file:at.tugraz.kmi.medokyservice.fca.util.ImportExport.java

License:Open Source License

@SuppressWarnings("unchecked")
private <E extends FCAAbstract> Map<Long, E> json2Absctract(JsonObject json,
        Map<Long, LearningObject> learningObjects, Class<E> type) {
    HashMap<Long, E> objects = new HashMap<Long, E>();
    JsonObject block = null;
    if (type == FCAObject.class)
        block = json.get(SECTION_O).getAsJsonObject();
    else if (type == FCAAttribute.class)
        block = json.get(SECTION_A).getAsJsonObject();
    Set<Entry<String, JsonElement>> entries = block.entrySet();
    for (Entry<String, JsonElement> o : entries) {
        JsonObject jsO = o.getValue().getAsJsonObject();
        E object;// www  .ja  va2  s.  co m
        String creationId;
        if (!jsO.has(CID)) {
            double num = rand.nextDouble() * 10000;
            int val = (int) num;
            creationId = Integer.toString(val, 16);
        } else
            creationId = jsO.get(CID).getAsString();
        if (type == FCAObject.class)
            object = (E) new FCAObject(jsO.get(NAME).getAsString(), jsO.get(DESCRIPTION).getAsString(),
                    creationId);
        else
            object = (E) new FCAAttribute(jsO.get(NAME).getAsString(), jsO.get(DESCRIPTION).getAsString(),
                    creationId);
        Set<LearningObject> lObjs = new HashSet<LearningObject>();
        Set<LearningObject> lObjsByLearner = new HashSet<LearningObject>();
        Iterator<JsonElement> lOs = jsO.getAsJsonArray(SECTION_LO).iterator();
        while (lOs.hasNext()) {
            LearningObject lo = learningObjects.get((lOs.next().getAsLong()));
            if (lo != null)
                lObjs.add(lo);
        }
        try {
            Iterator<JsonElement> lOsByLearner = jsO.getAsJsonArray(SECTION_LO_L).iterator();
            while (lOsByLearner.hasNext()) {
                LearningObject lo = learningObjects.get((lOsByLearner.next().getAsLong()));
                if (lo != null)
                    lObjsByLearner.add(lo);
            }
        } catch (Exception notAnError) {

        }
        clean(lObjsByLearner);
        object.setLearningObjectsByLearners(lObjsByLearner);
        clean(lObjs);
        object.setLearningObjects(lObjs);
        objects.put(Long.parseLong(o.getKey()), object);
    }
    return objects;
}

From source file:at.tugraz.kmi.medokyservice.fca.util.ImportExport.java

License:Open Source License

private Map<Long, FCAItemMetadata> json2Metadata(JsonObject json, Map<Long, LearningObject> learningObjects) {
    Map<Long, FCAItemMetadata> result = new HashMap<Long, FCAItemMetadata>();
    JsonObject jsM = json.get(SECTION_M).getAsJsonObject();
    for (Entry<String, JsonElement> entry : jsM.entrySet()) {
        JsonObject val = entry.getValue().getAsJsonObject();
        JsonArray arr = val.get(SECTION_LO).getAsJsonArray();
        LinkedHashSet<LearningObject> l_objsByLearner = new LinkedHashSet<LearningObject>();
        try {/*  w w  w  . j a  v  a2  s. c om*/
            JsonArray arrByLearner = val.get(SECTION_LO_L).getAsJsonArray();
            for (JsonElement loID : arrByLearner)
                l_objsByLearner.add(learningObjects.get(loID.getAsLong()));
        } catch (Exception notAnError) {

        }
        LinkedHashSet<LearningObject> l_objs = new LinkedHashSet<LearningObject>();
        for (JsonElement loID : arr)
            l_objs.add(learningObjects.get(loID.getAsLong()));
        clean(l_objs);
        clean(l_objsByLearner);
        result.put(Long.parseLong(entry.getKey()), new FCAItemMetadata(val.get(DESCRIPTION).getAsString(),
                val.get(O_ID).getAsLong(), l_objs, l_objsByLearner));
    }
    return result;
}

From source file:bammerbom.ultimatecore.bukkit.resources.utils.JsonRepresentedObject.java

License:MIT License

/**
 * Deserializes a fancy message from its JSON representation. This JSON
 * representation is of the format of that returned by
 * {@link #toJSONString()}, and is compatible with vanilla inputs.
 *
 * @param json The JSON string which represents a fancy message.
 * @return A {@code MessageUtil} representing the parameterized JSON
 * message.//from   www.  jav a 2  s  . com
 */
public static MessageUtil deserialize(String json) {
    JsonObject serialized = _stringParser.parse(json).getAsJsonObject();
    JsonArray extra = serialized.getAsJsonArray("extra"); // Get the extra component
    MessageUtil returnVal = new MessageUtil();
    returnVal.messageParts.clear();
    for (JsonElement mPrt : extra) {
        MessagePart component = new MessagePart();
        JsonObject messagePart = mPrt.getAsJsonObject();
        for (Map.Entry<String, JsonElement> entry : messagePart.entrySet()) {
            // Deserialize text
            if (TextualComponent.isTextKey(entry.getKey())) {
                // The map mimics the YAML serialization, which has a "key" field and one or more "value" fields
                Map<String, Object> serializedMapForm = new HashMap<>(); // Must be object due to Bukkit serializer API compliance
                serializedMapForm.put("key", entry.getKey());
                if (entry.getValue().isJsonPrimitive()) {
                    // Assume string
                    serializedMapForm.put("value", entry.getValue().getAsString());
                } else {
                    // Composite object, but we assume each element is a string
                    for (Map.Entry<String, JsonElement> compositeNestedElement : entry.getValue()
                            .getAsJsonObject().entrySet()) {
                        serializedMapForm.put("value." + compositeNestedElement.getKey(),
                                compositeNestedElement.getValue().getAsString());
                    }
                }
                component.text = TextualComponent.deserialize(serializedMapForm);
            } else if (MessagePart.stylesToNames.inverse().containsKey(entry.getKey())) {
                if (entry.getValue().getAsBoolean()) {
                    component.styles.add(MessagePart.stylesToNames.inverse().get(entry.getKey()));
                }
            } else if (entry.getKey().equals("color")) {
                component.color = ChatColor.valueOf(entry.getValue().getAsString().toUpperCase());
            } else if (entry.getKey().equals("clickEvent")) {
                JsonObject object = entry.getValue().getAsJsonObject();
                component.clickActionName = object.get("action").getAsString();
                component.clickActionData = object.get("value").getAsString();
            } else if (entry.getKey().equals("hoverEvent")) {
                JsonObject object = entry.getValue().getAsJsonObject();
                component.hoverActionName = object.get("action").getAsString();
                if (object.get("value").isJsonPrimitive()) {
                    // Assume string
                    component.hoverActionData = new JsonString(object.get("value").getAsString());
                } else {
                    // Assume composite type
                    // The only composite type we currently store is another MessageUtil
                    // Therefore, recursion time!
                    component.hoverActionData = deserialize(object.get("value")
                            .toString() /* This should properly serialize the JSON object as a JSON string */);
                }
            } else if (entry.getKey().equals("insertion")) {
                component.insertionData = entry.getValue().getAsString();
            } else if (entry.getKey().equals("with")) {
                for (JsonElement object : entry.getValue().getAsJsonArray()) {
                    if (object.isJsonPrimitive()) {
                        component.translationReplacements.add(new JsonString(object.getAsString()));
                    } else {
                        // Only composite type stored in this array is - again - MessageUtils
                        // Recurse within this function to parse this as a translation replacement
                        component.translationReplacements.add(deserialize(object.toString()));
                    }
                }
            }
        }
        returnVal.messageParts.add(component);
    }
    return returnVal;
}

From source file:be.iminds.iot.dianne.builder.DianneLearner.java

License:Open Source License

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    String id = request.getParameter("id");
    if (id == null) {
        System.out.println("No neural network instance specified");
    }//  ww  w  .j  a  va  2 s.c  o  m
    UUID nnId = UUID.fromString(id);
    NeuralNetworkInstanceDTO nni = platform.getNeuralNetworkInstance(nnId);
    if (nni == null) {
        System.out.println("Neural network instance " + id + " not deployed");
        return;
    }

    String action = request.getParameter("action");
    if (action.equals("stop")) {
        learner.stop();
        return;
    }

    String target = request.getParameter("target");
    // this list consists of all ids of modules that are needed for trainer:
    // the input, output, trainable and preprocessor modules
    String configJsonString = request.getParameter("config");

    JsonObject configJson = parser.parse(configJsonString).getAsJsonObject();

    JsonObject learnerConfig = (JsonObject) configJson.get(target);

    for (Entry<String, JsonElement> configs : configJson.entrySet()) {
        JsonObject datasetConfig = (JsonObject) configs.getValue();
        if (datasetConfig.get("category").getAsString().equals("Dataset")
                && datasetConfig.get("input") != null) {
            String dataset = datasetConfig.get("dataset").getAsString();
            if (action.equals("learn")) {
                int start = 0;
                int end = datasetConfig.get("train").getAsInt();

                int batch = learnerConfig.get("batch").getAsInt();
                float learningRate = learnerConfig.get("learningRate").getAsFloat();
                float momentum = learnerConfig.get("momentum").getAsFloat();
                float regularization = learnerConfig.get("regularization").getAsFloat();
                String criterion = learnerConfig.get("loss").getAsString();
                String method = learnerConfig.get("method").getAsString();

                boolean clean = learnerConfig.get("clean").getAsBoolean();

                Map<String, String> config = new HashMap<>();
                config.put("range", "" + start + "," + end);
                config.put("batchSize", "" + batch);
                config.put("learningRate", "" + learningRate);
                config.put("momentum", "" + momentum);
                config.put("regularization", "" + regularization);
                config.put("criterion", criterion);
                config.put("method", method);
                config.put("syncInterval", "" + interval);
                config.put("clean", clean ? "true" : "false");
                config.put("trace", "true");

                try {
                    Dataset d = datasets.getDataset(dataset);
                    if (d != null) {
                        JsonObject labels = new JsonObject();
                        labels.add(target, new JsonPrimitive(Arrays.toString(d.getLabels())));
                        response.getWriter().write(labels.toString());
                        response.getWriter().flush();
                    }

                    learner.learn(dataset, config, nni);

                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else if (action.equals("evaluate")) {
                int start = datasetConfig.get("train").getAsInt();
                int end = start + datasetConfig.get("test").getAsInt();

                Map<String, String> config = new HashMap<>();
                config.put("range", "" + start + "," + end);

                try {
                    Evaluation result = evaluator.eval(dataset, config, nni);

                    JsonObject eval = new JsonObject();

                    eval.add("metric", new JsonPrimitive(result.metric()));
                    eval.add("time", new JsonPrimitive(result.time()));

                    if (result instanceof ErrorEvaluation) {
                        ErrorEvaluation ee = (ErrorEvaluation) result;
                        eval.add("error", new JsonPrimitive(ee.error()));
                    }

                    if (result instanceof ClassificationEvaluation) {
                        ClassificationEvaluation ce = (ClassificationEvaluation) result;
                        eval.add("accuracy", new JsonPrimitive(ce.accuracy() * 100));

                        Tensor confusionMatrix = ce.confusionMatrix();
                        JsonArray data = new JsonArray();
                        for (int i = 0; i < confusionMatrix.size(0); i++) {
                            for (int j = 0; j < confusionMatrix.size(1); j++) {
                                JsonArray element = new JsonArray();
                                element.add(new JsonPrimitive(i));
                                element.add(new JsonPrimitive(j));
                                element.add(new JsonPrimitive(confusionMatrix.get(i, j)));
                                data.add(element);
                            }
                        }
                        eval.add("confusionMatrix", data);
                    }

                    response.getWriter().write(eval.toString());
                    response.getWriter().flush();
                } catch (Exception e) {
                    e.printStackTrace();
                    JsonObject eval = new JsonObject();
                    eval.add("error", new JsonPrimitive(e.getCause().getMessage()));
                    response.getWriter().write(eval.toString());
                    response.getWriter().flush();
                }
            }
            break;
        }
    }
}

From source file:be.iminds.iot.dianne.dataset.DatasetConfigurator.java

License:Open Source License

private void parseDatasetConfiguration(File f) {
    try {/*from   w  w  w. j  av  a2  s .c  om*/
        // parse any adapter configurations from JSON and apply config?
        JsonParser parser = new JsonParser();
        JsonObject json = parser.parse(new JsonReader(new FileReader(f))).getAsJsonObject();

        String name = json.get("name").getAsString();
        if (name == null)
            return; // should have a name

        Hashtable<String, Object> props = new Hashtable<>();

        String dir = f.getParentFile().getAbsolutePath();
        props.put("dir", dir);

        String pid = null;

        if (json.has("adapter")) {
            String adapter = json.get("adapter").getAsString();
            pid = adapter.contains(".") ? adapter : "be.iminds.iot.dianne.dataset.adapters." + adapter;
            // in case of adapter, set Dataset target: the dataset it is adapting
            String dataset = json.get("dataset").getAsString();
            props.put("Dataset.target", "(name=" + dataset + ")");
        } else if (json.has("type")) {
            String type = json.get("type").getAsString();
            pid = "be.iminds.iot.dianne.dataset." + type;
        } else {
            // some hard coded pids
            if (name.startsWith("MNIST")) {
                pid = "be.iminds.iot.dianne.dataset.MNIST";
            } else if (name.startsWith("CIFAR-100")) {
                pid = "be.iminds.iot.dianne.dataset.CIFAR100";
            } else if (name.startsWith("CIFAR-10")) {
                pid = "be.iminds.iot.dianne.dataset.CIFAR10";
            } else if (name.startsWith("STL-10")) {
                pid = "be.iminds.iot.dianne.dataset.STL10";
            } else if (name.startsWith("SVHN")) {
                pid = "be.iminds.iot.dianne.dataset.SVHN";
            } else if (name.equalsIgnoreCase("ImageNetValidation")) {
                pid = "be.iminds.iot.dianne.dataset.ImageNet.validation";
            } else if (name.equalsIgnoreCase("ImageNetTraining")) {
                pid = "be.iminds.iot.dianne.dataset.ImageNet.training";
            } else {
                pid = "be.iminds.iot.dianne.dataset." + name;
            }
        }

        // set an aiolos instance id using the dataset name to treat
        // equally named datasets as single instance in the network
        props.put("aiolos.instance.id", name);
        // combine all offered interfaces (might be SequenceDataset or ExperiencePool)
        props.put("aiolos.combine", "*");

        // TODO use object conversion from JSON here?
        Configuration config = ca.createFactoryConfiguration(pid, null);
        json.entrySet().stream().forEach(e -> {
            if (e.getValue().isJsonArray()) {
                JsonArray a = e.getValue().getAsJsonArray();
                String[] val = new String[a.size()];
                for (int i = 0; i < val.length; i++) {
                    val[i] = a.get(i).getAsString();
                }
                props.put(e.getKey(), val);
            } else {
                props.put(e.getKey(), e.getValue().getAsString());
            }
        });
        config.update(props);
    } catch (Exception e) {
        System.err.println("Error parsing Dataset config file: " + f.getAbsolutePath());
        e.printStackTrace();
    }
}

From source file:be.iminds.iot.dianne.nn.util.DianneJSONConverter.java

License:Open Source License

public static NeuralNetworkDTO parseJSON(JsonObject json) {
    String name = null;//  www.ja va 2 s  .c om
    List<ModuleDTO> modules = new ArrayList<ModuleDTO>();

    if (json.has("name")) {
        name = json.get("name").getAsString();
    }

    // could be either a nice NeuralNetworkDTO or just a bunch of modules
    JsonObject jsonModules = json;
    if (json.has("modules")) {
        jsonModules = json.get("modules").getAsJsonObject();
    }

    for (Entry<String, JsonElement> module : jsonModules.entrySet()) {
        JsonObject moduleJson = (JsonObject) module.getValue();
        modules.add(parseModuleJSON(moduleJson));
    }

    return new NeuralNetworkDTO(name, modules);
}

From source file:be.iminds.iot.dianne.nn.util.DianneJSONConverter.java

License:Open Source License

private static ModuleDTO parseModuleJSON(JsonObject jsonModule) {

    UUID id = UUID.fromString(jsonModule.get("id").getAsString());
    String type = jsonModule.get("type").getAsString();

    UUID[] next = null, prev = null;
    Map<String, String> properties = new HashMap<String, String>();

    if (jsonModule.has("next")) {
        if (jsonModule.get("next").isJsonArray()) {
            JsonArray jsonNext = jsonModule.get("next").getAsJsonArray();

            next = new UUID[jsonNext.size()];
            int i = 0;
            Iterator<JsonElement> it = jsonNext.iterator();
            while (it.hasNext()) {
                JsonElement e = it.next();
                next[i++] = UUID.fromString(e.getAsString());
            }/*w w w  . j av a2  s . co m*/
        } else {
            next = new UUID[1];
            next[0] = UUID.fromString(jsonModule.get("next").getAsString());
        }
    }
    if (jsonModule.has("prev")) {
        if (jsonModule.get("prev").isJsonArray()) {
            JsonArray jsonPrev = jsonModule.get("prev").getAsJsonArray();

            prev = new UUID[jsonPrev.size()];
            int i = 0;
            Iterator<JsonElement> it = jsonPrev.iterator();
            while (it.hasNext()) {
                JsonElement e = it.next();
                prev[i++] = UUID.fromString(e.getAsString());
            }
        } else {
            prev = new UUID[1];
            prev[0] = UUID.fromString(jsonModule.get("prev").getAsString());
        }
    }

    // TODO this uses the old model where properties where just stored as flatmap      
    for (Entry<String, JsonElement> property : jsonModule.entrySet()) {
        String key = property.getKey();
        if (key.equals("id") || key.equals("type") || key.equals("prev") || key.equals("next")) {
            continue;
            // this is only for module-specific properties
        }
        properties.put(property.getKey(), property.getValue().getAsString());
    }

    // TODO evolve to a separate "properties" item
    if (jsonModule.has("properties")) {
        JsonObject jsonProperties = jsonModule.get("properties").getAsJsonObject();
        for (Entry<String, JsonElement> jsonProperty : jsonProperties.entrySet()) {
            String key = jsonProperty.getKey();
            String value = jsonProperty.getValue().getAsString();

            properties.put(key, value);
        }
    }

    ModuleDTO dto = new ModuleDTO(id, type, next, prev, properties);
    return dto;
}

From source file:bind.JsonTreeReader.java

License:Apache License

@Override
public void beginObject() throws IOException {
    expect(JsonToken.BEGIN_OBJECT);/*www.j  a v  a 2s .  c  o m*/
    JsonObject object = ((JsonElement) peekStack()).getAsJsonObject();
    stack.add(object.entrySet().iterator());
}

From source file:blusunrize.immersiveengineering.client.ClientProxy.java

public void addChangelogToManual() {
    FontRenderer fr = ManualHelper.getManual().fontRenderer;
    boolean isUnicode = fr.getUnicodeFlag();
    fr.setUnicodeFlag(true);/* w w w  . ja v a 2  s.  com*/
    SortedMap<ComparableVersion, Pair<String, IManualPage[]>> allChanges = new TreeMap<>(
            Comparator.reverseOrder());
    ComparableVersion currIEVer = new ComparableVersion(ImmersiveEngineering.VERSION);
    //Included changelog
    try (InputStream in = Minecraft.getMinecraft().getResourceManager()
            .getResource(new ResourceLocation(ImmersiveEngineering.MODID, "changelog.json")).getInputStream()) {
        JsonElement ele = new JsonParser().parse(new InputStreamReader(in));
        JsonObject upToCurrent = ele.getAsJsonObject();
        for (Entry<String, JsonElement> entry : upToCurrent.entrySet()) {
            ComparableVersion version = new ComparableVersion(entry.getKey());
            Pair<String, IManualPage[]> manualEntry = addVersionToManual(currIEVer, version,
                    entry.getValue().getAsString(), false);
            if (manualEntry != null)
                allChanges.put(version, manualEntry);
        }
    } catch (IOException x) {
        x.printStackTrace();
    }
    //Changelog from update JSON
    CheckResult result = ForgeVersion.getResult(Loader.instance().activeModContainer());
    if (result.status != Status.PENDING && result.status != Status.FAILED)
        for (Entry<ComparableVersion, String> e : result.changes.entrySet())
            allChanges.put(e.getKey(), addVersionToManual(currIEVer, e.getKey(), e.getValue(), true));

    for (Pair<String, IManualPage[]> entry : allChanges.values())
        ManualHelper.addEntry(entry.getLeft(), ManualHelper.CAT_UPDATE, entry.getRight());
    fr.setUnicodeFlag(isUnicode);
}