Example usage for com.google.gson Gson Gson

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

Introduction

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

Prototype

public Gson() 

Source Link

Document

Constructs a Gson object with default configuration.

Usage

From source file:ReportFiltering.java

/**
 * This method uses GSON to set the values
 * of each report using reflection.//from  w w  w  . j  a  va2 s. c  o m
 * @return a Report array, containing all reports from the JSON file
 * @throws Exception if the file pathname is null, or if the file
 * is not found by the scanner
 */
private static Report[] parseJSON() throws Exception {
    Gson gson = new Gson();
    File file = new File(LOC + "reports.json");
    StringBuilder sb = new StringBuilder();
    Scanner input = new Scanner(file);

    // Parse entire file
    while (input.hasNext())
        sb.append(input.next());

    input.close();
    return gson.fromJson(sb.toString(), Report[].class);
}

From source file:aaa.AdminMgmt.java

@GET
@Path("login")
@Produces(MediaType.APPLICATION_JSON)/*from  w w  w.j  a  va2 s.  co m*/
public Response login(@QueryParam("user") String uid, @QueryParam("psswd") String psswd)
        throws NamingException, SQLException {
    dao.open();
    pst = dao.cn.prepareStatement("select *from admin where email=? AND password=?");
    String res = null;
    pst.setString(1, uid);
    pst.setString(2, psswd);
    ResultSet rs = pst.executeQuery();
    if (rs != null) {
        rs.next();
        //if(rs.getString(4).equals(uid) && rs.getString(5).equals(psswd)){
        rs.previous();
        Gson gson = new Gson();
        try (StringWriter stringWriter = new StringWriter()) {
            JsonWriter writer = new JsonWriter(stringWriter);
            tools.ResultSetAdapter ra = new tools.ResultSetAdapter();
            ra.write(writer, rs);
            res = "{ \"data\" :" + stringWriter.getBuffer().toString() + "}";
        } catch (Exception e) {
            res = e.getMessage() + "";
        } finally {
            if (pst != null && dao.cn != null) {
                rs.close();
                pst.close();
                dao.cn.close();
            }
            //}
        }

    }
    return modRes.cbrs(res);

}

From source file:aaa.AssettypeMgt.java

@GET
@Path("get")
@Produces(MediaType.APPLICATION_JSON)//from   ww  w. j  ava  2s  . c  om
public Response getdetails(@QueryParam("id") String id) throws SQLException, IOException, Exception {
    String res = "error";
    try {
        dao.open();
        if (id.equals("*")) {
            pst = (PreparedStatement) dao.cn.prepareStatement("select *from assettypes");
            rs = pst.executeQuery();
        } else {
            pst = (PreparedStatement) dao.cn.prepareStatement("select *from assettypes where idassettypes=?");
            pst.setString(1, id);
            rs = pst.executeQuery();
        }
        Gson gson = new Gson();
        try {
            if (rs.isBeforeFirst()) {
                res = JsonMan.rstojson(rs);
            }
        } catch (Exception er) {
            return modRes.cbrs(res + ":" + er.getMessage());
        }
        return modRes.cbrs(res);
    } catch (SQLException e) {
        return modRes.cbrs(e.getMessage() + "");
        //encod
    } finally {
        if (cst != null && dao.cn != null) {
            pst.close();
            dao.cn.close();
        }
    }
}

From source file:aaa.GenericResource.java

@GET
@Path("login")
@Produces(MediaType.APPLICATION_JSON)//ww w.ja  va 2 s .  c o m
public Response loginsa(@QueryParam("user") String user, @QueryParam("psswd") String psswd)
        throws NamingException, SQLException {
    dao.open();
    pst = dao.cn.prepareStatement("select *from superadmin where email=? AND password=?");
    String res = null;
    pst.setString(1, user);
    pst.setString(2, psswd);
    ResultSet rs = pst.executeQuery();
    if (rs != null) {
        rs.next();
        if (rs.getString(4).equals(user) && rs.getString(5).equals(psswd)) {
            rs.previous();
            Gson gson = new Gson();
            try (StringWriter stringWriter = new StringWriter()) {
                JsonWriter writer = new JsonWriter(stringWriter);
                tools.ResultSetAdapter ra = new tools.ResultSetAdapter();
                ra.write(writer, rs);
                res = "{ \"data\" :" + stringWriter.getBuffer().toString() + "}";
            } catch (Exception e) {
                res = e.getMessage() + "";
            } finally {
                if (pst != null && dao.cn != null) {
                    rs.close();
                    pst.close();
                    dao.cn.close();
                }
            }
        }

    }
    return modRes.cbrs(res);
}

From source file:aajavafx.CustomerController.java

@FXML
private void handleRegisterButton(ActionEvent event) {
    //labelError.setText(null);
    try {/* w  ww  .  jav  a  2s. c o  m*/
        //String customerNumber = customerID.getText();
        //customerID.clear();
        String lastName = lastNameID.getText();
        lastNameID.clear();
        String firstName = firstNameID.getText();
        firstNameID.clear();
        String address = addressID.getText();
        addressID.clear();
        String birthdate = birthdateID.getText();
        birthdateID.clear();
        String persunnumer = persunnumerID.getText();
        persunnumerID.clear();
        try {
            Gson gson = new Gson();
            Customers customer = new Customers(1, firstName, lastName, address, birthdate, persunnumer);
            String jsonString = new String(gson.toJson(customer));
            System.out.println("json string: " + jsonString);
            StringEntity postString = new StringEntity(jsonString);
            CredentialsProvider provider = new BasicCredentialsProvider();
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password");
            provider.setCredentials(AuthScope.ANY, credentials);
            HttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
            HttpPost post = new HttpPost(postCustomerURL);
            post.setEntity(postString);
            post.setHeader("Content-type", "application/json");
            HttpResponse response = httpClient.execute(post);
            ByteArrayOutputStream outstream = new ByteArrayOutputStream();
            if (response != null) {
                response.getEntity().writeTo(outstream);
                byte[] responseBody = outstream.toByteArray();
                String str = new String(responseBody, "UTF-8");
                System.out.print(str);
            } else {
                System.out.println("Success");
            }
        } catch (UnsupportedEncodingException ex) {
            System.out.println(ex);
        } catch (IOException e) {
            System.out.println(e);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        // labelError.setText("Salary or phone field does not have a integer!");
    }
}

From source file:aajavafx.CustomerController.java

public ObservableList<CustomerProperty> getCustomer() throws IOException, JSONException {

    ObservableList<CustomerProperty> customers = FXCollections.observableArrayList();
    //customers.add(new CustomerProperty(1, "Johny", "Walker", "London", "1972-07-01", "7207012222"));
    Customers myCustomer = new Customers();
    //Managers manager = new Managers();
    Gson gson = new Gson();
    ObservableList<CustomerProperty> customersProperty = FXCollections.observableArrayList();
    JSONObject jo = new JSONObject();
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password");
    provider.setCredentials(AuthScope.ANY, credentials);
    HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
    HttpGet get = new HttpGet("http://localhost:8080/MainServerREST/api/customers");
    HttpResponse response = client.execute(get);
    System.out.println("RESPONSE IS: " + response);
    JSONArray jsonArray = new JSONArray(
            IOUtils.toString(response.getEntity().getContent(), Charset.forName("UTF-8")));
    System.out.println(jsonArray);
    for (int i = 0; i < jsonArray.length(); i++) {
        jo = (JSONObject) jsonArray.getJSONObject(i);
        myCustomer = gson.fromJson(jo.toString(), Customers.class);
        System.out.println(myCustomer.getCuId());
        customersProperty.add(new CustomerProperty(myCustomer.getCuId(), myCustomer.getCuFirstname(),
                myCustomer.getCuLastname(), myCustomer.getCuBirthdate(), myCustomer.getCuAddress(),
                myCustomer.getCuPersonnummer()));
    }/*from  w  w  w  .ja v  a  2  s .c o m*/
    return customersProperty;
}

From source file:aajavafx.CustomerMedicineController.java

@FXML
private void handleSaveButton(ActionEvent event) {
    //labelError.setText(null);
    try {/*from   ww  w  . j a  v  a2  s .  com*/

        String dosage = dose.getText();
        dose.clear();
        String stDate = startDate.getText();
        startDate.clear();
        String sched = schedule.getText();
        schedule.clear();
        Customers customer = (Customers) customerBox.getSelectionModel().getSelectedItem();
        Medicines medicine = (Medicines) medicinesBox.getSelectionModel().getSelectedItem();
        CustomersTakesMedicinesPK ctmPK = new CustomersTakesMedicinesPK(customer.getCuId(),
                medicine.getmedId());
        CustomersTakesMedicines ctm = new CustomersTakesMedicines(ctmPK, dosage, stDate,
                Double.parseDouble(sched));
        ctm.setCustomers(customer);
        ctm.setMedicines(medicine);
        //System.out.println(customerBox.getValue());
        //String string = (String)customerBox.getValue();
        //System.out.println("STRING VALUE: "+string);
        //int customerId = Integer.parseInt(""+string.charAt(0));
        //System.out.println("CUSTOMER ID VALUE:"+customerId);
        //Customers customer = getCustomerByID(customerId);

        Gson gson = new Gson();
        //......for ssl handshake....
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password");
        provider.setCredentials(AuthScope.ANY, credentials);
        //........
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpEntityEnclosingRequestBase HttpEntity = null; //this is the superclass for post, put, get, etc
        if (startDate.isEditable()) { //then we are posting a new record
            HttpEntity = new HttpPost(MedicineCustomerRootURL); //so make a http post object
        } else { //we are editing a record 
            HttpEntity = new HttpPut(MedicineCustomerRootURL + startDate); //so make a http put object
        }

        String jsonString = new String(gson.toJson(ctm));
        System.out.println("json string: " + jsonString);
        StringEntity postString = new StringEntity(jsonString);

        HttpEntity.setEntity(postString);
        HttpEntity.setHeader("Content-type", "application/json");
        HttpResponse response = httpClient.execute(HttpEntity);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 204) {
            System.out.println("Customer binded to medicine successfully");
        } else {
            System.out.println("Server error: " + response.getStatusLine());
        }
        dose.setEditable(false);
        startDate.setEditable(false);
        schedule.setEditable(false);
        customerBox.setDisable(true);

    } catch (Exception ex) {
        System.out.println("Error: " + ex);
    }
    try {
        //refresh table
        tableCustomer.setItems(getCustomersTakesMedicines());
    } catch (IOException ex) {
        Logger.getLogger(DevicesController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(DevicesController.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:aajavafx.CustomerMedicineController.java

public ObservableList<Customers> getCustomer() throws IOException, JSONException {

    ObservableList<Customers> customers = FXCollections.observableArrayList();
    Customers myCustomer = new Customers();
    Gson gson = new Gson();
    JSONObject jo = new JSONObject();
    // SSL update..........
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password");
    provider.setCredentials(AuthScope.ANY, credentials);

    HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
    HttpGet get = new HttpGet("http://localhost:8080/MainServerREST/api/customers");

    HttpResponse response = client.execute(get);
    System.out.println("RESPONSE IS: " + response);
    //................

    //JSONArray jsonArray = new JSONArray(IOUtils.toString(new URL(CustomersRootURL), Charset.forName("UTF-8")));
    JSONArray jsonArray = new JSONArray(
            IOUtils.toString(response.getEntity().getContent(), Charset.forName("UTF-8")));

    System.out.println(jsonArray);
    for (int i = 0; i < jsonArray.length(); i++) {
        jo = (JSONObject) jsonArray.getJSONObject(i);
        myCustomer = gson.fromJson(jo.toString(), Customers.class);
        customers.add(myCustomer);/*from   w  w  w.  ja  va 2s.c  om*/

    }
    return customers;
}

From source file:aajavafx.CustomerMedicineController.java

public ObservableList<Medicines> getMedicines() throws IOException, JSONException {

    ObservableList<Medicines> medicines = FXCollections.observableArrayList();
    //Managers manager = new Managers();
    Gson gson = new Gson();
    JSONObject jo = new JSONObject();

    //........SSL Update
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password");
    provider.setCredentials(AuthScope.ANY, credentials);
    HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
    HttpGet get = new HttpGet("http://localhost:8080/MainServerREST/api/medicines");

    HttpResponse response = client.execute(get);
    System.out.println("RESPONSE IS: " + response);
    //...................
    // JSONArray jsonArray = new JSONArray(IOUtils.toString(new URL(MedicineRootURL), Charset.forName("UTF-8")));
    JSONArray jsonArray = new JSONArray(
            IOUtils.toString(response.getEntity().getContent(), Charset.forName("UTF-8")));

    System.out.println(jsonArray);
    for (int i = 0; i < jsonArray.length(); i++) {
        jo = (JSONObject) jsonArray.getJSONObject(i);
        Medicines medicine = gson.fromJson(jo.toString(), Medicines.class);
        System.out.println("JSON OBJECT #" + i + " " + jo);
        medicines.add(medicine);//  ww  w  . ja v a2  s  .  com

    }
    return medicines;
}

From source file:aajavafx.CustomerMedicineController.java

public ObservableList<CustomersTakesMedicines> getCustomersTakesMedicines() throws IOException, JSONException {

    ObservableList<CustomersTakesMedicines> ctMeds = FXCollections.observableArrayList();
    //Managers manager = new Managers();
    Gson gson = new Gson();
    JSONObject jo = new JSONObject();
    //........SSL Update
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password");
    provider.setCredentials(AuthScope.ANY, credentials);
    HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
    HttpGet get = new HttpGet("http://localhost:8080/MainServerREST/api/customersmedicines/");

    HttpResponse response = client.execute(get);
    System.out.println("RESPONSE IS: " + response);
    //...................
    // JSONArray jsonArray = new JSONArray(IOUtils.toString(new URL(MedicineRootURL), Charset.forName("UTF-8")));
    JSONArray jsonArray = new JSONArray(
            IOUtils.toString(response.getEntity().getContent(), Charset.forName("UTF-8")));

    //JSONArray jsonArray = new JSONArray(IOUtils.toString(new URL(MedicineCustomerRootURL), Charset.forName("UTF-8")));
    System.out.println(jsonArray);
    for (int i = 0; i < jsonArray.length(); i++) {
        //get the main json object, which contains customer object, pk object, dosage, start date, schedule and medicine object
        jo = (JSONObject) jsonArray.getJSONObject(i);
        System.out.println("JSON OBJECT #" + i + " " + jo);
        //get the customer json sub-string
        JSONObject custObj = (JSONObject) jo.get("customers");
        Customers customer = gson.fromJson(custObj.toString(), Customers.class);
        //get the primary key json sub-string
        JSONObject pkObj = (JSONObject) jo.get("customersTakesMedicinesPK");
        CustomersTakesMedicinesPK ctmPK = gson.fromJson(pkObj.toString(), CustomersTakesMedicinesPK.class);
        //get the medicine json sub-string
        JSONObject medObj = (JSONObject) jo.get("medicines");
        Medicines medicine = gson.fromJson(medObj.toString(), Medicines.class);
        //get the individual strings
        String dose = jo.getString("medDosage");
        String startDate = jo.getString("medStartDate");
        double schedule = jo.getDouble("medicationintakeschedule");
        CustomersTakesMedicines cuTaMe = new CustomersTakesMedicines(ctmPK, dose, startDate, schedule);
        cuTaMe.setCustomers(customer);//  w  w  w.jav a2s.  co  m
        cuTaMe.setMedicines(medicine);
        ctMeds.add(cuTaMe);
    }
    return ctMeds;
}