Example usage for com.google.gson JsonObject add

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

Introduction

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

Prototype

public void add(String property, JsonElement value) 

Source Link

Document

Adds a member, which is a name-value pair, to self.

Usage

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

License:Open Source License

private String export() {
    JsonObject output = new JsonObject();

    output.add(SECTION_U, users2JSON());

    output.add(SECTION_LO, learningObjects2JSON());

    output.add(SECTION_O, objects2JSON());

    output.add(SECTION_A, attributes2JSON());

    output.add(SECTION_M, metadata2JSON());

    output.add(SECTION_D, domains2JSON());

    output.add(SECTION_C, courses2JSON());

    return output.toString();
}

From source file:au.edu.unsw.cse.soc.federatedcloud.cloudRessourceBase.RecommenderAPI.java

License:Open Source License

private JsonObject returnDummyObject() {
    JsonObject json = new JsonObject();
    JsonArray descriptionsJsonArray = new JsonArray();

    JsonObject desciption1 = new JsonObject();
    desciption1.addProperty("Id", "1");
    desciption1.addProperty("Name", "SE-Bucket");
    desciption1.addProperty("TargetEnv", "IaaS");
    desciption1.addProperty("Deployer", "au.edu.unsw.cse.soc.federatedcloud.deployers.aws.AWSS3Deployer");
    descriptionsJsonArray.add(desciption1);

    JsonObject desciption2 = new JsonObject();
    desciption2.addProperty("Id", "2");
    desciption2.addProperty("Name", "Rackspace-VM");
    desciption2.addProperty("TargetEnv", "IaaS");
    desciption2.addProperty("Deployer",
            "au.edu.unsw.cse.soc.federatedcloud.deployers.rackspace.RackspaceDeployer");
    descriptionsJsonArray.add(desciption2);

    JsonObject desciption3 = new JsonObject();
    desciption3.addProperty("Id", "3");
    desciption3.addProperty("Name", "GoogleDrive");
    desciption3.addProperty("TargetEnv", "SaaS");
    desciption3.addProperty("Deployer", "au.edu.unsw.cse.soc.federatedcloud.deployers.GoogleDriveDeployer");
    descriptionsJsonArray.add(desciption3);

    json.add("CloudResourceDescriptions", descriptionsJsonArray);

    return json;/* w w  w  .j  a  v a  2s  .c  om*/
}

From source file:bank.GetBankPaymentHeader.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  ww  w.j ava 2 s .c o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Connection dataConnection = null;

    final JsonObject jResultObj = new JsonObject();
    final String from_date = request.getParameter("from_date");
    final String to_date = request.getParameter("to_date");
    final String v_type = request.getParameter("v_type");
    final String branch_cd = request.getParameter("branch_cd");
    if (dataConnection == null) {
        dataConnection = helper.getConnMpAdmin();
    }

    if (dataConnection != null) {
        try {
            String sql = "select c.AC_CD,c.REF_NO,VDATE,a.FNAME,c1.BAL,c1.REMARK,c.cheque_no,c.branch_cd from bprhd c left join bprdt c1 on c.REF_NO=c1.REF_NO"
                    + " left join ACNTMST a on c.AC_CD=a.AC_CD where VDATE>=? and VDATE<=? and CTYPE=?  ";
            if (!branch_cd.equalsIgnoreCase("0")) {
                sql += " and branch_cd=" + branch_cd;
            }
            sql += " order by VDATE,ref_no";
            PreparedStatement pstLocal = dataConnection.prepareStatement(sql);
            pstLocal.setString(1, from_date);
            pstLocal.setString(2, to_date);
            pstLocal.setString(3, v_type);
            ResultSet rsLocal = pstLocal.executeQuery();
            JsonArray array = new JsonArray();
            while (rsLocal.next()) {
                JsonObject object = new JsonObject();
                object.addProperty("REF_NO", rsLocal.getString("REF_NO"));
                object.addProperty("VDATE", rsLocal.getString("VDATE"));
                object.addProperty("FNAME", rsLocal.getString("FNAME"));
                object.addProperty("BAL", rsLocal.getString("BAL"));
                object.addProperty("REMARK", rsLocal.getString("REMARK"));
                object.addProperty("AC_CD", rsLocal.getString("AC_CD"));
                object.addProperty("CHEQUE_NO", rsLocal.getString("CHEQUE_NO"));
                object.addProperty("BRANCH_CD", rsLocal.getString("BRANCH_CD"));
                array.add(object);
            }
            jResultObj.addProperty("result", 1);
            jResultObj.addProperty("Cause", "success");
            jResultObj.add("data", array);
        } catch (SQLNonTransientConnectionException ex1) {
            jResultObj.addProperty("result", -1);
            jResultObj.addProperty("Cause", "Server is down");
        } catch (SQLException ex) {
            jResultObj.addProperty("result", -1);
            jResultObj.addProperty("Cause", ex.getMessage());
        }
    }
    response.getWriter().print(jResultObj);
}

From source file:basic.BasicExample.java

License:Open Source License

public BasicExample() throws Exception {
    socket = new SocketIO();
    socket.connect("http://127.0.0.1:3001/", this);

    // Sends a string to the server.
    socket.send("Hello Server");

    // Sends a JSON object to the server.
    JsonObject json = new JsonObject();

    json.add("key", new JsonPrimitive("value"));
    json.add("key2", new JsonPrimitive("another value"));
    socket.send(json);/*from w w  w.  jav  a  2s. c  o m*/

    // Emits an event to the server.
    socket.emit("event", "argument1", "argument2", 13.37);
}

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

License:Open Source License

private void getAvailableModules(PrintWriter writer) {
    List<ModuleTypeDTO> moduleTypes = new ArrayList<ModuleTypeDTO>();
    synchronized (factories) {
        for (ModuleFactory f : factories) {
            moduleTypes.addAll(f.getAvailableModuleTypes());
        }/*from  w w  w  . j  a  v a  2 s .co m*/
    }

    JsonArray jsonModules = new JsonArray();
    for (ModuleTypeDTO moduleType : moduleTypes) {
        JsonObject jsonModule = new JsonObject();
        jsonModule.add("type", new JsonPrimitive(moduleType.type));
        jsonModule.add("category", new JsonPrimitive(moduleType.category));
        if (moduleType.trainable) {
            jsonModule.add("trainable", new JsonPrimitive(true));
        }
        jsonModules.add(jsonModule);
    }
    writer.write(jsonModules.toString());
    writer.flush();
}

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

License:Open Source License

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    String action = request.getParameter("action");

    if (action.equals("available-datasets")) {
        JsonArray result = new JsonArray();
        synchronized (datasets) {
            for (DatasetDTO d : datasets.getDatasets()) {
                JsonObject r = new JsonObject();
                r.add("dataset", new JsonPrimitive(d.name));
                r.add("size", new JsonPrimitive(d.size));
                if (d.inputType != null)
                    r.add("inputType", new JsonPrimitive(d.inputType));
                if (d.targetType != null)
                    r.add("targetType", new JsonPrimitive(d.targetType));
                String[] ll = d.labels;
                if (ll != null) {
                    JsonArray labels = new JsonArray();
                    for (String l : ll) {
                        labels.add(new JsonPrimitive(l));
                    }// ww w . ja  va 2 s .  c  o m
                    r.add("labels", labels);
                }
                result.add(r);
            }
        }
        response.getWriter().println(result.toString());
        response.getWriter().flush();
    } else if (action.equals("sample")) {
        String dataset = request.getParameter("dataset");
        Dataset d = datasets.getDataset(dataset);
        if (d != null && d.size() > 0) {
            int index = rand.nextInt(d.size());
            Sample s = d.getSample(index);
            JsonObject sample = converter.toJson(s.input);
            sample.add("index", new JsonPrimitive(index));
            String[] labels = d.getLabels();
            if (labels != null) {
                sample.add("target", new JsonPrimitive(labels[TensorOps.argmax(s.target)]));
            } else {
                if (s.target.size() < 10) {
                    JsonObject target = converter.toJson(s.target);
                    sample.add("target", target.get("data").getAsJsonArray());
                }
            }

            response.getWriter().println(sample.toString());
            response.getWriter().flush();
        }
    }
}

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

License:Open Source License

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String action = request.getParameter("action");

    if (action.equals("available-datasets")) {
        JsonArray result = new JsonArray();
        synchronized (datasets) {
            for (Dataset d : datasets.values()) {
                JsonObject r = new JsonObject();
                r.add("dataset", new JsonPrimitive(d.getName()));
                r.add("size", new JsonPrimitive(d.size()));
                JsonArray labels = new JsonArray();
                for (String l : d.getLabels()) {
                    labels.add(new JsonPrimitive(l));
                }// w w  w  . j  av  a  2 s  . co m
                r.add("labels", labels);
                result.add(r);
            }
        }
        response.getWriter().println(result.toString());
        response.getWriter().flush();
    } else if (action.equals("sample")) {
        String dataset = request.getParameter("dataset");
        Dataset d = datasets.get(dataset);
        if (d != null) {
            JsonObject sample = new JsonObject();

            Tensor t = d.getInputSample(rand.nextInt(d.size()));

            if (t.dims().length == 3) {
                sample.add("channels", new JsonPrimitive(t.dims()[0]));
                sample.add("height", new JsonPrimitive(t.dims()[1]));
                sample.add("width", new JsonPrimitive(t.dims()[2]));
            } else {
                sample.add("channels", new JsonPrimitive(1));
                sample.add("height", new JsonPrimitive(t.dims()[0]));
                sample.add("width", new JsonPrimitive(t.dims()[1]));
            }
            sample.add("data", parser.parse(Arrays.toString(t.get())));
            response.getWriter().println(sample.toString());
            response.getWriter().flush();
        }
    }
}

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

License:Open Source License

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");

    String action = request.getParameter("action");
    if (action.equals("deploy")) {
        String id = request.getParameter("id");
        if (id == null) {
            id = UUID.randomUUID().toString();
        }//from   w  ww . j  a  v  a 2  s .  c om
        String name = request.getParameter("name");
        if (name == null) {
            name = "unknown";
        }
        String[] tags = null;
        String t = request.getParameter("tags");
        if (t != null && !t.isEmpty()) {
            tags = t.split(",");
        }

        List<ModuleDTO> toDeploy = new ArrayList<ModuleDTO>();
        if (request.getParameter("modules") != null) {
            String modulesJsonString = request.getParameter("modules");
            NeuralNetworkDTO nn = DianneJSONConverter.parseJSON(modulesJsonString);
            toDeploy.addAll(nn.modules.values());
        } else if (request.getParameter("module") != null) {
            String moduleJsonString = request.getParameter("module");
            ModuleDTO module = DianneJSONConverter.parseModuleJSON(moduleJsonString);
            toDeploy.add(module);
        }

        try {
            String target = request.getParameter("target");
            if (target == null) {
                throw new Exception("No DIANNE runtime selected to deploy to");
            }
            UUID runtimeId = UUID.fromString(target);

            UUID nnId = UUID.fromString(id);
            List<ModuleInstanceDTO> moduleInstances = platform.deployModules(nnId, name, toDeploy, runtimeId,
                    tags);

            // return json object with deployment
            JsonObject result = new JsonObject();
            JsonObject deployment = deploymentToJSON(moduleInstances);
            result.add("id", new JsonPrimitive(id));
            result.add("deployment", deployment);
            try {
                response.getWriter().write(result.toString());
                response.getWriter().flush();
            } catch (IOException e) {
            }

        } catch (Exception ex) {
            System.out.println("Failed to deploy modules: " + ex.getMessage());
            JsonObject result = new JsonObject();
            result.add("error", new JsonPrimitive("Failed to deploy modules: " + ex.getMessage()));
            try {
                response.getWriter().write(result.toString());
                response.getWriter().flush();
            } catch (IOException e) {
            }
        }

    } else if (action.equals("undeploy")) {
        String id = request.getParameter("id");
        String moduleId = request.getParameter("moduleId");
        if (id != null) {
            NeuralNetworkInstanceDTO nn = platform.getNeuralNetworkInstance(UUID.fromString(id));
            if (nn != null) {
                ModuleInstanceDTO moduleInstance = nn.modules.get(UUID.fromString(moduleId));
                if (moduleInstance != null)
                    platform.undeployModules(Collections.singletonList(moduleInstance));

                response.getWriter().write(new JsonPrimitive(id).toString());
                response.getWriter().flush();
            }
        }
    } else if (action.equals("targets")) {
        JsonArray targets = new JsonArray();

        Map<UUID, String> runtimes = platform.getRuntimes();
        runtimes.entrySet().stream().forEach(e -> {
            JsonObject o = new JsonObject();
            o.add("id", new JsonPrimitive(e.getKey().toString()));
            o.add("name", new JsonPrimitive(e.getValue()));
            targets.add(o);
        });

        response.getWriter().write(targets.toString());
        response.getWriter().flush();
    } else if ("recover".equals(action)) {
        String id = request.getParameter("id");
        if (id == null) {
            // list all options
            JsonArray nns = new JsonArray();
            platform.getNeuralNetworkInstances().stream().forEach(nni -> {
                JsonObject o = new JsonObject();
                o.add("id", new JsonPrimitive(nni.id.toString()));
                o.add("name", new JsonPrimitive(nni.name));
                if (nni.description != null) {
                    o.add("description", new JsonPrimitive(nni.description));
                }
                nns.add(o);
            });
            response.getWriter().write(nns.toString());
            response.getWriter().flush();

        } else {
            NeuralNetworkInstanceDTO nni = platform.getNeuralNetworkInstance(UUID.fromString(id));
            if (nni == null) {
                System.out.println("Failed to recover " + id + " , instance not found");
                return;
            }

            try {
                response.getWriter().write("{\"nn\":");
                NeuralNetworkDTO nn = repository.loadNeuralNetwork(nni.name);
                String s = DianneJSONConverter.toJsonString(nn);
                response.getWriter().write(s);
                response.getWriter().write(", \"layout\":");
                String layout = repository.loadLayout(nni.name);
                response.getWriter().write(layout);
                response.getWriter().write(", \"deployment\":");
                JsonObject deployment = deploymentToJSON(nni.modules.values());
                response.getWriter().write(deployment.toString());
                response.getWriter().write(", \"id\":");
                response.getWriter().write("\"" + id + "\"");
                response.getWriter().write("}");
                response.getWriter().flush();
            } catch (Exception e) {
                System.out.println("Failed to recover " + nni.name + " " + nni.id);
            }
        }
    }

}

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

License:Open Source License

private JsonObject deploymentToJSON(Collection<ModuleInstanceDTO> moduleInstances) {
    JsonObject deployment = new JsonObject();
    for (ModuleInstanceDTO moduleInstance : moduleInstances) {
        String runtime = moduleInstance.runtimeId.toString();
        if (runtime == null) {
            runtime = moduleInstance.runtimeId.toString();
        }// ww  w .  ja  v  a 2 s .  co  m
        deployment.add(moduleInstance.moduleId.toString(), new JsonPrimitive(runtime));
    }
    return deployment;
}

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

License:Open Source License

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");

    String action = request.getParameter("action");
    if ("available-inputs".equals(action)) {
        JsonArray availableInputs = new JsonArray();
        synchronized (inputs) {
            for (DianneInputs i : inputs) {
                for (InputDescription input : i.getAvailableInputs()) {
                    JsonObject o = new JsonObject();
                    o.add("name", new JsonPrimitive(input.getName()));
                    o.add("type", new JsonPrimitive(input.getType()));
                    availableInputs.add(o);
                }//from  www.j a  va2 s.com
            }
        }
        response.getWriter().write(availableInputs.toString());
        response.getWriter().flush();
    } else if ("setinput".equals(action)) {
        String nnId = request.getParameter("nnId");
        String inputId = request.getParameter("inputId");
        String input = request.getParameter("input");

        synchronized (inputs) {
            // TODO select the right one instead of forwarding to all?
            for (DianneInputs i : inputs) {
                i.setInput(UUID.fromString(nnId), UUID.fromString(inputId), input);
            }

            ForwardListener inputListener = new ForwardListener() {
                @Override
                public void onForward(UUID moduleId, Tensor output, String... tags) {
                    if (sses.get(input) != null) {
                        JsonObject json = converter.toJson(output);
                        StringBuilder builder = new StringBuilder();
                        builder.append("data: ").append(json.toString()).append("\n\n");
                        String msg = builder.toString();

                        List<AsyncContext> list = sses.get(input);
                        Iterator<AsyncContext> it = list.iterator();
                        while (it.hasNext()) {
                            AsyncContext sse = it.next();
                            try {
                                PrintWriter writer = sse.getResponse().getWriter();
                                writer.write(msg);
                                writer.flush();
                                if (writer.checkError()) {
                                    System.err.println("Writer error: removing async endpoint.");
                                    writer.close();
                                    it.remove();
                                }
                            } catch (Exception e) {
                                try {
                                    sse.getResponse().getWriter().close();
                                } catch (Exception ignore) {
                                }
                                it.remove();
                                e.printStackTrace();
                            }
                        }
                    }
                }

                @Override
                public void onError(UUID moduleId, ModuleException e, String... tags) {
                    e.printStackTrace();
                }
            };
            Dictionary<String, Object> properties = new Hashtable<String, Object>();
            properties.put("targets", new String[] { nnId + ":" + inputId });
            properties.put("aiolos.unique", true);
            ServiceRegistration<ForwardListener> r = context.registerService(ForwardListener.class,
                    inputListener, properties);
            inputListeners.put(UUID.fromString(inputId), r);
        }
    } else if ("unsetinput".equals(action)) {
        String nnId = request.getParameter("nnId");
        String inputId = request.getParameter("inputId");
        String input = request.getParameter("input");

        synchronized (inputs) {
            for (DianneInputs i : inputs) {
                i.unsetInput(UUID.fromString(nnId), UUID.fromString(inputId), input);
            }
        }

        ServiceRegistration<ForwardListener> r = inputListeners.get(UUID.fromString(inputId));
        if (r != null) {
            r.unregister();
        }
    }
}