Example usage for com.google.gson JsonObject addProperty

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

Introduction

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

Prototype

public void addProperty(String property, Character value) 

Source Link

Document

Convenience method to add a char member.

Usage

From source file:actions.ListeLieuxAction.java

@Override
public String execute(HttpServletRequest request) {

    ServiceMetier sm = new ServiceMetier();
    List<Lieu> ll = sm.obtenirLieux();

    if (ll != null) {
        request.setAttribute("ListLieu", ll);
    } else {/*from  w ww .  j a va2  s  .  c om*/
        request.setAttribute("ListLieu", "NULL");
    }

    JsonArray jsonListe = new JsonArray();

    for (Lieu lieu : ll) {

        JsonObject jsonActivite = new JsonObject();

        jsonActivite.addProperty("id", lieu.getId());
        jsonActivite.addProperty("denomination", lieu.getDenomination());
        jsonActivite.addProperty("lat", lieu.getLatitude());
        jsonActivite.addProperty("lng", lieu.getLongitude());
        jsonActivite.addProperty("adresse", lieu.getAdresse());

        jsonListe.add(jsonActivite);
    }

    //Objet JSON "conteneur"
    JsonObject container = new JsonObject();
    container.add("lieux", jsonListe);

    //Serialisation & Ecriture sur le flux de sortie
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String json = gson.toJson(container);

    return json;
}

From source file:Actions.ModifierCommandeAction.java

@Override
@SuppressWarnings("empty-statement")
public void execute(HttpServletRequest request, HttpServletResponse reponse) {
    System.out.println("Je suis dans function ModifierCommandeAction");
    ConnectionSession connectionSession = ConnectionSession.INSTANCE;
    Client client = (Client) request.getSession().getAttribute("client");
    HttpSession session = request.getSession(true);
    String but = request.getParameter("but");
    if (but.equals("ajout")) {
        System.out.println("Je suis dans cas ajout");
        //Commande commande = connectionSession.getCommandeByClient(client.getId());
        Commande commande = (Commande) session.getAttribute("commande");
        System.out.println("CommandeID: " + commande.getNumCommande());
        long idProduit = parseLong((request.getParameter("idProduit")));
        //System.out.println("idProduit: "+idProduit);
        List<Produit> produits = ServiceMetier.searchProduits(" ", commande.getRestaurant());
        Produit produitFind = null;//from  ww w .  j  a  v  a 2  s. c om
        for (Produit produit : produits) {
            if (produit.getId() == idProduit) {
                produitFind = produit;
                break;
            }
        }
        int qte = parseInt((request.getParameter("quantite")));
        ProduitCommande produitCommande = new ProduitCommande(produitFind, qte);
        ServiceMetier.addProduitCommande(commande, produitCommande);
        session.setAttribute("commande", commande);
        //connectionSession.creerCommande(client.getId(), commande);
    } else {
        System.out.println("Je suis dans cas supprime");
        //Commande commande = connectionSession.getCommandeByClient(client.getId());
        Commande commande = (Commande) session.getAttribute("commande");
        long idProduit = parseLong((request.getParameter("idProduit")));
        //System.out.println("idProduit: "+idProduit);
        List<Produit> produits = ServiceMetier.searchProduits(" ", commande.getRestaurant());
        Produit produitFind = null;
        for (Produit produit : produits) {
            if (produit.getId() == idProduit) {
                produitFind = produit;
                break;
            }
        }
        int qte = parseInt((request.getParameter("quantite")));
        ProduitCommande produitCommande = new ProduitCommande(produitFind, qte);
        ServiceMetier.removeProduitCommande(commande, produitCommande);
        session.setAttribute("commande", commande);
        //connectionSession.creerCommande(client.getId(), commande);
        System.out.println("CommandeID: " + commande.getNumCommande());

        // -------------envoi du prix du truc  supprimer--------------
        JsonObject prixSuppr = new JsonObject();
        prixSuppr.addProperty("prixSuppr", commande.getPrixTotal());
        reponse.setContentType("text/html;charset=UTF-8");
        PrintWriter out = null;
        try {
            out = reponse.getWriter();
        } catch (IOException ex) {
            Logger.getLogger(GetRestaurantsAction.class.getName()).log(Level.SEVERE, null, ex);
        }
        out.println(prixSuppr);
        out.close();

    }

}

From source file:actions.MomentsAction.java

@Override
public String execute(HttpServletRequest request) {
    ServiceMetier sm = new ServiceMetier();

    List<Moment> lm = sm.obtenirMoments();

    if (lm != null) {
        request.setAttribute("ListMoment", lm);
    } else {/*from  w  w w. jav  a  2  s  . c  o m*/
        request.setAttribute("ListMoment", "NULL");
    }

    JsonArray jsonListe = new JsonArray();

    for (Moment moment : lm) {
        JsonObject jsonActivite = new JsonObject();

        jsonActivite.addProperty("id", moment.ordinal());
        jsonActivite.addProperty("denomination", moment.name());

        jsonListe.add(jsonActivite);
    }

    //Objet JSON "conteneur"
    JsonObject container = new JsonObject();
    container.add("moments", jsonListe);

    //Serialisation & Ecriture sur le flux de sortie
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String json = gson.toJson(container);

    return json;
}

From source file:actions.ValiderAction.java

@Override
public String execute(HttpServletRequest request) {
    ServiceMetier sm = new ServiceMetier();
    long prix = Long.parseLong(request.getParameter("prix"));
    long id_lieu = Long.parseLong(request.getParameter("lieu"));
    long id_demande = Long.parseLong(request.getParameter("id"));
    Evenement evt = null;/*from  w w  w  .j a  v  a  2s  .co  m*/
    Lieu lieu = null;
    //Recherche du lieu
    List<Lieu> ll = sm.obtenirLieux();
    for (Lieu l : ll) {
        if (l.getId() == id_lieu) {
            lieu = l;
            break;
        }
    }

    //Recherche de la d'vnement
    List<Evenement> le = sm.obtenirEvenementAValider();
    for (Evenement e : le) {
        if (e.getId() == id_demande) {
            if (e instanceof EvenementPayant) {
                System.out.println("EvenementPayant");
                evt = sm.validerEvenement((EvenementPayant) e, lieu, prix);
            }
            if (e instanceof EvenementGratuit) {
                System.out.println("EvenementGratuit");
                evt = sm.validerEvenement((EvenementGratuit) e, lieu);
            }
            break;
        }
    }

    JsonObject jsonResponse = new JsonObject();

    if (evt == null) { // Evenement pas OK
        jsonResponse.addProperty("Validation", "KO");
    } else {
        jsonResponse.addProperty("Validation", "OK");
    }

    //Serialisation & Ecriture sur le flux de sortie
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String json = gson.toJson(jsonResponse);
    return json;
}

From source file:Actions.ValiderCommandeAction.java

@Override
public void execute(HttpServletRequest request, HttpServletResponse reponse) {
    // Recupere les datas de commande
    System.out.println("Je suis dans action ValiderCommandeAction");
    ConnectionSession connectionSession = ConnectionSession.INSTANCE;
    HttpSession session = request.getSession(true);
    Client client = connectionSession.getUser(request.getSession().getId());
    //Commande commande = connectionSession.getCommandeByClient(client.getId());
    Commande commande = (Commande) session.getAttribute("commande");
    System.out.println(commande);

    //pour trouver si il y un livreur disponible
    List<Livreur> livreurs = ServiceMetier.findAllLivreurs();
    boolean livreurDisponi = false;
    for (Livreur livreur : livreurs) {
        if (livreur.getCmdeEnCours() == null) {
            livreurDisponi = true;/*  ww w.j a v  a 2  s. co m*/
            break;
        }
    }
    System.out.println("livreurDisponi:" + livreurDisponi);

    reponse.setContentType("text/html;charset=UTF-8");
    JsonObject jsonMessage = new JsonObject();
    PrintWriter out = null;
    try {
        out = reponse.getWriter();
    } catch (IOException ex) {
        Logger.getLogger(GetRestaurantsAction.class.getName()).log(Level.SEVERE, null, ex);
    }
    if (livreurDisponi) {
        ServiceMetier.traiterCommande(commande);
        jsonMessage.addProperty("info", "Votre commande est bien valid");
        out.println(jsonMessage);
        out.close();
    } else {
        System.out.println("Dans le cas pas de livreur disponible");
        ServiceMetier.traiterCommande(commande);
        jsonMessage.addProperty("info",
                "Aucun livreur n'est actuellement disponible pour traiter votre commande. Veuillez ressayer ultrieurement.");
        out.println(jsonMessage);
        out.close();
    }
    session.setAttribute("commande", commande);
    //connectionSession.enregistrerCommande(request.getSession().getId(),commande.getNumCommande());
}

From source file:adams.data.report.ReportJsonUtils.java

License:Open Source License

/**
 * Turns the report into a json structure.
 *
 * @param report   the report to convert
 * @return      the json data structure//from  w  w  w .j  a v a  2 s . c o  m
 */
public static JsonObject toJson(Report report) {
    JsonObject result;

    result = new JsonObject();

    // report
    for (AbstractField field : report.getFields()) {
        switch (field.getDataType()) {
        case NUMERIC:
            result.addProperty(field.getName(), report.getDoubleValue(field));
            break;
        case BOOLEAN:
            result.addProperty(field.getName(), report.getBooleanValue(field));
            break;
        case STRING:
        case UNKNOWN:
            result.addProperty(field.getName(), report.getStringValue(field));
            break;
        default:
            throw new IllegalStateException("Unhandled data type: " + field.getDataType());
        }
    }

    return result;
}

From source file:adams.scripting.processor.JsonProcessor.java

License:Open Source License

/**
 * Turns the command properties and payload into a single string to send.
 *
 * @param header   the header data//from  w  w  w.ja  v  a  2  s  .  co m
 * @param payload   the payload
 * @return      the assembled string
 */
@Override
public String format(Properties header, byte[] payload) {
    JsonObject result;
    String data;
    JsonObject objHeader;
    Gson gson;

    if (payload.length == 0)
        data = "";
    else
        data = Base64.encodeBase64String(payload);

    objHeader = new JsonObject();
    for (String key : header.keySetAll())
        objHeader.addProperty(key, header.getProperty(key));

    result = new JsonObject();
    result.add("header", objHeader);
    result.addProperty("payload", data);

    if (m_PrettyPrinting) {
        gson = new GsonBuilder().setPrettyPrinting().create();
        return gson.toJson(result);
    } else {
        return result.toString();
    }
}

From source file:adminservlets_ads.Apr_ReviewAdsJson.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from  w  w  w  . j a  va  2s  .  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 doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    AdminClass_ReviewAds ar = new AdminClass_ReviewAds();
    AdminClass_SendMail as = new AdminClass_SendMail();
    AdminClass_Message am = new AdminClass_Message();
    String alert = null;
    AdminClass_Links al = new AdminClass_Links();

    String reciever = ar.getUserEmail(request.getParameter("to"));
    String subject = "Approval of your ad \"" + request.getParameter("subject") + "\"";
    String view_link = "<a href='" + al.getAdView()
            + "' target='blank'><p>Click here to view your advertisement</p></a>";

    String content = "Your ad \"" + request.getParameter("subject") + "\", successfully posted on Superb.lk.\n"
            + "\n" + "To view your ad, please click the following link. \n"
            + "If you have any questions, feel free to reply to the email and we will get back to you.\n";

    String inbox_content = "Hello,\n" + "\n" + "Your ad \"" + request.getParameter("subject")
            + "\", successfully posted on Superb.lk.\n" + "\n" + "Regards,\n"
            + "The support team at Superb.lk\n" + "\n";

    int inbox_result = am.sendMessage(inbox_content, request.getParameter("to"));

    String action = request.getParameter("action");
    String item = request.getParameter("item");
    int result;
    if ("Approve".equals(action) && item != null) {

        result = ar.approveAd(item); //Approving advertiesment
        int mail_result = as.mailClass(reciever, subject, content, view_link);//sending mail to the user

        if (result == 1) {
            alert = "<button class=\"btn btn-green\">" //returning notification of the success 
                    + "<i  class=\"glyphicon glyphicon-ok-sign\">"
                    + "</i></button><br><strong>Approved!</strong>" + " Advertiesment number "
                    + request.getParameter("item") + "";

        } else {
            alert = "<button class=\"btn btn-red\">" //returning notification of the the failure
                    + "<i  class=\"glyphicon glyphicon-remove-circle\">"
                    + "</i></button><br><strong>Failed!</strong>" + " Advertiesment number "
                    + request.getParameter("item") + " Try again.";

        }

    }

    PrintWriter out = response.getWriter();

    Gson gson = new Gson();
    JsonObject myObj = new JsonObject();

    myObj.addProperty("result", alert);

    out.write(myObj.toString());
    out.close();
}

From source file:adminservlets_ads.Mod_ReviewAdsJson.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*  w  w w  .j  av a 2s .  com*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    AdminClass_ReviewAds ar = new AdminClass_ReviewAds();
    AdminClass_SendMail as = new AdminClass_SendMail();
    AdminClass_Message am = new AdminClass_Message();
    AdminClass_Links al = new AdminClass_Links();
    String alert = null;

    if (request.getParameter("subject") != null) {

        String reciever = ar.getUserEmail(request.getParameter("to"));
        String subject = request.getParameter("subject");
        String edit_link = "<a href='" + al.getAdEdit()
                + "' target='blank'><p>Click here to update your advertisement</p></a>";

        String content = request.getParameter("content_header") + "<br/><br/>"
                + request.getParameter("content_body");
        String itemId = request.getParameter("itemname");
        String reason = "Modified due to- " + request.getParameter("reason");

        String inbox_content = request.getParameter("content_header") + request.getParameter("content_body")
                + "\n\nPlease update your ad" + "\n" + "Regards,\n" + "The support team at Superb.lk\n" + "\n";

        int inbox_result = am.sendMessage(inbox_content, request.getParameter("to"));

        int result = ar.modifyAds(itemId, reason); //updating advertiesment status
        int result2 = as.mailClass(reciever, subject, content, edit_link);//sending mail to the user

        if (result == 1 && result2 == 1) {
            alert = "<button class=\"btn btn-green\">" //returning notification of the success 
                    + "<i  class=\"glyphicon glyphicon-ok-sign\">" + "</i></button><br>Email is sent to "
                    + "<strong> " + reciever + " !</strong>";

        } else {
            alert = "<button class=\"btn btn-red\">" //returning notification of the failure 
                    + "<i  class=\"glyphicon glyphicon-remove-circle\">"
                    + "</i></button><strong> Failed !</strong>";

        }
    }
    PrintWriter out = response.getWriter();

    Gson gson = new Gson();
    JsonObject myObj = new JsonObject();

    myObj.addProperty("result", alert);

    out.write(myObj.toString());
    out.close();

}

From source file:adminservlets_ads.Rmv_ReviewAdsJson.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/* www  .j av  a2  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 doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    AdminClass_ReviewAds ar = new AdminClass_ReviewAds();
    AdminClass_SendMail as = new AdminClass_SendMail();
    AdminClass_Message am = new AdminClass_Message();
    String alert = null;

    String reciever = ar.getUserEmail(request.getParameter("to"));
    String subject = "Refusal of your Ad \"" + request.getParameter("subject") + "\"";

    String content = "Your ad \"" + request.getParameter("subject") + "\", cannot be posted on Superb.lk.\n"
            + "\n" + "The reason why we could not approve your ad:\n" + "\n"
            + "<br/><br/>- Illegal item or service\n"
            + "<br/>Your ad features an item or service that is illegal or not suitable, which we cannot allow on our site. Please post a new ad with suitable content.\n"
            + "<br/><br/>we do not allow any content that Superb.lk considers in its complete and unfettered discretion to be- \n"
            + "<br/>(i) offensive and/or inappropriate (including, without limitation, defamatory, threatening, hateful, or pornographic content);\n"
            + "\n" + "<br/>(ii) false, fraudulent, misleading or deceptive, or incorrect;\n" + "\n"
            + "<br/>(iv) Content that discloses anothers personal, confidential or proprietary information (including content that identifies a person, or that is capable of being used to identify a person without that person's consent)."
            + "\n"
            + "<br/>If you have any questions, feel free to reply to the email and we will get back to you.\n";

    String inbox_content = "Hello,\n" + "\n" + "Your ad \"" + request.getParameter("subject")
            + "\", cannot be posted on Superb.lk.\n" + "\n" + "The reason why we could not approve your ad:\n"
            + "\n" + "- Illegal item or service\n"
            + "Your ad features an item or service that is illegal or not suitable, which we cannot allow on our site. Please post a new ad with suitable content.\n"
            + "\n" + "Regards,\n" + "The support team at Superb.lk\n" + "\n";

    int inbox_result = am.sendMessage(inbox_content, request.getParameter("to"));

    String action = request.getParameter("action");
    String item = request.getParameter("item");

    int result;

    if (("Remove".equals(action) && item != null)) {
        result = ar.removeAd(item); //removing advertiesment
        int mail_result = as.mailClass(reciever, subject, content, "");//sending mail to the user

        if (result == 1) {
            alert = "<button class=\"btn btn-green\">" //returning notification of the success 
                    + "<i  class=\"glyphicon glyphicon-ok-sign\">"
                    + "</i></button><br><strong>Removed!</strong>" + " Advertiesment number "
                    + request.getParameter("item") + "";
        } else {
            alert = "<button class=\"btn btn-red\">" //returning notification of the failure 
                    + "<i  class=\"glyphicon glyphicon-remove-circle\">"
                    + "</i></button><br><strong>Failed!</strong> Advertiesment number "
                    + request.getParameter("item") + " Try again.";
        }

    }
    PrintWriter out = response.getWriter();

    Gson gson = new Gson();
    JsonObject myObj = new JsonObject();

    myObj.addProperty("result", alert);

    out.write(myObj.toString());
    out.close();
}