Quantum version 2.4.1
[phpeclipse.git] / archive / net.sourceforge.phpeclipse.quantum.sql / src / com / quantum / model / Bookmark.java
1 package com.quantum.model;
2
3 import java.beans.PropertyChangeListener;
4 import java.beans.PropertyChangeSupport;
5 import java.sql.Connection;
6 import java.sql.SQLException;
7 import java.util.ArrayList;
8 import java.util.Arrays;
9 import java.util.Collections;
10 import java.util.HashSet;
11 import java.util.Hashtable;
12 import java.util.List;
13 import java.util.Map;
14 import java.util.Set;
15
16 import com.quantum.IQuantumConstants;
17 import com.quantum.QuantumPlugin;
18 import com.quantum.adapters.AdapterFactory;
19 import com.quantum.adapters.DatabaseAdapter;
20 import com.quantum.sql.ConnectionEstablisher;
21 import com.quantum.sql.MultiSQLServer;
22
23 import org.eclipse.jface.preference.IPreferenceStore;
24
25 /**
26  * Class Bookmark holds the "static" information of a bookmark, that is the data that
27  * is saved and loaded from the external file and describes a bookmark. This info will
28  * be filled up by the end user.
29  * 
30  * @author root
31  */
32 public class Bookmark implements Displayable {
33         
34         public static final int SCHEMA_RULE_USE_ALL = 1;
35         public static final int SCHEMA_RULE_USE_DEFAULT = 2;
36         public static final int SCHEMA_RULE_USE_SELECTED = 3;
37     
38     private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
39         private String name = ""; //$NON-NLS-1$
40         private String username = ""; //$NON-NLS-1$
41     private String password = ""; //$NON-NLS-1$
42     private String connectionUrl = ""; //$NON-NLS-1$
43     private JDBCDriver driver;
44     
45     private int schemaRule = SCHEMA_RULE_USE_ALL;
46     
47     /**
48      * A quick list is a list of favourite tables that a person might want to view
49      * without having to look at the entire list of tables.
50      */
51     private Map quickList = new Hashtable();
52         private Set schemas = new HashSet();   
53         private Connection connection = null;
54     private ConnectionEstablisher connectionEstablisher;
55     private boolean changed = true;
56     private List queries = Collections.synchronizedList(new ArrayList());
57     private boolean promptForPassword = false;
58     private boolean autoCommit = true;
59     private String autoCommitPreference = IQuantumConstants.autoCommitTrue;
60         
61         public Bookmark() {
62         this(MultiSQLServer.getInstance());
63         }
64     
65     public Bookmark(ConnectionEstablisher connectionEstablisher) {
66         this.connectionEstablisher = connectionEstablisher;
67     }
68
69         public Bookmark(Bookmark data) {
70                 this();
71                 setName(data.getName());
72                 setUsername(data.getUsername());
73                 setPassword(data.getPassword());
74                 setConnect(data.getConnect());
75                 setJDBCDriver(data.getJDBCDriver());
76         setPromptForPassword(data.getPromptForPassword());
77         setAutoCommit(data.isAutoCommit());
78         setAutoCommitPreference(data.getAutoCommitPreference());
79         setSchemaRule(data.getSchemaRule());
80         
81         this.schemas.addAll(data.schemas);
82         this.quickList = new Hashtable(data.quickList);
83         }
84
85         /**
86          * Returns the JDBC URL.
87          * @return String
88          */
89         public String getConnect() {
90                 return this.connectionUrl;
91         }
92
93         /**
94          * Returns the password.
95          * @return String
96          */
97         public String getPassword() {
98                 if (this.promptForPassword) {
99                         return null;
100                 } else {
101                         return this.password;
102                 }
103         }
104
105         /**
106          * Returns the username.
107          * @return String
108          */
109         public String getUsername() {
110                 return username;
111         }
112
113         /**
114          * Sets the connect.
115          * @param connectionUrl The connect to set
116          */
117         public void setConnect(String connectionUrl) {
118                 if (connectionUrl == null) {
119                         connectionUrl = ""; //$NON-NLS-1$
120                 }
121                 this.connectionUrl = connectionUrl;
122         }
123
124         /**
125          * Sets the password.
126          * @param password The password to set
127          */
128         public void setPassword(String password) {
129                 if (password == null) {
130                         password = ""; //$NON-NLS-1$
131                 }
132                 this.password = password;
133         }
134
135         /**
136          * Sets the username.
137          * @param username The username to set
138          */
139         public void setUsername(String username) {
140                 if (username == null) {
141                         username = ""; //$NON-NLS-1$
142                 }
143                 this.username = username;
144         }
145
146         /**
147          * Returns the name.
148          * @return String
149          */
150         public String getName() {
151                 return name;
152         }
153
154         /**
155          * Sets the name.
156          * @param name The name to set
157          */
158         public void setName(String name) {
159                 if (name == null) {
160                         name = ""; //$NON-NLS-1$
161                 }
162         if (!name.equals(this.name)) {
163          
164             String oldName = this.name;
165             this.name = name;
166             this.propertyChangeSupport.firePropertyChange("name", oldName, this.name);
167             this.changed = true;
168         }
169         }
170
171         public boolean isEmpty() {
172                 if (name.equals("") && //$NON-NLS-1$
173                 username.equals("") && //$NON-NLS-1$
174                 password.equals("") && //$NON-NLS-1$
175                 connectionUrl.equals("") && //$NON-NLS-1$
176                 driver.equals("") && //$NON-NLS-1$
177                 driver == null) {
178                         return true;
179                 }
180                 return false;
181         }
182         public String toString() {
183                 StringBuffer buffer = new StringBuffer();
184                 buffer.append("["); //$NON-NLS-1$
185                 buffer.append("name="); //$NON-NLS-1$
186                 buffer.append(name);
187                 buffer.append(", "); //$NON-NLS-1$
188                 buffer.append("username="); //$NON-NLS-1$
189                 buffer.append(username);
190                 buffer.append(", "); //$NON-NLS-1$
191                 buffer.append("password=****"); //$NON-NLS-1$
192                 buffer.append(", "); //$NON-NLS-1$
193                 buffer.append("connect="); //$NON-NLS-1$
194                 buffer.append(connectionUrl);
195                 buffer.append(", "); //$NON-NLS-1$
196                 buffer.append("driver="); //$NON-NLS-1$
197                 buffer.append(driver);
198                 buffer.append("]"); //$NON-NLS-1$
199                 return buffer.toString();
200         }
201         
202     public Connection connect(PasswordFinder passwordFinder) throws ConnectionException {
203         boolean isConnected = isConnected();
204         if (this.connection == null) {
205             this.connection = this.connectionEstablisher.connect(this, passwordFinder);
206         }
207         
208         if (isConnected() != isConnected) {
209             this.propertyChangeSupport.firePropertyChange(
210                 "connected", isConnected, isConnected());
211         }
212         return this.connection;
213     }
214
215     /**
216          * Returns the connection object. 
217          * @return the Connection object associated with the current JDBC source.
218          * 
219          */
220     public Connection getConnection() throws NotConnectedException {
221         if (this.connection == null) {
222             throw new NotConnectedException();
223         }
224         return this.connection;
225     }
226
227     /**
228          * @return true if the BookmarkNode is connected to a JDBC source
229          */
230     public boolean isConnected() {
231         return (connection != null);
232     }
233
234     /**
235          * Sets the connection member. From that moment on the BookmarkNode is "connected" (open)
236          * @param connection : a valid connection to a JDBC source
237          */
238     public void setConnection(Connection connection) {
239         this.connection = connection;
240     }
241
242     public void disconnect() throws ConnectionException {
243         boolean isConnected = isConnected();
244         try {
245             if (this.connection != null) {
246                 this.connectionEstablisher.disconnect(this.connection);
247             }
248         } finally {
249             this.connection = null;
250             if (isConnected() != isConnected) {
251                 this.propertyChangeSupport.firePropertyChange(
252                     "connected", isConnected, isConnected());
253             }
254         }
255     }
256     public void addSchema(String schema) {
257         if (schema != null && schema.trim().length() > 0) {
258             addSchema(new Schema(schema));
259         }
260     }
261
262     public void addSchema(Schema qualifier) {
263         if (qualifier != null) {
264             this.schemas.add(qualifier);
265             this.changed = true;
266             this.propertyChangeSupport.firePropertyChange("schemas", null, null);
267         }
268     }
269
270     public void setSchemaSelections(Schema[] schemas) {
271         this.schemas.clear();
272         for (int i = 0, length = (schemas == null) ? 0 : schemas.length;
273             i < length;
274             i++) {
275             this.schemas.add(schemas[i]);
276             
277         }
278         this.changed = true;
279         this.propertyChangeSupport.firePropertyChange("schemas", null, null);
280     }
281
282     /**
283      * @return a list of all the schemas that have been set up.
284      */
285     public Schema[] getSchemaSelections() {
286         List list = new ArrayList(this.schemas);
287         Collections.sort(list);
288         return (Schema[]) list.toArray(new Schema[list.size()]);
289     }
290     
291     public Schema[] getSchemas() throws NotConnectedException, SQLException {
292         Schema[] schemas = null;
293         if (useUsernameAsSchema()) {
294                 // do nothing
295         } else if (useAllSchemas()) {
296                 schemas = getDatabase().getSchemas();
297         } else {
298                 schemas = verifySchemas(getSchemaSelections());
299         }
300         return (schemas == null || schemas.length == 0) 
301                                 ? new Schema[] { getDefaultSchema() } 
302                         : schemas;
303     }
304
305         /**
306          * @param schemaSelections
307          * @return
308          * @throws SQLException
309          * @throws NotConnectedException
310          */
311         private Schema[] verifySchemas(Schema[] schemaSelections) 
312                         throws NotConnectedException, SQLException {
313                 Schema[] schemasFromDatabase = getDatabase().getSchemas();
314                 List list = Arrays.asList(schemasFromDatabase);
315                 for (int i = 0, length = schemaSelections == null ? 0 : schemaSelections.length; 
316                                 i < length; i++) {
317                         schemaSelections[i].setExists(list.contains(schemaSelections[i]));
318                 }
319                 return schemaSelections;
320         }
321
322         /**
323          * @return
324          * @throws NotConnectedException
325          * @throws SQLException
326          */
327         private Schema getDefaultSchema() throws NotConnectedException, SQLException {
328                 String username = getDatabase().getUsername();
329                 String actual = getAdapter().getDefaultSchema(username);
330                 return new Schema(actual, username, true);
331         }
332
333         /**
334          * @see java.lang.Object#equals(java.lang.Object)
335          */
336         public boolean equals(Object obj) {
337                 if (!(obj instanceof Bookmark)) return false;
338                 String name = ((Bookmark)obj).getName();
339                 if (name.equals(this.getName())) return true;
340                 return false;
341         }
342
343     /**
344      * @param listener
345      */
346     public synchronized void addPropertyChangeListener(PropertyChangeListener listener) {
347         this.propertyChangeSupport.addPropertyChangeListener(listener);
348     }
349
350     /**
351      * @param listener
352      */
353     public synchronized void removePropertyChangeListener(PropertyChangeListener listener) {
354         this.propertyChangeSupport.removePropertyChangeListener(listener);
355     }
356
357     public void addQuickListEntry(String type, String schemaName, String name) {
358         Entity entity = EntityFactory.getInstance().create(this, schemaName, name, type);
359         this.quickList.put(entity.getQualifiedName(), entity);
360         this.propertyChangeSupport.firePropertyChange("quickList", null, null);
361         this.changed = true;
362     }
363     
364     public void addQuickListEntry(Entity entity) {
365         addQuickListEntry(entity.getType(), entity.getSchema(), entity.getName());
366     }
367     
368     public void removeQuickListEntry(Entity entity) {
369         if (entity != null  && this.quickList.containsKey(entity.getQualifiedName())) {
370             this.quickList.remove(entity.getQualifiedName());
371             this.propertyChangeSupport.firePropertyChange("quickList", null, null);
372             this.changed = true;
373         }
374     }
375     
376     public Entity[] getQuickListEntries() {
377         return (Entity[]) this.quickList.values().toArray(new Entity[this.quickList.size()]);
378     }
379     
380     public boolean hasQuickList() {
381         return !this.quickList.isEmpty();
382     }
383     /**
384      * @return
385      */
386     public boolean isChanged() {
387         return changed;
388     }
389
390     /**
391      * @param b
392      */
393     public void setChanged(boolean b) {
394         changed = b;
395     }
396     
397     public Database getDatabase() throws NotConnectedException {
398         if (!isConnected()) {
399             throw new NotConnectedException();
400         }
401         return new Database(this);
402     }
403     
404     public DatabaseAdapter getAdapter() {
405         return this.driver == null 
406                                 ? null 
407                                 : AdapterFactory.getInstance().getAdapter(this.driver.getType());
408     }
409
410     public Entity[] getEntitiesForSchema(Schema schema, String type) throws SQLException {
411         try {
412             Entity[] entities = getDatabase().getEntities(this, schema, type);
413             return entities;
414         } catch (NotConnectedException e) {
415             return new Entity[0];
416         }
417     }
418     
419     public Entity getEntity(Schema schema, String name) throws SQLException {
420         Entity result = null;
421         if (schema != null && name != null) {
422             Entity[] entities = getEntitiesForSchema(schema, null);
423             for (int i = 0, length = (entities == null) ? 0 : entities.length;
424                 result == null && i < length;
425                 i++) {
426                 if (schema.equals(entities[i].getSchema()) &&
427                     name.equals(entities[i].getName())) {
428                     result = entities[i];
429                 }
430             }
431         }
432         return result;
433     }
434     
435     public boolean isInQuickList(Entity entity) {
436         return this.quickList.containsKey(entity.getQualifiedName());
437     }
438     
439     /**
440      * 
441      * @param queryString
442      */
443     public void addQuery(String queryString) {
444         if (this.queries.contains(queryString)) {
445             this.queries.remove(queryString);
446         }
447         this.queries.add(queryString);
448         
449         int size = getQueryHistorySize();
450         
451         while (this.queries.size() > size) {
452             this.queries.remove(0);
453         }
454         this.propertyChangeSupport.firePropertyChange("queries", null, null);
455         this.changed = true;
456     }
457     
458     public String[] getQueries() {
459         return (String[]) this.queries.toArray(new String[this.queries.size()]);
460     }
461     
462     private int getQueryHistorySize() {
463         IPreferenceStore store =
464             QuantumPlugin.getDefault().getPreferenceStore();
465         return store.getInt(getClass().getName() + ".queryHistorySize"); //$NON-NLS-1$
466     }
467     /**
468      * @return
469      */
470     public boolean getPromptForPassword() {
471         return promptForPassword;
472     }
473
474     /**
475      * @param b
476      */
477     public void setPromptForPassword(boolean b) {
478         promptForPassword = b;
479     }
480
481         /**
482          * @return
483          */
484         public boolean isAutoCommit() {
485                 return autoCommit;
486         }
487
488         /**
489          * @return
490          */
491         public String getAutoCommitPreference() {
492                 return autoCommitPreference;
493         }
494
495         /**
496          * @param b
497          */
498         public void setAutoCommit(boolean b) {
499                 autoCommit = b;
500         }
501
502         /**
503          * @param string
504          */
505         public void setAutoCommitPreference(String string) {
506                 autoCommitPreference = string;
507         }
508
509         // Returns true or false indicating whether this bookmark must be set to AutoCommit on connection or not 
510         public boolean getDefaultAutoCommit(){
511                 if (autoCommitPreference.equals(IQuantumConstants.autoCommitTrue)) return true;
512                 else if (autoCommitPreference.equals(IQuantumConstants.autoCommitFalse)) return false;
513                 else if (autoCommitPreference.equals(IQuantumConstants.autoCommitSaved)) return autoCommit;
514                 
515                 return true;    
516         }
517         
518         public void setJDBCDriver(JDBCDriver jdbcDriver) {
519                 this.driver = BookmarkCollection.getInstance().findDriver(jdbcDriver);
520         this.changed = true;
521         }
522         
523         public JDBCDriver getJDBCDriver() {
524                 return this.driver;
525         }
526         public boolean useAllSchemas() {
527                 return this.schemaRule == SCHEMA_RULE_USE_ALL;
528         }
529         public boolean useUsernameAsSchema() {
530                 return this.schemaRule == SCHEMA_RULE_USE_DEFAULT;
531         }
532         public boolean useSelectedSchemas() {
533                 return this.schemaRule == SCHEMA_RULE_USE_SELECTED;
534         }
535         public int getSchemaRule() {
536                 return this.schemaRule;
537         }
538         public void setSchemaRule(int schemaRule) {
539         if (this.schemaRule != schemaRule) {
540             this.schemaRule = schemaRule;
541             this.propertyChangeSupport.firePropertyChange("schemas", null, null);
542         }
543         }
544
545         public String getDisplayName() {
546                 return this.name;
547         }
548 }