Example usage for com.google.gson JsonParser JsonParser

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

Introduction

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

Prototype

@Deprecated
public JsonParser() 

Source Link

Usage

From source file:com.bios.controller.services.DumpSectionService.java

/**
   * Handles the HTTP <code>GET</code> method which uses the courseid, a sectionid and  token of an administrator. After the
   * courseid, sectionid and token of the administrator is obtained, the method first verifies that the token is valid and present in the session
   * object. Subsequently, if  the token is valid, the method checks the respective DAOs and retrieves the respective information of the bids of
   * that particular courses section and places it in a json object. If an error occurs, such as a missing input, a json object will be created
   * with the status "error" and will reflect the errors in a json array within the object.
   * @param request servlet request//from   www.jav  a 2 s.c o  m
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ConnectionManager manager = new ConnectionManager();
    String requestObject = request.getParameter("r");
    String token = request.getParameter("token");
    ArrayList<String> errorList = new ArrayList<String>();

    JsonObject responseObject = new JsonObject();
    JsonArray allErrors = new JsonArray();

    if (requestObject == null) {
        errorList.add("missing r");
    } else if (requestObject.length() == 0) {
        errorList.add("blank r");
    }

    if (token == null) {
        errorList.add("missing token");
    } else if (token.length() == 0) {
        errorList.add("blank token");
    } else {
        try {
            String result = JWTUtility.verify(token, "abcdefgh12345678");
            if (!result.equals("admin")) {
                errorList.add("invalid token");
            }
        } catch (JWTException e) { // do we need this?
            // This means not an admin, or token expired
            errorList.add("invalid username/token");
        }
    }

    JsonElement jelementRequest = new JsonParser().parse(requestObject);
    JsonObject json = jelementRequest.getAsJsonObject();

    JsonElement crse = json.get("course");
    JsonElement sec = json.get("section");

    if (crse == null) {
        errorList.add("missing course");
    } else if (crse.getAsString().length() == 0) {
        errorList.add("blank course");
    }

    if (sec == null) {
        errorList.add("missing section");
    } else if (sec.getAsString().length() == 0) {
        errorList.add("blank section");
    }

    if (errorList.size() > 0) {
        errorList.sort(new ErrorMsgComparator());
        for (String s : errorList) {
            allErrors.add(new JsonPrimitive(s));
        }
        responseObject.addProperty("status", "error");
        responseObject.add("message", allErrors);
        response.setContentType("application/json");
        response.getWriter().write(responseObject.toString());
        return;
    }

    String courseID = crse.getAsString();
    String sectionID = sec.getAsString();

    int round = manager.getBiddingRound();
    String status = manager.getBiddingRoundStatus();

    // Will now check to see if there are any errors here
    Course course = CourseDAO.getInstance().findCourse(crse.getAsString());
    Section section = null;
    if (course == null) {
        allErrors.add(new JsonPrimitive("invalid course"));
    } else {
        section = SectionDAO.getInstance().findSection(course.getCourseID(), sec.getAsString());
        if (section == null) {
            allErrors.add(new JsonPrimitive("invalid section"));
        }
    }

    if (allErrors.size() != 0) {
        responseObject.add("status", new JsonPrimitive("error"));
        responseObject.add("message", allErrors);
        response.setContentType("application/json");
        response.getWriter().write(responseObject.toString());
        return;
    }

    JsonArray allResults = new JsonArray();
    ArrayList<SectionStudent> allSecStudList = SectionStudentDAO.getInstance()
            .getSectionStudentListWithID(crse.getAsString(), sec.getAsString());
    ArrayList<SectionStudent> secStudList = new ArrayList<>();

    for (SectionStudent secStud : allSecStudList) {
        if (secStud.getCourseID().equals(courseID) && secStud.getSectionID().equals(sectionID)) {
            secStudList.add(secStud);
        }
        //            String cID = secStud.getCourseID();
        //            String sID = secStud.getSectionID();
        //
        //            ArrayList<Bid> halfBids = new ArrayList<>();
        //            if (round == 1 || round == 2 && status.equals("started")) {
        //                halfBids = BidDAO.getInstance().getSuccessfulBidsWithID(cID, sID);
        //            } else if (round == 2 && status.equals("stopped")) {
        //                halfBids = BidDAO.getInstance().getBids(sID, sID);
        //            }
        //            allBids.addAll(halfBids);
    }

    secStudList.sort(new SectionStudentComparator());
    for (SectionStudent secStud : secStudList) {
        JsonObject obj = new JsonObject();
        obj.addProperty("userid", secStud.getUserID());
        obj.addProperty("amount", secStud.getAmount());
        allResults.add(obj);
    }

    //        // After we sort all the bids, then we shall add them to be responded to
    //        allBids.sort(new BidUserComparator());
    //        for (Bid bid : allBids) {
    //            JsonObject obj = new JsonObject();
    //            obj.add("userid", new JsonPrimitive(bid.getUserID()));
    //            obj.add("amount", new JsonPrimitive(bid.getAmount()));
    //            allResults.add(obj);
    //        }

    responseObject.add("status", new JsonPrimitive("success"));
    responseObject.add("students", allResults);

    response.setContentType("application/json");
    response.getWriter().write(responseObject.toString());
}

From source file:com.bios.controller.services.DumpUserService.java

/**
* Handles the HTTP <code>GET</code> method which takes in the userid of a
* user and a token of an administrator. After the userid of the student and
* token of the administrator is passed in, the method first verifies that
* the token is valid. If the token is invalid, a json object is created
* with the status "error" and an error message "invalid username/token".
* Subsequently, if the token is valid, the method checks the respective
* DAOs and retrieves the respective information of the user and places it
* in the json object. If an error occurs, such as a missing input, the json
* object will also reflect the error without displaying the user's
* information./*  w w  w.j  a va 2 s  . c o  m*/
 * @param request servlet requesty
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ConnectionManager manager = new ConnectionManager();
    String requestObject = request.getParameter("r");
    String token = request.getParameter("token");
    ArrayList<String> errorList = new ArrayList<String>();

    JsonObject responseObject = new JsonObject();
    JsonArray allErrors = new JsonArray();

    if (requestObject == null) {
        errorList.add("missing r");
    } else if (requestObject.length() == 0) {
        errorList.add("blank r");
    }

    if (token == null) {
        errorList.add("missing token");
    } else if (token.length() == 0) {
        errorList.add("blank token");
    } else {
        try {
            String result = JWTUtility.verify(token, "abcdefgh12345678");
            if (!result.equals("admin")) {
                errorList.add("invalid token");
            }
        } catch (JWTException e) { // do we need this?
            // This means not an admin, or token expired
            errorList.add("invalid username/token");
        }
    }

    JsonElement jelementRequest = new JsonParser().parse(requestObject);
    JsonObject json = jelementRequest.getAsJsonObject();

    JsonElement userID = json.get("userid");

    if (userID == null) {
        errorList.add("missing userid");
    } else if (userID.getAsString().length() == 0) {
        errorList.add("blank userid");
    }

    if (errorList.size() > 0) {
        errorList.sort(new ErrorMsgComparator());
        for (String s : errorList) {
            allErrors.add(new JsonPrimitive(s));
        }
        responseObject.addProperty("status", "error");
        responseObject.add("message", allErrors);
        response.setContentType("application/json");
        response.getWriter().write(responseObject.toString());
        return;
    }

    Student s = StudentDAO.getInstance().retrieve(userID.getAsString());

    if (s == null) {
        allErrors.add(new JsonPrimitive("invalid userid"));
        responseObject.addProperty("status", "error");
        responseObject.add("message", allErrors);
        response.setContentType("application/json");
        response.getWriter().write(responseObject.toString());
        return;
    } else {
        responseObject.addProperty("status", "success");
        responseObject.addProperty("userid", s.getId());
        responseObject.addProperty("password", s.getPassword());
        responseObject.addProperty("name", s.getNameOfUser());
        responseObject.addProperty("school", s.getSchool());
        DecimalFormat df = new DecimalFormat("0.00");
        String result = df.format(s.geteDollar());
        double eDollar = Double.parseDouble(result);
        responseObject.addProperty("edollar", eDollar);
    }

    response.setContentType("application/json");
    response.getWriter().write(responseObject.toString());
    return;
}

From source file:com.bios.controller.services.UpdateBidService.java

/**
* Handles the HTTP <code>GET</code> method which updates a bid. Firstly, the token
* is checked for its validity. If the token is valid, the method then goes into the
* respective DAOs to look for the bid. If the bid is valid and can be deleted, the
* bid is then deleted from the DAO and the database. Subsequentyly, a json object
* with the status "success" will be created. If any errors occur such as an
* invalid course or missing token is detected, a json object with the status "error"
* will be created with a json array of the erros that caused the failure to update.
* @param request servlet request//from www.ja  va2 s .c  o m
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ConnectionManager manager = new ConnectionManager();
    String requestObject = request.getParameter("r");
    String token = request.getParameter("token");
    ArrayList<String> errorList = new ArrayList<String>();

    JsonObject reponseObject = new JsonObject();
    JsonArray allErrors = new JsonArray();

    if (requestObject == null) {
        errorList.add("missing r");
    } else if (requestObject.length() == 0) {
        errorList.add("blank r");
    }

    if (token == null) {
        errorList.add("missing token");
    } else if (token.length() == 0) {
        errorList.add("blank token");
    } else {
        try {
            String result = JWTUtility.verify(token, "abcdefgh12345678");
            if (!result.equals("admin")) {
                errorList.add("invalid token");
            }
        } catch (JWTException e) { // do we need this?
            // This means not an admin, or token expired
            errorList.add("invalid username/token");
        }
    }

    JsonElement jelement = new JsonParser().parse(requestObject);
    JsonObject json = jelement.getAsJsonObject();
    Bid existingBid = null;

    JsonElement amt = json.get("amount");
    JsonElement crse = json.get("course");
    JsonElement sec = json.get("section");
    JsonElement user = json.get("userid");

    if (amt == null) {
        errorList.add("missing amount");
    } else if (amt.getAsString().length() == 0) {
        errorList.add("blank amount");
    }

    if (crse == null) {
        errorList.add("missing course");
    } else if (crse.getAsString().length() == 0) {
        errorList.add("blank course");
    }

    if (sec == null) {
        errorList.add("missing section");
    } else if (sec.getAsString().length() == 0) {
        errorList.add("blank section");
    }

    if (user == null) {
        errorList.add("missing userid");
    } else if (user.getAsString().length() == 0) {
        errorList.add("blank userid");
    }

    if (errorList.size() > 0) {
        errorList.sort(new ErrorMsgComparator());
        for (String s : errorList) {
            allErrors.add(new JsonPrimitive(s));
        }
        reponseObject.addProperty("status", "error");
        reponseObject.add("message", allErrors);
        response.setContentType("application/json");
        response.getWriter().write(reponseObject.toString());
        return;
    }

    // There may be type errors for the double here
    double amount = amt.getAsDouble();
    String courseID = crse.getAsString();
    String sectionID = sec.getAsString();
    String userID = user.getAsString();

    Course course = CourseDAO.getInstance().findCourse(courseID);
    Section section = SectionDAO.getInstance().findSection(courseID, sectionID);
    Student student = StudentDAO.retrieve(userID);

    int round = manager.getBiddingRound();
    BootstrapValidator bv = new BootstrapValidator();
    if (bv.parseBidAmount(amt.getAsString()) != null) {
        allErrors.add(new JsonPrimitive("invalid amount"));
    }

    if (course == null) {
        allErrors.add(new JsonPrimitive("invalid course"));
    }

    // only check if course code is valid
    if (course != null && section == null) {
        allErrors.add(new JsonPrimitive("invalid section"));
    }

    if (student == null) {
        allErrors.add(new JsonPrimitive("invalid userid"));
    }

    if (allErrors.size() > 0) {
        reponseObject.addProperty("status", "error");
        reponseObject.add("message", allErrors);
        response.setContentType("application/json");
        response.getWriter().write(reponseObject.toString());
        return;
    }

    if (manager.getBiddingRoundStatus().equals("started")) {
        if (round == 2) {
            double minBidAmt = MinBidDAO.getInstance().getValue(courseID + "-" + sectionID);
            System.out.println(courseID + "-" + sectionID);
            System.out.println("UPDATE amount: " + amount);
            System.out.println("UPDATE min bid: " + minBidAmt);
            if (amount < minBidAmt) {
                errorList.add("bid too low");
            }
        } else if (round == 1) {
            if (amount < 10) {
                errorList.add("bid too low");
            }
        }

        existingBid = BidDAO.getInstance().getStudentBidWithCourseID(userID, courseID);
        //no existing bid
        if (existingBid == null) {
            if (bv.parseEDollarEnough(userID, courseID, sectionID, amt.getAsString()) != null) {
                errorList.add("insufficient e$");
            }
        } else if (existingBid.getStatus().equals("pending")) {
            if (bv.parseEDollarEnoughExistingBid(userID, courseID, sectionID, amt.getAsString()) != null) {
                // Think too much alr, this line is not needed
                //                    errorList.add("insufficient e$");
            }
        } else if (existingBid.getStatus().equals("success")) {
            errorList.add("course enrolled");
        }

        if (bv.parseClassTimeTableClash(userID, courseID, sectionID) != null) {
            errorList.add("class timetable clash");
        }

        if (bv.parseExamTimeTableClash(userID, courseID, sectionID) != null) {
            errorList.add("exam timetable clash");
        }

        if (bv.parseIncompletePrerequisite(userID, courseID) != null) {
            errorList.add("incomplete prerequisites");
        }

        if (bv.parseAlreadyComplete(userID, courseID) != null) {
            errorList.add("course completed");
        }

        if (bv.parseSectionLimit(userID, courseID, sectionID) != null) {
            errorList.add("section limit reached");
        }

        if (bv.parseNotOwnSchoolCourse(userID, courseID) != null) {
            errorList.add("not own school course");
        }

        ArrayList<SectionStudent> sectionStudentList = SectionStudentDAO.getInstance()
                .getSectionStudentListWithID(courseID, sectionID);
        int vacancy = section.getSize() - sectionStudentList.size();
        if (vacancy <= 0) {
            errorList.add("no vacancy");
        }
    } else {
        errorList.add("round ended");
    }

    if (errorList.size() > 0) {
        Collections.sort(errorList);
        for (String s : errorList) {
            allErrors.add(new JsonPrimitive(s));
        }
        reponseObject.addProperty("status", "error");
        reponseObject.add("message", allErrors);
        response.setContentType("application/json");
        response.getWriter().write(reponseObject.toString());
        return;
    } else { //success state
        Bid newBid = new Bid(userID, amount, courseID, sectionID, "pending");
        if (existingBid != null) { //there is an existing bid
            MinBidDAO.getInstance().getMinBidList().remove(courseID + "-" + sectionID);
            MinBidDAO.getInstance().refresh();
            BidPlacementServlet.updateCurrentBid(userID, courseID, sectionID, amount, student);
        } else {
            student.seteDollar(student.geteDollar() - amount);
            manager.setEDollar(userID, student.geteDollar());
            BidDAO.getInstance().addBid(newBid);
            manager.addBid(newBid);
            //dk if this is needed
            if (round == 1) {
                RoundOneBidDAO.getInstance().addBid(newBid);
            } else if (round == 2) {
                RoundTwoBidDAO.getInstance().addBid(newBid);
            }
        }
        MinBidDAO.getInstance().refresh();
        reponseObject.addProperty("status", "success");
    }

    response.setContentType("application/json");
    response.getWriter().write(reponseObject.toString());
    return;
}

From source file:com.birdv5.ir.ui.home.fragment.SuperAwesomeFragment.java

License:Apache License

private void getData() {
    SQLiteDatabase db = ((IRecordApp) getActivity().getApplication()).getDB();
    String[] columns = { ArticlesTable.Columns.COLUMN_CONTENT };

    String selection = ArticlesTable.Columns.COLUMN_TYPE + "=? " + " limit " + PAGE_SIZE + " offset " + pos;
    String[] selectionArgs = { type + "" };

    Cursor cursor = ArticlesTable.getInstance().query(db, columns, selection, selectionArgs, null);

    cursor.moveToFirst();/*from ww w. j ava 2  s  .  co m*/

    int count = 0;
    while (!cursor.isAfterLast()) {
        String content = cursor.getString(0);
        JsonObject obj = new JsonParser().parse(content).getAsJsonObject();

        adapter.add(obj);
        cursor.moveToNext();
        count++;
    }

    if (count > 0) {
        pos++;
    }

    cursor.close();
    db.close();

}

From source file:com.bizideal.whoami.utils.cloopen.CCPRestSmsSDK.java

License:Open Source License

/**
 * ???//from   w w w. jav a  2s  . com
 * 
 * @param to
 *            ? ??????????100
 * @param templateId
 *            ? ?Id
 * @param datas
 *            ?? ???{??}
 * @return
 */
public HashMap<String, Object> sendTemplateSMS(String to, String templateId, String[] datas) {
    HashMap<String, Object> validate = accountValidate();
    if (validate != null)
        return validate;
    if ((isEmpty(to)) || (isEmpty(App_ID)) || (isEmpty(templateId)))
        throw new IllegalArgumentException("?:" + (isEmpty(to) ? " ?? " : "")
                + (isEmpty(templateId) ? " ?Id " : "") + "");
    CcopHttpClient chc = new CcopHttpClient();
    DefaultHttpClient httpclient = null;
    try {
        httpclient = chc.registerSSL(SERVER_IP, "TLS", Integer.parseInt(SERVER_PORT), "https");
    } catch (Exception e1) {
        e1.printStackTrace();
        throw new RuntimeException("?httpclient" + e1.getMessage());
    }
    String result = "";
    try {
        HttpPost httppost = (HttpPost) getHttpRequestBase(1, TemplateSMS);
        String requsetbody = "";
        if (BODY_TYPE == BodyType.Type_JSON) {
            JsonObject json = new JsonObject();
            json.addProperty("appId", App_ID);
            json.addProperty("to", to);
            json.addProperty("templateId", templateId);
            if (datas != null) {
                StringBuilder sb = new StringBuilder("[");
                for (String s : datas) {
                    sb.append("\"" + s + "\"" + ",");
                }
                sb.replace(sb.length() - 1, sb.length(), "]");
                JsonParser parser = new JsonParser();
                JsonArray Jarray = parser.parse(sb.toString()).getAsJsonArray();
                json.add("datas", Jarray);
            }
            requsetbody = json.toString();
        } else {
            StringBuilder sb = new StringBuilder("<?xml version='1.0' encoding='utf-8'?><TemplateSMS>");
            sb.append("<appId>").append(App_ID).append("</appId>").append("<to>").append(to).append("</to>")
                    .append("<templateId>").append(templateId).append("</templateId>");
            if (datas != null) {
                sb.append("<datas>");
                for (String s : datas) {
                    sb.append("<data>").append(s).append("</data>");
                }
                sb.append("</datas>");
            }
            sb.append("</TemplateSMS>").toString();
            requsetbody = sb.toString();
        }

        LoggerUtil.info("sendTemplateSMS Request body =  " + requsetbody);
        BasicHttpEntity requestBody = new BasicHttpEntity();
        requestBody.setContent(new ByteArrayInputStream(requsetbody.getBytes("UTF-8")));
        requestBody.setContentLength(requsetbody.getBytes("UTF-8").length);
        httppost.setEntity(requestBody);
        HttpResponse response = httpclient.execute(httppost);

        HttpEntity entity = response.getEntity();
        if (entity != null)
            result = EntityUtils.toString(entity, "UTF-8");

        EntityUtils.consume(entity);
    } catch (IOException e) {
        e.printStackTrace();
        LoggerUtil.error(e.getMessage());
        return getMyError("172001", "");
    } catch (Exception e) {
        e.printStackTrace();
        LoggerUtil.error(e.getMessage());
        return getMyError("172002", "");
    } finally {
        if (httpclient != null)
            httpclient.getConnectionManager().shutdown();
    }

    LoggerUtil.info("sendTemplateSMS response body = " + result);

    try {
        if (BODY_TYPE == BodyType.Type_JSON) {
            return jsonToMap(result);
        } else {
            return xmlToMap(result);
        }
    } catch (Exception e) {

        return getMyError("172003", "");
    }
}

From source file:com.bizideal.whoami.utils.cloopen.CCPRestSmsSDK.java

License:Open Source License

private HashMap<String, Object> jsonToMap(String result) {
    HashMap<String, Object> hashMap = new HashMap<String, Object>();
    JsonParser parser = new JsonParser();
    JsonObject asJsonObject = parser.parse(result).getAsJsonObject();
    Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet();
    HashMap<String, Object> hashMap2 = new HashMap<String, Object>();

    for (Map.Entry<String, JsonElement> m : entrySet) {
        if ("statusCode".equals(m.getKey()) || "statusMsg".equals(m.getKey()))
            hashMap.put(m.getKey(), m.getValue().getAsString());
        else {/*  w w  w. ja va 2s.  co  m*/
            if ("SubAccount".equals(m.getKey()) || "totalCount".equals(m.getKey()) || "token".equals(m.getKey())
                    || "downUrl".equals(m.getKey())) {
                if (!"SubAccount".equals(m.getKey()))
                    hashMap2.put(m.getKey(), m.getValue().getAsString());
                else {
                    try {
                        if ((m.getValue().toString().trim().length() <= 2)
                                && !m.getValue().toString().contains("[")) {
                            hashMap2.put(m.getKey(), m.getValue().getAsString());
                            hashMap.put("data", hashMap2);
                            break;
                        }
                        if (m.getValue().toString().contains("[]")) {
                            hashMap2.put(m.getKey(), new JsonArray());
                            hashMap.put("data", hashMap2);
                            continue;
                        }
                        JsonArray asJsonArray = parser.parse(m.getValue().toString()).getAsJsonArray();
                        ArrayList<HashMap<String, Object>> arrayList = new ArrayList<HashMap<String, Object>>();
                        for (JsonElement j : asJsonArray) {
                            Set<Entry<String, JsonElement>> entrySet2 = j.getAsJsonObject().entrySet();
                            HashMap<String, Object> hashMap3 = new HashMap<String, Object>();
                            for (Map.Entry<String, JsonElement> m2 : entrySet2) {
                                hashMap3.put(m2.getKey(), m2.getValue().getAsString());
                            }
                            arrayList.add(hashMap3);
                        }
                        hashMap2.put("SubAccount", arrayList);
                    } catch (Exception e) {
                        JsonObject asJsonObject2 = parser.parse(m.getValue().toString()).getAsJsonObject();
                        Set<Entry<String, JsonElement>> entrySet2 = asJsonObject2.entrySet();
                        HashMap<String, Object> hashMap3 = new HashMap<String, Object>();
                        for (Map.Entry<String, JsonElement> m2 : entrySet2) {
                            hashMap3.put(m2.getKey(), m2.getValue().getAsString());
                        }
                        hashMap2.put(m.getKey(), hashMap3);
                        hashMap.put("data", hashMap2);
                    }

                }
                hashMap.put("data", hashMap2);
            } else {

                JsonObject asJsonObject2 = parser.parse(m.getValue().toString()).getAsJsonObject();
                Set<Entry<String, JsonElement>> entrySet2 = asJsonObject2.entrySet();
                HashMap<String, Object> hashMap3 = new HashMap<String, Object>();
                for (Map.Entry<String, JsonElement> m2 : entrySet2) {
                    hashMap3.put(m2.getKey(), m2.getValue().getAsString());
                }
                if (hashMap3.size() != 0) {
                    hashMap2.put(m.getKey(), hashMap3);
                } else {
                    hashMap2.put(m.getKey(), m.getValue().getAsString());
                }
                hashMap.put("data", hashMap2);
            }
        }
    }
    return hashMap;
}

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

License:Apache License

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

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

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

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

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

    List<String> labels = new ArrayList<String>();
    boolean isFirst = true;
    for (JsonElement elem : values) {
        JsonObject obj = elem.getAsJsonObject();
        entrySet = obj.entrySet();//from   www . j  a  v  a  2 s. co  m
        cols.clear();
        if (isFirst) {
            for (Map.Entry<String, JsonElement> entry : entrySet) {
                labels.add(entry.getKey());
            }
            isFirst = false;
        }

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

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

From source file:com.bizosys.dataservice.sql.SqlSensor.java

License:Apache License

private void initializePool(Request request, Response response) {

    String jsonData = request.mapData.get("jsonData");
    JsonObject jsonObject = new JsonParser().parse(jsonData).getAsJsonObject();

    String agentIP = jsonObject.getAsJsonPrimitive("agentIP").getAsString();
    String poolName = jsonObject.getAsJsonPrimitive("poolName").getAsString();

    try {/*from   w  w  w.j  a  v a 2s  .  c o  m*/
        DbConfigUtil.setupPoolByPoolName(agentIP, poolName);
        response.writeTextWithNoHeaderAndFooter("OK");
    } catch (Exception e) {
        LOG.warn("Error initializing drone user pool for ip - " + agentIP);
    }
}

From source file:com.blackducksoftware.integration.email.EmailEngine.java

License:Apache License

public ExtensionConfigManager createExtensionConfigManager() {
    // has to be separate from the dataservicesfactory otherwise we have a
    // chicken and egg problem
    final ExtensionConfigManager extConfigManager = new ExtensionConfigManager(extensionInfoData,
            new JsonParser());
    return extConfigManager;
}

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

License:Apache License

NpmParseResult convertNpmJsonFileToCodeLocation(final String sourcePath, final String npmLsOutput) {
    final JsonObject npmJson = new JsonParser().parse(npmLsOutput).getAsJsonObject();
    final MutableDependencyGraph graph = new MutableMapDependencyGraph();

    final JsonElement projectNameElement = npmJson.getAsJsonPrimitive(JSON_NAME);
    final JsonElement projectVersionElement = npmJson.getAsJsonPrimitive(JSON_VERSION);
    String projectName = null;/*from ww  w  .  ja  v a  2 s.c o  m*/
    String projectVersion = null;
    if (projectNameElement != null) {
        projectName = projectNameElement.getAsString();
    }
    if (projectVersionElement != null) {
        projectVersion = projectVersionElement.getAsString();
    }

    populateChildren(graph, null, npmJson.getAsJsonObject(JSON_DEPENDENCIES), true);

    final ExternalId externalId = externalIdFactory.createNameVersionExternalId(Forge.NPM, projectName,
            projectVersion);

    final DetectCodeLocation codeLocation = new DetectCodeLocation.Builder(DetectCodeLocationType.NPM,
            sourcePath, externalId, graph).build();

    return new NpmParseResult(projectName, projectVersion, codeLocation);

}