GeoApi.java 6.49 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
package api;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import controlador.GeoConexion;
import modelo.PuntoGeografico;






/**
 * Servlet implementation class GeoApi
 */
@WebServlet({ "/GeoApi", "/punto/*", "/guardar", "/buscar_puntos" })
public class GeoApi extends HttpServlet {
	private static final long serialVersionUID = 1L;
Pedro Rolon committed
26 27
	//El valor del api key
	private String apiKey = "pqntslc";
28 29 30 31 32 33
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GeoApi() {
        super();
Pedro Rolon committed
34
        
35 36 37 38 39 40 41
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Pedro Rolon committed
42 43 44 45 46
		
		//Para la validacion del api key
		if(!request.getHeader("apiKey").equals(this.apiKey))
			response.sendError(401, "El api key es incorrecto");
		
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
		String url = request.getRequestURI();

		String[] partes = url.split("/");

		//Si entra por la URL /buscar_puntos
		if(partes[2].equals("buscar_puntos")){
			double latitud = Double.parseDouble(request.getParameter("lat"));
			double longitud = Double.parseDouble(request.getParameter("lon"));

			GeoConexion geo = new GeoConexion();
			
			PuntoGeografico[] puntos= geo.buscarPuntosCercanos(latitud, longitud);
			
			if(puntos!=null) {
				
				PrintWriter respuesta = response.getWriter();	
				
				/**
				 * [{"latitud":12,"longitud":12,"nombre":"rami","distancia":151},{"latitud":12,"longitud":12,"nombre":"rami","distancia":151}]
				 */
				
				//el String jsonReturn contendrá el json que se va a retornar.
				//este se va armando con los datos del array que se obtuvo de
				//GeoConexion
				String jsonReturn = "";
				jsonReturn += "[";	
				
				for(int i=0; i<puntos.length; i++) {
					jsonReturn += "{";
					jsonReturn += "\"latitud\": " + puntos[i].getLatitud() + ",";
					jsonReturn += "\"longitud\":" + puntos[i].getLongitud() + ",";
					jsonReturn += "\"nombre\":" +"\""+ puntos[i].getNombre() +"\""+ ",";
					jsonReturn += " \"distancia\":" + puntos[i].getDistancia();
					jsonReturn += "}";					
					
					
					if(i<puntos.length-1) {
						jsonReturn += ",";
					}					
				}
				
				jsonReturn += "]";
				System.out.println(jsonReturn);		
				
				response.setContentType("application/json");
				
				respuesta.print(jsonReturn);				
			}
		}
		
		
		
		//Si entra por la URL /punto/*
		else if(partes[2].equals("punto")){
			//Obtiene los parámetros de más en el url, antecedidos
			//por una /			
			//Se extrae la id, que se encuentra luego de la /
			int id =Integer.parseInt(request.getPathInfo().split("/")[1]) ;
			
			GeoConexion geo = new GeoConexion();
			
			PuntoGeografico punto = geo.buscarPunto(id);

			/*
			 * En caso de que no se recupere ningun valor de la base de datos
			 * el nombre será nulo, entonces se envia un 404
			if(punto.getNombre()==null){
				response.sendError(404,"No se recuperó nada kp");
			}
			*/

			
			String jsonReturn = "";
			
			jsonReturn += "{";
			jsonReturn += "\"latitud\": " + punto.getLatitud() + ",";
			jsonReturn += "\"longitud\":" + punto.getLongitud() + ",";
			jsonReturn += "\"nombre\":" +"\""+ punto.getNombre() +"\"";
			jsonReturn += "}";
			
			System.out.println(jsonReturn);
			
			response.setContentType("application/json");
			
			PrintWriter respuesta = response.getWriter();
			
			respuesta.print(jsonReturn);
		}
		else {
			response.getWriter().write("usted ha entrado en un lugar sin datos jeje");
		}
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Pedro Rolon committed
146 147 148 149
		//Para la validacion del api key
		if(!request.getHeader("apiKey").equals(this.apiKey))
			response.sendError(401, "El api key es incorrecto");
		
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
		// TODO Auto-generated method stub
		response.setContentType("application/json");
		
		PrintWriter resp = response.getWriter();
		
		//Extrae los datos que vienen en el request y los guarda en variables
		double latitud = Double.parseDouble(request.getParameter("lat"));
		double longitud = Double.parseDouble(request.getParameter("lon"));
		String nombre = request.getParameter("nombre");
		
		//Se instancia una objeto GeoConexion, que es la clase que posee comunicación con
		//la base de datos
		GeoConexion gc = new GeoConexion();
		
		//Se agrega el punto, lo que retorna su id de la base de datos;
		int identificadorPunto = gc.agregarPunto(latitud, longitud, nombre);
		
		String jsonReturn = "{\"identificador\":"+ identificadorPunto +"}";
		
		/**
		 * {"latitud":1234,"longitud":1234,"nombre":"roshka"}
		 */		
		System.out.println(jsonReturn);
		resp.write(jsonReturn);
		
		System.out.println(identificadorPunto);
		System.out.println(request.getParameter("lat"));
		System.out.println(request.getParameter("lon"));
		System.out.println(request.getParameter("nombre"));
	}

	/**
	 * @see HttpServlet#doDelete(HttpServletRequest, HttpServletResponse)
	 */
	protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Pedro Rolon committed
185 186 187 188
		//Para la validacion del api key
		if(!request.getHeader("apiKey").equals(this.apiKey))
			response.sendError(401, "El api key es incorrecto");
				
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
		System.out.println("Ejecutando el delete");
		
		//Extrae los parámetros del URL. ya que el url que llama a este servlet es
		//  /punto/* entonces los parámetros entran por /* que es un wildcard
		String pathInfo = request.getPathInfo();
		
		//Con este se quitan las barras y se escoge la segunda posición (1)
		//del array, porque en ese lugar queda, en este caso, la información
		//que nos interesa, o sea el id
		//Se parese a integer porque inicialmente está como String
		int id = Integer.parseInt(pathInfo.split("/")[1]);
		
		
		//Se setea la salida para que sea interpretada como JSON
		response.setContentType("application/json");
		
		//Se instancia un objeto de GeoConexion, la clase que contiene
		//todos los métodos que se comunica con la base de datos
		GeoConexion geo = new GeoConexion();		
		
		//el método geo.borrarPunto(id) retorna un booleano
		String jsonReturn = "{\"isDelete\":" + geo.borrarPunto(id)+"}";		
		
		PrintWriter respuesta = response.getWriter();
		respuesta.print(jsonReturn);
		
		
	}

}