Example usage for com.google.gson JsonObject JsonObject

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

Introduction

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

Prototype

JsonObject

Source Link

Usage

From source file:cashPR.GetCashPaymentHeader.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w  w w.j  av  a2 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.branch_cd from CPRHD c left join CPRDT 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("BRANCH_CD", rsLocal.getString("BRANCH_CD"));
                array.add(object);
            }
            //                response.getWriter().print(array.toString());
            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:catalog.CloudantUtil.java

License:Apache License

/**
 * create a document in the cloudant database
 *
 * @throws UnsupportedEncodingException//from w  w  w  .  jav a 2 s.  com
 */
public static JsonObject createDocument(Credential credential, String jsonObj)
        throws UnsupportedEncodingException {
    JsonObject obj = new JsonParser().parse(jsonObj).getAsJsonObject();

    CloudantClient client = new CloudantClient(credential.user, credential.user, credential.password);
    Database db = client.database(credential.dbname, false);
    com.cloudant.client.api.model.Response res = db.post(obj);
    client.shutdown();

    JsonObject ret = new JsonObject();
    ret.addProperty("ok", true);
    ret.addProperty("id", res.getId());
    ret.addProperty("rev", res.getRev());
    return ret;
}

From source file:catalog.CloudantUtil.java

License:Apache License

/**
 * Read bulk documents from the cloudant database
 *
 * @throws UnsupportedEncodingException//from  w  ww  .j  ava  2s .  c o  m
 */
public static JsonArray bulkDocuments(Credential credential, JsonArray bulkDocs)
        throws UnsupportedEncodingException {
    JsonObject docs = new JsonObject();
    docs.add("docs", bulkDocs);
    // use GET to get the document
    String dbname = credential.dbname;
    Response response = given().port(443).baseUri(cloudantAccount(credential.user)).auth()
            .basic(credential.user, credential.password).contentType("application/json").body(docs)
            .post("/" + credential.dbname + "/_bulk_docs?include_docs=true");
    String responseStr = response.asString();
    if (responseStr.length() > 500)
        responseStr = responseStr.substring(0, 500);
    System.out.format("Response of get document from database %s: %s\n", dbname, responseStr);
    return (JsonArray) new JsonParser().parse(response.asString());
}

From source file:catalog.CloudantUtil.java

License:Apache License

public static JsonObject createDocParameterForWhisk(String doc) {
    JsonObject cloudantDoc = new JsonObject();
    String now = new Date().toString();
    cloudantDoc.addProperty("_id", DOC_ID);
    cloudantDoc.addProperty("date", now);
    // Create JSON object that will be passed as an argument to whisk cli
    JsonObject param = new JsonObject();
    if (doc != null && !doc.isEmpty()) {
        param.addProperty("doc", doc);
    } else {/*from   w  ww.  ja  v a  2 s.c o m*/
        param.addProperty("doc", cloudantDoc.toString());
    }
    return param;
}

From source file:catalog.CloudantUtil.java

License:Apache License

public static JsonArray createDocumentArray(int numDocs) {
    // Array of docs for bulk
    JsonArray bulkDocs = new JsonArray();
    for (int i = 1; i <= numDocs; i++) {
        JsonObject cloudantDoc = new JsonObject();
        String now = new Date().toString();
        cloudantDoc.addProperty("_id", CloudantUtil.DOC_ID + i);
        cloudantDoc.addProperty("date", now);
        bulkDocs.add(cloudantDoc);//  w  w  w. ja  v  a 2s .  com
    }
    return bulkDocs;
}

From source file:cc.kave.commons.utils.json.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }/*from   w ww . j  a v a 2  s  .  c o m*/

    final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<String, TypeAdapter<?>>();
    final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<Class<?>, TypeAdapter<?>>();
    for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
        TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
        labelToDelegate.put(entry.getKey(), delegate);
        subtypeToDelegate.put(entry.getValue(), delegate);
    }

    return new TypeAdapter<R>() {
        @Override
        public R read(JsonReader in) throws IOException {
            JsonElement jsonElement = Streams.parse(in);
            // (kave adaptation) was: ".remove(typeFiledName)"
            JsonElement labelJsonElement = jsonElement.getAsJsonObject().get(typeFieldName);
            if (labelJsonElement == null) {
                throw new JsonParseException("cannot deserialize " + baseType
                        + " because it does not define a field named " + typeFieldName);
            }
            String label = labelJsonElement.getAsString();
            @SuppressWarnings("unchecked") // registration requires that
            // subtype extends T
            TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label);
            if (delegate == null) {
                throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label
                        + "; did you forget to register a subtype?");
            }
            return delegate.fromJsonTree(jsonElement);
        }

        @Override
        public void write(JsonWriter out, R value) throws IOException {
            if (value == null) {
                Streams.write(null, out);
                return;
            }
            Class<?> srcType = value.getClass();
            String label = subtypeToLabel.get(srcType);
            @SuppressWarnings("unchecked") // registration requires that
            // subtype extends T
            TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType);
            if (delegate == null) {
                throw new JsonParseException(
                        "cannot serialize " + srcType.getName() + "; did you forget to register a subtype?");
            }
            JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject();
            // (kave adaptation) disabled check
            // if (jsonObject.has(typeFieldName)) {
            // throw new JsonParseException("cannot serialize " +
            // srcType.getName()
            // + " because it already defines a field named " +
            // typeFieldName);
            // }
            JsonObject clone = new JsonObject();
            clone.add(typeFieldName, new JsonPrimitive(label));
            for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
                clone.add(e.getKey(), e.getValue());
            }
            Streams.write(clone, out);
        }
    };
}

From source file:ccm.pay2spawn.configurator.Configurator.java

License:Open Source License

@Override
public void callback(Object... data) {
    int rewardID = (int) data[0];
    String type = (String) data[1];
    JsonObject newData = (JsonObject) data[2];

    if (rewardID == -1) {
        JsonObject object = new JsonObject();
        object.addProperty("type", type);
        object.add("data", newData);
        rewardData.add(object);/*from  w  w  w  .ja va2 s .c  o m*/
        rewards.updateUI();
    } else {
        rewardData.get(rewardID).getAsJsonObject().add("data", newData);
        rewards.updateUI();
    }
}

From source file:ccm.pay2spawn.configurator.Configurator.java

License:Open Source License

private void setupListeners() {
    typeList.addMouseListener(new MouseAdapter() {
        @Override//from ww  w.j  a v  a  2  s .  c o m
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
                TypeRegistry.getByName(typeList.getSelectedValue()).openNewGui(-1, new JsonObject());
            }
        }
    });
    rewards.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
                int id = rewards.getSelectedIndex();
                TypeRegistry.getByName(rewards.getSelectedValue()).openNewGui(id,
                        rewardData.get(id).getAsJsonObject().getAsJsonObject("data"));
            }
        }
    });
    rewards.addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            deleteSelectedRewardButton.setEnabled(!rewards.isSelectionEmpty());
            duplicateSelectedRewardButton.setEnabled(!rewards.isSelectionEmpty());
        }
    });
    helpMeWithRandomizationButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            Help.init();
        }
    });
    mainTable.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
                currentlyEditingID = mainTable.getSelectedRow();
                currentlyEditingData = rootArray.get(currentlyEditingID).getAsJsonObject();
                if (currentlyEditingData.has("rewards"))
                    rewardData = JsonNBTHelper.cloneJSON(currentlyEditingData.getAsJsonArray("rewards"))
                            .getAsJsonArray();
                else
                    rewardData = new JsonArray();
                rewards.updateUI();
                rewards.clearSelection();
                typeList.clearSelection();
                saveOverOldGroupButton.setEnabled(true);
                removeGroupButton.setEnabled(true);

                tabbedPane1.setSelectedIndex(1);
                nameField.setText(currentlyEditingData.getAsJsonPrimitive(COLUMN_KEYS[0]).getAsString());
                amountField.setText(currentlyEditingData.getAsJsonPrimitive(COLUMN_KEYS[1]).getAsString());
                messageField.setText(currentlyEditingData.getAsJsonPrimitive(COLUMN_KEYS[2]).getAsString());
                countdownTextField.setText(currentlyEditingData.has(COLUMN_KEYS[3])
                        ? currentlyEditingData.getAsJsonPrimitive(COLUMN_KEYS[3]).getAsString()
                        : "");
            }
        }
    });
    clearButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            clear();
        }
    });
    saveOverOldGroupButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (saveEdits()) {
                JsonArray newRoot = new JsonArray();
                for (int i = 0; i < rootArray.size(); i++)
                    if (i != currentlyEditingID)
                        newRoot.add(rootArray.get(i));

                rootArray = newRoot;
                rootArray.add(currentlyEditingData);
                mainTable.updateUI();
                saveMainJsonToFile();
                ColumnsAutoSizer.sizeColumnsToFit(mainTable, 20);
            }
        }
    });
    saveAsNewGroupButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (saveEdits()) {
                rootArray.add(currentlyEditingData);
                currentlyEditingID = rootArray.size() - 1;
                saveOverOldGroupButton.setEnabled(true);
                removeGroupButton.setEnabled(true);
                mainTable.updateUI();
                saveMainJsonToFile();
                ColumnsAutoSizer.sizeColumnsToFit(mainTable, 20);
            }
        }
    });
    removeGroupButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JsonArray newRoot = new JsonArray();
            for (int i = 0; i < rootArray.size(); i++)
                if (i != currentlyEditingID)
                    newRoot.add(rootArray.get(i));

            rootArray = newRoot;
            clear();
            tabbedPane1.setSelectedIndex(0);
            saveMainJsonToFile();
        }
    });
    duplicateSelectedRewardButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            int toDuplicate = rewards.getSelectedIndex();
            rewardData.add(JsonNBTHelper.cloneJSON(rewardData.get(toDuplicate)));

            rewards.updateUI();
        }
    });
    deleteSelectedRewardButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            int toRemove = rewards.getSelectedIndex();
            JsonArray newRewardData = new JsonArray();
            for (int i = 0; i < rewardData.size(); i++)
                if (i != toRemove)
                    newRewardData.add(rewardData.get(i));
            rewardData = newRewardData;

            rewards.clearSelection();
            rewards.updateUI();
        }
    });
    makeNiceHtmlPageButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                HTMLGenerator.generate();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    });
}

From source file:ccm.pay2spawn.configurator.Configurator.java

License:Open Source License

public boolean saveEdits() {
    currentlyEditingData = new JsonObject();

    boolean flag = true;
    if (nameField.getText().equals("")) {
        nameLabel.setForeground(Color.red);
        flag = false;/*  w w w .j a  v a2  s . c  om*/
    } else {
        nameLabel.setForeground(Color.black);
        currentlyEditingData.addProperty(COLUMN_KEYS[0], nameField.getText());
    }

    if (amountField.getText().equals("") || !Helper.isDouble(amountField.getText())) {
        amountLabel.setForeground(Color.red);
        flag = false;
    } else {
        amountLabel.setForeground(Color.black);
        currentlyEditingData.addProperty(COLUMN_KEYS[1], amountField.getText());
    }
    currentlyEditingData.addProperty(COLUMN_KEYS[2], messageField.getText());
    currentlyEditingData.addProperty(COLUMN_KEYS[3], countdownTextField.getText());
    currentlyEditingData.add(COLUMN_KEYS[4], rewardData);

    return flag;
}

From source file:ccm.pay2spawn.configurator.Configurator.java

License:Open Source License

public void clear() {
    currentlyEditingID = -1;/*  w  w  w.j  av a2s  .  c o m*/
    currentlyEditingData = new JsonObject();
    rewardData = new JsonArray();
    rewards.updateUI();
    rewards.clearSelection();
    typeList.clearSelection();
    saveOverOldGroupButton.setEnabled(false);
    removeGroupButton.setEnabled(false);

    nameField.setText("");
    amountField.setText("");
    messageField.setText("");
    mainTable.updateUI();
    countdownTextField.setText("");

    nameLabel.setForeground(Color.black);
    amountLabel.setForeground(Color.black);
}