Example usage for com.google.gson JsonArray add

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

Introduction

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

Prototype

public void add(JsonElement element) 

Source Link

Document

Adds the specified element to self.

Usage

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

License:Open Source License

public static JsonObject createDeployRequest(int id, String nnName) {
    JsonObject request = new JsonObject();
    request.add("jsonrpc", new JsonPrimitive("2.0"));
    request.add("method", new JsonPrimitive("deploy"));
    request.add("id", new JsonPrimitive(id));

    JsonArray params = new JsonArray();
    params.add(new JsonPrimitive(nnName));
    request.add("params", params);

    return request;
}

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

License:Open Source License

public static JsonObject createUndeployRequest(int id, String nnId) {
    JsonObject request = new JsonObject();
    request.add("jsonrpc", new JsonPrimitive("2.0"));
    request.add("method", new JsonPrimitive("undeploy"));
    request.add("id", new JsonPrimitive(id));

    JsonArray params = new JsonArray();
    params.add(new JsonPrimitive(nnId));
    request.add("params", params);

    return request;
}

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

License:Open Source License

public static JsonObject createForwardRequest(int id, String nnId, int[] dims) {
    JsonObject request = new JsonObject();
    request.add("jsonrpc", new JsonPrimitive("2.0"));
    request.add("method", new JsonPrimitive("forward"));
    request.add("id", new JsonPrimitive(id));

    JsonArray params = new JsonArray();
    params.add(new JsonPrimitive(nnId));

    // create input
    JsonArray input = new JsonArray();
    List<JsonArray> toAdd = new ArrayList<>();
    toAdd.add(input);/* w  w  w .j  a v a2s  .  co m*/
    for (int i = 0; i < dims.length; i++) {
        List<JsonArray> nextAdd = new ArrayList<>();
        int d = dims[i];
        for (int k = 0; k < d; k++) {
            if (i == dims.length - 1) {
                // add floats
                for (JsonArray a : toAdd) {
                    a.add(new JsonPrimitive(0.0f));
                }
            } else {
                // add jsonarrays
                for (JsonArray a : toAdd) {
                    JsonArray newArray = new JsonArray();
                    a.add(newArray);
                    nextAdd.add(newArray);
                }
            }
        }
        toAdd = nextAdd;
    }
    params.add(input);

    request.add("params", params);

    return request;
}

From source file:be.uantwerpen.dc.studyassistant.StudyAssistant.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  ww  w .  ja  va  2 s .c om*/
 *
 * @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 {
    response.setContentType("text/html;charset=UTF-8");

    String urlPath = request.getServletPath();

    if (urlPath.equalsIgnoreCase("/resources")) {

        ArrayList<Environment> lcs = this.getEnvironmentResources();

        Integer min = Integer.MAX_VALUE;
        Integer max = Integer.MIN_VALUE;
        for (Environment e : lcs) {
            if (e.getArduinoloudness() != null && e.getArduinoloudness() < min) {
                min = e.getArduinoloudness();
            }
            if (e.getArduinoloudness() != null && e.getArduinoloudness() > max) {
                max = e.getArduinoloudness();
            }
        }

        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet StudyAssistant</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet StudyAssistant at " + request.getContextPath() + "</h1>");
            for (Environment e : lcs) {
                out.println(e.toString());
            }

            out.println("Noise MAX: " + max);
            out.println("Noise MIN: " + min);

            out.println("</body>");
            out.println("</html>");
        }
    } else if (urlPath.equalsIgnoreCase("/resources/gauge")) {
        Environment lastRecord = this.getLastEnvironmentRecord();

        StudyIndex inx = new StudyIndex(lastRecord);
        double index = inx.getStudyIndex();
        index *= 100;

        index = Math.round(index * 100.0) / 100.0;

        JsonObject obj = new JsonObject();

        // create an array called cols
        JsonArray cols = new JsonArray();
        JsonArray rows = new JsonArray();
        JsonArray messages = new JsonArray();

        JsonObject col = new JsonObject();
        col.addProperty("id", "Index");
        col.addProperty("label", "Index");
        col.addProperty("type", "string");
        cols.add(col);

        JsonObject col2 = new JsonObject();
        col2.addProperty("id", "Value");
        col2.addProperty("label", "Value");
        col2.addProperty("type", "number");
        cols.add(col2);

        obj.add("cols", cols);

        JsonObject c = new JsonObject();
        JsonArray row = new JsonArray();

        JsonObject v1 = new JsonObject();
        v1.addProperty("v", "Index");
        row.add(v1);

        JsonObject v2 = new JsonObject();
        v2.addProperty("v", index);
        row.add(v2);

        c.add("c", row);

        rows.add(c);

        obj.add("rows", rows);

        String msg = "";
        if ((inx.alcoholIndex < 0.90) || (inx.methaneIndex < 0.90)) {
            msg += "Room needs better air circulation.";
            JsonObject msg1 = new JsonObject();
            msg1.addProperty("text", msg);
            messages.add(msg1);
        }

        JsonObject msg2 = new JsonObject();
        msg = "";
        if (lastRecord.getArduinolight() < StudyIndex.lightOptimalValue) {
            msg += "Increase room luminance!";
        } else if (lastRecord.getArduinolight() > StudyIndex.lightOptimalValue) {
            msg += "Lower room luminance!";
        } else {
            msg += "Room luminance is optimal!";
        }
        msg2.addProperty("text", msg);
        messages.add(msg2);

        JsonObject msg3 = new JsonObject();
        msg = "";
        if (lastRecord.getDs18b20temp() < StudyIndex.temperatureOptimalValue) {
            msg += "Increase room temperature!";
        } else if (lastRecord.getDs18b20temp() > StudyIndex.temperatureOptimalValue) {
            msg += "Lower room temperature!";
        } else {
            msg += "Room temperature is optimal!";
        }
        msg3.addProperty("text", msg);
        messages.add(msg3);

        JsonObject msg4 = new JsonObject();
        msg = "";
        if (lastRecord.getArduinoloudness() > StudyIndex.loudnessOptimalValue) {
            msg += "Room is too noisy!";
            msg4.addProperty("text", msg);
            messages.add(msg4);
        }

        JsonObject msg5 = new JsonObject();
        msg = "";
        if (lastRecord.getDs18b20temp() < StudyIndex.temperatureOptimalValue) {
            msg += "Humidity is less than optimal.";
        } else if (lastRecord.getDs18b20temp() > StudyIndex.temperatureOptimalValue) {
            msg += "Humidity is above optimal.";
        } else {
            msg += "Humidity is optimal!";
        }
        msg5.addProperty("text", msg);
        messages.add(msg5);

        obj.add("messages", messages);

        Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls()
                .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();

        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");

        PrintWriter out = response.getWriter();

        out.print(gson.toJson(obj));
    } else if (urlPath.equalsIgnoreCase("/resources/humidity")) {
        JsonObject obj = this.getCoreChartsJson("Humidity");
        this.printJson(obj, response);
    } else if (urlPath.equalsIgnoreCase("/resources/temperature")) {
        JsonObject obj = this.getCoreChartsJson("Temperature");
        this.printJson(obj, response);
    } else if (urlPath.equalsIgnoreCase("/resources/loudness")) {
        JsonObject obj = this.getCoreChartsJson("Loudness");
        this.printJson(obj, response);
    } else if (urlPath.equalsIgnoreCase("/resources/light")) {
        JsonObject obj = this.getCoreChartsJson("Light");
        this.printJson(obj, response);
    } else if (urlPath.equalsIgnoreCase("/resources/bubbleindex")) {
        JsonObject obj = this.getCoreChartsJson("Environment Index Score");
        this.printJson(obj, response);
    } else if (urlPath.equalsIgnoreCase("/resources/minmax")) {
        JsonObject obj = this.findMinMax();
        this.printJson(obj, response);
    }
}

From source file:be.uantwerpen.dc.studyassistant.StudyAssistant.java

private JsonObject getCoreChartsJson(String property) {

    ArrayList<Environment> envs = this.getEnvironmentResources();

    JsonObject obj = new JsonObject();

    // create an array called cols
    JsonArray cols = new JsonArray();
    JsonArray rows = new JsonArray();

    JsonObject col = new JsonObject();
    col.addProperty("id", "Time");
    col.addProperty("label", "Time");
    col.addProperty("type", "date");
    cols.add(col);

    JsonObject col2 = new JsonObject();
    col2.addProperty("id", property);
    col2.addProperty("label", property);
    col2.addProperty("type", "number");
    cols.add(col2);/*from  ww w.j a v a2s.  c  o m*/

    obj.add("cols", cols);

    for (Environment e : envs) {
        JsonObject c = new JsonObject();
        JsonArray row = new JsonArray();

        JsonObject v1 = new JsonObject();
        v1.addProperty("v", "Date(" + e.getCreated().getTime() + ")");
        row.add(v1);

        JsonObject v2 = new JsonObject();

        if (property.equalsIgnoreCase("temperature")) {
            v2.addProperty("v", e.getDs18b20temp());
            row.add(v2);
            c.add("c", row);
            rows.add(c);
            obj.add("rows", rows);
        } else if (property.equalsIgnoreCase("humidity")) {
            v2.addProperty("v", e.getDht11hum());
            row.add(v2);
            c.add("c", row);
            rows.add(c);
            obj.add("rows", rows);
        } else if (property.equalsIgnoreCase("loudness")) {
            v2.addProperty("v", e.getArduinoloudness());
            row.add(v2);
            c.add("c", row);
            rows.add(c);
            obj.add("rows", rows);
        } else if (property.equalsIgnoreCase("light")) {
            v2.addProperty("v", e.getArduinolight());
            row.add(v2);
            c.add("c", row);
            rows.add(c);
            obj.add("rows", rows);
        } else if (property.equalsIgnoreCase("Environment Index Score")) {
            StudyIndex in = null;
            double index = 0;
            try {
                in = new StudyIndex(e);
                index = in.getStudyIndex();
            } catch (Exception exc) {
                //Logger.getLogger(StudyAssistant.class.getName()).log(Level.SEVERE, null, exc);                                                
            }
            v2.addProperty("v", index);
            row.add(v2);
            c.add("c", row);
            rows.add(c);
            obj.add("rows", rows);
        }
    }

    return obj;
}

From source file:be.uantwerpen.dc.studyassistant.StudyAssistant.java

private JsonObject findMinMax() {
    ArrayList<Environment> envs = this.getEnvironmentResources();

    Double minTemperature = Double.MAX_VALUE;
    Double maxTemperature = Double.MIN_NORMAL;

    Double minHumidity = Double.MAX_VALUE;
    Double maxHumidity = Double.MIN_NORMAL;

    Double minLoudness = Double.MAX_VALUE;
    Double maxLoudness = Double.MIN_NORMAL;

    Double minLight = Double.MAX_VALUE;
    Double maxLight = Double.MIN_NORMAL;

    Double minAlcohol = Double.MAX_VALUE;
    Double maxAlcohol = Double.MIN_NORMAL;

    Double minMethaine = Double.MAX_VALUE;
    Double maxMethaine = Double.MIN_NORMAL;

    Double minPressure = Double.MAX_VALUE;
    Double maxPressure = Double.MIN_NORMAL;

    for (Environment e : envs) {
        if (e.getDs18b20temp() != null && e.getDs18b20temp() < minTemperature) {
            minTemperature = Double.parseDouble(e.getDs18b20temp() + "");
        }//  w  ww  .j a v  a  2  s  .  c  o  m

        if (e.getDs18b20temp() != null && e.getDs18b20temp() > maxTemperature) {
            maxTemperature = Double.parseDouble(e.getDs18b20temp() + "");
        }

        if (e.getDht11hum() != null && e.getDht11hum() < minHumidity) {
            minHumidity = Double.parseDouble(e.getDht11hum() + "");
        }

        if (e.getDht11hum() != null && e.getDht11hum() > maxHumidity) {
            maxHumidity = Double.parseDouble(e.getDht11hum() + "");
        }

        if (e.getArduinolight() != null && e.getArduinolight() < minLight) {
            minLight = Double.parseDouble(e.getArduinolight() + "");
        }

        if (e.getArduinolight() != null && e.getArduinolight() > maxLight) {
            maxLight = Double.parseDouble(e.getArduinolight() + "");
        }

        if (e.getArduinoloudness() != null && e.getArduinoloudness() < minLoudness) {
            minLoudness = Double.parseDouble(e.getArduinoloudness() + "");
        }

        if (e.getArduinoloudness() != null && e.getArduinoloudness() > maxLoudness) {
            maxLoudness = Double.parseDouble(e.getArduinoloudness() + "");
        }

        if (e.getArduinoalcohol() != null && e.getArduinoalcohol() < minAlcohol) {
            minAlcohol = Double.parseDouble(e.getArduinoalcohol() + "");
        }

        if (e.getArduinoalcohol() != null && e.getArduinoalcohol() > maxAlcohol) {
            maxAlcohol = Double.parseDouble(e.getArduinoalcohol() + "");
        }

        if (e.getArduinomethaine() != null && e.getArduinomethaine() < minMethaine) {
            minMethaine = Double.parseDouble(e.getArduinomethaine() + "");
        }

        if (e.getArduinomethaine() != null && e.getArduinomethaine() > maxMethaine) {
            maxMethaine = Double.parseDouble(e.getArduinomethaine() + "");
        }

        if (e.getBmp180pressure() != null && e.getBmp180pressure() < minPressure) {
            minPressure = Double.parseDouble(e.getBmp180pressure() + "");
        }

        if (e.getBmp180pressure() != null && e.getBmp180pressure() > maxPressure) {
            maxPressure = Double.parseDouble(e.getBmp180pressure() + "");
        }

    }

    ArrayList<String> types = new ArrayList<String>();
    types.add("Temperature");
    types.add("Humidity");
    types.add("Loudness");
    types.add("Luminance");
    types.add("Alcohol");
    types.add("Methane");
    types.add("Pressure");

    JsonObject obj = new JsonObject();

    // create an array called cols
    JsonArray cols = new JsonArray();
    JsonArray rows = new JsonArray();

    JsonObject col = new JsonObject();
    col.addProperty("id", "Variable");
    col.addProperty("label", "Variable");
    col.addProperty("type", "string");
    cols.add(col);

    JsonObject col2 = new JsonObject();
    col2.addProperty("id", "Minimum");
    col2.addProperty("label", "Minimum");
    col2.addProperty("type", "number");
    cols.add(col2);

    JsonObject col3 = new JsonObject();
    col3.addProperty("id", "Maximum");
    col3.addProperty("label", "Maximum");
    col3.addProperty("type", "number");
    cols.add(col3);

    obj.add("cols", cols);

    for (String s : types) {
        JsonObject c = new JsonObject();
        JsonArray row = new JsonArray();

        JsonObject v1 = new JsonObject();
        v1.addProperty("v", s);
        row.add(v1);

        if (s.equalsIgnoreCase("temperature")) {
            JsonObject v2 = new JsonObject();
            v2.addProperty("v", minTemperature);
            row.add(v2);

            JsonObject v3 = new JsonObject();
            v3.addProperty("v", maxTemperature);
            row.add(v3);

            c.add("c", row);
            rows.add(c);
        } else if (s.equalsIgnoreCase("humidity")) {
            JsonObject v2 = new JsonObject();
            v2.addProperty("v", minHumidity);
            row.add(v2);

            JsonObject v3 = new JsonObject();
            v3.addProperty("v", maxHumidity);
            row.add(v3);

            c.add("c", row);
            rows.add(c);
        } else if (s.equalsIgnoreCase("loudness")) {
            JsonObject v2 = new JsonObject();
            v2.addProperty("v", minLoudness);
            row.add(v2);

            JsonObject v3 = new JsonObject();
            v3.addProperty("v", maxLoudness);
            row.add(v3);

            c.add("c", row);
            rows.add(c);
        } else if (s.equalsIgnoreCase("luminance")) {
            JsonObject v2 = new JsonObject();
            v2.addProperty("v", minLight);
            row.add(v2);

            JsonObject v3 = new JsonObject();
            v3.addProperty("v", maxLight);
            row.add(v3);

            c.add("c", row);
            rows.add(c);
        } else if (s.equalsIgnoreCase("alcohol")) {
            JsonObject v2 = new JsonObject();
            v2.addProperty("v", minAlcohol);
            row.add(v2);

            JsonObject v3 = new JsonObject();
            v3.addProperty("v", maxAlcohol);
            row.add(v3);

            c.add("c", row);
            rows.add(c);
        } else if (s.equalsIgnoreCase("methane")) {
            JsonObject v2 = new JsonObject();
            v2.addProperty("v", minMethaine);
            row.add(v2);

            JsonObject v3 = new JsonObject();
            v3.addProperty("v", maxMethaine);
            row.add(v3);

            c.add("c", row);
            rows.add(c);
        } else if (s.equalsIgnoreCase("pressure")) {
            JsonObject v2 = new JsonObject();
            v2.addProperty("v", minPressure);
            row.add(v2);

            JsonObject v3 = new JsonObject();
            v3.addProperty("v", maxPressure);
            row.add(v3);

            c.add("c", row);
            rows.add(c);
        }
    }

    obj.add("rows", rows);

    return obj;

}

From source file:beans.cart.SimpleCart.java

@Override
public String toStringJsonArray() {

    JsonArray jsonarr = new JsonArray();

    JsonObject job;//from   w w  w .  java 2 s .co m
    for (Item item : items) {
        job = new JsonObject();
        job.addProperty("item", item.toStringJson());
        jsonarr.add(job);
    }

    return jsonarr.toString();
}

From source file:beans.TripleStoreBean.java

public static String answerLiteqQuery(String query, boolean useCache) {
    JsonObject response = new JsonObject();
    Gson gson = new Gson();

    if (useCache) {
        String cachedResult = CacheBean.getCachedLiteqQueryResult(query.hashCode());
        if (cachedResult != null) {
            Logger.getLogger(TripleStoreBean.class.getName()).log(Level.INFO, "returning cached result");
            return cachedResult;
        }//from  w  ww  .  ja  v a  2s.  c o m
    }
    JsonElement result = null;
    JsonArray values;

    ResultSet rs;
    Connection conn = null;
    try {
        conn = getTripleStoreConnection();
        Statement stmt = conn.createStatement();

        boolean more = stmt.execute(query);
        ResultSetMetaData data = stmt.getResultSet().getMetaData();

        if (data.getColumnCount() == 1) {
            result = new JsonArray();
        } else {
            result = new JsonObject();
        }

        while (more) {
            rs = stmt.getResultSet();
            while (rs.next()) {
                if (data.getColumnCount() > 1) {
                    String key = convertToIRI(rs.getObject(1));
                    if (key == null) {
                        key = rs.getString(1);
                    }
                    String value = convertToIRI(rs.getObject(2));
                    if (value == null) {
                        value = rs.getString(2);
                    }
                    if (((JsonObject) result).has(key)) {
                        values = ((JsonObject) result).get(key).getAsJsonArray();
                        values.add(new JsonPrimitive(value));
                    } else {
                        values = new JsonArray();
                        values.add(new JsonPrimitive(value));
                        ((JsonObject) result).add(key, values);
                    }
                } else if (data.getColumnCount() == 1) {
                    String key = convertToIRI(rs.getObject(1));
                    if (key == null) {
                        key = rs.getString(1);
                    }
                    ((JsonArray) result).add(new JsonPrimitive(key));
                }
            }
            more = stmt.getMoreResults();
        }
        response.add("response", result);

        if (useCache) {
            CacheBean.storeResponseInCache(gson.toJson(response), query.hashCode());
        }
    } catch (SQLException ex) {
        Logger.getLogger(TripleStoreBean.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            conn.close();
        } catch (SQLException ex) {
            Logger.getLogger(TripleStoreBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    return gson.toJson(response);
}

From source file:bisq.desktop.main.dao.governance.result.VoteResultView.java

License:Open Source License

private JsonElement getVotingHistoryJson() {
    JsonArray cyclesArray = new JsonArray();

    sortedCycleListItemList.sorted(Comparator.comparing(CycleListItem::getCycleStartTime))
            .forEach(cycleListItem -> {
                JsonObject cycleJson = new JsonObject();
                // No domain data, taken from UI model
                // TODO move the data structure needed for UI to core and use as pure domain model and use that here
                cycleJson.addProperty("cycleIndex", cycleListItem.getCycleIndex());
                cycleJson.addProperty("cycleDateTime", cycleListItem.getCycleDateTime(false));
                cycleJson.addProperty("votesCount", cycleListItem.getNumVotesAsString());
                cycleJson.addProperty("voteWeight", cycleListItem.getMeritAndStake());
                cycleJson.addProperty("issuance", cycleListItem.getIssuance());
                cycleJson.addProperty("startTime", cycleListItem.getCycleStartTime());
                cycleJson.addProperty("totalAcceptedVotes",
                        cycleListItem.getResultsOfCycle().getNumAcceptedVotes());
                cycleJson.addProperty("totalRejectedVotes",
                        cycleListItem.getResultsOfCycle().getNumRejectedVotes());

                JsonArray proposalsArray = new JsonArray();
                List<EvaluatedProposal> evaluatedProposals = cycleListItem.getResultsOfCycle()
                        .getEvaluatedProposals();
                evaluatedProposals.sort(Comparator.comparingLong(o -> o.getProposal().getCreationDate()));

                evaluatedProposals.forEach(evaluatedProp -> {
                    JsonObject proposalJson = new JsonObject();
                    proposalJson.addProperty("isAccepted",
                            evaluatedProp.isAccepted() ? "Accepted" : "Rejected");

                    // Proposal
                    Proposal proposal = evaluatedProp.getProposal();
                    proposalJson.addProperty("proposal.name", proposal.getName());
                    proposalJson.addProperty("proposal.link", proposal.getLink());
                    proposalJson.addProperty("proposal.version", proposal.getVersion());
                    proposalJson.addProperty("proposal.creationDate", proposal.getCreationDate());
                    proposalJson.addProperty("proposal.txId", proposal.getTxId());
                    proposalJson.addProperty("proposal.txType", proposal.getTxType().name());
                    proposalJson.addProperty("proposal.quorumParam", proposal.getQuorumParam().name());
                    proposalJson.addProperty("proposal.thresholdParam", proposal.getThresholdParam().name());
                    proposalJson.addProperty("proposal.proposalType", proposal.getType().name());

                    if (proposal.getExtraDataMap() != null)
                        proposalJson.addProperty("proposal.extraDataMap",
                                proposal.getExtraDataMap().toString());

                    switch (proposal.getType()) {
                    case UNDEFINED:
                        break;
                    case COMPENSATION_REQUEST:
                        CompensationProposal compensationProposal = (CompensationProposal) proposal;
                        proposalJson.addProperty("proposal.requestedBsq",
                                compensationProposal.getRequestedBsq().getValue());
                        proposalJson.addProperty("proposal.bsqAddress", compensationProposal.getBsqAddress());
                        break;
                    case REIMBURSEMENT_REQUEST:
                        ReimbursementProposal reimbursementProposal = (ReimbursementProposal) proposal;
                        proposalJson.addProperty("proposal.requestedBsq",
                                reimbursementProposal.getRequestedBsq().getValue());
                        proposalJson.addProperty("proposal.bsqAddress", reimbursementProposal.getBsqAddress());
                        break;
                    case CHANGE_PARAM:
                        ChangeParamProposal changeParamProposal = (ChangeParamProposal) proposal;
                        Param param = changeParamProposal.getParam();
                        proposalJson.addProperty("proposal.param", param.name());
                        proposalJson.addProperty("proposal.param.defaultValue", param.getDefaultValue());
                        proposalJson.addProperty("proposal.param.type", param.getParamType().name());
                        proposalJson.addProperty("proposal.param.maxDecrease", param.getMaxDecrease());
                        proposalJson.addProperty("proposal.param.maxIncrease", param.getMaxIncrease());
                        proposalJson.addProperty("proposal.paramValue", changeParamProposal.getParamValue());
                        break;
                    case BONDED_ROLE:
                        RoleProposal roleProposal = (RoleProposal) proposal;
                        Role role = roleProposal.getRole();
                        proposalJson.addProperty("proposal.requiredBondUnit",
                                roleProposal.getRequiredBondUnit());
                        proposalJson.addProperty("proposal.unlockTime", roleProposal.getUnlockTime());
                        proposalJson.addProperty("proposal.role.uid", role.getUid());
                        proposalJson.addProperty("proposal.role.name", role.getName());
                        proposalJson.addProperty("proposal.role.link", role.getLink());
                        BondedRoleType bondedRoleType = role.getBondedRoleType();
                        proposalJson.addProperty("proposal.bondedRoleType", bondedRoleType.name());
                        // bondedRoleType enum must not change anyway so we don't print it
                        break;
                    case CONFISCATE_BOND:
                        ConfiscateBondProposal confiscateBondProposal = (ConfiscateBondProposal) proposal;
                        proposalJson.addProperty("proposal.lockupTxId", confiscateBondProposal.getLockupTxId());
                        break;
                    case GENERIC:
                        // No extra fields
                        break;
                    case REMOVE_ASSET:
                        RemoveAssetProposal removeAssetProposal = (RemoveAssetProposal) proposal;
                        proposalJson.addProperty("proposal.tickerSymbol",
                                removeAssetProposal.getTickerSymbol());
                        break;
                    }/*from  w w w.j  a  va  2 s.co m*/

                    ProposalVoteResult proposalVoteResult = evaluatedProp.getProposalVoteResult();
                    proposalJson.addProperty("stakeOfAcceptedVotes",
                            proposalVoteResult.getStakeOfAcceptedVotes());
                    proposalJson.addProperty("stakeOfRejectedVotes",
                            proposalVoteResult.getStakeOfRejectedVotes());
                    proposalJson.addProperty("numAcceptedVotes", proposalVoteResult.getNumAcceptedVotes());
                    proposalJson.addProperty("numRejectedVotes", proposalVoteResult.getNumRejectedVotes());
                    proposalJson.addProperty("numIgnoredVotes", proposalVoteResult.getNumIgnoredVotes());
                    proposalJson.addProperty("numActiveVotes", proposalVoteResult.getNumActiveVotes());
                    proposalJson.addProperty("quorum", proposalVoteResult.getQuorum());
                    proposalJson.addProperty("threshold", proposalVoteResult.getThreshold());

                    // Not part of pure domain data, but useful to add here
                    // required quorum and threshold for cycle for proposal type
                    proposalJson.addProperty("requiredQuorum",
                            proposalService.getRequiredQuorum(proposal).value);
                    proposalJson.addProperty("requiredThreshold",
                            proposalService.getRequiredThreshold(proposal));

                    // TODO provide better domain object as now we loop inside the loop. Use lookup map instead....
                    JsonArray votesArray = new JsonArray();
                    evaluatedProposals.stream()
                            .filter(evaluatedProposal -> evaluatedProposal.getProposal().equals(proposal))
                            .forEach(evaluatedProposal -> {
                                List<DecryptedBallotsWithMerits> decryptedVotesForCycle = cycleListItem
                                        .getResultsOfCycle().getDecryptedVotesForCycle();
                                // Make sure the votes are sorted so we can easier compare json files from different users
                                decryptedVotesForCycle.sort(
                                        Comparator.comparing(DecryptedBallotsWithMerits::getBlindVoteTxId));
                                decryptedVotesForCycle.forEach(decryptedBallotsWithMerits -> {
                                    JsonObject voteJson = new JsonObject();
                                    // Domain data of decryptedBallotsWithMerits
                                    voteJson.addProperty("hashOfBlindVoteList", Utilities.bytesAsHexString(
                                            decryptedBallotsWithMerits.getHashOfBlindVoteList()));
                                    voteJson.addProperty("blindVoteTxId",
                                            decryptedBallotsWithMerits.getBlindVoteTxId());
                                    voteJson.addProperty("voteRevealTxId",
                                            decryptedBallotsWithMerits.getVoteRevealTxId());
                                    voteJson.addProperty("stake", decryptedBallotsWithMerits.getStake());

                                    voteJson.addProperty("voteWeight",
                                            decryptedBallotsWithMerits.getMerit(daoStateService));
                                    String voteResult = decryptedBallotsWithMerits
                                            .getVote(evaluatedProp.getProposalTxId())
                                            .map(vote -> vote.isAccepted() ? "Accepted" : "Rejected")
                                            .orElse("Ignored");
                                    voteJson.addProperty("vote", voteResult);
                                    votesArray.add(voteJson);
                                });
                            });

                    proposalJson.addProperty("numberOfVotes", votesArray.size());
                    proposalJson.add("votes", votesArray);

                    proposalsArray.add(proposalJson);
                });
                cycleJson.addProperty("numberOfProposals", proposalsArray.size());
                cycleJson.add("proposals", proposalsArray);
                cyclesArray.add(cycleJson);
            });
    return cyclesArray;
}

From source file:blockplus.exports.ContextRepresentation.java

License:Open Source License

public JsonElement encodeBoard() {
    final JsonObject boardState = new JsonObject();
    final JsonObject meta = new JsonObject();
    final JsonObject data = new JsonObject();
    final Board board = this.context.board();
    final int rows = board.rows();
    final int columns = board.columns();
    meta.addProperty("rows", rows);
    meta.addProperty("columns", columns);
    final Set<Colors> colors = board.getColors();
    for (final Colors color : colors) {
        final JsonArray jsonArray = new JsonArray();
        for (final IPosition position : board.getSelves(color))
            jsonArray.add(new JsonPrimitive(columns * position.row() + position.column() % rows)); // TODO extract method
        data.add(color.toString(), jsonArray);
    }//from w w w . j  a  va 2s . c  om
    boardState.add("dimension", meta);
    boardState.add("cells", data);
    return boardState;
}