com.sociesc.findasmartphonespark.Main.java Source code

Java tutorial

Introduction

Here is the source code for com.sociesc.findasmartphonespark.Main.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.sociesc.findasmartphonespark;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sociesc.findasmartphonespark.model.AccessPoint;
import com.sociesc.findasmartphonespark.model.User;
import com.eclipsesource.json.JsonArray;
import com.eclipsesource.json.JsonObject;
import com.sociesc.findasmartphonespark.dao.Dao;
import com.sociesc.findasmartphonespark.utils.DatabaseUtils;
import com.sociesc.findasmartphonespark.utils.rwJson;
import org.codehaus.jackson.type.TypeReference;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import static spark.Spark.*;

/**
 *
 * @author Daniel
 */
public class Main {

    public static void main(String[] args) {
        String apiPrefix = "api/v1/";

        //setIpAddress("192.168.56.1");
        setPort(9010);

        try {
            Logger.getLogger(Main.class.getName()).log(Level.INFO, "Criando banco de dados");
            DatabaseUtils.seedDatabase();
        } catch (SQLException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

        Dao<User> userDao = new Dao(User.class);

        get(apiPrefix + "/hello/:name", (request, response) -> {
            ObjectMapper objectMapper = new ObjectMapper();

            /*ArrayList<AccessPoint> arrayAp = new ArrayList<AccessPoint>();
                
            for (int i = 0; i < 10; i++) {
            AccessPoint ap = new AccessPoint();
            ap.setBSSID("AP" + i);
            ap.setSSID("00:00:00:0" + i);
            ap.setRSSI(-50 + i);
            ap.setSala("Sala" + i);
                
            arrayAp.add(ap);
                
            //System.out.println("Nome: " + ap.getBSSID() + " - Mac: " + ap.getSSID() + " - Sinal: " + ap.getRSSI());
            }
                
            String retornoJson = rwJson.writeJson(arrayAp);*/

            //objectMapper.readValue(URLDecoder.decode(request.params(":name"), "UTF-8"), new TypeReference(String("lol")));
            ArrayList<AccessPoint> arrayAp = null;
            try {
                arrayAp = rwJson.readJson(URLDecoder.decode(request.params(":name"), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return arrayAp.get(0).getBSSID();

            //return "Hello: " + request.params(":name");
            //return arrayAp[0].get;
        });

        post(apiPrefix + "/findUser/:data", (request, response) -> {
            String userId = request.params(":data");

            ArrayList<AccessPoint> aps = rwJson.readJson(userId.toString());

            /*JsonObject json = new JsonObject();
                
            try {
            json = JsonObject.readFrom(request.params(":data"));
            } catch (Exception ex) {
            System.out.println("erro no json:\n" + ex.getMessage());
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            json.add("error", ex.getMessage());
            response.status(500);
            }*/
            try {
                for (int i = 0; i < aps.size(); i++) {
                    System.out.println("Nome: " + aps.get(i).getBSSID() + " - Mac: " + aps.get(i).getSSID()
                            + " - Sinal: " + aps.get(i).getRSSI() + " - Sala: " + aps.get(i).getSala());
                }
            } catch (Exception ex) {
                System.out.println("erro no json:\n" + ex.getMessage());
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                //json.add("error", ex.getMessage());
                response.status(500);
                return ex.getMessage();
            }

            return userId.toString();
        });

        /*post(apiPrefix + "/findUser/", (request, response) ->{
         JsonObject json = new JsonObject();
            
        // Informaes do roteador/AP
        String[] BSSID; // basic service set identifier - nome da conexo
        String[] SSID; // service set identifier - identificador nico da conexo
        int[]    RSSI; // received signal strength indicator - potencia do sinal (-87 a -32)
        String   sala;
            
        String jsonBody = request.body();
        JsonObject reqJson = JsonObject.readFrom(jsonBody);
        JsonObject wifiJson = reqJson.get("wifi").asObject();
            
        System.out.println("reqJson.size()" + reqJson.size() + "\nwifiJson.size()" + wifiJson.size());
            
        RSSI = new int[wifiJson.size()];
        BSSID = new String[wifiJson.size()];
        SSID = new String[wifiJson.size()];
            
        try{
            for (int i = 0; i < wifiJson.size(); i++) {
                // recebe informaes das conexes encontradas
                BSSID[i] = wifiJson.get("BSSID").asString();
                SSID[i] = wifiJson.get("SSID").asString();
                RSSI[i] = wifiJson.get("RSSI").asInt();
            }
            
            return json.toString();
        }catch(Exception ex){
            System.out.println("erro no json:\n" + ex.getMessage());
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            json.add("error", ex.getMessage());
            response.status(500);
        }
        return json.toString();
        });*/

        get(apiPrefix + "/users", (request, response) -> {
            JsonObject json = new JsonObject();

            request.params();

            try {
                List<User> users = userDao.findAll();
                JsonArray usersJson = new JsonArray();
                for (User u : users) {
                    JsonObject uJson = new JsonObject();
                    uJson.add("id", u.getId());
                    uJson.add("name", u.getName());
                    uJson.add("email", u.getEmail());
                    usersJson.add(uJson);
                }
                json.add("users", usersJson);

            } catch (SQLException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                json.add("error", ex.getMessage());
                response.status(500);
            }

            return json.toString();
        });

        /*get(apiPrefix + "/users/:id", (request, response) -> {
        Long userId = Long.parseLong(request.params(":id"));
        JsonObject json = new JsonObject();
        try{
            User user = userDao.findById(userId);
            if(user == null){
                json.add("error", "user not found");
                response.status(404);
                return json.toString();
            }
                
            JsonObject userJson = new JsonObject();
            userJson.add("id", user.getId());
            userJson.add("name", user.getName());
            userJson.add("email", user.getEmail());
            json.add("user", userJson);
            return json.toString();
                
        }catch(Exception ex){
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            json.add("error", ex.getMessage());
            response.status(500);
        }
            
        return json.toString();
        });*/

        delete(apiPrefix + "/users/:id", (request, response) -> {
            Long userId = Long.parseLong(request.params(":id"));
            JsonObject json = new JsonObject();
            try {
                userDao.removeById(userId);
                json.add("message", "user removed");
                response.status(200);
                return json.toString();
            } catch (Exception ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                json.add("error", ex.getMessage());
                response.status(500);
            }

            return json.toString();
        });

        put(apiPrefix + "/users/:id", (request, response) -> {
            Long userId = Long.parseLong(request.params(":id"));
            JsonObject json = new JsonObject();
            try {
                String jsonBody = request.body();
                JsonObject reqJson = JsonObject.readFrom(jsonBody);
                JsonObject userJson = reqJson.get("user").asObject();
                String name = userJson.get("name") != null ? userJson.get("name").asString() : null;
                String email = userJson.get("email") != null ? userJson.get("email").asString() : null;
                String password = userJson.get("password") != null ? userJson.get("password").asString() : null;

                User user = userDao.findById(userId);

                if (name != null)
                    user.setName(name);

                if (email != null)
                    user.setEmail(email);

                if (password != null) {
                    String passwordDigest = DatabaseUtils.criptPass(password);
                    user.setPasswordDigest(passwordDigest);
                }

                userDao.update(user);

                JsonObject resUserJson = new JsonObject();
                resUserJson.add("id", user.getId());
                resUserJson.add("name", user.getName());
                resUserJson.add("email", user.getEmail());

                json.add("user", resUserJson);
                return json.toString();

            } catch (Exception ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                json.add("error", ex.getMessage());
                response.status(500);
            }
            return json.toString();
        });

        post(apiPrefix + "/users", (request, response) -> {
            JsonObject json = new JsonObject();
            try {
                String jsonBody = request.body();
                JsonObject reqJson = JsonObject.readFrom(jsonBody);
                JsonObject userJson = reqJson.get("user").asObject();
                User user = new User();
                user.setName(userJson.get("name").asString());
                user.setEmail(userJson.get("email").asString());
                user.setPasswordDigest(DatabaseUtils.criptPass("tempPass"));
                userDao.create(user);

                JsonObject resUserJson = new JsonObject();
                resUserJson.add("id", user.getId());
                resUserJson.add("name", user.getName());
                resUserJson.add("email", user.getEmail());
                resUserJson.add("passwordDigest", user.getPasswordDigest());

                json.add("user", resUserJson);
                return json.toString();
            } catch (Exception ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                json.add("error", ex.getMessage());
                response.status(500);
            }
            return json.toString();
        });

    }

}