Example usage for com.google.gson JsonObject JsonObject

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

Introduction

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

Prototype

JsonObject

Source Link

Usage

From source file:QuoteSetvlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  ww  w.java  2 s. c  om
 *
 * @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 {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        String[] split = request.getRequestURI().split("/");
        String parameter = split.length == 4 ? split[4] : "all";

        JsonObject quote = new JsonObject();

        if (parameter.equals("random")) {
            int randIndex = rand.nextInt(quotes.size()) + 1;
            quote.addProperty("quote", quotes.get(randIndex));
        } else {
            quote.addProperty("quote", quotes.get(Integer.parseInt(parameter)));
        }

        String jsonResponse = new Gson().toJson(quote);
        out.println(jsonResponse);
    } finally {
        out.close();
    }
}

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);/*from  w  ww.  j a  v  a  2s.com*/
    quotes.remove(id);
}

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;//from w  w w  . j a va  2  s. 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 {//  www.j  av a2  s .  c  o m
        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:RunnerRepository.java

License:Apache License

public static void parseIni(File ini) {
    try {/*from  ww w.j a va2 s .  c  om*/
        FileInputStream in = new FileInputStream(ini);
        InputStreamReader inputStreamReader = new InputStreamReader(in);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        StringBuffer b = new StringBuffer("");
        String line;
        try {
            while ((line = bufferedReader.readLine()) != null) {
                b.append(line);
            }
            bufferedReader.close();
            inputStreamReader.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        JsonElement jelement = new JsonParser().parse(b.toString());
        inifile = jelement.getAsJsonObject();
        editors = inifile.getAsJsonObject("editors");
        looks = inifile.getAsJsonObject("looks");
        layout = inifile.getAsJsonObject("layout");
        plugins = inifile.getAsJsonArray("plugins");
        if (layout == null) {
            inifile.add("layout", new JsonObject());
            writeJSon();
            layout = inifile.getAsJsonObject("layout");
        }
        if (plugins == null) {
            inifile.add("plugins", new JsonArray());
            writeJSon();
            plugins = inifile.getAsJsonArray("plugins");
        }
    } catch (Exception e) {
        System.out.print("Could not parse ini file: ");
        try {
            System.out.println(ini.getCanonicalPath());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        e.printStackTrace();
    }
}

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 {//from  w w w.ja v a2s .  co m

        /////// 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]));
    }// w w w . ja v a  2s  .c o m
    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 {// www  .j a v a  2s . 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);

}