KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > genimen > djeneric > tools > administrator > helpers > AdminPanel


1 /*
2  * Copyright (c) 2001-2005 by Genimen BV (www.genimen.com) All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, is permitted provided that the following conditions are met: -
6  * Redistributions of source code must retain the above copyright notice, this
7  * list of conditions and the following disclaimer. - Redistributions in binary
8  * form must reproduce the above copyright notice, this list of conditions and
9  * the following disclaimer in the documentation and/or other materials
10  * provided with the distribution. - All advertising materials mentioning
11  * features or use of this software must display the following acknowledgment:
12  * "This product includes Djeneric." - Products derived from this software may
13  * not be called "Djeneric" nor may "Djeneric" appear in their names without
14  * prior written permission of Genimen BV. - Redistributions of any form
15  * whatsoever must retain the following acknowledgment: "This product includes
16  * Djeneric."
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
19  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED. IN NO EVENT SHALL GENIMEN BV, DJENERIC.ORG, OR CONTRIBUTORS
22  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28  * POSSIBILITY OF SUCH DAMAGE.
29  */

30 package com.genimen.djeneric.tools.administrator.helpers;
31
32 import java.awt.BorderLayout JavaDoc;
33 import java.awt.Dimension JavaDoc;
34 import java.awt.Image JavaDoc;
35 import java.awt.Toolkit JavaDoc;
36 import java.awt.event.ActionEvent JavaDoc;
37 import java.awt.event.MouseEvent JavaDoc;
38 import java.io.BufferedReader JavaDoc;
39 import java.io.BufferedWriter JavaDoc;
40 import java.io.File JavaDoc;
41 import java.io.FileNotFoundException JavaDoc;
42 import java.io.FileReader JavaDoc;
43 import java.io.FileWriter JavaDoc;
44 import java.io.IOException JavaDoc;
45 import java.net.URL JavaDoc;
46 import java.sql.Connection JavaDoc;
47 import java.sql.SQLException JavaDoc;
48 import java.util.ArrayList JavaDoc;
49 import java.util.StringTokenizer JavaDoc;
50
51 import javax.swing.ImageIcon JavaDoc;
52 import javax.swing.JButton JavaDoc;
53 import javax.swing.JFileChooser JavaDoc;
54 import javax.swing.JOptionPane JavaDoc;
55 import javax.swing.JPanel JavaDoc;
56 import javax.swing.JScrollPane JavaDoc;
57 import javax.swing.JSplitPane JavaDoc;
58 import javax.swing.event.TreeExpansionEvent JavaDoc;
59 import javax.swing.event.TreeSelectionEvent JavaDoc;
60 import javax.swing.tree.DefaultMutableTreeNode JavaDoc;
61 import javax.swing.tree.DefaultTreeModel JavaDoc;
62 import javax.swing.tree.ExpandVetoException JavaDoc;
63 import javax.swing.tree.TreePath JavaDoc;
64
65 import com.genimen.djeneric.language.Messages;
66 import com.genimen.djeneric.repository.DjExtent;
67 import com.genimen.djeneric.repository.DjModelView;
68 import com.genimen.djeneric.repository.DjPersistenceManager;
69 import com.genimen.djeneric.repository.DjPersistenceManagerFactory;
70 import com.genimen.djeneric.repository.DjRepositoryDescriptor;
71 import com.genimen.djeneric.repository.DjSession;
72 import com.genimen.djeneric.repository.exceptions.DjenericException;
73 import com.genimen.djeneric.repository.exceptions.LogonException;
74 import com.genimen.djeneric.repository.exceptions.ObjectNotDefinedException;
75 import com.genimen.djeneric.repository.rdbms.RdbmsPersistenceManager;
76 import com.genimen.djeneric.repository.rdbms.SqlStatement;
77 import com.genimen.djeneric.tools.administrator.Administrator;
78 import com.genimen.djeneric.tools.administrator.editors.AdminEditor;
79 import com.genimen.djeneric.tools.administrator.nodes.AdministratorTree;
80 import com.genimen.djeneric.tools.administrator.nodes.AdministratorTreeCellRenderer;
81 import com.genimen.djeneric.tools.administrator.nodes.AdministratorTreeNode;
82 import com.genimen.djeneric.tools.administrator.nodes.ContextFolder;
83 import com.genimen.djeneric.tools.administrator.nodes.ContextNode;
84 import com.genimen.djeneric.tools.administrator.nodes.ModelViewFolder;
85 import com.genimen.djeneric.tools.administrator.nodes.ModelViewNode;
86 import com.genimen.djeneric.tools.administrator.nodes.RootNode;
87 import com.genimen.djeneric.tools.common.ExportSelectionDialog;
88 import com.genimen.djeneric.tools.export.Exporter;
89 import com.genimen.djeneric.tools.export.Importer;
90 import com.genimen.djeneric.tools.modeler.ModelEditor;
91 import com.genimen.djeneric.ui.DjCloseable;
92 import com.genimen.djeneric.ui.DjTabbedPane;
93 import com.genimen.djeneric.ui.DjVerticalFlowLayout;
94 import com.genimen.djeneric.ui.Util;
95 import com.genimen.djeneric.util.DjDefaultProgressDisplayer;
96 import com.genimen.djeneric.util.DjFileFilter;
97 import com.genimen.djeneric.util.DjFileUtil;
98 import com.genimen.djeneric.util.DjLogger;
99 import com.genimen.djeneric.util.DjProgressDisplayer;
100 import com.genimen.djeneric.util.DjStringReplacer;
101
102 public class AdminPanel extends JPanel JavaDoc implements DjCloseable, DjProgressDisplayer
103 {
104   private static final long serialVersionUID = 1L;
105   public static final String JavaDoc EXPORTLOCATION = "exportlocation";
106   public static final String JavaDoc DUMPLOCATION = "dumplocation";
107
108   private static final String JavaDoc SQLSERVER_DB = "sqlserver";
109   private static final String JavaDoc HYPERSONIC_DB = "hypersonic";
110   private static final String JavaDoc ORACLE_DB = "oracle";
111   private static final String JavaDoc DERBY_DB = "derby";
112   private static final String JavaDoc DB2_DB = "db2";
113   private static final String JavaDoc POINTBASE_DB = "pointbase";
114   private static final String JavaDoc UNKNOWN_DB = "unknown";
115   public final static String JavaDoc OK_MSG = Messages.getString("global.Ok");
116
117   BorderLayout JavaDoc borderLayout1 = new BorderLayout JavaDoc();
118   JButton JavaDoc _butEdit = new JButton JavaDoc();
119   JButton JavaDoc _butDelete = new JButton JavaDoc();
120   JScrollPane JavaDoc jScrollPane1 = new JScrollPane JavaDoc();
121   DjTabbedPane _tabs = new DjTabbedPane();
122   JButton JavaDoc _butReload = new JButton JavaDoc();
123   BorderLayout JavaDoc borderLayout3 = new BorderLayout JavaDoc();
124   JSplitPane JavaDoc _pnlUsers = new JSplitPane JavaDoc();
125   DjVerticalFlowLayout verticalFlowLayout1 = new DjVerticalFlowLayout();
126   JButton JavaDoc _butCreate = new JButton JavaDoc();
127   JPanel JavaDoc jPanel3 = new JPanel JavaDoc();
128   JPanel JavaDoc jPanel2 = new JPanel JavaDoc();
129   DjRepositoryDescriptor _repositoryDescriptor;
130   AdministratorTree _tree = new AdministratorTree();
131   RootNode _root = new RootNode();
132   DefaultTreeModel JavaDoc _treeModel = new DefaultTreeModel JavaDoc(_root);
133   AdministratorTreeCellRenderer _treeCellRendrer = new AdministratorTreeCellRenderer();
134
135   DjPersistenceManager _mgr;
136   Administrator _admin;
137   JButton JavaDoc _butClearContext = new JButton JavaDoc();
138   JButton JavaDoc _butExport = new JButton JavaDoc();
139   JButton JavaDoc _butImport = new JButton JavaDoc();
140
141   public AdminPanel(Administrator admin, DjRepositoryDescriptor repositoryDescriptor) throws DjenericException,
142       ClassNotFoundException JavaDoc, SQLException JavaDoc
143   {
144     _admin = admin;
145     _repositoryDescriptor = repositoryDescriptor;
146
147     DjPersistenceManagerFactory fact;
148     try
149     {
150       fact = new DjPersistenceManagerFactory(admin.getConfigFileName());
151       fact.setMessenger(admin);
152     }
153     catch (FileNotFoundException JavaDoc e)
154     {
155       throw new DjenericException(e);
156     }
157
158     /*
159      * Try to connect to the repository. If we get a LoadModelException the loading of the model failed. If this is
160      * caused by a table not found (getSQLState == S0002) the repository is probably not yet created. In this case we
161      * ask the user if we should create the tables for him. This is currently supported for Hypersonic, SqlServer and
162      * Oracle.
163      */

164     try
165     {
166       _mgr = fact.createInstance(repositoryDescriptor);
167     }
168     catch (Exception JavaDoc x)
169     {
170       Throwable JavaDoc rootException = x;
171       if (rootException instanceof DjenericException)
172       {
173         boolean lastXReached = false;
174         while (!lastXReached && !(rootException instanceof SQLException JavaDoc)
175                && (rootException instanceof DjenericException))
176         {
177           Throwable JavaDoc newRootException = ((DjenericException) rootException).getRootException();
178
179           lastXReached = (newRootException == x) || newRootException == rootException;
180           rootException = newRootException;
181         }
182       }
183
184       boolean rethrow = true;
185       boolean retry = false;
186       if (x.getMessage().toLowerCase().indexOf("table not found") != -1) retry = true;
187       if (x.getMessage().toLowerCase().indexOf("table or view does not exist") != -1) retry = true;
188       else if (rootException instanceof SQLException JavaDoc)
189       {
190         SQLException JavaDoc se = (SQLException JavaDoc) rootException;
191
192         String JavaDoc sqlState = se.getSQLState();
193         if (sqlState == null) sqlState = "";
194
195         int vendorCode = se.getErrorCode();
196         // Table not found?
197
if (sqlState.startsWith("42") || "S0002".equals(sqlState) || "ZD004".equals(sqlState) || vendorCode == 15006
198             || vendorCode == 942)
199         {
200           retry = true;
201         }
202       }
203       if (retry)
204       {
205         if (createRepositoryTables(repositoryDescriptor))
206         {
207           // retry the create...
208
_mgr = fact.createInstance(repositoryDescriptor);
209           rethrow = false;
210         }
211       }
212       if (rethrow) throw new DjenericException(x);
213     }
214
215     jbInit();
216
217     DjDefaultProgressDisplayer pd = new DjDefaultProgressDisplayer(true);
218     if (_mgr.bootstrapRepositoryIfNeeded(pd))
219     {
220       setStatusMessage(pd.getLog(), true);
221     }
222
223     boolean importExportSupported = _mgr instanceof RdbmsPersistenceManager;
224
225     _butExport.setVisible(importExportSupported);
226     _butImport.setVisible(importExportSupported);
227
228     _butReload.setIcon(getImageIcon("reload.gif"));
229     _butEdit.setIcon(getImageIcon("edit.gif"));
230     _butCreate.setIcon(getImageIcon("new.gif"));
231     _butDelete.setIcon(getImageIcon("delete.gif"));
232     _butImport.setIcon(getImageIcon("import.gif"));
233     _butExport.setIcon(getImageIcon("export.gif"));
234     _butClearContext.setIcon(getImageIcon("clear.gif"));
235     _tree_valueChanged(null);
236     _tree.putClientProperty("JTree.lineStyle", "Angled");
237
238   }
239
240   protected boolean createRepositoryTables(DjRepositoryDescriptor repositoryDescriptor) throws DjenericException,
241       ClassNotFoundException JavaDoc, SQLException JavaDoc
242   {
243     try
244     {
245       String JavaDoc dbType = UNKNOWN_DB;
246       boolean created = false;
247
248       if (repositoryDescriptor.getDriver().toLowerCase().indexOf("oracle") != -1) dbType = ORACLE_DB;
249       else if (repositoryDescriptor.getDriver().toLowerCase().indexOf("hsqldb") != -1) dbType = HYPERSONIC_DB;
250       else if (repositoryDescriptor.getDriver().toLowerCase().indexOf("sqlserver") != -1) dbType = SQLSERVER_DB;
251       else if (repositoryDescriptor.getDriver().toLowerCase().indexOf("pointbase") != -1) dbType = POINTBASE_DB;
252       else if (repositoryDescriptor.getDriver().toLowerCase().indexOf("derby") != -1) dbType = DERBY_DB;
253       else if (repositoryDescriptor.getUrl().toLowerCase().indexOf("derby") != -1) dbType = DERBY_DB;
254       else if (repositoryDescriptor.getDriver().toLowerCase().indexOf("db2") != -1) dbType = DB2_DB;
255       else if (repositoryDescriptor.getDriver().toLowerCase().indexOf("tds") != -1) dbType = SQLSERVER_DB;
256
257       if (dbType.equals(UNKNOWN_DB))
258       {
259         JFileChooser JavaDoc fc = new JFileChooser JavaDoc();
260
261         DjFileFilter filter = new DjFileFilter(new String JavaDoc[]{"sql"}, "SQL Create script");
262         fc.setFileFilter(filter);
263
264         fc.setDialogTitle(Messages.getString("AdminPanel.SelectCreateScript"));
265         String JavaDoc path = System.getProperties().getProperty("user.dir");
266         fc.setCurrentDirectory(new File JavaDoc(path));
267         fc.setSelectedFile(new File JavaDoc(path));
268         fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
269
270         if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
271         {
272           String JavaDoc fileName = fc.getSelectedFile().getAbsolutePath();
273
274           doRunCreateScript(repositoryDescriptor, DjFileUtil.readFile(fileName));
275
276           created = true;
277         }
278         else
279         {
280           JOptionPane.showMessageDialog(_admin, Messages.getString("AdminPanel.EmptyDb"), Messages
281               .getString("AdminPanel.NoTables"), JOptionPane.WARNING_MESSAGE);
282         }
283       }
284       else
285       {
286         int result = JOptionPane.showOptionDialog(_admin, Messages.getString("AdminPanel.EmptyDbKnown"), Messages
287             .getString("AdminPanel.CreateTables"), JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null,
288                                                   new String JavaDoc[]{Messages.getString("global.Create"),
289                                                       Messages.getString("global.Cancel")}, null);
290         if (result == 0)
291         {
292           runCreateScript(repositoryDescriptor, dbType);
293           created = true;
294         }
295       }
296       return created;
297     }
298     catch (IOException JavaDoc iox)
299     {
300       throw new DjenericException(iox);
301     }
302   }
303
304   private void runCreateScript(DjRepositoryDescriptor repositoryDescriptor, String JavaDoc dbType) throws IOException JavaDoc,
305       DjenericException, ClassNotFoundException JavaDoc, SQLException JavaDoc
306   {
307     String JavaDoc script = null;
308
309     if (dbType.equals(ORACLE_DB)) script = DjFileUtil.readResource(Administrator.class, "schemas/createoracle.sql");
310     else if (dbType.equals(HYPERSONIC_DB)) script = DjFileUtil.readResource(Administrator.class,
311                                                                             "schemas/createhypersonic.sql");
312     else if (dbType.equals(SQLSERVER_DB)) script = DjFileUtil.readResource(Administrator.class,
313                                                                            "schemas/createsqlserver.sql");
314     else if (dbType.equals(POINTBASE_DB)) script = DjFileUtil.readResource(Administrator.class,
315                                                                            "schemas/createpointbase.sql");
316     else if (dbType.equals(DB2_DB)) script = DjFileUtil.readResource(Administrator.class, "schemas/createdb2.sql");
317     else if (dbType.equals(DERBY_DB)) script = DjFileUtil.readResource(Administrator.class, "schemas/createderby.sql");
318     else throw new DjenericException(Messages.getString("AdminPanel.UnknownDb", dbType));
319
320     doRunCreateScript(repositoryDescriptor, script);
321   }
322
323   private void doRunCreateScript(DjRepositoryDescriptor repositoryDescriptor, String JavaDoc script) throws LogonException,
324       DjenericException, ClassNotFoundException JavaDoc, SQLException JavaDoc
325   {
326     setStatusMessage("Create " + repositoryDescriptor, true);
327     DjStringReplacer sr = new DjStringReplacer(script);
328     sr.replace("\nGO", ";");
329     script = sr.toString();
330     Connection JavaDoc conn = getConnection(repositoryDescriptor);
331     try
332     {
333       StringTokenizer JavaDoc stok = new StringTokenizer JavaDoc(script, ";");
334       while (stok.hasMoreElements())
335       {
336         String JavaDoc sql = stok.nextToken().trim();
337         if (sql.length() > 0)
338         {
339           SqlStatement stmt = new SqlStatement(conn, sql);
340           stmt.executeUpdate();
341         }
342       }
343
344       // some database require a commit for DDL, so just to be sure:
345
conn.commit();
346     }
347     finally
348     {
349       conn.close();
350     }
351     JOptionPane.showMessageDialog(_admin, Messages.getString("AdminPanel.RepositoryCreated"), Messages
352         .getString("AdminPanel.RepositoryCreatedTitle"), JOptionPane.INFORMATION_MESSAGE);
353   }
354
355   public Connection JavaDoc getConnection(DjRepositoryDescriptor repositoryDescriptor) throws LogonException,
356       DjenericException, ClassNotFoundException JavaDoc, SQLException JavaDoc
357   {
358     return _admin.getConnection(repositoryDescriptor);
359   }
360
361   public boolean canClose()
362   {
363     if (_tabs.getComponentCount() == 0) return true;
364
365     int result = JOptionPane.showOptionDialog(_admin, Messages.getString("AdminPanel.CloseDiscard"), Messages
366         .getString("AdminPanel.CloseDiscardTitle"), JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null,
367                                               new String JavaDoc[]{Messages.getString("AdminPanel.Close"),
368                                                   Messages.getString("global.Cancel")}, null);
369     return result == 0;
370   }
371
372   public boolean close()
373   {
374     _mgr.close();
375     _admin.removeTab(this);
376     return true;
377   }
378
379   void jbInit()
380   {
381     _butDelete.setPreferredSize(new Dimension JavaDoc(24, 24));
382     _butDelete.setToolTipText(Messages.getString("global.DeleteCtrl"));
383     _butDelete.addActionListener(new java.awt.event.ActionListener JavaDoc()
384     {
385       public void actionPerformed(ActionEvent JavaDoc e)
386       {
387         _butDelete_actionPerformed(e);
388       }
389     });
390     _butEdit.setPreferredSize(new Dimension JavaDoc(24, 24));
391     _butEdit.setToolTipText(Messages.getString("global.Edit"));
392     _butEdit.addActionListener(new java.awt.event.ActionListener JavaDoc()
393     {
394       public void actionPerformed(ActionEvent JavaDoc e)
395       {
396         _butEdit_actionPerformed(e);
397       }
398     });
399     this.setLayout(borderLayout1);
400     _butReload.setPreferredSize(new Dimension JavaDoc(24, 24));
401     _butReload.setToolTipText(Messages.getString("AdminPanel.ReloadSelectedNode"));
402     _butReload.addActionListener(new java.awt.event.ActionListener JavaDoc()
403     {
404       public void actionPerformed(ActionEvent JavaDoc e)
405       {
406         _butReload_actionPerformed(e);
407       }
408     });
409     _butCreate.setPreferredSize(new Dimension JavaDoc(24, 24));
410     _butCreate.setToolTipText(Messages.getString("AdminPanel.CreateNew"));
411     _butCreate.addActionListener(new java.awt.event.ActionListener JavaDoc()
412     {
413       public void actionPerformed(ActionEvent JavaDoc e)
414       {
415         _butCreate_actionPerformed(e);
416       }
417     });
418     jPanel3.setLayout(verticalFlowLayout1);
419     jPanel2.setLayout(borderLayout3);
420     _pnlUsers.setDividerLocation(220);
421     _tree.addTreeWillExpandListener(new javax.swing.event.TreeWillExpandListener JavaDoc()
422     {
423       public void treeWillExpand(TreeExpansionEvent JavaDoc e) throws ExpandVetoException JavaDoc
424       {
425         _tree_treeWillExpand(e);
426       }
427
428       public void treeWillCollapse(TreeExpansionEvent JavaDoc e)
429       {
430       }
431     });
432     _tree.addMouseListener(new java.awt.event.MouseAdapter JavaDoc()
433     {
434       public void mouseClicked(MouseEvent JavaDoc e)
435       {
436         _tree_mouseClicked(e);
437       }
438     });
439     _tree.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener JavaDoc()
440     {
441       public void valueChanged(TreeSelectionEvent JavaDoc e)
442       {
443         _tree_valueChanged(e);
444       }
445     });
446     _butExport.addActionListener(new java.awt.event.ActionListener JavaDoc()
447     {
448       public void actionPerformed(ActionEvent JavaDoc e)
449       {
450         _butExport_actionPerformed(e);
451       }
452     });
453     _butExport.setToolTipText(Messages.getString("AdminPanel.ExportContext"));
454     _butExport.setPreferredSize(new Dimension JavaDoc(24, 24));
455
456     _butClearContext.setToolTipText(Messages.getString("AdminPanel.ClearContext"));
457     _butClearContext.setPreferredSize(new Dimension JavaDoc(24, 24));
458     _butClearContext.addActionListener(new java.awt.event.ActionListener JavaDoc()
459     {
460       public void actionPerformed(ActionEvent JavaDoc e)
461       {
462         _butClearContext_actionPerformed(e);
463       }
464     });
465
466     _butImport.setPreferredSize(new Dimension JavaDoc(24, 24));
467     _butImport.setToolTipText(Messages.getString("global.ImportContext"));
468     _butImport.addActionListener(new java.awt.event.ActionListener JavaDoc()
469     {
470       public void actionPerformed(ActionEvent JavaDoc e)
471       {
472         _butImport_actionPerformed(e);
473       }
474     });
475     _pnlUsers.setOrientation(JSplitPane.VERTICAL_SPLIT);
476     _pnlUsers.add(_tabs, JSplitPane.RIGHT);
477     _pnlUsers.add(jPanel2, JSplitPane.LEFT);
478     jPanel2.add(jScrollPane1, BorderLayout.CENTER);
479     jScrollPane1.getViewport().add(_tree, null);
480     jPanel2.add(jPanel3, BorderLayout.WEST);
481     jPanel3.add(_butReload, null);
482     jPanel3.add(_butEdit, null);
483     jPanel3.add(_butCreate, null);
484     jPanel3.add(_butClearContext, null);
485     jPanel3.add(_butDelete, null);
486     add(_pnlUsers, BorderLayout.CENTER);
487     jPanel3.add(_butExport, null);
488     jPanel3.add(_butImport, null);
489
490     _tree.setRootVisible(false);
491     _tree.setCellRenderer(_treeCellRendrer);
492     _tree.setModel(_treeModel);
493     _tree.setShowsRootHandles(true);
494     _tree.setAutoscrolls(true);
495     _tree.setDoubleBuffered(true);
496     _tree.setToggleClickCount(0);
497
498     _tree.setManager(_mgr);
499
500     _root.setTree(_tree);
501     _root.insertAsChild(new RootNode());
502     _tree.expandPath(new TreePath JavaDoc(_root.getPath()));
503
504   }
505
506   /**
507    * @param e
508    */

509   protected void _butClearContext_actionPerformed(ActionEvent JavaDoc e)
510   {
511     if (!(_mgr instanceof RdbmsPersistenceManager))
512     {
513       setStatusMessage(Messages.getString("AdminPanel.OnlyRdbms"), false);
514     }
515     AdministratorTreeNode[] sels = getSelectedNodes();
516     if (sels[0] instanceof ContextNode)
517     {
518       ContextNode cn = (ContextNode) sels[0];
519       try
520       {
521         int result = JOptionPane.showOptionDialog(_admin, Messages.getString("AdminPanel.ClearContextAssert", cn
522             .toString()), Messages.getString("AdminPanel.ClearContextAssertTitle", cn.toString()),
523                                                   JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null,
524                                                   new String JavaDoc[]{Messages.getString("AdminPanel.Clear"),
525                                                       Messages.getString("global.Cancel")}, null);
526         if (result == 0)
527         {
528           cn.clearContext();
529           setStatusMessage(Messages.getString("AdminPanel.Cleared", cn.toString()), true);
530         }
531
532       }
533       catch (Exception JavaDoc x)
534       {
535         setStatusMessage(x);
536       }
537     }
538
539   }
540
541   public static ImageIcon JavaDoc getImageIcon(String JavaDoc fileName)
542   {
543     URL JavaDoc url = Administrator.class.getResource("images/" + fileName);
544     if (url != null) return new ImageIcon JavaDoc(url);
545     else return new ImageIcon JavaDoc("");
546     // Default to empty image
547
}
548
549   public static Image JavaDoc getImage(String JavaDoc fileName)
550   {
551     URL JavaDoc url = Administrator.class.getResource("images/" + fileName);
552     if (url != null) return Toolkit.getDefaultToolkit().getImage(url);
553
554     else return Toolkit.getDefaultToolkit().getImage("");
555   }
556
557   void _tree_treeWillExpand(TreeExpansionEvent JavaDoc e) throws ExpandVetoException JavaDoc
558   {
559     try
560     {
561       if (e.getPath().getLastPathComponent() instanceof AdministratorTreeNode)
562       {
563         AdministratorTreeNode node = (AdministratorTreeNode) e.getPath().getLastPathComponent();
564         node.expandNode();
565       }
566       _admin.setStatusMessage(OK_MSG);
567     }
568     catch (Exception JavaDoc x)
569     {
570       DjLogger.log(x);
571       throw new ExpandVetoException JavaDoc(new TreeExpansionEvent JavaDoc(this, e.getPath()), x.getMessage());
572     }
573   }
574
575   public AdministratorTreeNode[] getSelectedNodes()
576   {
577     if (_tree.getSelectionPath() == null) return new AdministratorTreeNode[0];
578     ArrayList JavaDoc result = new ArrayList JavaDoc(10);
579
580     TreePath JavaDoc[] tp = _tree.getSelectionPaths();
581
582     for (int qq = 0; qq < tp.length; qq++)
583     {
584       DefaultMutableTreeNode JavaDoc node = (DefaultMutableTreeNode JavaDoc) (tp[qq].getLastPathComponent());
585       if (node instanceof AdministratorTreeNode) result.add(node);
586     }
587     return (AdministratorTreeNode[]) result.toArray(new AdministratorTreeNode[0]);
588   }
589
590   void _butEdit_actionPerformed(ActionEvent JavaDoc e)
591   {
592     AdministratorTreeNode[] sels = getSelectedNodes();
593
594     for (int i = 0; i < sels.length; i++)
595     {
596       AdminEditor editor = sels[i].getEditor(this);
597       if (editor != null) addToTabs(editor, sels[i].toString(), sels[i].getImageIcon());
598     }
599   }
600
601   public void closeEditor(JPanel JavaDoc editor)
602   {
603     for (int i = 0; i < _tabs.getComponentCount(); i++)
604     {
605       if (_tabs.getComponentAt(i) == editor)
606       {
607         _tabs.remove(editor);
608         return;
609       }
610     }
611     setStatusMessage(Messages.getString("global.Ok"), true);
612   }
613
614   public void addToTabs(AdminEditor editor, String JavaDoc title, ImageIcon JavaDoc icon)
615   {
616     String JavaDoc id = editor.getID();
617
618     // Check to see if an editor is already open
619
if (id != null)
620     {
621       for (int i = 0; i < _tabs.getComponentCount(); i++)
622       {
623         if (_tabs.getComponent(i) instanceof AdminEditor)
624         {
625           AdminEditor e = (AdminEditor) _tabs.getComponent(i);
626           if (e.getID() != null)
627           {
628             if (e.getID().equals(id))
629             {
630               _tabs.setSelectedComponent(e);
631               return;
632             }
633           }
634         }
635       }
636     }
637
638     _tabs.addTab(title, icon, editor);
639     _tabs.setSelectedComponent(editor);
640     editor.requestFocus();
641   }
642
643   public void setStatusMessage(String JavaDoc msg, boolean isInformative)
644   {
645     _admin.setStatusMessageNow(msg, isInformative);
646   }
647
648   public void setStatusMessage(Throwable JavaDoc t)
649   {
650     _admin.setStatusMessage(t);
651   }
652
653   public DjPersistenceManager getManager()
654   {
655     return _mgr;
656   }
657
658   void _butCreate_actionPerformed(ActionEvent JavaDoc e)
659   {
660     try
661     {
662       AdministratorTreeNode[] sels = getSelectedNodes();
663
664       for (int i = 0; i < sels.length; i++)
665       {
666         AdminEditor editor = sels[i].getCreateEditor(this);
667         if (editor != null) addToTabs(editor, Messages.getString("AdminPanel.New") + " " + sels[i].getNodeType(),
668                                       sels[i].getObjectImageIcon());
669       }
670     }
671     catch (Exception JavaDoc x)
672     {
673       setStatusMessage(x.getMessage(), false);
674     }
675   }
676
677   void _butDelete_actionPerformed(ActionEvent JavaDoc e)
678   {
679     AdministratorTreeNode[] sels = getSelectedNodes();
680     try
681     {
682       boolean dontask = false;
683       for (int i = 0; i < sels.length; i++)
684       {
685         if (!dontask)
686         {
687           int result = JOptionPane.showOptionDialog(_admin, Messages.getString("AdminPanel.SureToDelete", sels[i]
688               .toString()), Messages.getString("AdminPanel.SureToDeleteTitle", sels[i].toString()),
689                                                     JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null,
690                                                     new String JavaDoc[]{Messages.getString("global.Yes"),
691                                                         Messages.getString("global.Yes2All"),
692                                                         Messages.getString("global.Cancel")}, null);
693           if ((result != 0) && (result != 1)) return;
694           // cancel or closed
695
if (result == 1) dontask = true;
696         }
697         sels[i].delete();
698       }
699       setStatusMessage(OK_MSG, true);
700     }
701     catch (Exception JavaDoc x)
702     {
703       setStatusMessage(x);
704     }
705   }
706
707   void _butReload_actionPerformed(ActionEvent JavaDoc e)
708   {
709     AdministratorTreeNode[] sels = getSelectedNodes();
710
711     try
712     {
713       for (int i = 0; i < sels.length; i++)
714       {
715         sels[i].reload();
716       }
717     }
718     catch (Exception JavaDoc x)
719     {
720       setStatusMessage(x);
721     }
722   }
723
724   void _tree_mouseClicked(MouseEvent JavaDoc e)
725   {
726     if (e.getClickCount() > 1) _butEdit_actionPerformed(null);
727   }
728
729   public DjPersistenceManager getPersistenceManager()
730   {
731     return _mgr;
732   }
733
734   void _tree_valueChanged(TreeSelectionEvent JavaDoc e)
735   {
736     boolean canEdit = false;
737     boolean canDelete = false;
738     boolean canCreate = false;
739     boolean canImport = false;
740     boolean canExport = false;
741     boolean canClear = false;
742
743     AdministratorTreeNode[] sels = getSelectedNodes();
744
745     for (int i = 0; i < sels.length; i++)
746     {
747       canEdit |= sels[i].canEdit();
748       canDelete |= sels[i].canDelete();
749       canCreate |= sels[i].canCreate();
750       canImport = sels[0].canImport();
751       canExport = sels[0].canExport();
752       canClear = sels[0].canClear();
753     }
754     _butImport.setEnabled(canImport);
755     _butExport.setEnabled(canExport);
756     _butCreate.setEnabled(canCreate);
757     _butDelete.setEnabled(canDelete);
758     _butEdit.setEnabled(canEdit);
759     _butClearContext.setEnabled(canClear);
760   }
761
762   private void exportContext(AdministratorTreeNode[] sels)
763   {
764     ContextNode cn = (ContextNode) sels[0];
765     JFileChooser JavaDoc fc = new JFileChooser JavaDoc();
766
767     DjFileFilter filter = new DjFileFilter(new String JavaDoc[]{ModelEditor.DUMP_EXTENSION}, "Dump");
768     fc.setFileFilter(filter);
769
770     fc.setDialogTitle(Messages.getString("AdminPanel.Export2File"));
771     String JavaDoc path = _admin.getProperty(DUMPLOCATION, System.getProperties().getProperty("user.dir")) + "/"
772                   + cn.getContext().getCode() + ".dmp";
773     fc.setCurrentDirectory(new File JavaDoc(path));
774     fc.setSelectedFile(new File JavaDoc(path));
775     fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
776
777     if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
778     {
779       try
780       {
781         String JavaDoc fileName = fc.getSelectedFile().getAbsolutePath();
782
783         if (!fileName.endsWith(ModelEditor.DUMP_EXTENSION)) fileName += "." + ModelEditor.DUMP_EXTENSION;
784
785         _admin.setProperty(DUMPLOCATION, fc.getSelectedFile().getParent());
786
787         File JavaDoc file = new File JavaDoc(fileName);
788         boolean skip = false;
789
790         if (file.exists())
791         {
792           skip = !Util.isOkToOverwrite(this, file);
793         }
794
795         if (!skip)
796         {
797           ExportSelectionDialog esd = new ExportSelectionDialog(Util.findFrame(this), _mgr.getExtents(), false, true);
798           if (!esd.wasCanceled() && esd.getSelectedExtents().length > 0)
799           {
800             DjExtent[] unsels = esd.getUnSelectedExtents();
801             Exporter exporter = new Exporter(this, (RdbmsPersistenceManager) _mgr, cn.getContext().getCode());
802             for (int i = 0; i < unsels.length; i++)
803               exporter.ignoreExtent(unsels[i].getName());
804             long counter = exporter.exportDump(file);
805             setStatusMessage(Messages.getString("AdminPanel.Exported", String.valueOf(counter)), true);
806           }
807           else
808           {
809             setStatusMessage(Messages.getString("AdminPanel.ExportCancelled"), true);
810           }
811         }
812       }
813       catch (Exception JavaDoc x)
814       {
815         setStatusMessage(x);
816       }
817     }
818   }
819
820   boolean isOkToMerge(String JavaDoc contextName)
821   {
822     int result = JOptionPane.showOptionDialog(_admin, Messages.getString("AdminPanel.IsMergeOk", contextName), Messages
823         .getString("AdminPanel.IsMergeOkTitle"), JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null,
824                                               new String JavaDoc[]{Messages.getString("AdminPanel.Merge"),
825                                                   Messages.getString("global.Cancel")}, null);
826     return result == 0;
827   }
828
829   void importContext(ContextNode cn)
830   {
831     ImportContextDialog icd;
832     try
833     {
834       if (!isOkToMerge(cn.getContext().getCode())) return;
835
836       icd = new ImportContextDialog(_admin, _mgr, cn.getContext().getCode());
837       if (!icd.wasCancelled())
838       {
839         //DjDefaultProgressDisplayer pd = new DjDefaultProgressDisplayer();
840

841         Importer importer = new Importer(this, (RdbmsPersistenceManager) _mgr);
842         importer.setContext(cn.getContext().getCode());
843         long count = importer.importDump(new File JavaDoc(icd.getFileName()));
844         setStatusMessage(Messages.getString("AdminPanel.Imported", String.valueOf(count)), true);
845       }
846     }
847     catch (Exception JavaDoc x)
848     {
849       setStatusMessage(x);
850     }
851   }
852
853   void importContext(ContextFolder cf)
854   {
855     try
856     {
857       ImportContextDialog icd = new ImportContextDialog(_admin, _mgr, null);
858       if (!icd.wasCancelled())
859       {
860         DjDefaultProgressDisplayer pd = new DjDefaultProgressDisplayer();
861
862         Importer importer = new Importer(pd, (RdbmsPersistenceManager) _mgr);
863         try
864         {
865           importer.setContext(icd.getContextName());
866           // If we get here the context already exist: ask if a merge is to be
867
// done
868
if (!isOkToMerge(icd.getContextName())) return;
869         }
870         catch (ObjectNotDefinedException onde)
871         {
872           importer.createAndSetContext(pd, icd.getContextName());
873         }
874         long count = importer.importDump(new File JavaDoc(icd.getFileName()));
875         cf.reload();
876         setStatusMessage(Messages.getString("AdminPanel.Imported", String.valueOf(count)), true);
877       }
878     }
879     catch (Exception JavaDoc x)
880     {
881       setStatusMessage(x);
882     }
883   }
884
885   void _butImport_actionPerformed(ActionEvent JavaDoc e)
886   {
887     if (!(_mgr instanceof RdbmsPersistenceManager))
888     {
889       setStatusMessage(Messages.getString("AdminPanel.OnlyRdbms"), false);
890     }
891     AdministratorTreeNode[] sels = getSelectedNodes();
892     if (sels[0] instanceof ContextNode)
893     {
894       importContext((ContextNode) sels[0]);
895
896     }
897     else if (sels[0] instanceof ContextFolder)
898     {
899       importContext((ContextFolder) sels[0]);
900     }
901     else if (sels[0] instanceof ModelViewFolder)
902     {
903       importView((ModelViewFolder) sels[0]);
904     }
905     else if (sels[0] instanceof ModelViewNode)
906     {
907       importView((ModelViewFolder) sels[0].getParentTreeNode());
908     }
909   }
910
911   private void importView(ModelViewFolder folder)
912   {
913     try
914     {
915       JFileChooser JavaDoc fc = new JFileChooser JavaDoc();
916
917       String JavaDoc path = _admin.getProperty(EXPORTLOCATION, System.getProperties().getProperty("user.dir"));
918       fc.setCurrentDirectory(new File JavaDoc(path));
919
920       DjFileFilter filter = new DjFileFilter(new String JavaDoc[]{ModelEditor.VIEW_EXTENSION}, Messages
921           .getString("ModelEditor.DjenericView"));
922       fc.setFileFilter(filter);
923       fc.setDialogTitle(Messages.getString("ModelEditor.ImportView"));
924       fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
925       fc.setMultiSelectionEnabled(true);
926
927       if (fc.showOpenDialog(this) != JFileChooser.CANCEL_OPTION)
928       {
929         File JavaDoc[] allFiles = fc.getSelectedFiles();
930
931         for (int i = 0; i < allFiles.length; i++)
932         {
933           if (i == 0) _admin.setProperty(EXPORTLOCATION, allFiles[0].getAbsolutePath());
934
935           String JavaDoc fileName = allFiles[i].getAbsolutePath();
936           File JavaDoc inFile = new File JavaDoc(fileName);
937           BufferedReader JavaDoc br = new BufferedReader JavaDoc(new FileReader JavaDoc(inFile));
938           StringBuffer JavaDoc src = new StringBuffer JavaDoc(10000);
939           String JavaDoc ln;
940           while ((ln = br.readLine()) != null)
941           {
942             src.append(ln);
943             src.append("\n");
944           }
945           br.close();
946
947           DjModelView newView = _mgr.createModelView();
948           String JavaDoc viewName = allFiles[i].getName();
949           if (viewName.indexOf(".") > 0) viewName = viewName.substring(0, viewName.indexOf("."));
950
951           newView.setCode(viewName);
952           newView.setDefinition(src.toString());
953           DjSession session = _mgr.createSession();
954           try
955           {
956             newView.persist(session);
957             session.commit();
958           }
959           finally
960           {
961             session.close();
962           }
963         }
964         folder.reload();
965       }
966     }
967     catch (Exception JavaDoc x)
968     {
969       setStatusMessage(x);
970     }
971
972   }
973
974   void _butExport_actionPerformed(ActionEvent JavaDoc e)
975   {
976     AdministratorTreeNode[] sels = getSelectedNodes();
977     if (sels[0] instanceof ContextNode)
978     {
979       if (!(_mgr instanceof RdbmsPersistenceManager))
980       {
981         setStatusMessage(Messages.getString("AdminPanel.OnlyRdbms"), false);
982       }
983       exportContext(sels);
984     }
985     if (sels[0] instanceof ModelViewFolder)
986     {
987       exportViews((ModelViewFolder) sels[0]);
988     }
989     if (sels[0] instanceof ModelViewNode)
990     {
991       exportView((ModelViewNode) sels[0]);
992     }
993   }
994
995   private void exportViews(ModelViewFolder folder)
996   {
997
998     try
999     {
1000      folder.reload();
1001
1002      JFileChooser JavaDoc fc = new JFileChooser JavaDoc();
1003      fc.setDialogTitle(Messages.getString("AdminPanel.Export2File"));
1004      DjFileFilter filter = new DjFileFilter(new String JavaDoc[]{ModelEditor.VIEW_EXTENSION}, Messages
1005          .getString("ModelEditor.DjenericView"));
1006      fc.setFileFilter(filter);
1007
1008      String JavaDoc path = _admin.getProperty(EXPORTLOCATION, System.getProperties().getProperty("user.dir"));
1009
1010      fc.setCurrentDirectory(new File JavaDoc(path));
1011      fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
1012
1013      if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
1014      {
1015        _admin.setProperty(EXPORTLOCATION, fc.getSelectedFile().getParent());
1016
1017        int count = 0;
1018        for (int i = 0; i < folder.getChildCount(); i++)
1019        {
1020          if (!(folder.getChildAt(i) instanceof ModelViewNode)) continue;
1021
1022          ModelViewNode node = (ModelViewNode) folder.getChildAt(i);
1023
1024          String JavaDoc fileName = fc.getSelectedFile().getAbsolutePath() + "/" + node.getModelView().getCode() + "."
1025                            + ModelEditor.VIEW_EXTENSION;
1026
1027          count += exportViewNode(fileName, node);
1028        }
1029        setStatusMessage(Messages.getString("AdminPanel.MultipleViewsExported", String.valueOf(count), fc
1030            .getSelectedFile().getAbsolutePath()), true);
1031      }
1032    }
1033    catch (Exception JavaDoc x)
1034    {
1035      setStatusMessage(x);
1036    }
1037  }
1038
1039  private void exportView(ModelViewNode node)
1040  {
1041    JFileChooser JavaDoc fc = new JFileChooser JavaDoc();
1042    fc.setDialogTitle(Messages.getString("AdminPanel.Export2File"));
1043    DjFileFilter filter = new DjFileFilter(new String JavaDoc[]{ModelEditor.VIEW_EXTENSION}, Messages
1044        .getString("ModelEditor.DjenericView"));
1045    fc.setFileFilter(filter);
1046
1047    String JavaDoc path = _admin.getProperty(EXPORTLOCATION, System.getProperties().getProperty("user.dir"));
1048    String JavaDoc filename = path + "/" + node.getModelView().getCode() + "." + ModelEditor.VIEW_EXTENSION;
1049
1050    fc.setCurrentDirectory(new File JavaDoc(path));
1051    fc.setSelectedFile(new File JavaDoc(filename));
1052    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
1053
1054    if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
1055    {
1056      try
1057      {
1058        String JavaDoc fileName = fc.getSelectedFile().getAbsolutePath();
1059        if (!fileName.endsWith(ModelEditor.VIEW_EXTENSION)) fileName += "." + ModelEditor.VIEW_EXTENSION;
1060        _admin.setProperty(EXPORTLOCATION, fc.getSelectedFile().getParent());
1061
1062        exportViewNode(fileName, node);
1063      }
1064      catch (Exception JavaDoc x)
1065      {
1066        setStatusMessage(x);
1067      }
1068    }
1069  }
1070
1071  private int exportViewNode(String JavaDoc fileName, ModelViewNode node) throws IOException JavaDoc
1072  {
1073    File JavaDoc file = new File JavaDoc(fileName);
1074    boolean skip = false;
1075    int result = 0;
1076
1077    if (file.exists())
1078    {
1079      skip = !Util.isOkToOverwrite(this, file);
1080    }
1081
1082    if (!skip)
1083    {
1084      DjModelView vw = node.getModelView();
1085      BufferedWriter JavaDoc w = new BufferedWriter JavaDoc(new FileWriter JavaDoc(file));
1086      w.write(vw.getDefinition());
1087      w.close();
1088      result = 1;
1089      setStatusMessage(Messages.getString("AdminPanel.ViewsExported", fileName), true);
1090    }
1091    return result;
1092  }
1093
1094  public void displayProgress(String JavaDoc msg)
1095  {
1096    setStatusMessage(msg, true);
1097  }
1098}
Popular Tags