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

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

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

revision 2151 by torben, Wed May 7 07:59:03 2014 UTC revision 2238 by torben, Tue Dec 9 20:39:45 2014 UTC
# Line 1  Line 1 
1  package dk.daoas.fulddaekning;  package dk.daoas.fulddaekning;
2    
3    import java.io.IOException;
4  import java.sql.Connection;  import java.sql.Connection;
5    import java.sql.DriverManager;
6  import java.sql.PreparedStatement;  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.List;  import java.util.List;
11    import java.util.Properties;
12  import java.util.Queue;  import java.util.Queue;
13  import java.util.concurrent.ConcurrentLinkedQueue;  import java.util.concurrent.ConcurrentLinkedQueue;
14  import java.util.logging.Logger;  import java.util.logging.Logger;
15    
16    
17    
18  public class Database {  public class Database {
19          Logger logger = Logger.getLogger(Database.class.getName());          Logger logger = Logger.getLogger(Database.class.getName());
20    
21            int batchCount = 0;
22    
23          Connection conn;          Connection conn;
24          PreparedStatement saveStmt;          PreparedStatement saveStmt;
25    
26          public Database(Connection conn)  throws SQLException {          public Database(SafeProperties conf)  throws SQLException,IOException {
27                  this.conn = conn;                                                this.conn = getConnection( conf );      
28    
29                  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_ny (orgId,orgPostnr, orgAdresse,orgGadeid,orgHusnr,orgHusnrBogstav,orgLatitude,orgLongitude,orgRute,id,postnr,adresse,gadeid,husnr,husnrbogstav,latitude,longitude,rute,afstand,`timestamp`) "+
30                                  "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, now() )";                                  "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, now() )";
31    
32                  saveStmt = conn.prepareStatement(sql);                            saveStmt = conn.prepareStatement(sql);          
# Line 29  public class Database { Line 34  public class Database {
34          }          }
35    
36          public void resetResultTable() throws SQLException {          public void resetResultTable() throws SQLException {
37                  logger.info("Truncating result table");                  logger.info("Dropping old result table (if exists)");
38                  String sql = "TRUNCATE TABLE fulddaekning.afstand_anden_rute_thn";                  String sql = "DROP TABLE IF EXISTS fulddaekning.afstand_anden_rute_ny";
39                    conn.createStatement().executeUpdate(sql);
40                    
41                    logger.info("Create new result table");
42                    sql = "CREATE TABLE fulddaekning.afstand_anden_rute_ny LIKE fulddaekning.afstand_anden_rute";
43                    conn.createStatement().executeUpdate(sql);              
44            }      
45            
46            public void renameResultTables() throws SQLException {
47                    Constants consts = Constants.getInstance();
48                    String ext = consts.getTableExtension();
49                    
50                    logger.info("Dropping old backup table (if exists)");
51                    String sql = "DROP TABLE IF EXISTS fulddaekning.afstand_anden_rute_old" + ext;
52                  conn.createStatement().executeUpdate(sql);                  conn.createStatement().executeUpdate(sql);
53                    
54                    logger.info("Rename tables");
55                    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;
56    
57                    logger.info("Executing: " + sql);
58                    conn.createStatement().executeUpdate(sql);              
59          }                }      
60    
61          public BoundingBox getBoundingbox(int postnr) throws SQLException {          public BoundingBox getBoundingbox(String postnr) throws SQLException {
62                    String minPostnr = postnr.replace("x", "0");
63                    String maxPostnr = postnr.replace("x", "9");
64    
65                  String sql =                  String sql =
66                                  "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  " +
67                                                  "from fulddaekning.adressetabel WHERE postnr=? and rute is null;";                                  "FROM fulddaekning.adressetabel WHERE postnr BETWEEN ? and ? and rute is null;";
68    
69                  PreparedStatement stmt = conn.prepareStatement(sql);                  PreparedStatement stmt = conn.prepareStatement(sql);
70                  stmt.setInt(1, postnr);                  stmt.setString(1, minPostnr);
71                    stmt.setString(2, maxPostnr);
72    
73                  ResultSet res = stmt.executeQuery();                  ResultSet res = stmt.executeQuery();
74                  res.next(); //query returnerer altid 1 række                  res.next(); //query returnerer altid 1 række
# Line 59  public class Database { Line 85  public class Database {
85                  return bbox;                  return bbox;
86          }          }
87    
88          public Queue<Adresse> hentIkkedaekkedeAdresser(int postnr)  throws SQLException {          public Queue<Adresse> hentIkkedaekkedeAdresser(String postnr)  throws SQLException {
89                    
90                    String minPostnr = postnr.replace("x", "0");
91                    String maxPostnr = postnr.replace("x", "9");
92                    
93                  ConcurrentLinkedQueue<Adresse> queue = new ConcurrentLinkedQueue<Adresse>();                  ConcurrentLinkedQueue<Adresse> queue = new ConcurrentLinkedQueue<Adresse>();
94    
95                  String sql = "SELECT id,postnr,adresse,gadeid,husnr,husnrbogstav,latitude,longitude,rute FROM fulddaekning.adressetabel " +                  String sql = "SELECT id,a.postnr,adresse,gadeid,husnr,husnrbogstav,latitude,longitude,rute,p.distributor as ho " +
96                                    "FROM fulddaekning.adressetabel a " +
97                                    "LEFT JOIN bogleveringer.postnummerdistributor p on (a.postnr=p.postnr) " +
98                                  "WHERE rute IS NULL " +  //Ingen dækning                                  "WHERE rute IS NULL " +  //Ingen dækning
99                                  "AND postnr=?  " +                                  "AND a.postnr BETWEEN ? AND ? " +
100                                  "AND latitude IS NOT NULL " +                                  "AND latitude IS NOT NULL " +
101                                  "AND longitude IS NOT NULL " +                                  "AND longitude IS NOT NULL " +
102                                  "AND gadeid IS NOT NULL ";                                  "AND gadeid IS NOT NULL " +
103                                    "AND (a.distributor IS NULL OR a.distributor<>'LUKKET') ";              
104                  PreparedStatement stmt = conn.prepareStatement(sql);                  PreparedStatement stmt = conn.prepareStatement(sql);
105                  stmt.setInt(1, postnr);                  stmt.setString(1, minPostnr);
106                    stmt.setString(2, maxPostnr);
107    
108                  queue.addAll( hentAdresseListe( stmt ) );                  queue.addAll( hentAdresseListe( stmt ) );
109                  return queue;                  return queue;
110          }          }
111    
112          public List<Integer> hentPostnumre() throws SQLException {          public List<String> hentPostnumre() throws SQLException {
113                  ArrayList<Integer> list = new ArrayList<Integer>();                  ArrayList<String> list = new ArrayList<String>();
114                    
115                    Constants consts = Constants.getInstance();
116                  String sql = "SELECT postnr FROM fulddaekning.adressetabel WHERE distributor = 'DAO' and rute is not null GROUP BY postnr ORDER by postnr";  
117                    /*
118                    String sql = "SELECT postnr " +
119                                             "FROM fulddaekning.adressetabel " +
120                                             "WHERE postnr BETWEEN ? AND ? " +
121                                             "AND rute is null " + // Træk kun liste på postnumre hvor der er ikke-dækkede adresser
122                                             "GROUP BY postnr " +
123                                             "ORDER by postnr";
124                    */
125                    
126                    
127                    String sql = "SELECT concat(left(postnr,3),'x') as postnr2 " +
128                                             "FROM fulddaekning.adressetabel " +
129                                             "WHERE postnr BETWEEN ? AND ? " +
130                                             "AND rute is null " + // Træk kun liste på postnumre hvor der er ikke-dækkede adresser
131                                             "GROUP BY postnr2 " +
132                                             "ORDER by postnr2 ";
133                    
134                                            
135                                            
136                  PreparedStatement stmt = conn.prepareStatement(sql);                  PreparedStatement stmt = conn.prepareStatement(sql);
137                    //stmt.setString(1, Lookup.distributor );
138                    stmt.setInt(1, consts.getMinPostnr());
139                    stmt.setInt(2, consts.getMaxPostnr());
140                  ResultSet res = stmt.executeQuery();                  ResultSet res = stmt.executeQuery();
141    
142                  while (res.next()) {                  while (res.next()) {
143                          int postnr = res.getInt("postnr");                          String postnr = res.getString("postnr2");
144                          list.add(postnr);                          list.add(postnr);
145                  }                  }
146                  res.close();                  res.close();
# Line 95  public class Database { Line 151  public class Database {
151                  return list;                  return list;
152          }          }
153    
154          public ArrayList<Adresse> hentDaekkedeAdresser( BoundingBox bbox) throws SQLException {          public Adresse[] hentDaekkedeAdresser( BoundingBox bbox) throws SQLException {
155                  String sql = "SELECT id,postnr,adresse,gadeid,husnr,husnrbogstav,latitude,longitude,rute FROM fulddaekning.adressetabel " +                  String sql = "SELECT id,a.postnr,adresse,gadeid,husnr,husnrbogstav,latitude,longitude,rute,p.distributor as ho " +
156                                    "FROM fulddaekning.adressetabel a " +
157                                    "LEFT JOIN bogleveringer.postnummerdistributor p on (a.postnr=p.postnr) " +
158                                  "WHERE rute IS NOT NULL " +                                  "WHERE rute IS NOT NULL " +
159                                  "AND latitude BETWEEN ? AND ? " +                                  "AND latitude BETWEEN ? AND ? " +
160                                  "AND longitude BETWEEN ? AND ? " +                                  "AND longitude BETWEEN ? AND ? " +
161                                  "AND distributor = 'DAO' ";                                  "AND a.distributor = ? ";
162    
163                  // 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)
164                  // 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 112  public class Database { Line 170  public class Database {
170                  stmt.setDouble(2, bbox.latitudeMax);                  stmt.setDouble(2, bbox.latitudeMax);
171                  stmt.setDouble(3, bbox.longitudeMin);                  stmt.setDouble(3, bbox.longitudeMin);
172                  stmt.setDouble(4, bbox.longitudeMax);                  stmt.setDouble(4, bbox.longitudeMax);
173                    stmt.setString(5, Lookup.distributor);
174    
175                  return hentAdresseListe( stmt );                  List<Adresse> list = hentAdresseListe( stmt );
176                    return list.toArray( new Adresse[ list.size() ] );
177          }          }
178            
179            
180            public Adresse[] hentAlleDaekkedeAdresser() throws SQLException {
181                    String sql = "SELECT id,a.postnr,adresse,gadeid,husnr,husnrbogstav,latitude,longitude,rute,p.distributor as ho " +
182                                    "FROM fulddaekning.adressetabel a " +
183                                    "LEFT JOIN bogleveringer.postnummerdistributor p on (a.postnr=p.postnr) " +
184                                    "WHERE rute IS NOT NULL " +
185                                    "AND latitude IS NOT NULL " +
186                                    "AND longitude IS NOT NULL " +
187                                    "AND a.distributor = ? ";
188    
189                    // Forward only + concur_read_only + fetchsize tvinger driver til at hente en række af gangen (bedre performance ved store result sets)
190                    // Se http://dev.mysql.com/doc/connector-j/en/connector-j-reference-implementation-notes.html
191                    //PreparedStatement stmt = conn.prepareStatement(sql);
192                    PreparedStatement stmt = conn.prepareStatement(sql, java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);
193                    stmt.setFetchSize(Integer.MIN_VALUE);
194    
195                    stmt.setString(1, Lookup.distributor);
196    
197                    List<Adresse> list = hentAdresseListe( stmt );
198                    return list.toArray( new Adresse[ list.size() ] );
199            }
200            
201            
202    
203          public synchronized void gemResultat(Adresse orgAdresse, Adresse bedsteAdresse, double bedsteAfstand) throws SQLException {          public synchronized void gemResultat(Adresse orgAdresse, Adresse bedsteAdresse, double bedsteAfstand) throws SQLException {
204                  /*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 147  public class Database { Line 229  public class Database {
229    
230                  saveStmt.setDouble(19, bedsteAfstand);                  saveStmt.setDouble(19, bedsteAfstand);
231    
232                  saveStmt.executeUpdate();                        saveStmt.addBatch();
233                  saveStmt.clearParameters();                  batchCount++;
234                    if (batchCount >= 100) {
235                            saveStmt.executeBatch();
236                            batchCount = 0;
237                    }
238                    //saveStmt.executeUpdate();    
239                    //saveStmt.clearParameters();
240    
241                  //saveStmt.close();                      //saveStmt.close();    
242            }
243            
244            public synchronized void saveBatch() throws SQLException{
245                    saveStmt.executeBatch();
246                    batchCount = 0;
247          }          }
248    
249    
250    
251          protected ArrayList<Adresse> hentAdresseListe(PreparedStatement stmt) throws SQLException{          protected ArrayList<Adresse> hentAdresseListe(PreparedStatement stmt) throws SQLException{
252                  ArrayList<Adresse> list = new ArrayList<Adresse>( 30000 );                  ArrayList<Adresse> list = new ArrayList<Adresse>( 1000000 );
253    
254                  //logger.info("Starting query");                  //logger.info("Starting query");
255                  ResultSet res = stmt.executeQuery();                  ResultSet res = stmt.executeQuery();
# Line 175  public class Database { Line 266  public class Database {
266                          adr.latitude = res.getDouble("latitude");                          adr.latitude = res.getDouble("latitude");
267                          adr.longitude = res.getDouble("longitude");                          adr.longitude = res.getDouble("longitude");
268                          adr.rute = res.getString("rute");                          adr.rute = res.getString("rute");
269                            adr.ho = res.getInt("ho");
270    
271                          list.add(adr);                          list.add(adr);
272    
# Line 187  public class Database { Line 279  public class Database {
279                  return list;                  return list;
280          }          }
281    
282            public Connection getConnection(SafeProperties conf) throws SQLException, IOException {
283                    
284                    String db_host = conf.getSafeProperty("DB_HOST");
285                    String db_user = conf.getSafeProperty("DB_USER");
286                    String db_pass = conf.getSafeProperty("DB_PASS");
287    
288                    
289                    
290    
291                Connection conn = null;
292                Properties connectionProps = new Properties();
293                connectionProps.put("user", db_user);
294                connectionProps.put("password", db_pass);
295    
296                //For debug output, tilføj denne til JDBC url'en: &profileSQL=true    
297                conn = DriverManager.getConnection(
298                               "jdbc:mysql://" +
299                               db_host +
300                               ":3306/?rewriteBatchedStatements=true",
301                               connectionProps);
302                logger.info("Connected to database");
303                return conn;
304            }
305    
306  }  }

Legend:
Removed from v.2151  
changed lines
  Added in v.2238

  ViewVC Help
Powered by ViewVC 1.1.20