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:anuncius.util.PlatformUtil.java

public static String toJsonString(Object data) {
    if (data != null) {
        Gson gson = new Gson();
        return gson.toJson(data);
    }/* w w  w . j  a v  a 2s. c om*/
    return "{}";
}

From source file:aop.behaviour.ListenBehaviour.java

@Override
protected void onTick() {
    ACLMessage msg = myAgent.receive(tpl);
    if (msg != null && !prisoner.atExit()) {
        //            System.out.println(this.myAgent.getLocalName() + " received: " + msg.getContent());
        String content = msg.getContent();
        Gson gson = new Gson();
        String json = content.substring(5);
        ArrayList array = new ArrayList();
        array = gson.fromJson(json, ArrayList.class);
        LinkedTreeMap map = (LinkedTreeMap) array.get(0);
        if ("exit".equals(content.substring(0, 4))) {
            Point exitPoint = new Point();
            exitPoint.setLocation((double) map.get("exitX"), (double) map.get("exitY"));
            prisoner.exitLocation = exitPoint;
            Point exitRoomPoint = new Point();
            exitRoomPoint.setLocation((double) map.get("passageX"), (double) map.get("passageY"));
            prisoner.exitRoomLocation = exitRoomPoint;
            int state = 1;
            if ("RoomMain".equals(prisoner.room.name)) {
                state = 2;//w  w w  . ja v a 2  s .com
            } else if (map.get("room").equals(prisoner.room.name)) {
                state = 3;
            }
            prisoner.addBehaviour(new GotoExitBehaviour(prisoner, 10, state));

        } else if ("room".equals(content.substring(0, 4))) {
            prisoner.roomsFound.put((String) map.get("room"), prisoner.roomsFound.get(map.get("room")) + 1);
        }
    } else {
        block();
    }
}

From source file:api.AgTools.java

public static String MarketCarts(ArrayList<String> productsList, HashMap<String, Double> markets,
        Connection connection) {/*from w  ww.  j  a  va  2 s .  co  m*/
    try {
        Statement select = connection.createStatement();
        ResultSet rs = null;
        //each market has a cart with product Id and their correspoinding price
        HashMap<String, HashMap<String, Float>> MarketAndProducts = new HashMap<String, HashMap<String, Float>>();
        // HashMap<String, ArrayList<String>> MarketAndProducts = new HashMap<String, ArrayList<String>>();
        //HashMap for products and their amount
        HashMap<String, Integer> products = new HashMap<String, Integer>();
        //string of the products requested
        String ProductStr = "'";
        for (String p : productsList) {
            String[] pr = p.split(":");
            //id:product and the respectice amount
            //products.put(pr[0] + ":" + pr[1], Integer.parseInt(pr[2]));
            //System.out.println(pr[0] + pr[0].length());
            products.put(pr[0], Integer.parseInt(pr[1]));
            // System.out.println(pr[0]);
            //str of names to query
            ProductStr = ProductStr.concat(pr[0] + "','");
        }
        //string of markets requested
        String MarketStr = "'";
        //HM for markets and their distance from costumer
        // HashMap<String, Double> markets = new HashMap<String, Double>();
        HashMap<String, String> marketLatLon = new HashMap<String, String>();
        HashMap<String, Double> marketsDist = new HashMap<String, Double>();
        for (String entry : markets.keySet()) {
            //market:distance
            //String[] pr = b.split(":");
            String[] e = entry.split("---");
            marketLatLon.put(e[0], e[1]);
            String ent = e[0];
            MarketStr = MarketStr.concat(ent + "','");
            marketsDist.put(ent, markets.get(entry));
            //hashmap of products and prices
            //  markets.put(ent.getKey(),ent.getValue() );
            //keep one hashmap with product-price for every market, representing the cart
            HashMap<String, Float> temp = new HashMap<String, Float>();
            MarketAndProducts.put(ent, temp);
        }

        if (ProductStr.length() > 0 && MarketStr.length() > 0) {
            //remoce the last , and the last ,'
            ProductStr = ProductStr.substring(0, ProductStr.length() - 2);
            MarketStr = MarketStr.substring(0, MarketStr.length() - 2);
            //query for the products
            String query = "SELECT name,price,market FROM prices WHERE name in (" + ProductStr
                    + ") and market in (" + MarketStr + ")";
            //CONCAT(id,':',name) as 

            rs = select.executeQuery(query);
            while (rs.next()) {
                String mar = rs.getString("market").trim();
                //take the list until now for this market
                HashMap<String, Float> temp = MarketAndProducts.get(mar);
                //add the new product to the already existing cart, with its price* the amount the costumer wants
                String name = rs.getString("name").trim();
                Float price = (float) rs.getDouble("price");
                // System.out.println(name + " " + price * 1);
                //product with the final price
                temp.put(name, price * products.get(name));
                //put the renewed cart in the respective market 
                MarketAndProducts.put(mar, temp);
            }
            if (MarketAndProducts.isEmpty()) {
                return "";
            }
            /*
             String ret=" "+name.length();
             for(String p:products.keySet()){
             ret=ret+" "+p.length();
             if(p.equalsIgnoreCase(name)){
             return name+Integer.toString(products.get(name));
             }
             }*/

            //find the expected price of all the products requested
            HashMap<String, Float> averages = new HashMap<String, Float>();
            query = "SELECT avg(price) as avg, name FROM prices WHERE name in (" + ProductStr
                    + ") GROUP BY name";////////

            rs = select.executeQuery(query);
            //the average cost of this basket generally
            float expAvg = 0;
            System.out.println(ProductStr);
            while (rs.next()) {
                Float avg = rs.getFloat("avg");
                String name = rs.getString("name").trim();
                //expected price is the average price of the product * # of these products the costumer wants to buy 

                //System.out.println(name + " " + avg);
                averages.put(name, avg * products.get(name));
                expAvg += avg * products.get(name);
            }
            //the final arraylist returned
            ArrayList<ArrayList<String>> fin = new ArrayList<ArrayList<String>>();
            HashMap<String, Double> feat = new HashMap<String, Double>();
            HashMap<String, ArrayList<String>> ca = new HashMap<String, ArrayList<String>>();
            //find the final features of each market's cart
            for (String m : MarketAndProducts.keySet()) {

                HashMap<String, Float> temp = MarketAndProducts.get(m);
                //for cases where the market has no suitable product
                if (temp.isEmpty()) {
                    continue;
                }
                //actual sum of market list's products
                float actSum = 0;
                for (float d : temp.values()) {
                    //System.out.println(d);
                    actSum += d;
                }

                //expected sum (with missing products)
                float expSum = actSum;
                for (String s : averages.keySet()) {
                    //if a product is not in the market's cart
                    if (!temp.keySet().contains(s)) {
                        // System.out.println(s);
                        //add its average price to the expected price of the cart
                        expSum += averages.get(s);
                    }
                }

                ///occupancy percentage of cart for that market
                double occ = temp.size() * 100 / products.size();
                //distance of the costumer to each market
                double dist = marketsDist.get(m);
                boolean expensive = false;
                if (expSum > expAvg) {
                    expensive = true;
                } // + occ + ":" 
                String features = m + ":" + actSum + ":" + expSum + ":" + dist + ":" + expensive + ":"
                        + marketLatLon.get(m);

                feat.put(features, occ);
                //the list of the market
                ArrayList<String> cart = new ArrayList<String>();
                //append the features to the first position of the market's cart
                cart.add(features + ":" + occ);
                //append to the rest of the posistions the products of the cart and their respective prices
                for (Map.Entry o : temp.entrySet()) {
                    cart.add(o.getKey() + ":" + o.getValue());
                }
                ca.put(features, cart);
                //fin.add(cart);
            }

            //sort by occupancy
            LinkedHashMap<String, Double> sorted = sortHashMapByValues(feat);
            for (Map.Entry<String, Double> plom : sorted.entrySet()) {
                String maStats = plom.getKey();
                fin.add(ca.get(maStats));
            }
            Gson gson = new Gson();
            String json = gson.toJson(fin);
            return json;
        }
    } catch (SQLException ex) {
        Logger.getLogger(AgTools.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:api.AgTools.java

public static String MinList(ArrayList<String> productsList, HashMap<String, Double> markets,
        Connection connection) {/*from   w  ww .  j  a va2  s  .c  o m*/
    try {
        Statement select = connection.createStatement();
        ResultSet rs = null;
        //string of products requested
        String ProductStr = "'";
        ArrayList<String> kla = new ArrayList<String>();
        for (String p : productsList) {
            String[] pr = p.split(":");
            ProductStr = ProductStr.concat(pr[0] + "','");
            // System.out.println("mesa "+pr[0]);
            kla.add(pr[0]);
        }
        //string of markets requested
        String MarketStr = "'";
        HashMap<String, String> marketLatLon = new HashMap<String, String>();
        HashMap<String, Double> marketsDist = new HashMap<String, Double>();
        for (String entry : markets.keySet()) {
            //String[] pr = b.split(":");
            //market:distance
            //String[] pr = b.split(":");
            String[] e = entry.split("---");
            marketLatLon.put(e[0], e[1]);
            marketsDist.put(e[0], markets.get(entry));
            MarketStr = MarketStr.concat(e[0] + "','");
        }
        if (ProductStr.length() > 0 && MarketStr.length() > 0) {
            //remove the last , and the last ,'
            ProductStr = ProductStr.substring(0, ProductStr.length() - 2);
            MarketStr = MarketStr.substring(0, MarketStr.length() - 2);
            /*
             String query = "SELECT min( price ) as min , market,CONCAT(id,':',name) as name FROM `prices` WHERE id in (" + ProductList + ") and market in (" + MarketList + ") GROUP BY id"; 
             while(rs.next()){
             String product = rs.getString("market") + ":" +  + ":" + rs.getString("name") + ":" + rs.getString("min");
             fin.add(product);
             }
             */

            String query = "SELECT name,price,market FROM prices WHERE name in (" + ProductStr
                    + ") and market in (" + MarketStr + ")";
            //CONCAT(id,':',name) as 
            // System.out.println(query);

            //HM for the product and the respective price
            HashMap<String, Double> prodPrice = new HashMap<String, Double>();
            //HM for the product and the market that currently has it cheaper
            HashMap<String, String> prodMarket = new HashMap<String, String>();
            ArrayList<String> fin = new ArrayList<String>();
            rs = select.executeQuery(query);
            while (rs.next()) {
                String name = rs.getString("name").trim();
                // System.out.println(name);
                //if the product has occured again in the result set
                if (prodPrice.containsKey(name)) {
                    Double price = rs.getDouble("price");
                    // and if its current price is cheaper than the previous 
                    if (price < prodPrice.get(name)) {
                        //keep that price
                        prodPrice.put(name, price);
                        String mar = rs.getString("market").trim();
                        //and keep that market as the best option for that product
                        prodMarket.put(name, mar);
                    }
                } else {
                    //if it is the first time this product occurs in the result set
                    Double price = rs.getDouble("price");
                    String mar = rs.getString("market").trim();
                    //keep this price as the min
                    prodPrice.put(name, price);
                    //keep this market as min's price market for this product
                    prodMarket.put(name, mar);
                }
            }
            for (Map.Entry a : prodMarket.entrySet()) {
                //take the id:name of the product
                String name = a.getKey().toString();
                //make the string that corresponds to market of min price:id:product:min(price of product)
                String product = a.getValue() + ":" + name + ":" + marketLatLon.get(a.getValue()) + ":"
                        + prodPrice.get(name) + ":" + marketsDist.get(a.getValue());
                // System.out.println(product);
                fin.add(product);
            }
            for (String s : kla) {
                if (!prodMarket.containsKey(s)) {
                    fin.add("-1:" + s + ":-1" + ":-1" + ":-1" + ":-1");
                }
            }
            Gson gson = new Gson();
            String json = gson.toJson(fin);
            // System.out.println(json);
            return json;
        }
        return null;
    } catch (SQLException ex) {
        Logger.getLogger(AgTools.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:api.airpatrolapi.java

@GET
@Produces("application/json")
public Response Test() {
    try {/*from  w  w  w .j av  a2 s.c o  m*/
        /*try {
        resourses r = new resourses();
        DatabaseHandler h = new DatabaseHandler();
                
        Gson gson = new Gson();
                
        //return "Hallo";
        return Response.ok()
        .entity(gson.toJson(r.getManufacturerByMac()))
        .header("Access-Control-Allow-Origin", "*")
        .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
        .allow("OPTIONS").build();
                
        } catch (NamingException ex) {
        Logger.getLogger(airpatrolapi.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
        Logger.getLogger(airpatrolapi.class.getName()).log(Level.SEVERE, null, ex);
        }*/

        resourses r = new resourses();
        DatabaseHandler h = new DatabaseHandler();

        Gson gson = new Gson();

        List<Manufacturer> s = r.sortList(r.getManufacturerByMac());

        return Response.ok().entity(gson.toJson(s)).header("Access-Control-Allow-Origin", "*")
                .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT").allow("OPTIONS").build();
    } catch (NamingException ex) {
        Logger.getLogger(airpatrolapi.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(airpatrolapi.class.getName()).log(Level.SEVERE, null, ex);
    }

    return Response.serverError().build();
}

From source file:api.airpatrolapi.java

@GET
@Produces("application/json")
@Path("/mac")
public Response getMacAddresses() {
    try {/*from   w  w  w .j  a v  a2s  .  c  o  m*/
        DatabaseHandler h = new DatabaseHandler();
        Gson gson = new Gson();

        return Response.ok().entity(gson.toJson(h.getAllMacAddresses()))
                .header("Access-Control-Allow-Origin", "*")
                .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT").allow("OPTIONS").build();

    } catch (NamingException ex) {
        Logger.getLogger(airpatrolapi.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(airpatrolapi.class.getName()).log(Level.SEVERE, null, ex);
    }

    return Response.serverError().build();
}

From source file:api.airpatrolapi.java

@GET
@Produces("application/json")
@Path("/manufacturer")
public Response getManufacturers() {
    try {/* w  w  w.  j av a  2s.  c o m*/
        Gson gson = new Gson();
        resourses r = new resourses();

        return Response.ok().entity(gson.toJson(r.sortList(r.getManufacturerByMac())))
                .header("Access-Control-Allow-Origin", "*")
                .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT").allow("OPTIONS").build();
    } catch (NamingException ex) {
        Logger.getLogger(airpatrolapi.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(airpatrolapi.class.getName()).log(Level.SEVERE, null, ex);
    }

    return Response.serverError().build();
}

From source file:API.APIcomm.java

/**
 * @desc: makes a http request to log in
 * @param userName users - userName, password - user password
 * @return a user object /*from w ww  .ja v  a  2 s.c  o  m*/
 */
public User logIn(String userName, String password) {
    String URL = baseURL + "/logIn/" + userName + "/" + password;
    RequestType = "POST";
    String response = executeURL(URL);
    Gson g = new Gson();

    ErrorResponse e = g.fromJson(response, ErrorResponse.class);
    if (e.errorType != null)
        return null;

    UserResponse r = g.fromJson(response, UserResponse.class);

    if (r.status.equals("OK")) {
        return r.userInfo;
    } else if (r.status.equals("ERROR")) {
        return null;
    } else {
        return null;
    }
}

From source file:API.APIcomm.java

/**
 * @desc makes a http request to create a new account.
 * @param userName - users username, password - users password, firstName - users first name, lastName users last name,
 * @return User object//from  www  .j  a va2 s  .  com
 */
public User createAccount(String userName, String password, String firstName, String lastName) {

    String URL = baseURL + "/createAccount/" + userName + "/" + password + "/" + firstName + "/" + lastName;
    RequestType = "PUT";
    String response = executeURL(URL);

    Gson g = new Gson();
    ErrorResponse e = g.fromJson(response, ErrorResponse.class);
    if (e.errorType != null)
        return null;

    UserResponse r = g.fromJson(response, UserResponse.class);
    if (r.status.equals("OK")) {
        return r.userInfo;
    } else if (r.status.equals("ERROR")) {
        return null;
    } else
        return null;
}

From source file:API.APIcomm.java

/**
 * @desc makes a http request to add a Location
 * @param userID - users id, latitude - users latitude , longitude - users longitude, place - name of location, auth - users authentication token
 *//*from   ww w .j  av  a  2 s.  com*/
public void addLocation(int userID, double latitude, double longitude, String place, String auth) {
    String URL = baseURL + "/addNewLocation/" + place + "/" + latitude + "/" + longitude + "/" + userID + "/"
            + auth;
    RequestType = "PUT";
    String response = executeURL(URL);
    Gson g = new Gson();

    ErrorResponse e = g.fromJson(response, ErrorResponse.class);
    if (e.errorType != null)
        return;

    Response r = g.fromJson(response, Response.class);
    if (r.status.equals("OK")) {

    } else if (r.status.equals("TOKENCLEARED")) {

    } else if (r.status.equals("ERROR")) {

    } else {

    }
}