Example usage for com.google.gson JsonObject add

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

Introduction

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

Prototype

public void add(String property, JsonElement value) 

Source Link

Document

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

Usage

From source file:com.basho.riakcs.client.impl.RiakCSClientImpl.java

License:Open Source License

private JsonObject getAclImpl(String bucketName, String objectKey) throws Exception {
    Map<String, String> parameters = new HashMap<String, String>();
    parameters.put("acl", null);

    CommunicationLayer comLayer = getCommunicationLayer();

    URL url = comLayer.generateCSUrl(bucketName, objectKey, parameters);
    HttpURLConnection conn = comLayer.makeCall(CommunicationLayer.HttpMethod.GET, url);

    Document xmlDoc = XMLUtils.parseToDocument(conn.getInputStream(), debugModeEnabled);
    JsonObject acl = new JsonObject();
    JsonArray grantsList = new JsonArray();

    for (Node grantNode : XMLUtils.xpathToNodeList("//Grant", xmlDoc)) {
        JsonObject grant = new JsonObject();
        grant.addProperty("permission", XMLUtils.xpathToContent("Permission", grantNode));

        String type = XMLUtils.xpathToContent("Grantee/@type", grantNode);

        JsonObject grantee = new JsonObject();
        grantee.addProperty("type", type);

        if (type.equals("Group")) {
            grantee.addProperty("uri", XMLUtils.xpathToContent("Grantee/URI", grantNode));
        } else {//  w w  w .j ava 2 s .com
            grantee.addProperty("id", XMLUtils.xpathToContent("Grantee/ID", grantNode));
            grantee.addProperty("displayName", XMLUtils.xpathToContent("Grantee/DisplayName", grantNode));
        }
        grant.add("grantee", grantee);
        grantsList.add(grant);
    }
    acl.add("grantsList", grantsList);
    JsonObject owner = new JsonObject();
    owner.addProperty("id", XMLUtils.xpathToContent("//Owner/ID", xmlDoc));
    owner.addProperty("displayName", XMLUtils.xpathToContent("//Owner/DisplayName", xmlDoc));
    acl.add("owner", owner);
    return acl;
}

From source file:com.beanstream.api.ProfilesAPI.java

License:Open Source License

/**
 * Updates the profile. You must first retrieve the profile using
 * ProfilesAPI.getProfileById(id)// www.  j a  v  a2s.com
 * 
 * @param profile
 *            object to update
 * @return ProfileResponse if successful, an BeanstreamApiException if not.
 **/
public ProfileResponse updateProfile(PaymentProfile profile) throws BeanstreamApiException {
    Gateway.assertNotNull(profile, "profile to update is null");
    ProfilesUtils.validateProfileId(profile.getId());

    ProfilesUtils.validateBillingAddr(profile.getBilling());

    String url = PaymentsUrls.getProfilesUrl(config.getPlatform(), config.getVersion(), profile.getId());

    JsonObject req = new JsonObject();
    req.add("billing", gson.toJsonTree(profile.getBilling(), Address.class));
    req.add("custom", gson.toJsonTree(profile.getCustom(), CustomFields.class));
    req.addProperty("language", profile.getLanguage());
    req.addProperty("comments", profile.getComments());
    String response = connector.ProcessTransaction(HttpMethod.put, url, req);
    return gson.fromJson(response, ProfileResponse.class);
}

From source file:com.bekwam.resignator.model.ConfigurationJSONAdapter.java

License:Apache License

@Override
public JsonElement serialize(Configuration configuration, Type type,
        JsonSerializationContext jsonSerializationContext) {

    if (logger.isDebugEnabled()) {
        logger.debug("[SERIALIZE]");
    }/*  w  ww .j ava  2 s. c o  m*/

    String ap = configuration.getActiveProfile().orElse("");
    String jdkHome = configuration.getJDKHome().orElse("");
    JsonArray profiles = serializeProfiles(configuration.getProfiles());
    String hp = configuration.getHashedPassword().orElse("");
    String lud = "";
    if (configuration.getLastUpdatedDateTime().isPresent()) {

        lud = configuration.getLastUpdatedDateTime().get().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
    }

    JsonObject root = new JsonObject();
    root.addProperty("activeProfile", ap);
    root.addProperty("jdkHome", jdkHome);
    root.addProperty("hashedPassword", hp);
    root.addProperty("lastUpdatedDate", lud);

    if (logger.isDebugEnabled()) {
        logger.debug("[SERIALIZE] ap={}, jdkHome={}, hp empty?={}, lastUpdatedDate={}", ap, jdkHome,
                StringUtils.isEmpty(hp), lud);
    }

    root.add("recentProfiles", serializeRecentProfiles(configuration.getRecentProfiles()));
    root.add("profiles", profiles);

    return root;
}

From source file:com.bekwam.resignator.model.ConfigurationJSONAdapter.java

License:Apache License

private JsonArray serializeProfiles(List<Profile> profiles) {
    JsonArray ps = new JsonArray();

    for (Profile p : profiles) {

        JsonObject profileObj = new JsonObject();

        profileObj.addProperty("profileName", p.getProfileName());
        profileObj.addProperty("replaceSignatures", p.getReplaceSignatures());
        profileObj.addProperty("argsType", String.valueOf(p.getArgsType()));

        if (p.getSourceFile().isPresent()) {
            SourceFile sf = p.getSourceFile().get();
            JsonObject sfObj = new JsonObject();
            sfObj.addProperty("fileName", sf.getFileName());
            profileObj.add("sourceFile", sfObj);
        }/*from   w w w . ja v a2  s .c  om*/

        if (p.getTargetFile().isPresent()) {
            TargetFile tf = p.getTargetFile().get();
            JsonObject tfObj = new JsonObject();
            tfObj.addProperty("fileName", tf.getFileName());
            profileObj.add("targetFile", tfObj);
        }

        if (p.getJarsignerConfig().isPresent()) {
            JarsignerConfig jc = p.getJarsignerConfig().get();
            JsonObject jcObj = new JsonObject();
            jcObj.addProperty("alias", jc.getAlias());

            //
            // #1 storepass and keypass become temporary fields while the encrypted fields
            // are persisted
            //

            jcObj.addProperty("storepass", jc.getEncryptedStorepass());
            jcObj.addProperty("keypass", jc.getEncryptedKeypass());

            jcObj.addProperty("keystore", jc.getKeystore());
            jcObj.addProperty("verbose", jc.getVerbose());
            profileObj.add("jarsignerConfig", jcObj);
        }

        ps.add(profileObj);
    }

    return ps;
}

From source file:com.bid.online.presentation.bidmanagement.BidItemServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*ww  w .  j a v  a 2s .  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 {

    List<Item> itemList = bidService.getItemList();
    List<ItemView> itemViewList = new ArrayList<>();
    for (Item item : itemList) {
        ItemView view = new ItemView();
        view.setId(String.valueOf(item.getId()));
        view.setName(item.getName());
        view.setDescription(item.getDescription());
        Date currentDate = new Date();
        long diff = item.getBidEndDate().getTime().getTime() - currentDate.getTime();
        if (diff < 0) {
            diff = 0;
        }
        view.setTimeInSeconds(String.valueOf((long) (diff / 1000)));
        DateFormat df = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss");
        view.setEndDate(df.format(item.getBidEndDate().getTime()));
        view.setStartDate(df.format(item.getBidStartDate().getTime()));

        Bid bid = bidService.getHighestBid(item.getId());

        StringBuilder sb = new StringBuilder();
        if (bid != null && bid.getValue().compareTo(item.getInitialBidValue()) == 1) {
            sb.append(bid.getValue());
        } else {
            sb.append(item.getInitialBidValue());
        }

        sb.append(StringUtils.SPACE);
        sb.append(StringUtils.SGD);

        view.setPrice(sb.toString());

        view.setImgUrl(item.getImage().getUrl());
        view.setMarketPrice(item.getActualValue().toString());
        itemViewList.add(view);
    }

    response.setContentType("text/html;charset=UTF-8");
    Gson gson = new Gson();
    JsonObject jResponse = new JsonObject();
    JsonElement items = gson.toJsonTree(itemViewList);
    jResponse.addProperty("success", Boolean.TRUE);
    jResponse.add("items", items);

    PrintWriter out = response.getWriter();
    response.setContentType("text/html");
    response.setHeader("Cache-control", "no-cache, no-store");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Expires", "-1");

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "86400");
    System.out.println(jResponse.toString());
    out.println(jResponse.toString());
    out.close();

}

From source file:com.bid.online.presentation.bidmanagement.CategoryServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from w  w  w.  ja v  a2s  .  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 {
    String code = request.getParameter("code");
    Map<String, List<CategoryView>> map = (Map<String, List<CategoryView>>) request.getServletContext()
            .getAttribute("subCategoryMap");
    List<CategoryView> catList = map.get(code);
    Gson gson = new Gson();
    JsonObject jResponse = new JsonObject();
    JsonElement items = gson.toJsonTree(catList);

    jResponse.addProperty("success", Boolean.TRUE);
    jResponse.add("items", items);

    PrintWriter out = response.getWriter();
    response.setContentType("text/html");
    response.setHeader("Cache-control", "no-cache, no-store");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Expires", "-1");

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "86400");
    System.out.println(jResponse.toString());
    out.println(jResponse.toString());
    out.close();

}

From source file:com.bid.online.presentation.bidmanagement.CreateBidServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w  w  w .j av  a 2s  .  co  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 {
    String value = request.getParameter("bidValue");
    String itemId = request.getParameter("itemId");
    User user = (User) request.getSession().getAttribute(StringUtils.USER);
    Bid bid = new Bid();
    bid.setCreateTimestamp(new Date());
    Item item = bidService.getItemById(Long.valueOf(itemId));
    bid.setItem(item);
    bid.setUser(user);
    bid.setValue(new BigDecimal(value));
    bid = bidService.createBid(bid);
    bid = bidService.getHighestBid(item.getId());

    BidView view = new BidView();
    view.setItemId(String.valueOf(item.getId()));
    if (item.getInitialBidValue().compareTo(bid.getValue()) == 1) {
        view.setValue(item.getInitialBidValue().toString());
    } else {
        view.setValue(bid.getValue().toString());
    }

    DateFormat df = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss");
    view.setCreateDate(df.format(bid.getCreateTimestamp()));

    response.setContentType("text/html;charset=UTF-8");
    Gson gson = new Gson();
    JsonObject jResponse = new JsonObject();
    JsonElement bidItem = gson.toJsonTree(view);
    jResponse.addProperty("success", Boolean.TRUE);
    jResponse.add("bidItem", bidItem);

    PrintWriter out = response.getWriter();
    response.setContentType("text/html");
    response.setHeader("Cache-control", "no-cache, no-store");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Expires", "-1");

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "86400");
    System.out.println(jResponse.toString());
    out.println(jResponse.toString());
    out.close();
}

From source file:com.bid.online.presentation.bidmanagement.CreateItemServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from w w w  .  j a va 2s.  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 {
    String name = request.getParameter("name");
    String description = request.getParameter("description");
    String marketPrice = request.getParameter("marketPrice");
    String bidPrice = request.getParameter("bidPrice");
    String code = request.getParameter("code");
    String startDate = request.getParameter("startDate");
    String endDate = request.getParameter("endDate");
    String imgId = request.getParameter("imgId");
    String imgUrl = request.getParameter("imgUrl");

    Item item = new Item();
    item.setActualValue(new BigDecimal(marketPrice));
    SimpleDateFormat format = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss");
    try {
        Date bidStartDate = format.parse(startDate);
        Date bidEndDate = format.parse(endDate);

        Calendar cs = Calendar.getInstance();
        cs.setTime(bidStartDate);
        item.setBidStartDate(cs);

        Calendar ce = Calendar.getInstance();
        ce.setTime(bidEndDate);
        item.setBidEndDate(ce);
    } catch (ParseException ex) {
        Logger.getLogger(CreateItemServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

    if (code != null) {
        SubCategory category = bidService.getSubCategoryById(Long.valueOf(code));
        item.setCategory(category);
    }
    item.setCreateTimestamp(new Date());
    item.setDescription(description);
    item.setInitialBidValue(new BigDecimal(bidPrice));
    item.setName(name);
    if (request.getSession().getAttribute(StringUtils.USER) != null) {
        User user = (User) request.getSession().getAttribute(StringUtils.USER);
        item.setOwner(user);
    }
    if (imgId != null) {
        Image img = bidService.getImageById(Long.valueOf(imgId));
        item.setImage(img);
    }
    item = bidService.createItem(item);
    ItemView view = new ItemView();

    view.setId(String.valueOf(item.getId()));
    view.setName(name);
    view.setPrice(bidPrice);
    view.setImgUrl(imgUrl);
    Gson gson = new Gson();
    JsonObject jResponse = new JsonObject();
    JsonElement jasonElement = gson.toJsonTree(view);

    jResponse.addProperty("success", Boolean.TRUE);
    jResponse.add("item", jasonElement);
    PrintWriter out = response.getWriter();
    response.setContentType("text/html");
    response.setHeader("Cache-control", "no-cache, no-store");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Expires", "-1");

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "86400");
    System.out.println(jResponse.toString());
    out.println(jResponse.toString());
    out.close();
}

From source file:com.bid.online.presentation.bidmanagement.ItemByCategory.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w  ww.ja v  a 2  s.  c  o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String code = request.getParameter("code");
    List<Item> itemList = bidService.getItemByCategory(Long.valueOf(code));

    List<ItemView> itemViewList = new ArrayList<>();
    for (Item item : itemList) {
        ItemView view = new ItemView();
        view.setId(String.valueOf(item.getId()));
        view.setName(item.getName());
        view.setDescription(item.getDescription());
        Date currentDate = new Date();
        long diff = item.getBidEndDate().getTime().getTime() - currentDate.getTime();
        if (diff < 0) {
            diff = 0;
        }
        view.setTimeInSeconds(String.valueOf((long) (diff / 1000)));
        DateFormat df = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss");
        view.setEndDate(df.format(item.getBidEndDate().getTime()));
        view.setStartDate(df.format(item.getBidStartDate().getTime()));

        StringBuilder sb = new StringBuilder();
        sb.append(item.getInitialBidValue());
        sb.append(StringUtils.SPACE);
        sb.append(StringUtils.SGD);
        view.setPrice(sb.toString());

        view.setImgUrl(item.getImage().getUrl());
        view.setMarketPrice(item.getActualValue().toString());
        itemViewList.add(view);
    }

    response.setContentType("text/html;charset=UTF-8");
    Gson gson = new Gson();
    JsonObject jResponse = new JsonObject();
    JsonElement items = gson.toJsonTree(itemViewList);
    jResponse.addProperty("success", Boolean.TRUE);
    jResponse.add("items", items);

    PrintWriter out = response.getWriter();
    response.setContentType("text/html");
    response.setHeader("Cache-control", "no-cache, no-store");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Expires", "-1");

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "86400");
    System.out.println(jResponse.toString());
    out.println(jResponse.toString());
    out.close();
}

From source file:com.bid.online.presentation.bidmanagement.UploadFile.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// w  w  w  .j ava2 s .  co 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 {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    String url = "";
    FileItem item = null;
    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List items = upload.parseRequest(request);
            Iterator it = items.iterator();

            while (it.hasNext()) {
                item = (FileItem) it.next();
                if (!item.isFormField()) {
                    String fileName = item.getName();
                    String root = getServletContext().getRealPath("/");
                    File path = new File(root + "/uploads");
                    if (!path.exists()) {
                        boolean status = path.mkdir();
                    }
                    File uploadedFile = new File(path + "/" + fileName);
                    //System.out.println(uploadedFile.getAbsolutePath());
                    url = "uploads" + "/" + fileName;
                    item.write(uploadedFile);
                }
            }

        } catch (FileUploadException e) {

        } catch (Exception e) {

        }
        Gson gson = new Gson();
        JsonObject jResponse = new JsonObject();
        if (item != null) {
            Image img = new Image();
            img.setName(item.getName());
            img.setUrl(url);
            img = bidService.createImage(img);

            ImageView imgView = new ImageView();
            imgView.setId(String.valueOf(img.getId()));
            imgView.setName(item.getName());
            imgView.setUrl(url);
            JsonElement imgJason = gson.toJsonTree(imgView);
            jResponse.addProperty("success", Boolean.TRUE);
            jResponse.add("img", imgJason);
        } else {
            jResponse.addProperty("success", Boolean.FALSE);
        }
        PrintWriter out = response.getWriter();
        response.setContentType("text/html");
        response.setHeader("Cache-control", "no-cache, no-store");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "-1");

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
        response.setHeader("Access-Control-Max-Age", "86400");
        System.out.println(jResponse.toString());
        out.println(jResponse.toString());
        out.close();
    }
}