com.demo.impl.CoordenadasImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.demo.impl.CoordenadasImpl.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.demo.impl;

import com.demo.dao.CoordenadasDAO;
import com.demo.model.UbicacionCredito;
import com.demo.util.HibernateUtil;
import com.demo.util.LogSistema;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdom2.*;
import org.jdom2.input.SAXBuilder;

/**
 *
 * @author brionvega
 */
public class CoordenadasImpl implements Serializable, CoordenadasDAO {

    @Override
    public List<UbicacionCredito> obtenerCoincidencias(String colonia, String CP) {
        try {

            Session session = HibernateUtil.getSessionFactory().openSession();
            Transaction t = session.beginTransaction();
            //direccion completa dir.`DomDeu`,",",dir.`ColDeu`,",",dir.`Entdeu`,",",dir.`EdoDeu`
            String sql = "select ct.`CreditosII` as noCredito, dp.`Deudor` as nombreDeudor, cg.`Usu_login` as gestor, \n"
                    + "ca.`Camp_Desc` as campagne, concat(dir.`DomDeu`,\",\",dir.`Entdeu`,\",\",dir.`EdoDeu`) as direccion from datos_primarios dp, direcciones dir, \n"
                    + "credito_sf_lt_nt_ct ct, campagne ca, cat_gestores cg where\n"
                    + "dp.`Folio`=dir.`Datos_primarios_Folio` \n" + "and (  (dir.`ColDeu`='" + colonia
                    + "' and dir.`CodPos`='" + CP + "') or (dir.`CodPos`='" + CP + "') )\n"
                    + "and dp.`Folio`=ct.`Datos_primarios_Folio`\n" + "and ct.`Campagne_Camp_Clv`=ca.`Camp_Clv` \n"
                    + "and ct.`Cat_Gestores_Cat_Gestor_clv`=cg.`Cat_Gestor_clv` GROUP by dir.`idDirecciones` order by ct.`CreditosII`;";

            List<UbicacionCredito> lista = session.createSQLQuery(sql).addEntity(UbicacionCredito.class).list();

            t.commit();

            if (lista.isEmpty()) {
                System.out.println(this.getClass().getName()
                        + " Method: obtenerCoincidencias, la consulta no trajo resultados");
            } else {
                Iterator iter = lista.listIterator();
                LogSistema.guardarlog("tam lista " + lista.size());
                while (iter.hasNext()) {
                    UbicacionCredito ubicacion = new UbicacionCredito();
                    ubicacion = (UbicacionCredito) iter.next();

                    try {
                        String direccion = ubicacion.getDireccion();
                        direccion = direccion.replace(" ", "%20");
                        direccion = direccion.replace(" norte ", "");
                        direccion = direccion.replace(" av ", "");
                        direccion = direccion.replace(" poniente ", "");
                        direccion = direccion.replace(" sur ", "");
                        direccion = direccion.replace(" oriente ", "");
                        direccion = direccion.replace(" calle ", "");
                        direccion = direccion.replace(" cll ", "");
                        direccion = direccion.replace(" col ", "");
                        direccion = direccion.replace(" norte ", "");
                        direccion = direccion.replace(" colonia ", "");
                        direccion = direccion.replace(" sn ", "");
                        direccion = direccion.replace(" SN ", "");
                        direccion = direccion.replace(" int ", "");
                        direccion = direccion.replace(" INT ", "");

                        URL url = new URL("https://maps.googleapis.com/maps/api/place/autocomplete/xml?input="
                                + direccion
                                + "&types=geocode&sensor=false&key=AIzaSyDHdJ0GD3efGWzFnyQ0Dcw08eh1fb_9Pq4");
                        // URL url = new URL("https://maps.googleapis.com/maps/api/place/details/xml?reference=CkQ-AAAAFivu82hu1JJ7FMRBgoqZPG8yeIxL0GDB1_4g46eSghm3mV7DHXeoZkSWgii4MegpQAP2RyYRsqINAYQGZu2fURIQCjcNgINyC1BwT4zDel2FvRoU6-wFkI9DOnkb0WFyTeKdxXYh-4M&sensor=true&key=AIzaSyDHdJ0GD3efGWzFnyQ0Dcw08eh1fb_9Pq4");
                        LogSistema.guardarlog("URL 1: " + url.toString());

                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        conn.setRequestMethod("GET");
                        conn.setRequestProperty("Accept", "application/xml");

                        if (conn.getResponseCode() != 200) {
                            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
                        }

                        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

                        String output;

                        StringBuffer buffer = new StringBuffer();
                        while ((output = br.readLine()) != null) {

                            buffer.append(output);
                        }
                        conn.disconnect();
                        SAXBuilder builder = new SAXBuilder();

                        Document doc = builder.build(new StringReader(buffer.toString()));

                        String ref = doc.getRootElement().getChildren("prediction").get(0).getChildren("reference")
                                .get(0).getValue();

                        url = new URL("https://maps.googleapis.com/maps/api/place/details/xml?reference=" + ref
                                + "&sensor=false&key=AIzaSyDHdJ0GD3efGWzFnyQ0Dcw08eh1fb_9Pq4");

                        conn = (HttpURLConnection) url.openConnection();
                        conn.setRequestMethod("GET");
                        conn.setRequestProperty("Accept", "application/xml");

                        if (conn.getResponseCode() != 200) {
                            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
                        }

                        br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

                        buffer = new StringBuffer();
                        while ((output = br.readLine()) != null) {

                            buffer.append(output);
                        }
                        conn.disconnect();
                        builder = new SAXBuilder();
                        doc = builder.build(new StringReader(buffer.toString()));

                        ubicacion.setLatitud(
                                doc.getRootElement().getChildren("result").get(0).getChildren("geometry").get(0)
                                        .getChildren("location").get(0).getChildren("lat").get(0).getValue());
                        ubicacion.setLongitud(
                                doc.getRootElement().getChildren("result").get(0).getChildren("geometry").get(0)
                                        .getChildren("location").get(0).getChildren("lng").get(0).getValue());
                        //lista.add(ubicacion);
                        ubicacion.setUbicacionEncontrada("ubicacionPositiva");
                        System.out.println("nombre  " + ubicacion.getNombreDeudor());
                        LogSistema.guardarlog(this.getClass().getName() + ", latitud"
                                + doc.getRootElement().getChildren("result").get(0).getChildren("geometry").get(0)
                                        .getChildren("location").get(0).getChildren("lat").get(0).getValue());
                        LogSistema.guardarlog(this.getClass().getName() + ",logitud "
                                + doc.getRootElement().getChildren("result").get(0).getChildren("geometry").get(0)
                                        .getChildren("location").get(0).getChildren("lng").get(0).getValue());

                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                        LogSistema.guardarlog(this.getClass().getName()
                                + " Method: obtenerCoincidencias, Exception: " + e.getMessage());
                        ubicacion.setUbicacionEncontrada("ubicacionNegativa");
                    } catch (IOException e) {
                        LogSistema.guardarlog(this.getClass().getName()
                                + " Method: obtenerCoincidencias, Exception: " + e.getMessage());
                        e.printStackTrace();
                        ubicacion.setUbicacionEncontrada("ubicacionNegativa");
                    } catch (JDOMException ex) {
                        LogSistema.guardarlog(this.getClass().getName()
                                + " Method: obtenerCoincidencias, Exception: " + ex.getMessage());
                        ubicacion.setUbicacionEncontrada("ubicacionNegativa");
                    } catch (IndexOutOfBoundsException ex) {
                        LogSistema.guardarlog(this.getClass().getName()
                                + " Method: obtenerCoincidencias, Exception: " + ex.getMessage());
                        ubicacion.setUbicacionEncontrada("ubicacionNegativa");
                    }

                } //fin del while

            }

            return lista;

        } catch (HibernateException he) {
            LogSistema.guardarlog(
                    this.getClass().getName() + " Method: obtenerCoincidencias, Exception: " + he.getMessage());
            List<UbicacionCredito> lista = new ArrayList<>();
            return lista;
        }

    }

}