/[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 2423 by torben, Tue Mar 3 08:30:02 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);                
         }        
   
         public BoundingBox getBoundingbox(int postnr) throws SQLException {  
   
                 String sql =  
                                 "SELECT max(latitude) latmax, min(latitude) latmin, max(longitude) lngmax,min(longitude) lngmin  " +  
                                 "FROM fulddaekning.adressetabel WHERE postnr=? and rute is null;";  
   
                 PreparedStatement stmt = conn.prepareStatement(sql);  
                 stmt.setInt(1, postnr);  
   
                 ResultSet res = stmt.executeQuery();  
                 res.next(); //query returnerer altid 1 række  
   
                 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();  
74    
75                  return bbox;                  logger.info("Executing: " + sql);
76                    conn.createStatement().executeUpdate(sql);              
77            }
78            
79            public BoundingBox getBoundingbox(int postnr)  {
80                    BoundingBox bb = bbCache.get(postnr);
81                    return bb.clone();//never return the original / cached object
82            }
83            
84            
85            public Set<Integer> hentPostnumreCache() {
86                    return postnumre;
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            }
   
                 String sql = "SELECT postnr " +  
                                          "FROM fulddaekning.adressetabel " +  
                                          //"WHERE distributor = ? and rute is not null " +  
                                          "WHERE postnr BETWEEN ? AND ? " +  
                                          "GROUP BY postnr " +  
                                          "ORDER by postnr";  
                 PreparedStatement stmt = conn.prepareStatement(sql);  
                 //stmt.setString(1, Lookup.distributor );  
                 stmt.setInt(1, consts.getMinPostnr());  
                 stmt.setInt(2, consts.getMaxPostnr());  
                 ResultSet res = stmt.executeQuery();  
147    
148                  while (res.next()) {          
149                          int postnr = res.getInt("postnr");          public Adresse[] hentDaekkedeAdresserCache( BoundingBox bbox) {
150                          list.add(postnr);                  long start = System.currentTimeMillis();
151                    ArrayList<Adresse> list = new ArrayList<Adresse>();
152                    for (Adresse a : alleAdresser) {
153                            if ( a.latitude > bbox.latitudeMin && a.latitude< bbox.latitudeMax && a.longitude> bbox.longitudeMin && a.longitude < bbox.longitudeMax) {
154                                    list.add(a);
155                            }
156                  }                  }
157                  res.close();                  long stop = System.currentTimeMillis();
158                  stmt.close();                  logger.info("Elapsed cache: " + (stop - start));
159                    return list.toArray( new Adresse[ list.size() ] );              
                 //list.add(8700);  
   
                 return list;  
160          }          }
161            
162          public ArrayList<Adresse> hentDaekkedeAdresser( BoundingBox bbox) throws SQLException {          
163                  String sql = "SELECT id,postnr,adresse,gadeid,husnr,husnrbogstav,latitude,longitude,rute " +          public Adresse[] hentAlleDaekkedeAdresser() throws SQLException {
164                                  "FROM fulddaekning.adressetabel " +                  if ( alleAdresser == null ) {
165                                  "WHERE rute IS NOT NULL " +                          String sql = "SELECT id,a.postnr,adresse,gadeid,husnr,husnrbogstav,latitude,longitude,rute,p.distributor as ho " +
166                                  "AND latitude BETWEEN ? AND ? " +                                          "FROM fulddaekning.adressetabel a " +
167                                  "AND longitude BETWEEN ? AND ? " +                                          "LEFT JOIN bogleveringer.postnummerdistributor p on (a.postnr=p.postnr) " +
168                                  "AND distributor = ? ";                                          "WHERE rute IS NOT NULL " +
169                                            "AND latitude IS NOT NULL " +
170                  // Forward only + concur_read_only + fetchsize tvinger driver til at hente en række af gangen (bedre performance ved store result sets)                                          "AND longitude IS NOT NULL " +
171                  // Se http://dev.mysql.com/doc/connector-j/en/connector-j-reference-implementation-notes.html                                          "AND a.distributor = ? ";
172                  //PreparedStatement stmt = conn.prepareStatement(sql);          
173                  PreparedStatement stmt = conn.prepareStatement(sql, java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);                          // Forward only + concur_read_only + fetchsize tvinger driver til at hente en række af gangen (bedre performance ved store result sets)
174                  stmt.setFetchSize(Integer.MIN_VALUE);                          // Se http://dev.mysql.com/doc/connector-j/en/connector-j-reference-implementation-notes.html
175                            PreparedStatement stmt = conn.prepareStatement(sql, java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);
176                  stmt.setDouble(1, bbox.latitudeMin);                          stmt.setFetchSize(Integer.MIN_VALUE);
177                  stmt.setDouble(2, bbox.latitudeMax);          
178                  stmt.setDouble(3, bbox.longitudeMin);                          stmt.setString(1, LookupMain.distributor);
179                  stmt.setDouble(4, bbox.longitudeMax);          
180                  stmt.setString(5, Lookup.distributor);                          List<Adresse> list = hentAdresseListe( stmt );
181                            alleAdresser = list.toArray( new Adresse[ list.size() ] );
182                  return hentAdresseListe( stmt );                  }
183                    return alleAdresser;
184          }          }
185            
186            
187    
188          public synchronized void gemResultat(Adresse orgAdresse, Adresse bedsteAdresse, double bedsteAfstand) throws SQLException {          public synchronized void gemResultat(Adresse orgAdresse, Adresse bedsteAdresse, double bedsteAfstand) throws SQLException {
189                  /*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 214  public class Database {
214    
215                  saveStmt.setDouble(19, bedsteAfstand);                  saveStmt.setDouble(19, bedsteAfstand);
216    
217                  saveStmt.executeUpdate();                        saveStmt.addBatch();
218                  saveStmt.clearParameters();                  batchCount++;
219                    if (batchCount >= 1000) {
220                            saveStmt.executeBatch();
221                            batchCount = 0;
222                    }
223                    //saveStmt.executeUpdate();    
224                    //saveStmt.clearParameters();
225    
226                  //saveStmt.close();                      //saveStmt.close();    
227            }
228            
229            public synchronized void saveBatch() throws SQLException{
230                    saveStmt.executeBatch();
231                    batchCount = 0;
232          }          }
233    
234    
235    
236          protected ArrayList<Adresse> hentAdresseListe(PreparedStatement stmt) throws SQLException{          protected ArrayList<Adresse> hentAdresseListe(PreparedStatement stmt) throws SQLException{
237                  ArrayList<Adresse> list = new ArrayList<Adresse>( 30000 );                  ArrayList<Adresse> list = new ArrayList<Adresse>( 1000000 );
238    
239                  //logger.info("Starting query");                  //logger.info("Starting query");
240                  ResultSet res = stmt.executeQuery();                  ResultSet res = stmt.executeQuery();
# Line 195  public class Database { Line 242  public class Database {
242    
243                  while (res.next()) {                  while (res.next()) {
244                          Adresse adr = new Adresse();                          Adresse adr = new Adresse();
245    
246                            /*
247                          adr.id = res.getInt("id");                          adr.id = res.getInt("id");
248                          adr.postnr = res.getInt("postnr");                          adr.postnr = res.getInt("postnr");
249                          adr.adresse = res.getString("adresse");                          adr.adresse = res.getString("adresse");
# Line 204  public class Database { Line 253  public class Database {
253                          adr.latitude = res.getDouble("latitude");                          adr.latitude = res.getDouble("latitude");
254                          adr.longitude = res.getDouble("longitude");                          adr.longitude = res.getDouble("longitude");
255                          adr.rute = res.getString("rute");                          adr.rute = res.getString("rute");
256                            adr.ho = res.getInt("ho");
257                            */
258            
259                            adr.id = res.getInt(1);
260                            adr.postnr = res.getInt(2);
261                            adr.adresse = res.getString(3);
262                            adr.gadeid = res.getInt(4);
263                            adr.husnr = res.getInt(5);
264                            adr.husnrbogstav = husnrbogstavCache.getInstance( res.getString(6) );
265                            adr.latitude = res.getDouble(7);
266                            adr.longitude = res.getDouble(8);
267                            adr.rute =  ruteCache.getInstance( res.getString(9) );
268                            adr.ho = res.getInt(10);
269    
270                          list.add(adr);                          list.add(adr);
271    
# Line 230  public class Database { Line 292  public class Database {
292              connectionProps.put("user", db_user);              connectionProps.put("user", db_user);
293              connectionProps.put("password", db_pass);              connectionProps.put("password", db_pass);
294    
295                //For debug output, tilføj denne til JDBC url'en: &profileSQL=true    
296              conn = DriverManager.getConnection(              conn = DriverManager.getConnection(
297                             "jdbc:mysql://" +                             "jdbc:mysql://" +
298                             db_host +                             db_host +
299                             ":3306/",                             ":3306/?rewriteBatchedStatements=true",
300                             connectionProps);                             connectionProps);
301              logger.info("Connected to database");              logger.info("Connected to database");
302              return conn;              return conn;
303          }          }
304    
305            
306            // //////////////////////////////////////////////////////////////////
307            /*
308            @Deprecated
309            private BoundingBox getBoundingboxFromDb_old(String postnr) throws SQLException {
310                    String minPostnr = postnr.replace('x', '0');
311                    String maxPostnr = postnr.replace('x', '9');
312    
313                    String sql =
314                                    "SELECT max(latitude) latmax, min(latitude) latmin, max(longitude) lngmax,min(longitude) lngmin  " +
315                                    "FROM fulddaekning.adressetabel WHERE postnr BETWEEN ? and ? and rute is null;";
316    
317                    PreparedStatement stmt = conn.prepareStatement(sql);
318                    stmt.setString(1, minPostnr);
319                    stmt.setString(2, maxPostnr);
320    
321                    ResultSet res = stmt.executeQuery();
322                    res.next(); //query returnerer altid 1 række
323    
324                    BoundingBox bbox = new BoundingBox();
325                    bbox.latitudeMax = res.getDouble("latmax");
326                    bbox.latitudeMin = res.getDouble("latmin");
327                    bbox.longitudeMax = res.getDouble("lngmax");
328                    bbox.longitudeMin = res.getDouble("lngmin");
329    
330                    res.close();
331                    stmt.close();
332    
333                    return bbox;
334            }
335    
336            @Deprecated
337            public Adresse[] hentDaekkedeAdresser_old( BoundingBox bbox) throws SQLException {
338                    long start = System.currentTimeMillis();
339                    String sql = "SELECT id,a.postnr,adresse,gadeid,husnr,husnrbogstav,latitude,longitude,rute,p.distributor as ho " +
340                                    "FROM fulddaekning.adressetabel a " +
341                                    "LEFT JOIN bogleveringer.postnummerdistributor p on (a.postnr=p.postnr) " +
342                                    "WHERE rute IS NOT NULL " +
343                                    "AND latitude BETWEEN ? AND ? " +
344                                    "AND longitude BETWEEN ? AND ? " +
345                                    "AND a.distributor = ? ";
346    
347                    // Forward only + concur_read_only + fetchsize tvinger driver til at hente en række af gangen (bedre performance ved store result sets)
348                    // Se http://dev.mysql.com/doc/connector-j/en/connector-j-reference-implementation-notes.html
349                    //PreparedStatement stmt = conn.prepareStatement(sql);
350                    PreparedStatement stmt = conn.prepareStatement(sql, java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);
351                    stmt.setFetchSize(Integer.MIN_VALUE);
352    
353                    stmt.setDouble(1, bbox.latitudeMin);
354                    stmt.setDouble(2, bbox.latitudeMax);
355                    stmt.setDouble(3, bbox.longitudeMin);
356                    stmt.setDouble(4, bbox.longitudeMax);
357                    stmt.setString(5, LookupMain.distributor);
358    
359                    List<Adresse> list = hentAdresseListe( stmt );
360                    long stop = System.currentTimeMillis();
361                    logger.info("Elapsed DB: " + (stop - start));
362                    return list.toArray( new Adresse[ list.size() ] );
363            }
364            
365            @Deprecated
366            public Queue<Adresse> hentIkkedaekkedeAdresser_old(String postnr)  throws SQLException {
367                    
368                    String minPostnr = postnr.replace('x', '0');
369                    String maxPostnr = postnr.replace('x', '9');
370                    
371                    ConcurrentLinkedQueue<Adresse> queue = new ConcurrentLinkedQueue<Adresse>();
372    
373                    String sql = "SELECT id,a.postnr,adresse,gadeid,husnr,husnrbogstav,latitude,longitude,rute,p.distributor as ho " +
374                                    "FROM fulddaekning.adressetabel a " +
375                                    "LEFT JOIN bogleveringer.postnummerdistributor p on (a.postnr=p.postnr) " +
376                                    "WHERE rute IS NULL " +  //Ingen dækning
377                                    "AND a.postnr BETWEEN ? AND ? " +
378                                    "AND latitude IS NOT NULL " +
379                                    "AND longitude IS NOT NULL " +
380                                    "AND gadeid IS NOT NULL " +
381                                    "AND (a.distributor IS NULL OR a.distributor<>'LUKKET') ";              
382                    PreparedStatement stmt = conn.prepareStatement(sql);
383                    stmt.setString(1, minPostnr);
384                    stmt.setString(2, maxPostnr);
385    
386                    queue.addAll( hentAdresseListe( stmt ) );
387                    return queue;
388            }
389            
390            @Deprecated
391            public List<String> hentPostnumre_old() throws SQLException {
392                    ArrayList<String> list = new ArrayList<String>();
393                    
394                    Constants consts = Constants.getInstance();
395    
396                    /*
397                    String sql = "SELECT postnr " +
398                                             "FROM fulddaekning.adressetabel " +
399                                             "WHERE postnr BETWEEN ? AND ? " +
400                                             "AND rute is null " + // Træk kun liste på postnumre hvor der er ikke-dækkede adresser
401                                             "GROUP BY postnr " +
402                                             "ORDER by postnr";
403                    * /
404                    
405                    
406                    String sql = "SELECT rpad(left(postnr,?),'4', 'x') as postnr2 " +
407                                             "FROM fulddaekning.adressetabel " +
408                                             "WHERE postnr BETWEEN ? AND ? " +
409                                             "AND rute is null " + // Trae kun liste paa postnumre hvor der er ikke-daekede adresser
410                                             "AND (postnr NOT BETWEEN 3900 and 3999) " + //Skip alle groenlandske postnumre
411                                             "GROUP BY postnr2 " +
412                                             "ORDER by postnr2 ";
413                    
414                                            
415                                            
416                    PreparedStatement stmt = conn.prepareStatement(sql);
417                    //stmt.setString(1, Lookup.distributor );
418    
419                    stmt.setInt(1, consts.getPostnrGroup() );
420    
421                    stmt.setInt(2, consts.getMinPostnr());
422                    stmt.setInt(3, consts.getMaxPostnr());
423                    ResultSet res = stmt.executeQuery();
424    
425                    while (res.next()) {
426                            String postnr = res.getString("postnr2");
427                            list.add(postnr);
428                    }
429                    res.close();
430                    stmt.close();
431    
432                    //list.add(8700);
433    
434                    return list;
435            }*/
436    
437            
438  }  }

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

  ViewVC Help
Powered by ViewVC 1.1.20