/[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 2247 by torben, Mon Dec 15 11:12:21 2014 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            private HashMap<String,BoundingBox> bbCache = new HashMap<String,BoundingBox>();
28    
29          public Database(SafeProperties conf)  throws SQLException,IOException {          public Database(SafeProperties conf)  throws SQLException,IOException {
30                  this.conn = getConnection( conf );                        this.conn = getConnection( conf );      
# Line 42  public class Database { Line 47  public class Database {
47          }                }      
48                    
49          public void renameResultTables() throws SQLException {          public void renameResultTables() throws SQLException {
50                    Constants consts = Constants.getInstance();
51                    String ext = consts.getTableExtension();
52                    
53                  logger.info("Dropping old backup table (if exists)");                  logger.info("Dropping old backup table (if exists)");
54                  String sql = "DROP TABLE IF EXISTS fulddaekning.afstand_anden_rute_old";                  String sql = "DROP TABLE IF EXISTS fulddaekning.afstand_anden_rute_old" + ext;
55                  conn.createStatement().executeUpdate(sql);                  conn.createStatement().executeUpdate(sql);
56                                    
57                  logger.info("Rename tables");                  logger.info("Rename tables");
58                  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;
59    
60                    logger.info("Executing: " + sql);
61                  conn.createStatement().executeUpdate(sql);                                conn.createStatement().executeUpdate(sql);              
62          }                }
63            
64            public BoundingBox getBoundingbox(String postnr) throws SQLException {
65                    BoundingBox bb = bbCache.get(postnr);
66                    if ( bb == null ) {
67                            bb = getBoundingboxFromDb(postnr);
68                            bbCache.put(postnr, bb);
69                    }
70                    
71                    return bb.clone();//never return the original / cached object
72            }
73    
74          public BoundingBox getBoundingbox(int postnr) throws SQLException {          private BoundingBox getBoundingboxFromDb(String postnr) throws SQLException {
75                    String minPostnr = postnr.replace('x', '0');
76                    String maxPostnr = postnr.replace('x', '9');
77    
78                  String sql =                  String sql =
79                                  "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  " +
80                                  "FROM fulddaekning.adressetabel WHERE postnr=? and rute is null;";                                  "FROM fulddaekning.adressetabel WHERE postnr BETWEEN ? and ? and rute is null;";
81    
82                  PreparedStatement stmt = conn.prepareStatement(sql);                  PreparedStatement stmt = conn.prepareStatement(sql);
83                  stmt.setInt(1, postnr);                  stmt.setString(1, minPostnr);
84                    stmt.setString(2, maxPostnr);
85    
86                  ResultSet res = stmt.executeQuery();                  ResultSet res = stmt.executeQuery();
87                  res.next(); //query returnerer altid 1 række                  res.next(); //query returnerer altid 1 række
# Line 74  public class Database { Line 97  public class Database {
97    
98                  return bbox;                  return bbox;
99          }          }
100            
101            
102    
103          public Queue<Adresse> hentIkkedaekkedeAdresser(int postnr)  throws SQLException {          public Queue<Adresse> hentIkkedaekkedeAdresser(String postnr)  throws SQLException {
104                    
105                    String minPostnr = postnr.replace('x', '0');
106                    String maxPostnr = postnr.replace('x', '9');
107                    
108                  ConcurrentLinkedQueue<Adresse> queue = new ConcurrentLinkedQueue<Adresse>();                  ConcurrentLinkedQueue<Adresse> queue = new ConcurrentLinkedQueue<Adresse>();
109    
110                  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 " +
111                                  "FROM fulddaekning.adressetabel " +                                  "FROM fulddaekning.adressetabel a " +
112                                    "LEFT JOIN bogleveringer.postnummerdistributor p on (a.postnr=p.postnr) " +
113                                  "WHERE rute IS NULL " +  //Ingen dækning                                  "WHERE rute IS NULL " +  //Ingen dækning
114                                  "AND postnr=?  " +                                  "AND a.postnr BETWEEN ? AND ? " +
115                                  "AND latitude IS NOT NULL " +                                  "AND latitude IS NOT NULL " +
116                                  "AND longitude IS NOT NULL " +                                  "AND longitude IS NOT NULL " +
117                                  "AND gadeid IS NOT NULL ";                                  "AND gadeid IS NOT NULL " +
118                                    "AND (a.distributor IS NULL OR a.distributor<>'LUKKET') ";              
119                  PreparedStatement stmt = conn.prepareStatement(sql);                  PreparedStatement stmt = conn.prepareStatement(sql);
120                  stmt.setInt(1, postnr);                  stmt.setString(1, minPostnr);
121                    stmt.setString(2, maxPostnr);
122    
123                  queue.addAll( hentAdresseListe( stmt ) );                  queue.addAll( hentAdresseListe( stmt ) );
124                  return queue;                  return queue;
125          }          }
126    
127          public List<Integer> hentPostnumre() throws SQLException {          public List<String> hentPostnumre() throws SQLException {
128                  ArrayList<Integer> list = new ArrayList<Integer>();                  ArrayList<String> list = new ArrayList<String>();
129                                    
130                  Constants consts = Constants.getInstance();                  Constants consts = Constants.getInstance();
131    
132                    /*
133                  String sql = "SELECT postnr " +                  String sql = "SELECT postnr " +
134                                           "FROM fulddaekning.adressetabel " +                                           "FROM fulddaekning.adressetabel " +
                                          //"WHERE distributor = ? and rute is not null " +  
135                                           "WHERE postnr BETWEEN ? AND ? " +                                           "WHERE postnr BETWEEN ? AND ? " +
136                                             "AND rute is null " + // Træk kun liste på postnumre hvor der er ikke-dækkede adresser
137                                           "GROUP BY postnr " +                                           "GROUP BY postnr " +
138                                           "ORDER by postnr";                                           "ORDER by postnr";
139                    */
140                    
141                    
142                    String sql = "SELECT rpad(left(postnr,?),'4', 'x') as postnr2 " +
143                                             "FROM fulddaekning.adressetabel " +
144                                             "WHERE postnr BETWEEN ? AND ? " +
145                                             "AND rute is null " + // Trae kun liste paa postnumre hvor der er ikke-daekede adresser
146                                             "AND (postnr NOT BETWEEN 3900 and 3999) " + //Skip alle groenlandske postnumre
147                                             "GROUP BY postnr2 " +
148                                             "ORDER by postnr2 ";
149                    
150                                            
151                                            
152                  PreparedStatement stmt = conn.prepareStatement(sql);                  PreparedStatement stmt = conn.prepareStatement(sql);
153                  //stmt.setString(1, Lookup.distributor );                  //stmt.setString(1, Lookup.distributor );
154                  stmt.setInt(1, consts.getMinPostnr());  
155                  stmt.setInt(2, consts.getMaxPostnr());                  stmt.setInt(1, consts.getPostnrGroup() );
156    
157                    stmt.setInt(2, consts.getMinPostnr());
158                    stmt.setInt(3, consts.getMaxPostnr());
159                  ResultSet res = stmt.executeQuery();                  ResultSet res = stmt.executeQuery();
160    
161                  while (res.next()) {                  while (res.next()) {
162                          int postnr = res.getInt("postnr");                          String postnr = res.getString("postnr2");
163                          list.add(postnr);                          list.add(postnr);
164                  }                  }
165                  res.close();                  res.close();
# Line 122  public class Database { Line 170  public class Database {
170                  return list;                  return list;
171          }          }
172    
173          public ArrayList<Adresse> hentDaekkedeAdresser( BoundingBox bbox) throws SQLException {          public Adresse[] hentDaekkedeAdresser( BoundingBox bbox) throws SQLException {
174                  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 " +
175                                  "FROM fulddaekning.adressetabel " +                                  "FROM fulddaekning.adressetabel a " +
176                                    "LEFT JOIN bogleveringer.postnummerdistributor p on (a.postnr=p.postnr) " +
177                                  "WHERE rute IS NOT NULL " +                                  "WHERE rute IS NOT NULL " +
178                                  "AND latitude BETWEEN ? AND ? " +                                  "AND latitude BETWEEN ? AND ? " +
179                                  "AND longitude BETWEEN ? AND ? " +                                  "AND longitude BETWEEN ? AND ? " +
180                                  "AND distributor = ? ";                                  "AND a.distributor = ? ";
181    
182                  // 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)
183                  // 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 189  public class Database {
189                  stmt.setDouble(2, bbox.latitudeMax);                  stmt.setDouble(2, bbox.latitudeMax);
190                  stmt.setDouble(3, bbox.longitudeMin);                  stmt.setDouble(3, bbox.longitudeMin);
191                  stmt.setDouble(4, bbox.longitudeMax);                  stmt.setDouble(4, bbox.longitudeMax);
192                  stmt.setString(5, Lookup.distributor);                  stmt.setString(5, LookupMain.distributor);
   
                 return hentAdresseListe( stmt );  
193    
194                    List<Adresse> list = hentAdresseListe( stmt );
195                    return list.toArray( new Adresse[ list.size() ] );
196          }          }
197            
198            
199            public Adresse[] hentAlleDaekkedeAdresser() throws SQLException {
200                    String sql = "SELECT id,a.postnr,adresse,gadeid,husnr,husnrbogstav,latitude,longitude,rute,p.distributor as ho " +
201                                    "FROM fulddaekning.adressetabel a " +
202                                    "LEFT JOIN bogleveringer.postnummerdistributor p on (a.postnr=p.postnr) " +
203                                    "WHERE rute IS NOT NULL " +
204                                    "AND latitude IS NOT NULL " +
205                                    "AND longitude IS NOT NULL " +
206                                    "AND a.distributor = ? ";
207    
208                    // Forward only + concur_read_only + fetchsize tvinger driver til at hente en række af gangen (bedre performance ved store result sets)
209                    // Se http://dev.mysql.com/doc/connector-j/en/connector-j-reference-implementation-notes.html
210                    //PreparedStatement stmt = conn.prepareStatement(sql);
211                    PreparedStatement stmt = conn.prepareStatement(sql, java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);
212                    stmt.setFetchSize(Integer.MIN_VALUE);
213    
214                    stmt.setString(1, LookupMain.distributor);
215    
216                    List<Adresse> list = hentAdresseListe( stmt );
217                    return list.toArray( new Adresse[ list.size() ] );
218            }
219            
220            
221    
222          public synchronized void gemResultat(Adresse orgAdresse, Adresse bedsteAdresse, double bedsteAfstand) throws SQLException {          public synchronized void gemResultat(Adresse orgAdresse, Adresse bedsteAdresse, double bedsteAfstand) throws SQLException {
223                  /*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 248  public class Database {
248    
249                  saveStmt.setDouble(19, bedsteAfstand);                  saveStmt.setDouble(19, bedsteAfstand);
250    
251                  saveStmt.executeUpdate();                        saveStmt.addBatch();
252                  saveStmt.clearParameters();                  batchCount++;
253                    if (batchCount >= 100) {
254                            saveStmt.executeBatch();
255                            batchCount = 0;
256                    }
257                    //saveStmt.executeUpdate();    
258                    //saveStmt.clearParameters();
259    
260                  //saveStmt.close();                      //saveStmt.close();    
261            }
262            
263            public synchronized void saveBatch() throws SQLException{
264                    saveStmt.executeBatch();
265                    batchCount = 0;
266          }          }
267    
268    
269    
270          protected ArrayList<Adresse> hentAdresseListe(PreparedStatement stmt) throws SQLException{          protected ArrayList<Adresse> hentAdresseListe(PreparedStatement stmt) throws SQLException{
271                  ArrayList<Adresse> list = new ArrayList<Adresse>( 30000 );                  ArrayList<Adresse> list = new ArrayList<Adresse>( 1000000 );
272    
273                  //logger.info("Starting query");                  //logger.info("Starting query");
274                  ResultSet res = stmt.executeQuery();                  ResultSet res = stmt.executeQuery();
# Line 204  public class Database { Line 285  public class Database {
285                          adr.latitude = res.getDouble("latitude");                          adr.latitude = res.getDouble("latitude");
286                          adr.longitude = res.getDouble("longitude");                          adr.longitude = res.getDouble("longitude");
287                          adr.rute = res.getString("rute");                          adr.rute = res.getString("rute");
288                            adr.ho = res.getInt("ho");
289    
290                          list.add(adr);                          list.add(adr);
291    
# Line 230  public class Database { Line 312  public class Database {
312              connectionProps.put("user", db_user);              connectionProps.put("user", db_user);
313              connectionProps.put("password", db_pass);              connectionProps.put("password", db_pass);
314    
315                //For debug output, tilføj denne til JDBC url'en: &profileSQL=true    
316              conn = DriverManager.getConnection(              conn = DriverManager.getConnection(
317                             "jdbc:mysql://" +                             "jdbc:mysql://" +
318                             db_host +                             db_host +
319                             ":3306/",                             ":3306/?rewriteBatchedStatements=true",
320                             connectionProps);                             connectionProps);
321              logger.info("Connected to database");              logger.info("Connected to database");
322              return conn;              return conn;

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

  ViewVC Help
Powered by ViewVC 1.1.20