/[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 2147 by torben, Wed Apr 30 12:53:01 2014 UTC revision 2235 by torben, Tue Nov 11 13:45:21 2014 UTC
# Line 14  import java.util.concurrent.ConcurrentLi Line 14  import java.util.concurrent.ConcurrentLi
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;
         Connection writeConn;  
           
24          PreparedStatement saveStmt;          PreparedStatement saveStmt;
25    
26          public Database(Properties conf)  throws SQLException,IOException {          public Database(SafeProperties conf)  throws SQLException,IOException {
27                  conn = getConnection(conf);                  this.conn = getConnection( conf );      
28                  writeConn = getConnection(conf);  
29                                    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() )";
31                  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`) "+  
32                  "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, now() )";                  saveStmt = conn.prepareStatement(sql);          
33    
                 saveStmt = writeConn.prepareStatement(sql);              
                   
         }  
           
         public void resetResultTable() throws SQLException {  
                 logger.info("Truncating result table");  
                 String sql = "TRUNCATE TABLE fulddaekning.afstand_anden_rute_thn";  
                 writeConn.createStatement().executeUpdate(sql);  
                   
34          }          }
           
         public Connection getConnection(Properties conf) throws SQLException, IOException {  
                   
                 String db_host = conf.getProperty("DB_HOST");  
                 String db_user = conf.getProperty("DB_USER");  
                 String db_pass = conf.getProperty("DB_PASS");  
35    
36            public void resetResultTable() throws SQLException {
37                    logger.info("Dropping old result table (if exists)");
38                    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);
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              Connection conn = null;                  logger.info("Executing: " + sql);
58              Properties connectionProps = new Properties();                  conn.createStatement().executeUpdate(sql);              
59              connectionProps.put("user", db_user);          }      
             connectionProps.put("password", db_pass);  
60    
                 conn = DriverManager.getConnection(  
                            "jdbc:mysql://" +  
                            db_host +  
                            ":3306/",  
                            connectionProps);  
             logger.info("Connected to database");  
             return conn;  
         }  
           
61          public BoundingBox getBoundingbox(int postnr) throws SQLException {          public BoundingBox getBoundingbox(int postnr) throws SQLException {
62                    
63                  String sql =                  String sql =
64                                  "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  " +
65                                  "from fulddaekning.adressetabel WHERE postnr=? and rute is null;";                                  "FROM fulddaekning.adressetabel WHERE postnr=? and rute is null;";
66                    
67                  PreparedStatement stmt = conn.prepareStatement(sql);                  PreparedStatement stmt = conn.prepareStatement(sql);
68                  stmt.setInt(1, postnr);                  stmt.setInt(1, postnr);
69                    
70                  ResultSet res = stmt.executeQuery();                  ResultSet res = stmt.executeQuery();
71                  res.next(); //query returnerer altid 1 række                  res.next(); //query returnerer altid 1 række
72                    
73                  BoundingBox bbox = new BoundingBox();                  BoundingBox bbox = new BoundingBox();
74                  bbox.latitudeMax = res.getDouble("latmax");                  bbox.latitudeMax = res.getDouble("latmax");
75                  bbox.latitudeMin = res.getDouble("latmin");                  bbox.latitudeMin = res.getDouble("latmin");
76                  bbox.longitudeMax = res.getDouble("lngmax");                  bbox.longitudeMax = res.getDouble("lngmax");
77                  bbox.longitudeMin = res.getDouble("lngmin");                  bbox.longitudeMin = res.getDouble("lngmin");
78                    
79                  res.close();                  res.close();
80                  stmt.close();                  stmt.close();
81                    
82                  return bbox;                  return bbox;
83          }          }
84            
85          public Queue<Adresse> hentIkkedaekkedeAdresser(int postnr)  throws SQLException {          public Queue<Adresse> hentIkkedaekkedeAdresser(int postnr)  throws SQLException {
86                  ConcurrentLinkedQueue<Adresse> queue = new ConcurrentLinkedQueue<Adresse>();                  ConcurrentLinkedQueue<Adresse> queue = new ConcurrentLinkedQueue<Adresse>();
87                    
88                  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 " +
89                                    "FROM fulddaekning.adressetabel a " +
90                                    "LEFT JOIN bogleveringer.postnummerdistributor p on (a.postnr=p.postnr) " +
91                                  "WHERE rute IS NULL " +  //Ingen dækning                                  "WHERE rute IS NULL " +  //Ingen dækning
92                                  "AND postnr=?  " +                                  "AND a.postnr=?  " +
93                                  "AND latitude IS NOT NULL " +                                  "AND latitude IS NOT NULL " +
94                                  "AND longitude IS NOT NULL " +                                  "AND longitude IS NOT NULL " +
95                                  "AND gadeid IS NOT NULL ";                                  "AND gadeid IS NOT NULL " +
96                                    "AND (a.distributor IS NULL OR a.distributor<>'LUKKET') ";              
97                  PreparedStatement stmt = conn.prepareStatement(sql);                  PreparedStatement stmt = conn.prepareStatement(sql);
98                  stmt.setInt(1, postnr);                  stmt.setInt(1, postnr);
99                    
100                  queue.addAll( hentAdresseListe( stmt ) );                  queue.addAll( hentAdresseListe( stmt ) );
101                  return queue;                  return queue;
102          }          }
103            
104          public List<Integer> hentPostnumre() throws SQLException {          public List<Integer> hentPostnumre() throws SQLException {
105                  ArrayList<Integer> list = new ArrayList<Integer>();                  ArrayList<Integer> list = new ArrayList<Integer>();
106                                    
107                                    Constants consts = Constants.getInstance();
108                  String sql = "SELECT postnr FROM fulddaekning.adressetabel WHERE distributor = 'DAO' and rute is not null GROUP BY postnr ORDER by postnr";  
109    
110                    String sql = "SELECT postnr " +
111                                             "FROM fulddaekning.adressetabel " +
112                                             //"WHERE distributor = ? and rute is not null " +
113                                             "WHERE postnr BETWEEN ? AND ? " +
114                                             "GROUP BY postnr " +
115                                             "ORDER by postnr";
116                  PreparedStatement stmt = conn.prepareStatement(sql);                  PreparedStatement stmt = conn.prepareStatement(sql);
117                    //stmt.setString(1, Lookup.distributor );
118                    stmt.setInt(1, consts.getMinPostnr());
119                    stmt.setInt(2, consts.getMaxPostnr());
120                  ResultSet res = stmt.executeQuery();                  ResultSet res = stmt.executeQuery();
121                    
122                  while (res.next()) {                  while (res.next()) {
123                          int postnr = res.getInt("postnr");                          int postnr = res.getInt("postnr");
124                          list.add(postnr);                          list.add(postnr);
125                  }                  }
126                  res.close();                  res.close();
127                  stmt.close();                  stmt.close();
128                    
129                  //list.add(8700);                  //list.add(8700);
130                    
131                  return list;                  return list;
132          }          }
133            
134          public ArrayList<Adresse> hentDaekkedeAdresser( BoundingBox bbox) throws SQLException {          public Adresse[] hentDaekkedeAdresser( BoundingBox bbox) throws SQLException {
135                  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 " +
136                                    "FROM fulddaekning.adressetabel a " +
137                                    "LEFT JOIN bogleveringer.postnummerdistributor p on (a.postnr=p.postnr) " +
138                                  "WHERE rute IS NOT NULL " +                                  "WHERE rute IS NOT NULL " +
139                                  "AND latitude BETWEEN ? AND ? " +                                  "AND latitude BETWEEN ? AND ? " +
140                                  "AND longitude BETWEEN ? AND ? " +                                  "AND longitude BETWEEN ? AND ? " +
141                                  "AND distributor = 'DAO' ";                                  "AND a.distributor = ? ";
142                    
143                  // 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)
144                  // 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
145                  //PreparedStatement stmt = conn.prepareStatement(sql);                  //PreparedStatement stmt = conn.prepareStatement(sql);
146                  PreparedStatement stmt = conn.prepareStatement(sql, java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);                  PreparedStatement stmt = conn.prepareStatement(sql, java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);
147                  stmt.setFetchSize(Integer.MIN_VALUE);                  stmt.setFetchSize(Integer.MIN_VALUE);
148                    
149                  stmt.setDouble(1, bbox.latitudeMin);                  stmt.setDouble(1, bbox.latitudeMin);
150                  stmt.setDouble(2, bbox.latitudeMax);                  stmt.setDouble(2, bbox.latitudeMax);
151                  stmt.setDouble(3, bbox.longitudeMin);                  stmt.setDouble(3, bbox.longitudeMin);
152                  stmt.setDouble(4, bbox.longitudeMax);                  stmt.setDouble(4, bbox.longitudeMax);
153                                    stmt.setString(5, Lookup.distributor);
154                  return hentAdresseListe( stmt );  
155                                    List<Adresse> list = hentAdresseListe( stmt );
156                    return list.toArray( new Adresse[ list.size() ] );
157          }          }
158            
159            
160            public Adresse[] hentAlleDaekkedeAdresser() throws SQLException {
161                    String sql = "SELECT id,a.postnr,adresse,gadeid,husnr,husnrbogstav,latitude,longitude,rute,p.distributor as ho " +
162                                    "FROM fulddaekning.adressetabel a " +
163                                    "LEFT JOIN bogleveringer.postnummerdistributor p on (a.postnr=p.postnr) " +
164                                    "WHERE rute IS NOT NULL " +
165                                    "AND latitude IS NOT NULL " +
166                                    "AND longitude IS NOT NULL " +
167                                    "AND a.distributor = ? ";
168    
169                    // Forward only + concur_read_only + fetchsize tvinger driver til at hente en række af gangen (bedre performance ved store result sets)
170                    // Se http://dev.mysql.com/doc/connector-j/en/connector-j-reference-implementation-notes.html
171                    //PreparedStatement stmt = conn.prepareStatement(sql);
172                    PreparedStatement stmt = conn.prepareStatement(sql, java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);
173                    stmt.setFetchSize(Integer.MIN_VALUE);
174    
175                    stmt.setString(1, Lookup.distributor);
176    
177                    List<Adresse> list = hentAdresseListe( stmt );
178                    return list.toArray( new Adresse[ list.size() ] );
179            }
180                    
181            
182    
183          public synchronized void gemResultat(Adresse orgAdresse, Adresse bedsteAdresse, double bedsteAfstand) throws SQLException {          public synchronized void gemResultat(Adresse orgAdresse, Adresse bedsteAdresse, double bedsteAfstand) throws SQLException {
184                  /*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`) "+
185                                  "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, now() )";                                  "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, now() )";
186                    
187                  PreparedStatement saveStmt = conn.prepareStatement(sql);*/                  PreparedStatement saveStmt = conn.prepareStatement(sql);*/
188                    
189                  saveStmt.setInt(1, orgAdresse.id);                  saveStmt.setInt(1, orgAdresse.id);
190                  saveStmt.setInt(2, orgAdresse.postnr);                  saveStmt.setInt(2, orgAdresse.postnr);
191                  saveStmt.setString(3, orgAdresse.adresse);                  saveStmt.setString(3, orgAdresse.adresse);
# Line 163  public class Database { Line 195  public class Database {
195                  saveStmt.setDouble(7, orgAdresse.latitude);                  saveStmt.setDouble(7, orgAdresse.latitude);
196                  saveStmt.setDouble(8, orgAdresse.longitude);                  saveStmt.setDouble(8, orgAdresse.longitude);
197                  saveStmt.setString(9, orgAdresse.rute);                  saveStmt.setString(9, orgAdresse.rute);
198                    
199                    
200                  saveStmt.setInt(10, bedsteAdresse.id);                  saveStmt.setInt(10, bedsteAdresse.id);
201                  saveStmt.setInt(11, bedsteAdresse.postnr);                  saveStmt.setInt(11, bedsteAdresse.postnr);
202                  saveStmt.setString(12, bedsteAdresse.adresse);                  saveStmt.setString(12, bedsteAdresse.adresse);
# Line 174  public class Database { Line 206  public class Database {
206                  saveStmt.setDouble(16, bedsteAdresse.latitude);                  saveStmt.setDouble(16, bedsteAdresse.latitude);
207                  saveStmt.setDouble(17, bedsteAdresse.longitude);                  saveStmt.setDouble(17, bedsteAdresse.longitude);
208                  saveStmt.setString(18, bedsteAdresse.rute);                  saveStmt.setString(18, bedsteAdresse.rute);
209                    
210                  saveStmt.setDouble(19, bedsteAfstand);                  saveStmt.setDouble(19, bedsteAfstand);
211                    
212                  saveStmt.executeUpdate();                        saveStmt.addBatch();
213                  saveStmt.clearParameters();                  batchCount++;
214                                    if (batchCount >= 100) {
215                                            saveStmt.executeBatch();
216                            batchCount = 0;
217                    }
218                    //saveStmt.executeUpdate();    
219                    //saveStmt.clearParameters();
220    
221                  //saveStmt.close();                      //saveStmt.close();    
                   
222          }          }
223                    
224                            public synchronized void saveBatch() throws SQLException{
225                            saveStmt.executeBatch();
226                    batchCount = 0;
227            }
228    
229    
230    
231          protected ArrayList<Adresse> hentAdresseListe(PreparedStatement stmt) throws SQLException{          protected ArrayList<Adresse> hentAdresseListe(PreparedStatement stmt) throws SQLException{
232                  ArrayList<Adresse> list = new ArrayList<Adresse>( 30000 );                  ArrayList<Adresse> list = new ArrayList<Adresse>( 1000000 );
233                    
234                  //logger.info("Starting query");                  //logger.info("Starting query");
235                  ResultSet res = stmt.executeQuery();                  ResultSet res = stmt.executeQuery();
236                  //logger.info("Starting exec query done");                  //logger.info("Starting exec query done");
237                    
238                  while (res.next()) {                  while (res.next()) {
239                          Adresse adr = new Adresse();                          Adresse adr = new Adresse();
240                          adr.id = res.getInt("id");                          adr.id = res.getInt("id");
# Line 205  public class Database { Line 246  public class Database {
246                          adr.latitude = res.getDouble("latitude");                          adr.latitude = res.getDouble("latitude");
247                          adr.longitude = res.getDouble("longitude");                          adr.longitude = res.getDouble("longitude");
248                          adr.rute = res.getString("rute");                          adr.rute = res.getString("rute");
249                                                    adr.ho = res.getInt("ho");
250    
251                          list.add(adr);                          list.add(adr);
252                            
253                          //logger.info( "Adress:" + adr);                          //logger.info( "Adress:" + adr);
254                  }                  }
255                                    
256                  res.close();                  res.close();
257                  stmt.close();                  stmt.close();
258                    
259                  return list;                  return list;
260          }          }
261    
262                    public Connection getConnection(SafeProperties conf) throws SQLException, IOException {
263                    
264                    String db_host = conf.getSafeProperty("DB_HOST");
265                    String db_user = conf.getSafeProperty("DB_USER");
266                    String db_pass = conf.getSafeProperty("DB_PASS");
267    
268                    
269                    
270    
271                Connection conn = null;
272                Properties connectionProps = new Properties();
273                connectionProps.put("user", db_user);
274                connectionProps.put("password", db_pass);
275    
276                //For debug output, tilføj denne til JDBC url'en: &profileSQL=true    
277                conn = DriverManager.getConnection(
278                               "jdbc:mysql://" +
279                               db_host +
280                               ":3306/?rewriteBatchedStatements=true",
281                               connectionProps);
282                logger.info("Connected to database");
283                return conn;
284            }
285    
286  }  }

Legend:
Removed from v.2147  
changed lines
  Added in v.2235

  ViewVC Help
Powered by ViewVC 1.1.20