Example usage for com.google.gson JsonPrimitive JsonPrimitive

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

Introduction

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

Prototype

public JsonPrimitive(Character c) 

Source Link

Document

Create a primitive containing a character.

Usage

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//w ww  .j a  va  2  s  .  c om
* @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.blogging.serialization.GsonObjectIdSerializer.java

License:Apache License

@Override
public JsonElement serialize(ObjectId id, Type typeOf, JsonSerializationContext context) {
    return new JsonPrimitive(id.toString());
}

From source file:com.canoo.dolphin.impl.codec.ValueEncoder.java

License:Apache License

static JsonElement encodeValue(Object value) {
    if (value instanceof String) {
        return new JsonPrimitive((String) value);
    }//  ww  w  .  ja  va 2  s  .c o m
    if (value instanceof Number) {
        return new JsonPrimitive((Number) value);
    }
    if (value instanceof Boolean) {
        return new JsonPrimitive((Boolean) value);
    }
    throw new IllegalStateException("Only String, Number, and Boolean are allowed currently");
}

From source file:com.canoo.dolphin.server.mbean.beans.ModelJsonSerializer.java

License:Apache License

public static JsonObject toJson(Object dolphinModel) {
    if (dolphinModel == null) {
        return null;
    }/*from   w w  w . ja  v a 2s.  c  om*/

    JsonObject jsonObject = new JsonObject();

    for (Field field : ReflectionHelper.getInheritedDeclaredFields(dolphinModel.getClass())) {
        if (ReflectionHelper.isProperty(field.getType())) {
            Property property = (Property) ReflectionHelper.getPrivileged(field, dolphinModel);
            Object value = property.get();
            if (value == null) {
                jsonObject.add(field.getName(), null);
            } else if (Number.class.isAssignableFrom(value.getClass())
                    || Double.TYPE.isAssignableFrom(value.getClass())
                    || Float.TYPE.isAssignableFrom(value.getClass())
                    || Long.TYPE.isAssignableFrom(value.getClass())
                    || Integer.TYPE.isAssignableFrom(value.getClass())) {
                jsonObject.add(field.getName(), new JsonPrimitive((Number) value));
            } else if (String.class.isAssignableFrom(value.getClass())) {
                jsonObject.add(field.getName(), new JsonPrimitive((String) value));
            } else if (Boolean.class.isAssignableFrom(value.getClass())
                    || Boolean.TYPE.isAssignableFrom(value.getClass())) {
                jsonObject.add(field.getName(), new JsonPrimitive((Boolean) value));
            } else {
                jsonObject.add(field.getName(), toJson(value));
            }
        } else if (ReflectionHelper.isObservableList(field.getType())) {
            ObservableList list = (ObservableList) ReflectionHelper.getPrivileged(field, dolphinModel);
            JsonArray jsonArray = new JsonArray();
            for (Object value : list) {
                if (value == null) {
                    //TODO
                    //jsonArray.add(null);
                } else if (Number.class.isAssignableFrom(value.getClass())
                        || Double.TYPE.isAssignableFrom(value.getClass())
                        || Float.TYPE.isAssignableFrom(value.getClass())
                        || Long.TYPE.isAssignableFrom(value.getClass())
                        || Integer.TYPE.isAssignableFrom(value.getClass())) {
                    jsonArray.add(new JsonPrimitive((Number) value));
                } else if (String.class.isAssignableFrom(value.getClass())) {
                    jsonArray.add(new JsonPrimitive((String) value));
                } else if (Boolean.class.isAssignableFrom(value.getClass())
                        || Boolean.TYPE.isAssignableFrom(value.getClass())) {
                    jsonArray.add(new JsonPrimitive((Boolean) value));
                } else {
                    jsonArray.add(toJson(value));
                }
            }
            jsonObject.add(field.getName(), jsonArray);
        }

    }
    return jsonObject;
}

From source file:com.certus.controllers.ChartExpenseAdapter.java

@Override
public JsonElement serialize(ChartExpenses exp, Type type, JsonSerializationContext jsc) {
    JsonObject jo = new JsonObject();
    jo.add("day", new JsonPrimitive(exp.getDay()));
    jo.add("sale", new JsonPrimitive(exp.getAmountSale()));
    jo.add("expense", new JsonPrimitive(exp.getAmountExpense()));
    return jo;//from   w w w  . ja v a2s.  c  om
}

From source file:com.certus.controllers.ChartsCriteriaAdapter.java

@Override
public JsonElement serialize(ChartsCriteria sale, Type type, JsonSerializationContext jsc) {
    JsonObject obj = new JsonObject();
    obj.add("day", new JsonPrimitive(sale.getDay()));
    obj.add("amount", new JsonPrimitive(sale.getAmount()));
    return obj;//from   ww w  . j a  va  2  s . c  o  m
}

From source file:com.certus.controllers.ProductFilterTypeAdapter.java

@Override
public JsonElement serialize(ProductHasSize phs, Type type, JsonSerializationContext jsc) {
    i++;//  ww  w . j  a  va 2 s  .  c om
    String productsPath1 = null;
    try {
        Context env1 = (Context) new InitialContext().lookup("java:comp/env");
        productsPath1 = (String) env1.lookup("uploadpathproducts");
    } catch (NamingException ex) {
        Logger.getLogger(ProductFilterTypeAdapter.class.getName()).log(Level.SEVERE, null, ex);
    }
    JsonObject jo = new JsonObject();
    jo.add("text", new JsonPrimitive(phs.getProduct().getName()));
    jo.add("value", new JsonPrimitive(i));
    jo.add("selected", i == 1 ? new JsonPrimitive(Boolean.TRUE) : new JsonPrimitive(Boolean.FALSE));
    jo.add("description", new JsonPrimitive(phs.getProduct().getBrand().getBrandName()));
    jo.add("imageSrc", new JsonPrimitive(productsPath1 + phs.getProduct().getImageMain()));
    return jo;
}

From source file:com.certus.controllers.UserTypeAdapter.java

@Override
public JsonElement serialize(User u, Type type, JsonSerializationContext jsc) {
    JsonObject object = new JsonObject();
    try {/*from www .  ja v a 2  s  .c o m*/
        object.add("name", new JsonPrimitive(u.getFName() + " " + u.getLName()));
        object.add("email", new JsonPrimitive(u.getEmail()));
        object.add("tel", new JsonPrimitive(u.getTelephone()));
        object.add("address", new JsonPrimitive(u.getAddress()));

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

From source file:com.certus.mobile.actions.getAllProductsAction.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Session s = com.certus.connection.HibernateUtil.getSessionFactory().openSession();
    if (request.getParameter("cartList") != null) {
        String jsonList = request.getParameter("cartList");
        Type type = new TypeToken<List<CartItem>>() {
        }.getType();//from  w  w w.  jav  a  2  s . c  om
        List<CartItem> conList = new Gson().fromJson(jsonList, type);
        List<ProductHasSize> myList = getCompleteProductCart(conList, s);

        String element = new Gson().toJson(myList, new TypeToken<List<ProductHasSize>>() {
        }.getType());
        response.getWriter().write(element);

    } else {
        JsonArray array = new JsonArray();
        JsonObject jo = new JsonObject();
        jo.add("error", new JsonPrimitive("Error response"));
        array.add(jo);
        String element = new Gson().toJson(array);
        response.getWriter().write(element);
    }

}

From source file:com.certus.mobile.actions.mobileFindSubCategoriesAction.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Session s = com.certus.connection.HibernateUtil.getSessionFactory().openSession();
    String catName = request.getParameter("catName");
    if (catName != null) {
        Category category = (Category) s.createCriteria(Category.class, "cat")
                .add(Restrictions.eq("cat.catName", catName)).uniqueResult();

        JsonObject jo = new JsonObject();
        JsonArray subCatAry = new JsonArray();
        for (SubCategory sub : category.getSubCategories()) {
            JsonObject subJo = new JsonObject();
            subJo.add("sub_id", new JsonPrimitive(sub.getId()));
            subJo.add("sub_name", new JsonPrimitive(sub.getSubCategoryName()));
            subCatAry.add(subJo);//from w w  w  .j  a  va2  s  .  c om
        }
        jo.add("cat_id", new JsonPrimitive(category.getId()));
        jo.add("cat_name", new JsonPrimitive(category.getCatName()));
        jo.add("sub_categories", subCatAry);
        String element = new Gson().toJson(jo);
        response.getWriter().write(element);
    }
}