/[projects]/dao/FuldDaekningWorker/src/main/java/dk/daoas/fulddaekning/Database.java
ViewVC logotype

Diff of /dao/FuldDaekningWorker/src/main/java/dk/daoas/fulddaekning/Database.java

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 2203 by torben, Thu Sep 11 14:46:59 2014 UTC revision 2424 by torben, Tue Mar 3 08:52:39 2015 UTC
# Line 7  import java.sql.PreparedStatement; Line 7  import java.sql.PreparedStatement;
7  import java.sql.ResultSet;  import java.sql.ResultSet;
8  import java.sql.SQLException;  import java.sql.SQLException;
9  import java.util.ArrayList;  import java.util.ArrayList;
10    import java.util.HashMap;
11  import java.util.List;  import java.util.List;
12    import java.util.Map;
13  import java.util.Properties;  import java.util.Properties;
14  import java.util.Queue;  import java.util.Queue;
15    import java.util.Set;
16    import java.util.TreeSet;
17  import java.util.concurrent.ConcurrentLinkedQueue;  import java.util.concurrent.ConcurrentLinkedQueue;
18  import java.util.logging.Logger;  import java.util.logging.Logger;
19    
20    
21    
22  public class Database {  public class Database {
23          Logger logger = Logger.getLogger(Database.class.getName());          Logger logger = Logger.getLogger(Database.class.getName());
24    
25            int batchCount = 0;
26    
27          Connection conn;          Connection conn;
28          PreparedStatement saveStmt;          PreparedStatement saveStmt;
29            
30            Adresse alleAdresser[];
31            Adresse alleIkkeDaekkede[];
32            
33            
34            DeduplicateHelper<String> husnrbogstavCache = new DeduplicateHelper<String>();
35            DeduplicateHelper<String> ruteCache = new DeduplicateHelper<String>();
36            
37            Set<Integer> postnumre = new TreeSet<Integer>();
38            
39            Map<Integer, List<Adresse>> ikkeDaekkedePrPost = new HashMap<Integer, List<Adresse>>();
40            
41            
42            private HashMap<Integer,BoundingBox> bbCache = new HashMap<Integer,BoundingBox>();
43    
44          public Database(SafeProperties conf)  throws SQLException,IOException {          public Database(SafeProperties conf)  throws SQLException,IOException {
45                  this.conn = getConnection( conf );                        this.conn = getConnection( conf );      
# Line 42  public class Database { Line 62  public class Database {
62          }                }      
63                    
64          public void renameResultTables() throws SQLException {          public void renameResultTables() throws SQLException {
65                    Constants consts = Constants.getInstance();
66                    String ext = consts.getTableExtension();
67                    
68                  logger.info("Dropping old backup table (if exists)");                  logger.info("Dropping old backup table (if exists)");
69                  String sql = "DROP TABLE IF EXISTS fulddaekning.afstand_anden_rute_old";                  String sql = "DROP TABLE IF EXISTS fulddaekning.afstand_anden_rute_old" + ext;
70                  conn.createStatement().executeUpdate(sql);                  conn.createStatement().executeUpdate(sql);
71                                    
72                  logger.info("Rename tables");                  logger.info("Rename tables");
73                  sql = "RENAME TABLE fulddaekning.afstand_anden_rute TO fulddaekning.afstand_anden_rute_old, fulddaekning.afstand_anden_rute_ny TO fulddaekning.afstand_anden_rute";                  sql = "RENAME TABLE fulddaekning.afstand_anden_rute" + ext + " TO fulddaekning.afstand_anden_rute_old" + ext + ", fulddaekning.afstand_anden_rute_ny TO fulddaekning.afstand_anden_rute" + ext;
                 conn.createStatement().executeUpdate(sql);                
         }        
74    
75          public BoundingBox getBoundingbox(int postnr) throws SQLException {                  logger.info("Executing: " + sql);
76                    conn.createStatement().executeUpdate(sql);              
77                  String sql =          }
78                                  "SELECT max(latitude) latmax, min(latitude) latmin, max(longitude) lngmax,min(longitude) lngmin  " +          
79                                  "FROM fulddaekning.adressetabel WHERE postnr=? and rute is null;";          public BoundingBox getBoundingbox(int postnr)  {
80                    BoundingBox bb = bbCache.get(postnr);
81                  PreparedStatement stmt = conn.prepareStatement(sql);                  return bb.clone();//never return the original / cached object
82                  stmt.setInt(1, postnr);          }
83            
84                  ResultSet res = stmt.executeQuery();          
85                  res.next(); //query returnerer altid 1 række          public Set<Integer> hentPostnumreCache() {
86                    return postnumre;
                 BoundingBox bbox = new BoundingBox();  
                 bbox.latitudeMax = res.getDouble("latmax");  
                 bbox.latitudeMin = res.getDouble("latmin");  
                 bbox.longitudeMax = res.getDouble("lngmax");  
                 bbox.longitudeMin = res.getDouble("lngmin");  
   
                 res.close();  
                 stmt.close();  
   
                 return bbox;  
87          }          }
88    
         public Queue<Adresse> hentIkkedaekkedeAdresser(int postnr)  throws SQLException {  
                 ConcurrentLinkedQueue<Adresse> queue = new ConcurrentLinkedQueue<Adresse>();  
89    
90                  String sql = "SELECT id,postnr,adresse,gadeid,husnr,husnrbogstav,latitude,longitude,rute " +          public void hentAlleIkkedaekkedeAdresser(int minPostnr, int maxPostnr)  throws SQLException {
91                                  "FROM fulddaekning.adressetabel " +                  
92                    logger.info("Henter alle IKKE-daekkede adresser");
93    
94                    String sql = "SELECT id,a.postnr,adresse,gadeid,husnr,husnrbogstav,latitude,longitude,rute,p.distributor as ho " +
95                                    "FROM fulddaekning.adressetabel a " +
96                                    "LEFT JOIN bogleveringer.postnummerdistributor p on (a.postnr=p.postnr) " +
97                                  "WHERE rute IS NULL " +  //Ingen dækning                                  "WHERE rute IS NULL " +  //Ingen dækning
98                                  "AND postnr=?  " +                                  "AND a.postnr BETWEEN ? AND ? " +
99                                  "AND latitude IS NOT NULL " +                                  "AND latitude IS NOT NULL " +
100                                  "AND longitude IS NOT NULL " +                                  "AND longitude IS NOT NULL " +
101                                  "AND gadeid IS NOT NULL ";                                  "AND gadeid IS NOT NULL " +
102                                    "AND (a.distributor IS NULL OR a.distributor<>'LUKKET') ";              
103                  PreparedStatement stmt = conn.prepareStatement(sql);                  PreparedStatement stmt = conn.prepareStatement(sql);
104                  stmt.setInt(1, postnr);                  stmt.setInt(1, minPostnr);
105                    stmt.setInt(2, maxPostnr);
106    
107                  queue.addAll( hentAdresseListe( stmt ) );                  List<Adresse> list = hentAdresseListe( stmt );
108                  return queue;                  alleIkkeDaekkede = list.toArray( new Adresse[ list.size() ] );
109                    
110                    logger.info("Analyserer ikke-daekkede adresser");
111                    
112                    for (Adresse a : alleIkkeDaekkede) {
113                            
114                            List<Adresse> postListe;
115                            
116                            BoundingBox bbox;
117                            
118                            if (! postnumre.contains(a.postnr )) {
119                                    postnumre.add( a.postnr );
120                                    
121                                    bbox = new BoundingBox();
122                                    postListe = new ArrayList<Adresse>();
123                                    
124                                    bbCache.put( a.postnr, bbox);                                                                                  
125                                    ikkeDaekkedePrPost.put(a.postnr, postListe);
126                                    
127                            } else {
128                                     bbox = bbCache.get( a.postnr);
129                                     postListe = ikkeDaekkedePrPost.get(a.postnr);
130                            }
131                            
132                            bbox.latitudeMax = Math.max(bbox.latitudeMax, a.latitude);
133                            bbox.latitudeMin = Math.min(bbox.latitudeMin, a.latitude);
134                            bbox.longitudeMax = Math.max(bbox.longitudeMax, a.longitude);
135                            bbox.longitudeMin = Math.min(bbox.longitudeMin, a.longitude);
136                            
137                            postListe.add(a);
138                            
139                    }
140          }          }
141            
142          public List<Integer> hentPostnumre() throws SQLException {          public Queue<Adresse> hentIkkedaekkedeAdresserCache(int postnr)  {
143                  ArrayList<Integer> list = new ArrayList<Integer>();                  List<Adresse> postListe = ikkeDaekkedePrPost.get(postnr);
144                                    
145                  Constants consts = Constants.getInstance();                  return new ConcurrentLinkedQueue<Adresse>(postListe);          
146            }
147            
148                  String sql = "SELECT postnr " +          public Adresse[] hentDaekkedeAdresserCache( BoundingBox bbox, Adresse adresseListe[] ) {
149                                           "FROM fulddaekning.adressetabel " +                  long start = System.currentTimeMillis();
150                                           //"WHERE distributor = ? and rute is not null " +                  ArrayList<Adresse> list = new ArrayList<Adresse>();
151                                           "WHERE postnr BETWEEN ? AND ? " +                  for (Adresse a : adresseListe) {
152                                           "GROUP BY postnr " +                          if ( a.latitude > bbox.latitudeMin && a.latitude< bbox.latitudeMax && a.longitude> bbox.longitudeMin && a.longitude < bbox.longitudeMax) {
153                                           "ORDER by postnr";                                  list.add(a);
154                  PreparedStatement stmt = conn.prepareStatement(sql);                          }
                 //stmt.setString(1, Lookup.distributor );  
                 stmt.setInt(1, consts.getMinPostnr());  
                 stmt.setInt(2, consts.getMaxPostnr());  
                 ResultSet res = stmt.executeQuery();  
   
                 while (res.next()) {  
                         int postnr = res.getInt("postnr");  
                         list.add(postnr);  
155                  }                  }
156                  res.close();                  long stop = System.currentTimeMillis();
157                  stmt.close();                  logger.info("Elapsed cache: " + (stop - start));
158                    return list.toArray( new Adresse[ list.size() ] );              
                 //list.add(8700);  
   
                 return list;  
159          }          }
160    
161          public ArrayList<Adresse> hentDaekkedeAdresser( BoundingBox bbox) throws SQLException {          
162                  String sql = "SELECT id,postnr,adresse,gadeid,husnr,husnrbogstav,latitude,longitude,rute " +          public Adresse[] hentDaekkedeAdresserCache( BoundingBox bbox) {
163                                  "FROM fulddaekning.adressetabel " +                  return hentDaekkedeAdresserCache(bbox, alleAdresser);  
                                 "WHERE rute IS NOT NULL " +  
                                 "AND latitude BETWEEN ? AND ? " +  
                                 "AND longitude BETWEEN ? AND ? " +  
                                 "AND distributor = ? ";  
   
                 // Forward only + concur_read_only + fetchsize tvinger driver til at hente en række af gangen (bedre performance ved store result sets)  
                 // Se http://dev.mysql.com/doc/connector-j/en/connector-j-reference-implementation-notes.html  
                 //PreparedStatement stmt = conn.prepareStatement(sql);  
                 PreparedStatement stmt = conn.prepareStatement(sql, java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);  
                 stmt.setFetchSize(Integer.MIN_VALUE);  
   
                 stmt.setDouble(1, bbox.latitudeMin);  
                 stmt.setDouble(2, bbox.latitudeMax);  
                 stmt.setDouble(3, bbox.longitudeMin);  
                 stmt.setDouble(4, bbox.longitudeMax);  
                 stmt.setString(5, Lookup.distributor);  
   
                 return hentAdresseListe( stmt );  
   
164          }          }
165            
166            
167            
168            
169            public Adresse[] hentAlleDaekkedeAdresser() throws SQLException {
170                    if ( alleAdresser == null ) {
171                            String sql = "SELECT id,a.postnr,adresse,gadeid,husnr,husnrbogstav,latitude,longitude,rute,p.distributor as ho " +
172                                            "FROM fulddaekning.adressetabel a " +
173                                            "LEFT JOIN bogleveringer.postnummerdistributor p on (a.postnr=p.postnr) " +
174                                            "WHERE rute IS NOT NULL " +
175                                            "AND latitude IS NOT NULL " +
176                                            "AND longitude IS NOT NULL " +
177                                            "AND a.distributor = ? ";
178            
179                            // Forward only + concur_read_only + fetchsize tvinger driver til at hente en række af gangen (bedre performance ved store result sets)
180                            // Se http://dev.mysql.com/doc/connector-j/en/connector-j-reference-implementation-notes.html
181                            PreparedStatement stmt = conn.prepareStatement(sql, java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);
182                            stmt.setFetchSize(Integer.MIN_VALUE);
183            
184                            stmt.setString(1, LookupMain.distributor);
185            
186                            List<Adresse> list = hentAdresseListe( stmt );
187                            alleAdresser = list.toArray( new Adresse[ list.size() ] );
188                    }
189                    return alleAdresser;
190            }
191            
192            
193    
194          public synchronized void gemResultat(Adresse orgAdresse, Adresse bedsteAdresse, double bedsteAfstand) throws SQLException {          public synchronized void gemResultat(Adresse orgAdresse, Adresse bedsteAdresse, double bedsteAfstand) throws SQLException {
195                  /*String sql = "INSERT INTO fulddaekning.afstand_anden_rute_thn (orgId,orgPostnr, orgAdresse,orgGadeid,orgHusnr,orgHusnrBogstav,orgLatitude,orgLongitude,orgRute,id,postnr,adresse,gadeid,husnr,husnrbogstav,latitude,longitude,rute,afstand,`timestamp`) "+                  /*String sql = "INSERT INTO fulddaekning.afstand_anden_rute_thn (orgId,orgPostnr, orgAdresse,orgGadeid,orgHusnr,orgHusnrBogstav,orgLatitude,orgLongitude,orgRute,id,postnr,adresse,gadeid,husnr,husnrbogstav,latitude,longitude,rute,afstand,`timestamp`) "+
# Line 176  public class Database { Line 220  public class Database {
220    
221                  saveStmt.setDouble(19, bedsteAfstand);                  saveStmt.setDouble(19, bedsteAfstand);
222    
223                  saveStmt.executeUpdate();                        saveStmt.addBatch();
224                  saveStmt.clearParameters();                  batchCount++;
225                    if (batchCount >= 1000) {
226                            saveStmt.executeBatch();
227                            batchCount = 0;
228                    }
229                    //saveStmt.executeUpdate();    
230                    //saveStmt.clearParameters();
231    
232                  //saveStmt.close();                      //saveStmt.close();    
233            }
234            
235            public synchronized void saveBatch() throws SQLException{
236                    saveStmt.executeBatch();
237                    batchCount = 0;
238          }          }
239    
240    
241    
242          protected ArrayList<Adresse> hentAdresseListe(PreparedStatement stmt) throws SQLException{          protected ArrayList<Adresse> hentAdresseListe(PreparedStatement stmt) throws SQLException{
243                  ArrayList<Adresse> list = new ArrayList<Adresse>( 30000 );                  ArrayList<Adresse> list = new ArrayList<Adresse>( 1000000 );
244    
245                  //logger.info("Starting query");                  //logger.info("Starting query");
246                  ResultSet res = stmt.executeQuery();                  ResultSet res = stmt.executeQuery();
# Line 195  public class Database { Line 248  public class Database {
248    
249                  while (res.next()) {                  while (res.next()) {
250                          Adresse adr = new Adresse();                          Adresse adr = new Adresse();
251    
252                            /*
253                          adr.id = res.getInt("id");                          adr.id = res.getInt("id");
254                          adr.postnr = res.getInt("postnr");                          adr.postnr = res.getInt("postnr");
255                          adr.adresse = res.getString("adresse");                          adr.adresse = res.getString("adresse");
# Line 204  public class Database { Line 259  public class Database {
259                          adr.latitude = res.getDouble("latitude");                          adr.latitude = res.getDouble("latitude");
260                          adr.longitude = res.getDouble("longitude");                          adr.longitude = res.getDouble("longitude");
261                          adr.rute = res.getString("rute");                          adr.rute = res.getString("rute");
262                            adr.ho = res.getInt("ho");
263                            */
264            
265                            adr.id = res.getInt(1);
266                            adr.postnr = res.getInt(2);
267                            adr.adresse = res.getString(3);
268                            adr.gadeid = res.getInt(4);
269                            adr.husnr = res.getInt(5);
270                            adr.husnrbogstav = husnrbogstavCache.getInstance( res.getString(6) );
271                            adr.latitude = res.getDouble(7);
272                            adr.longitude = res.getDouble(8);
273                            adr.rute =  ruteCache.getInstance( res.getString(9) );
274                            adr.ho = res.getInt(10);
275    
276                          list.add(adr);                          list.add(adr);
277    
# Line 230  public class Database { Line 298  public class Database {
298              connectionProps.put("user", db_user);              connectionProps.put("user", db_user);
299              connectionProps.put("password", db_pass);              connectionProps.put("password", db_pass);
300    
301                //For debug output, tilføj denne til JDBC url'en: &profileSQL=true    
302              conn = DriverManager.getConnection(              conn = DriverManager.getConnection(
303                             "jdbc:mysql://" +                             "jdbc:mysql://" +
304                             db_host +                             db_host +
305                             ":3306/",                             ":3306/?rewriteBatchedStatements=true",
306                             connectionProps);                             connectionProps);
307              logger.info("Connected to database");              logger.info("Connected to database");
308              return conn;              return conn;
309          }          }
310    
311            
312            // //////////////////////////////////////////////////////////////////
313            /*
314            @Deprecated
315            private BoundingBox getBoundingboxFromDb_old(String postnr) throws SQLException {
316                    String minPostnr = postnr.replace('x', '0');
317                    String maxPostnr = postnr.replace('x', '9');
318    
319                    String sql =
320                                    "SELECT max(latitude) latmax, min(latitude) latmin, max(longitude) lngmax,min(longitude) lngmin  " +
321                                    "FROM fulddaekning.adressetabel WHERE postnr BETWEEN ? and ? and rute is null;";
322    
323                    PreparedStatement stmt = conn.prepareStatement(sql);
324                    stmt.setString(1, minPostnr);
325                    stmt.setString(2, maxPostnr);
326    
327                    ResultSet res = stmt.executeQuery();
328                    res.next(); //query returnerer altid 1 række
329    
330                    BoundingBox bbox = new BoundingBox();
331                    bbox.latitudeMax = res.getDouble("latmax");
332                    bbox.latitudeMin = res.getDouble("latmin");
333                    bbox.longitudeMax = res.getDouble("lngmax");
334                    bbox.longitudeMin = res.getDouble("lngmin");
335    
336                    res.close();
337                    stmt.close();
338    
339                    return bbox;
340            }
341    
342            @Deprecated
343            public Adresse[] hentDaekkedeAdresser_old( BoundingBox bbox) throws SQLException {
344                    long start = System.currentTimeMillis();
345                    String sql = "SELECT id,a.postnr,adresse,gadeid,husnr,husnrbogstav,latitude,longitude,rute,p.distributor as ho " +
346                                    "FROM fulddaekning.adressetabel a " +
347                                    "LEFT JOIN bogleveringer.postnummerdistributor p on (a.postnr=p.postnr) " +
348                                    "WHERE rute IS NOT NULL " +
349                                    "AND latitude BETWEEN ? AND ? " +
350                                    "AND longitude BETWEEN ? AND ? " +
351                                    "AND a.distributor = ? ";
352    
353                    // Forward only + concur_read_only + fetchsize tvinger driver til at hente en række af gangen (bedre performance ved store result sets)
354                    // Se http://dev.mysql.com/doc/connector-j/en/connector-j-reference-implementation-notes.html
355                    //PreparedStatement stmt = conn.prepareStatement(sql);
356                    PreparedStatement stmt = conn.prepareStatement(sql, java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);
357                    stmt.setFetchSize(Integer.MIN_VALUE);
358    
359                    stmt.setDouble(1, bbox.latitudeMin);
360                    stmt.setDouble(2, bbox.latitudeMax);
361                    stmt.setDouble(3, bbox.longitudeMin);
362                    stmt.setDouble(4, bbox.longitudeMax);
363                    stmt.setString(5, LookupMain.distributor);
364    
365                    List<Adresse> list = hentAdresseListe( stmt );
366                    long stop = System.currentTimeMillis();
367                    logger.info("Elapsed DB: " + (stop - start));
368                    return list.toArray( new Adresse[ list.size() ] );
369            }
370            
371            @Deprecated
372            public Queue<Adresse> hentIkkedaekkedeAdresser_old(String postnr)  throws SQLException {
373                    
374                    String minPostnr = postnr.replace('x', '0');
375                    String maxPostnr = postnr.replace('x', '9');
376                    
377                    ConcurrentLinkedQueue<Adresse> queue = new ConcurrentLinkedQueue<Adresse>();
378    
379                    String sql = "SELECT id,a.postnr,adresse,gadeid,husnr,husnrbogstav,latitude,longitude,rute,p.distributor as ho " +
380                                    "FROM fulddaekning.adressetabel a " +
381                                    "LEFT JOIN bogleveringer.postnummerdistributor p on (a.postnr=p.postnr) " +
382                                    "WHERE rute IS NULL " +  //Ingen dækning
383                                    "AND a.postnr BETWEEN ? AND ? " +
384                                    "AND latitude IS NOT NULL " +
385                                    "AND longitude IS NOT NULL " +
386                                    "AND gadeid IS NOT NULL " +
387                                    "AND (a.distributor IS NULL OR a.distributor<>'LUKKET') ";              
388                    PreparedStatement stmt = conn.prepareStatement(sql);
389                    stmt.setString(1, minPostnr);
390                    stmt.setString(2, maxPostnr);
391    
392                    queue.addAll( hentAdresseListe( stmt ) );
393                    return queue;
394            }
395            
396            @Deprecated
397            public List<String> hentPostnumre_old() throws SQLException {
398                    ArrayList<String> list = new ArrayList<String>();
399                    
400                    Constants consts = Constants.getInstance();
401    
402                    /*
403                    String sql = "SELECT postnr " +
404                                             "FROM fulddaekning.adressetabel " +
405                                             "WHERE postnr BETWEEN ? AND ? " +
406                                             "AND rute is null " + // Træk kun liste på postnumre hvor der er ikke-dækkede adresser
407                                             "GROUP BY postnr " +
408                                             "ORDER by postnr";
409                    * /
410                    
411                    
412                    String sql = "SELECT rpad(left(postnr,?),'4', 'x') as postnr2 " +
413                                             "FROM fulddaekning.adressetabel " +
414                                             "WHERE postnr BETWEEN ? AND ? " +
415                                             "AND rute is null " + // Trae kun liste paa postnumre hvor der er ikke-daekede adresser
416                                             "AND (postnr NOT BETWEEN 3900 and 3999) " + //Skip alle groenlandske postnumre
417                                             "GROUP BY postnr2 " +
418                                             "ORDER by postnr2 ";
419                    
420                                            
421                                            
422                    PreparedStatement stmt = conn.prepareStatement(sql);
423                    //stmt.setString(1, Lookup.distributor );
424    
425                    stmt.setInt(1, consts.getPostnrGroup() );
426    
427                    stmt.setInt(2, consts.getMinPostnr());
428                    stmt.setInt(3, consts.getMaxPostnr());
429                    ResultSet res = stmt.executeQuery();
430    
431                    while (res.next()) {
432                            String postnr = res.getString("postnr2");
433                            list.add(postnr);
434                    }
435                    res.close();
436                    stmt.close();
437    
438                    //list.add(8700);
439    
440                    return list;
441            }*/
442    
443            
444  }  }

Legend:
Removed from v.2203  
changed lines
  Added in v.2424

  ViewVC Help
Powered by ViewVC 1.1.20