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:QuoteSetvlet.java

private void processDelete(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();

    int id = Integer.parseInt(request.getRequestURI().split("/")[3]);

    JsonObject quote = new JsonObject();
    quote.addProperty("quote", quotes.get(id));
    out.println(quote);/* w  w  w. j  a  va  2  s.c o m*/
    quotes.remove(id);
}

From source file:QuoteSetvlet.java

private void processPut(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    int id = Integer.parseInt(request.getRequestURI().split("/")[3]);

    JsonObject newQuote = getJson(request);
    String quote = newQuote.get("quote").getAsString();

    quotes.put(id, quote);//from   ww w . j av  a2 s  .c  o m

    newQuote.addProperty("id", id);
    out.println(newQuote);
}

From source file:AlertGeneration.java

License:Open Source License

@SuppressWarnings("unchecked")
public static void main(String[] args) throws InterruptedException {
    Yaml yaml = new Yaml();
    InputStream ios = AlertGeneration.class.getClassLoader().getResourceAsStream("properties.yml");
    Map<String, Object> result = (Map<String, Object>) yaml.load(ios);

    String apiBaseURL = (String) result.get("api.base.url");
    String apiClientKey = (String) result.get("api.client.key");
    String apiClientSecret = (String) result.get("api.client.secret");
    String apiGrantType = (String) result.get("api.grant.type");

    long clientId = new Long((Integer) result.get("client.id")).longValue();

    JsonObject json = new JsonObject();
    json.addProperty("subject", "Test Alert Subject");
    json.addProperty("description", "Test alert description");
    json.addProperty("serviceName", "system.ping.rta");
    json.addProperty("app", "Vistara");

    JsonObject device = new JsonObject();
    device.addProperty("hostName", "meena");
    device.addProperty("resourceUUID", "e32f9e6a-8909-4181-8684-910e82bd6f33");
    json.add("device", device);

    RestAssured.useRelaxedHTTPSValidation();
    RestAssured.baseURI = apiBaseURL;//  w  ww .  j  a v  a2s  .c  om
    String accessToken = generateAccessToken(apiBaseURL, apiClientKey, apiClientSecret, apiGrantType);

    for (int i = 1; i <= 600; i++) {
        try {
            Calendar cal = Calendar.getInstance();
            int currentSecond = cal.get(Calendar.SECOND);

            if ((currentSecond / 5) % 2 == 0) {
                json.addProperty("currentState", "Ok");
            } else {
                json.addProperty("currentState", "Critical");
            }

            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            json.addProperty("alertTime", formatter.format(cal.getTime()));
            System.out.println("Input payload " + i + ":" + json.toString());

            Response response = RestAssured.given().auth().oauth2(accessToken).contentType(ContentType.JSON)
                    .body(json.toString()).post("/api/v2/tenants/client_" + clientId + "/alert");
            System.out.println("Response: " + response.getStatusCode() + ",Output: " + response.prettyPrint());
            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
            accessToken = generateAccessToken(apiBaseURL, apiClientKey, apiClientSecret, apiGrantType);
        }
    }
}

From source file:RunnerRepository.java

License:Apache License

public static void generateJSon() {
    JsonObject root = new JsonObject();
    JsonObject array = new JsonObject();
    array.addProperty("Embedded", "embedded");
    array.addProperty("DEFAULT", "Embedded");
    JsonObject array2 = new JsonObject();
    array2.addProperty("NimbusLookAndFeel", "javax.swing.plaf.nimbus.NimbusLookAndFeel");
    array2.addProperty("MetalLookAndFeel", "javax.swing.plaf.metal.MetalLookAndFeel");
    array2.addProperty("MotifLookAndFeel", "com.sun.java.swing.plaf.motif.MotifLookAndFeel");
    array2.addProperty("WindowsLookAndFeel", "com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    array2.addProperty("JGoodiesWindowsLookAndFeel", "com.jgoodies.looks.windows.WindowsLookAndFeel");
    array2.addProperty("Plastic3DLookAndFeel", "com.jgoodies.looks.plastic.Plastic3DLookAndFeel");
    array2.addProperty("PlasticXPLookAndFeel", "com.jgoodies.looks.plastic.PlasticXPLookAndFeel");
    array2.addProperty("DEFAULT", "MetalLookAndFeel");
    root.add("plugins", new JsonArray());
    root.add("editors", array);
    root.add("looks", array2);
    root.add("layout", new JsonObject());
    try {//  ww  w .j ava 2  s  .  c om
        FileWriter writer = new FileWriter(TWISTERINI);
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        writer.write(gson.toJson(root));
        writer.close();
    } catch (Exception e) {
        System.out.println("Could not write default JSon to twister.conf");
        e.printStackTrace();
    }
    System.out.println("twister.conf successfully created");
}

From source file:contactDAO.java

@GET
@Path("/add")
public String addContact(@QueryParam("myEmail") String myEmail, @QueryParam("fEmail") String fEmail) {

    JsonObject jsonResponse = new JsonObject();

    /////// 0. Extract My ID from DB
    int userID = getUserId(myEmail);

    if (userID == -1) {
        //// internal error in DB
        jsonResponse.addProperty("status", "failed");
        jsonResponse.addProperty("result", "Errors with our Servers, Try again later!");

    } else {//  w ww.jav  a2  s. c  om

        /////// 1. Check if user already exists
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        Query query = entityManager.createNamedQuery("User.findByEmail").setParameter("email", fEmail);
        List<User> users = query.getResultList();

        if (!users.isEmpty()) {
            /////// 2. if YES
            ////////////////////////// add to contacts and return POSITIVE response

            User friend = users.get(0);

            int friendId = friend.getId();
            Contact contact = new Contact(userID, friendId);

            entityManager.getTransaction().begin();
            entityManager.persist(contact);
            entityManager.getTransaction().commit();

            ///// prepare response as JSON
            jsonResponse.addProperty("status", "success");

            Gson gson = new Gson();
            jsonResponse.addProperty("result", gson.toJson(friend));

        } else {
            /////// 3. if NO
            /////////////////////// return user not found NEGATIVE response
            jsonResponse.addProperty("status", "failed");
            jsonResponse.addProperty("result", "Corresponding user is not fount, Check his email");

        }

    }

    return jsonResponse.toString();
}

From source file:HyperLogLog.java

public String ToJson() {
    Gson g = new Gson();
    JsonObject elm = new JsonObject();
    elm.addProperty("M", this.m);
    elm.addProperty("B", this.b);
    elm.addProperty("A", this.alpha);
    JsonArray registerArr = new JsonArray();
    for (int i = 0; i < registers.length; i++) {
        registerArr.add(new JsonPrimitive(registers[i]));
    }//www  . j a v  a  2s.com
    elm.add("R", registerArr);
    return g.toJson(elm);
}

From source file:userDAO.java

@GET
@Path("/login")
@Produces("application/json")
public String loginUser(@QueryParam("email") String email, @QueryParam("password") String password) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    Query query = entityManager.createNamedQuery("User.findByEmail").setParameter("email", email);
    List<User> users = query.getResultList();
    JsonObject jsonObject = new JsonObject();
    if (users.size() == 0) {
        jsonObject.addProperty("status", "FAILED");
        jsonObject.addProperty("result", "Sorry! This Email is not registered on ContactO!");
    } else {//ww  w  . jav a 2 s.co m
        Query query2 = entityManager.createNamedQuery("User.findByEmailandPassword")
                .setParameter("email", email).setParameter("password", password);
        List<User> userss = query2.getResultList();
        if (userss.size() == 0) {
            jsonObject.addProperty("status", "FAILED");
            jsonObject.addProperty("result", "Sorry! Wrong Password!");
        } else {
            jsonObject.addProperty("status", "SUCCESS");
            Gson gson = new Gson();
            //                JsonArray jsonArray=new JsonArray();
            //                for (User user : userss) {
            //               
            //                    jsonArray.add(JsonObj);
            //                }
            jsonObject.add("result", getAllcontacts(email));
        }
    }
    return new Gson().toJson(jsonObject);
}

From source file:JavaTestRunner.java

License:Apache License

private static JsonObject mkConstants(JsonElement input, ZonedDateTime now) {
    JsonObject jsonObject = new JsonObject();
    jsonObject.add("CONST$WORLD", input);
    jsonObject.addProperty("CONST$NOW", now.toString());
    return jsonObject;
}

From source file:rest.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    JsonObject quote = new JsonObject();
    int key = 1; //Get the second quote
    quote.addProperty("quote", quotes.get(key));
    String jsonResponse = new Gson().toJson(quote);

}

From source file:ListAction.java

@Override
public void execute(HttpServletRequest request, PrintWriter out, File folder) {

    try {//from   w ww .jav a 2 s .  com
        String type = request.getParameter("type");

        JsonArray list = new JsonArray();

        switch (type) {
        case "movie":
            File[] movies = Service.listAllMovies(folder);

            for (int i = 0; i < movies.length; i++) {
                JsonObject m = new JsonObject();
                m.addProperty("title", movies[i].getName());
                list.add(m);
            }

            break;

        case "series":
            File[] series = Service.listAllSeries(folder);

            for (int i = 0; i < series.length; i++) {
                JsonObject m = new JsonObject();
                m.addProperty("title", series[i].getName());
                list.add(m);
            }

            break;

        case "episode":
            String series_title = request.getParameter("series");

            folder = new File(folder.getAbsolutePath() + "\\Series\\" + series_title);

            List<File> episodes = Service.listAllEpisodes(folder);

            for (File f : episodes) {
                JsonObject episode = new JsonObject();

                String title = f.getName().split(" - ")[0];

                episode.addProperty("title", series_title + " - " + title);

                list.add(episode);
            }

            break;
        }

        JsonObject container = new JsonObject();

        container.add("list", list);

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String json = gson.toJson(container);
        out.println(json);
    } catch (Exception e) {
        throw e;
    }
}