/[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 2327 by torben, Thu Feb 19 10:36:40 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.Properties;  import java.util.Properties;
13  import java.util.Queue;  import java.util.Queue;
# Line 14  import java.util.concurrent.ConcurrentLi Line 15  import java.util.concurrent.ConcurrentLi
15  import java.util.logging.Logger;  import java.util.logging.Logger;
16    
17    
18    
19  public class Database {  public class Database {
20          Logger logger = Logger.getLogger(Database.class.getName());          Logger logger = Logger.getLogger(Database.class.getName());
21    
22            int batchCount = 0;
23    
24          Connection conn;          Connection conn;
25          PreparedStatement saveStmt;          PreparedStatement saveStmt;
26            
27            Adresse alleAdresser[];
28            
29            DeduplicateHelper<String> husnrbogstavCache = new DeduplicateHelper<String>();
30            DeduplicateHelper<String> ruteCache = new DeduplicateHelper<String>();
31            
32            private HashMap<String,BoundingBox> bbCache = new HashMap<String,BoundingBox>();
33    
34          public Database(SafeProperties conf)  throws SQLException,IOException {          public Database(SafeProperties conf)  throws SQLException,IOException {
35                  this.conn = getConnection( conf );                        this.conn = getConnection( conf );      
# Line 42  public class Database { Line 52  public class Database {
52          }                }      
53                    
54          public void renameResultTables() throws SQLException {          public void renameResultTables() throws SQLException {
55                    Constants consts = Constants.getInstance();
56                    String ext = consts.getTableExtension();
57                    
58                  logger.info("Dropping old backup table (if exists)");                  logger.info("Dropping old backup table (if exists)");
59                  String sql = "DROP TABLE IF EXISTS fulddaekning.afstand_anden_rute_old";                  String sql = "DROP TABLE IF EXISTS fulddaekning.afstand_anden_rute_old" + ext;
60                  conn.createStatement().executeUpdate(sql);                  conn.createStatement().executeUpdate(sql);
61                                    
62                  logger.info("Rename tables");                  logger.info("Rename tables");
63                  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;
64    
65                    logger.info("Executing: " + sql);
66                  conn.createStatement().executeUpdate(sql);                                conn.createStatement().executeUpdate(sql);              
67          }                }
68            
69            public BoundingBox getBoundingbox(String postnr) throws SQLException {
70                    BoundingBox bb = bbCache.get(postnr);
71                    if ( bb == null ) {
72                            bb = getBoundingboxFromDb(postnr);
73                            bbCache.put(postnr, bb);
74                    } else {
75                            logger.info("Serving BB from cache");
76                    }
77                    
78                    return bb.clone();//never return the original / cached object
79            }
80    
81          public BoundingBox getBoundingbox(int postnr) throws SQLException {          private BoundingBox getBoundingboxFromDb(String postnr) throws SQLException {
82                    String minPostnr = postnr.replace('x', '0');
83                    String maxPostnr = postnr.replace('x', '9');
84    
85                  String sql =                  String sql =
86                                  "SELECT max(latitude) latmax, min(latitude) latmin, max(longitude) lngmax,min(longitude) lngmin  " +                                  "SELECT max(latitude) latmax, min(latitude) latmin, max(longitude) lngmax,min(longitude) lngmin  " +
87                                  "FROM fulddaekning.adressetabel WHERE postnr=? and rute is null;";                                  "FROM fulddaekning.adressetabel WHERE postnr BETWEEN ? and ? and rute is null;";
88    
89                  PreparedStatement stmt = conn.prepareStatement(sql);                  PreparedStatement stmt = conn.prepareStatement(sql);
90                  stmt.setInt(1, postnr);                  stmt.setString(1, minPostnr);
91                    stmt.setString(2, maxPostnr);
92    
93                  ResultSet res = stmt.executeQuery();                  ResultSet res = stmt.executeQuery();
94                  res.next(); //query returnerer altid 1 række                  res.next(); //query returnerer altid 1 række
# Line 74  public class Database { Line 104  public class Database {
104    
105                  return bbox;                  return bbox;
106          }          }
107            
108            
109    
110          public Queue<Adresse> hentIkkedaekkedeAdresser(int postnr)  throws SQLException {          public Queue<Adresse> hentIkkedaekkedeAdresser(String postnr)  throws SQLException {
111                    
112                    String minPostnr = postnr.replace('x', '0');
113                    String maxPostnr = postnr.replace('x', '9');
114                    
115                  ConcurrentLinkedQueue<Adresse> queue = new ConcurrentLinkedQueue<Adresse>();                  ConcurrentLinkedQueue<Adresse> queue = new ConcurrentLinkedQueue<Adresse>();
116    
117                  String sql = "SELECT id,postnr,adresse,gadeid,husnr,husnrbogstav,latitude,longitude,rute " +                  String sql = "SELECT id,a.postnr,adresse,gadeid,husnr,husnrbogstav,latitude,longitude,rute,p.distributor as ho " +
118                                  "FROM fulddaekning.adressetabel " +                                  "FROM fulddaekning.adressetabel a " +
119                                    "LEFT JOIN bogleveringer.postnummerdistributor p on (a.postnr=p.postnr) " +
120                                  "WHERE rute IS NULL " +  //Ingen dækning                                  "WHERE rute IS NULL " +  //Ingen dækning
121                                  "AND postnr=?  " +                                  "AND a.postnr BETWEEN ? AND ? " +
122                                  "AND latitude IS NOT NULL " +                                  "AND latitude IS NOT NULL " +
123                                  "AND longitude IS NOT NULL " +                                  "AND longitude IS NOT NULL " +
124                                  "AND gadeid IS NOT NULL ";                                  "AND gadeid IS NOT NULL " +
125                                    "AND (a.distributor IS NULL OR a.distributor<>'LUKKET') ";              
126                  PreparedStatement stmt = conn.prepareStatement(sql);                  PreparedStatement stmt = conn.prepareStatement(sql);
127                  stmt.setInt(1, postnr);                  stmt.setString(1, minPostnr);
128                    stmt.setString(2, maxPostnr);
129    
130                  queue.addAll( hentAdresseListe( stmt ) );                  queue.addAll( hentAdresseListe( stmt ) );
131                  return queue;                  return queue;
132          }          }
133    
134          public List<Integer> hentPostnumre() throws SQLException {          public List<String> hentPostnumre() throws SQLException {
135                  ArrayList<Integer> list = new ArrayList<Integer>();                  ArrayList<String> list = new ArrayList<String>();
136                                    
137                  Constants consts = Constants.getInstance();                  Constants consts = Constants.getInstance();
138    
139                    /*
140                  String sql = "SELECT postnr " +                  String sql = "SELECT postnr " +
141                                           "FROM fulddaekning.adressetabel " +                                           "FROM fulddaekning.adressetabel " +
                                          //"WHERE distributor = ? and rute is not null " +  
142                                           "WHERE postnr BETWEEN ? AND ? " +                                           "WHERE postnr BETWEEN ? AND ? " +
143                                             "AND rute is null " + // Træk kun liste på postnumre hvor der er ikke-dækkede adresser
144                                           "GROUP BY postnr " +                                           "GROUP BY postnr " +
145                                           "ORDER by postnr";                                           "ORDER by postnr";
146                    */
147                    
148                    
149                    String sql = "SELECT rpad(left(postnr,?),'4', 'x') as postnr2 " +
150                                             "FROM fulddaekning.adressetabel " +
151                                             "WHERE postnr BETWEEN ? AND ? " +
152                                             "AND rute is null " + // Trae kun liste paa postnumre hvor der er ikke-daekede adresser
153                                             "AND (postnr NOT BETWEEN 3900 and 3999) " + //Skip alle groenlandske postnumre
154                                             "GROUP BY postnr2 " +
155                                             "ORDER by postnr2 ";
156                    
157                                            
158                                            
159                  PreparedStatement stmt = conn.prepareStatement(sql);                  PreparedStatement stmt = conn.prepareStatement(sql);
160                  //stmt.setString(1, Lookup.distributor );                  //stmt.setString(1, Lookup.distributor );
161                  stmt.setInt(1, consts.getMinPostnr());  
162                  stmt.setInt(2, consts.getMaxPostnr());                  stmt.setInt(1, consts.getPostnrGroup() );
163    
164                    stmt.setInt(2, consts.getMinPostnr());
165                    stmt.setInt(3, consts.getMaxPostnr());
166                  ResultSet res = stmt.executeQuery();                  ResultSet res = stmt.executeQuery();
167    
168                  while (res.next()) {                  while (res.next()) {
169                          int postnr = res.getInt("postnr");                          String postnr = res.getString("postnr2");
170                          list.add(postnr);                          list.add(postnr);
171                  }                  }
172                  res.close();                  res.close();
# Line 122  public class Database { Line 177  public class Database {
177                  return list;                  return list;
178          }          }
179    
180          public ArrayList<Adresse> hentDaekkedeAdresser( BoundingBox bbox) throws SQLException {          @Deprecated
181                  String sql = "SELECT id,postnr,adresse,gadeid,husnr,husnrbogstav,latitude,longitude,rute " +          public Adresse[] hentDaekkedeAdresser( BoundingBox bbox) throws SQLException {
182                                  "FROM fulddaekning.adressetabel " +                  long start = System.currentTimeMillis();
183                    String sql = "SELECT id,a.postnr,adresse,gadeid,husnr,husnrbogstav,latitude,longitude,rute,p.distributor as ho " +
184                                    "FROM fulddaekning.adressetabel a " +
185                                    "LEFT JOIN bogleveringer.postnummerdistributor p on (a.postnr=p.postnr) " +
186                                  "WHERE rute IS NOT NULL " +                                  "WHERE rute IS NOT NULL " +
187                                  "AND latitude BETWEEN ? AND ? " +                                  "AND latitude BETWEEN ? AND ? " +
188                                  "AND longitude BETWEEN ? AND ? " +                                  "AND longitude BETWEEN ? AND ? " +
189                                  "AND distributor = ? ";                                  "AND a.distributor = ? ";
190    
191                  // Forward only + concur_read_only + fetchsize tvinger driver til at hente en række af gangen (bedre performance ved store result sets)                  // Forward only + concur_read_only + fetchsize tvinger driver til at hente en række af gangen (bedre performance ved store result sets)
192                  // Se http://dev.mysql.com/doc/connector-j/en/connector-j-reference-implementation-notes.html                  // Se http://dev.mysql.com/doc/connector-j/en/connector-j-reference-implementation-notes.html
# Line 140  public class Database { Line 198  public class Database {
198                  stmt.setDouble(2, bbox.latitudeMax);                  stmt.setDouble(2, bbox.latitudeMax);
199                  stmt.setDouble(3, bbox.longitudeMin);                  stmt.setDouble(3, bbox.longitudeMin);
200                  stmt.setDouble(4, bbox.longitudeMax);                  stmt.setDouble(4, bbox.longitudeMax);
201                  stmt.setString(5, Lookup.distributor);                  stmt.setString(5, LookupMain.distributor);
   
                 return hentAdresseListe( stmt );  
202    
203                    List<Adresse> list = hentAdresseListe( stmt );
204                    long stop = System.currentTimeMillis();
205                    logger.info("Elapsed DB: " + (stop - start));
206                    return list.toArray( new Adresse[ list.size() ] );
207          }          }
208            
209            public Adresse[] hentDaekkedeAdresserCache( BoundingBox bbox) {
210                    long start = System.currentTimeMillis();
211                    ArrayList<Adresse> list = new ArrayList<Adresse>();
212                    for (Adresse a : alleAdresser) {
213                            if ( a.latitude > bbox.latitudeMin && a.latitude< bbox.latitudeMax && a.longitude> bbox.longitudeMin && a.longitude < bbox.longitudeMax) {
214                                    list.add(a);
215                            }
216                    }
217                    long stop = System.currentTimeMillis();
218                    logger.info("Elapsed cache: " + (stop - start));
219                    return list.toArray( new Adresse[ list.size() ] );              
220            }
221            
222            
223            public Adresse[] hentAlleDaekkedeAdresser() throws SQLException {
224                    if ( alleAdresser == null ) {
225                            String sql = "SELECT id,a.postnr,adresse,gadeid,husnr,husnrbogstav,latitude,longitude,rute,p.distributor as ho " +
226                                            "FROM fulddaekning.adressetabel a " +
227                                            "LEFT JOIN bogleveringer.postnummerdistributor p on (a.postnr=p.postnr) " +
228                                            "WHERE rute IS NOT NULL " +
229                                            "AND latitude IS NOT NULL " +
230                                            "AND longitude IS NOT NULL " +
231                                            "AND a.distributor = ? ";
232            
233                            // Forward only + concur_read_only + fetchsize tvinger driver til at hente en række af gangen (bedre performance ved store result sets)
234                            // Se http://dev.mysql.com/doc/connector-j/en/connector-j-reference-implementation-notes.html
235                            //PreparedStatement stmt = conn.prepareStatement(sql);
236                            PreparedStatement stmt = conn.prepareStatement(sql, java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);
237                            stmt.setFetchSize(Integer.MIN_VALUE);
238            
239                            stmt.setString(1, LookupMain.distributor);
240            
241                            List<Adresse> list = hentAdresseListe( stmt );
242                            alleAdresser = list.toArray( new Adresse[ list.size() ] );
243                    }
244                    return alleAdresser;
245            }
246            
247            
248    
249          public synchronized void gemResultat(Adresse orgAdresse, Adresse bedsteAdresse, double bedsteAfstand) throws SQLException {          public synchronized void gemResultat(Adresse orgAdresse, Adresse bedsteAdresse, double bedsteAfstand) throws SQLException {
250                  /*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 275  public class Database {
275    
276                  saveStmt.setDouble(19, bedsteAfstand);                  saveStmt.setDouble(19, bedsteAfstand);
277    
278                  saveStmt.executeUpdate();                        saveStmt.addBatch();
279                  saveStmt.clearParameters();                  batchCount++;
280                    if (batchCount >= 100) {
281                            saveStmt.executeBatch();
282                            batchCount = 0;
283                    }
284                    //saveStmt.executeUpdate();    
285                    //saveStmt.clearParameters();
286    
287                  //saveStmt.close();                      //saveStmt.close();    
288            }
289            
290            public synchronized void saveBatch() throws SQLException{
291                    saveStmt.executeBatch();
292                    batchCount = 0;
293          }          }
294    
295    
296    
297          protected ArrayList<Adresse> hentAdresseListe(PreparedStatement stmt) throws SQLException{          protected ArrayList<Adresse> hentAdresseListe(PreparedStatement stmt) throws SQLException{
298                  ArrayList<Adresse> list = new ArrayList<Adresse>( 30000 );                  ArrayList<Adresse> list = new ArrayList<Adresse>( 1000000 );
299    
300                  //logger.info("Starting query");                  //logger.info("Starting query");
301                  ResultSet res = stmt.executeQuery();                  ResultSet res = stmt.executeQuery();
# Line 195  public class Database { Line 303  public class Database {
303    
304                  while (res.next()) {                  while (res.next()) {
305                          Adresse adr = new Adresse();                          Adresse adr = new Adresse();
306    
307                            /*
308                          adr.id = res.getInt("id");                          adr.id = res.getInt("id");
309                          adr.postnr = res.getInt("postnr");                          adr.postnr = res.getInt("postnr");
310                          adr.adresse = res.getString("adresse");                          adr.adresse = res.getString("adresse");
# Line 204  public class Database { Line 314  public class Database {
314                          adr.latitude = res.getDouble("latitude");                          adr.latitude = res.getDouble("latitude");
315                          adr.longitude = res.getDouble("longitude");                          adr.longitude = res.getDouble("longitude");
316                          adr.rute = res.getString("rute");                          adr.rute = res.getString("rute");
317                            adr.ho = res.getInt("ho");
318                            */
319            
320                            adr.id = res.getInt(1);
321                            adr.postnr = res.getInt(2);
322                            adr.adresse = res.getString(3);
323                            adr.gadeid = res.getInt(4);
324                            adr.husnr = res.getInt(5);
325                            adr.husnrbogstav = husnrbogstavCache.getInstance( res.getString(6) );
326                            adr.latitude = res.getDouble(7);
327                            adr.longitude = res.getDouble(8);
328                            adr.rute =  ruteCache.getInstance( res.getString(9) );
329                            adr.ho = res.getInt(10);
330    
331                          list.add(adr);                          list.add(adr);
332    
# Line 230  public class Database { Line 353  public class Database {
353              connectionProps.put("user", db_user);              connectionProps.put("user", db_user);
354              connectionProps.put("password", db_pass);              connectionProps.put("password", db_pass);
355    
356                //For debug output, tilføj denne til JDBC url'en: &profileSQL=true    
357              conn = DriverManager.getConnection(              conn = DriverManager.getConnection(
358                             "jdbc:mysql://" +                             "jdbc:mysql://" +
359                             db_host +                             db_host +
360                             ":3306/",                             ":3306/?rewriteBatchedStatements=true",
361                             connectionProps);                             connectionProps);
362              logger.info("Connected to database");              logger.info("Connected to database");
363              return conn;              return conn;

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

  ViewVC Help
Powered by ViewVC 1.1.20