KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > hibernate > eclipse > console > wizards > ConsoleConfigurationWizardPage


1 /*
2  * Created on 2004-10-13
3  *
4  *
5  */

6 package org.hibernate.eclipse.console.wizards;
7
8 import java.lang.reflect.InvocationTargetException JavaDoc;
9 import java.util.ArrayList JavaDoc;
10 import java.util.Collections JavaDoc;
11 import java.util.Iterator JavaDoc;
12 import java.util.List JavaDoc;
13
14 import org.eclipse.core.internal.resources.File;
15 import org.eclipse.core.resources.IContainer;
16 import org.eclipse.core.resources.IProject;
17 import org.eclipse.core.resources.IResource;
18 import org.eclipse.core.resources.IResourceProxy;
19 import org.eclipse.core.resources.IResourceProxyVisitor;
20 import org.eclipse.core.resources.ResourcesPlugin;
21 import org.eclipse.core.runtime.CoreException;
22 import org.eclipse.core.runtime.IPath;
23 import org.eclipse.core.runtime.IProgressMonitor;
24 import org.eclipse.core.runtime.Path;
25 import org.eclipse.jdt.core.IJavaElement;
26 import org.eclipse.jdt.core.IJavaProject;
27 import org.eclipse.jdt.core.JavaCore;
28 import org.eclipse.jdt.core.search.IJavaSearchConstants;
29 import org.eclipse.jdt.core.search.IJavaSearchScope;
30 import org.eclipse.jdt.core.search.SearchEngine;
31 import org.eclipse.jdt.core.search.SearchMatch;
32 import org.eclipse.jdt.core.search.SearchParticipant;
33 import org.eclipse.jdt.core.search.SearchPattern;
34 import org.eclipse.jdt.ui.wizards.BuildPathDialogAccess;
35 import org.eclipse.jface.dialogs.IDialogPage;
36 import org.eclipse.jface.dialogs.ProgressMonitorDialog;
37 import org.eclipse.jface.operation.IRunnableWithProgress;
38 import org.eclipse.jface.viewers.ISelection;
39 import org.eclipse.jface.viewers.IStructuredSelection;
40 import org.eclipse.jface.wizard.WizardPage;
41 import org.eclipse.swt.SWT;
42 import org.eclipse.swt.events.ModifyEvent;
43 import org.eclipse.swt.events.ModifyListener;
44 import org.eclipse.swt.events.SelectionAdapter;
45 import org.eclipse.swt.events.SelectionEvent;
46 import org.eclipse.swt.layout.GridData;
47 import org.eclipse.swt.layout.GridLayout;
48 import org.eclipse.swt.widgets.Button;
49 import org.eclipse.swt.widgets.Composite;
50 import org.eclipse.swt.widgets.Label;
51 import org.eclipse.swt.widgets.Table;
52 import org.eclipse.swt.widgets.TableItem;
53 import org.eclipse.swt.widgets.Text;
54 import org.hibernate.console.KnownConfigurations;
55 import org.hibernate.eclipse.console.EclipseConsoleConfiguration;
56 import org.hibernate.eclipse.console.HibernateConsolePlugin;
57 import org.hibernate.eclipse.console.utils.DialogSelectionHelper;
58
59 /**
60  * @author max
61  *
62  *
63  */

64 public class ConsoleConfigurationWizardPage extends WizardPage {
65     
66     private Text propertyFileText;
67     private Text configurationFileText;
68     private Text configurationNameText;
69     private EclipseConsoleConfiguration oldConfiguaration = null;
70     
71     private ISelection selection;
72     private UpDownList mappingFilesViewer;
73     private UpDownList classPathViewer;
74     
75     /**
76      * Constructor for SampleNewWizardPage.
77      * @param pageName
78      */

79     public ConsoleConfigurationWizardPage(ISelection selection) {
80         super("configurationPage");
81         setTitle("Create Hibernate Console Configuration");
82         setDescription("This wizard allows you to create a configuration for Hibernate Console.");
83         this.selection = selection;
84     }
85     
86     /**
87      * @see IDialogPage#createControl(Composite)
88      */

89     public void createControl(Composite parent) {
90         Composite container = new Composite(parent, SWT.NULL);
91         GridLayout layout = new GridLayout();
92         container.setLayout(layout);
93         layout.numColumns = 3;
94         layout.verticalSpacing = 9;
95         
96         Label label;
97         Button button;
98         GridData gd;
99         
100         ModifyListener modifyListener = new ModifyListener() {
101             public void modifyText(ModifyEvent e) {
102                 dialogChanged();
103             }
104         };
105         
106         label = new Label(container, SWT.NULL);
107         label.setText("&Name:");
108         
109         configurationNameText = new Text(container, SWT.BORDER | SWT.SINGLE);
110         gd = new GridData(GridData.FILL_HORIZONTAL);
111         gd.horizontalSpan = 2;
112         configurationNameText.setLayoutData(gd);
113         configurationNameText.addModifyListener(modifyListener);
114         
115         label = new Label(container, SWT.NULL);
116         label.setText("&Property file:");
117         
118         propertyFileText = new Text(container, SWT.BORDER | SWT.SINGLE);
119         gd = new GridData(GridData.FILL_HORIZONTAL);
120         propertyFileText.setLayoutData(gd);
121         propertyFileText.addModifyListener(modifyListener);
122         
123         
124         button = new Button(container, SWT.PUSH);
125         button.setText("Browse...");
126         button.addSelectionListener(new SelectionAdapter() {
127             public void widgetSelected(SelectionEvent e) {
128                 handlePropertyFileBrowse();
129             }
130         });
131         
132         label = new Label(container, SWT.NULL);
133         label.setText("&Configuration file:");
134         
135         configurationFileText = new Text(container, SWT.BORDER | SWT.SINGLE);
136         gd = new GridData(GridData.FILL_HORIZONTAL);
137         configurationFileText.setLayoutData(gd);
138         configurationFileText.addModifyListener(modifyListener);
139         
140         button = new Button(container, SWT.PUSH);
141         button.setText("Browse...");
142         button.addSelectionListener(new SelectionAdapter() {
143             public void widgetSelected(SelectionEvent e) {
144                 handleConfigurationFileBrowse();
145             }
146         });
147         
148         buildMappingFileTable(container);
149         buildClassPathTable(container);
150         initialize();
151         dialogChanged();
152         setControl(container);
153     }
154     
155     
156     private void buildClassPathTable(Composite parent) {
157         classPathViewer = new UpDownList(parent, getShell(), "Classpath (only add path for POJO and driver - No Hibernate jars!)") {
158             protected Object JavaDoc[] handleAdd(int idx) {
159
160                 TableItem[] items = getTable().getItems();
161                 IPath[] exclude = new IPath[items.length];
162                 
163                 for (int i = 0; i < items.length; i++) {
164                     TableItem item = items[i];
165                     exclude[i] = (IPath) item.getData();
166                 }
167                 
168                 switch (idx) {
169                 case 0:
170                     return DialogSelectionHelper.chooseFileEntries(getShell(), null, exclude, "Add classpath entry", "Add a directory, .zip or .jar file", new String JavaDoc[] { ".jar", ".zip" }, true, true, true);
171                 case 1:
172                     return BuildPathDialogAccess.chooseExternalJAREntries(getShell());
173                 default:
174                     return null;
175                 }
176                 
177             }
178
179             protected String JavaDoc[] getAddButtonLabels() {
180                 return new String JavaDoc[] { "Add JARS...", "Add External JARS..." };
181             }
182             protected void listChanged() {
183                 dialogChanged();
184             }
185             
186         };
187         
188     }
189
190     private void buildMappingFileTable(Composite parent) {
191         mappingFilesViewer = new UpDownList(parent, getShell(), "Mapping files") {
192             protected Object JavaDoc[] handleAdd(int idx) {
193                 TableItem[] items = getTable().getItems();
194                 IPath[] exclude = new IPath[items.length];
195                 
196                 for (int i = 0; i < items.length; i++) {
197                     TableItem item = items[i];
198                     exclude[i] = (IPath) item.getData();
199                 }
200                 
201                 return DialogSelectionHelper.chooseFileEntries(getShell(), null, exclude, "Add hbm.xml file", "Add a Hibernate Mapping file", new String JavaDoc[] { "hbm.xml" }, true, false, true);
202             }
203
204             protected void listChanged() {
205                 dialogChanged();
206             }
207         };
208     }
209     
210     
211         
212     /**
213      * A visitor class that will make a "best guess" on which files the
214      * user want for the properties and config file.
215      *
216      * @author max
217      *
218      */

219     static class Visitor implements IResourceProxyVisitor {
220         
221         public IPath propertyFile;
222         public IPath configFile;
223         public IJavaProject javaProject;
224         public List JavaDoc classpath = new ArrayList JavaDoc();
225         public List JavaDoc mappings = new ArrayList JavaDoc();
226         
227         public boolean visit(IResourceProxy proxy) throws CoreException {
228             //System.out.println("visit: " + proxy.getName());
229
IPath fullPath = proxy.requestFullPath();
230             if(proxy.getType() == IResource.FILE) {
231                 if("hibernate.properties".equals(proxy.getName())) {
232                     propertyFile = fullPath;
233                     return false;
234                 }
235                 
236                 if("hibernate.cfg.xml".equals(proxy.getName())) {
237                     configFile = fullPath;
238                     mappings.clear(); // we prefer af cfg.xml over mappings
239
return false;
240                 }
241                 
242                 // only add mappings if we don't have a config file.
243
if(configFile==null && proxy.getName().endsWith(".hbm.xml")) {
244                     mappings.add(fullPath);
245                     return false;
246                 }
247             } else if(proxy.getType() == IResource.FOLDER) {
248                 if(javaProject!=null) {
249                     if(javaProject.getOutputLocation().isPrefixOf(fullPath)) {
250                         classpath.add(fullPath);
251                         //System.out.println("SKIPPING " + proxy.getName());
252
return false; // skip output locations
253
}
254                 }
255             }
256             return true;
257         }
258     }
259
260
261     /**
262      * Tests if the current workbench selection is a suitable
263      * container to use.
264      * @throws
265      */

266     
267     private void initialize() {
268         try {
269             Visitor v = new Visitor();
270         // use selection to build configuration from it...
271
if (selection!=null && selection.isEmpty()==false && selection instanceof IStructuredSelection) {
272             IStructuredSelection ssel = (IStructuredSelection)selection;
273             if (ssel.size()>1) return;
274             Object JavaDoc obj = ssel.getFirstElement();
275             
276             IContainer container = null;
277             if (obj instanceof IJavaProject) {
278                 v.javaProject = (IJavaProject) obj;
279                 container = ((IJavaProject)obj).getProject();
280             } else if (obj instanceof IResource) {
281                 if (obj instanceof IContainer)
282                     container = (IContainer)obj;
283                 else
284                     container = ((IResource)obj).getParent();
285             }
286             
287             if(container!=null) {
288                 container.accept(v, IResource.NONE);
289                 
290                 if(v.javaProject==null) {
291                     IProject project = container.getProject();
292                     v.javaProject = JavaCore.create(project);
293                 }
294                 
295                 if(v.javaProject!=null) configurationNameText.setText(v.javaProject.getElementName());
296                 if (v.propertyFile!=null) propertyFileText.setText(v.propertyFile.toOSString());
297                 if (v.configFile!=null) configurationFileText.setText(v.configFile.toOSString());
298                 if (!v.mappings.isEmpty()) mappingFilesViewer.add(v.mappings.toArray(), false);
299                 if (!v.classpath.isEmpty()) classPathViewer.add(v.classpath.toArray(), false);
300
301                 
302                 if(v.javaProject!=null) {
303                     classPathViewer.add(locateTypes(v.javaProject).toArray(), false);
304                 }
305             } else if (obj instanceof EclipseConsoleConfiguration) {
306                 // trying to edit an EXISTING consoleconfiguration
307
EclipseConsoleConfiguration cc = (EclipseConsoleConfiguration) obj;
308                 EclipseConsoleConfigurationPreferences prefs = (EclipseConsoleConfigurationPreferences) cc.getPreferences();
309                 
310                 configurationNameText.setText(prefs.getName());
311                 if(prefs.getPropertyFilename()!=null) propertyFileText.setText(prefs.getPropertyFilename().toOSString());
312                 if(prefs.getCfgFile()!=null) configurationFileText.setText(prefs.getCfgFile().toOSString());
313                 if(prefs.getMappings()!=null) mappingFilesViewer.add(prefs.getMappings(),false);
314                 if(prefs.getCustomClasspath()!=null) classPathViewer.add(prefs.getCustomClasspath(),false);
315                 
316                 oldConfiguaration = cc;
317             }
318             
319             
320             
321             
322         }
323         } catch (CoreException ce) {
324             HibernateConsolePlugin.getDefault().logErrorMessage("Problem while initializing ConsoleConfigurationWizardPage", ce);
325         }
326         
327     }
328
329     List JavaDoc locateTypes(final IJavaProject javaProject) {
330         
331         try {
332             String JavaDoc typeName = "java.sql.Driver";
333             final SearchPattern pattern = SearchPattern.createPattern(typeName, IJavaSearchConstants.TYPE, IJavaSearchConstants.IMPLEMENTORS, SearchPattern.R_EXACT_MATCH);
334             final IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaElement[] {javaProject });
335             
336             final SearchEngine engine = new SearchEngine();
337             
338             final CollectingSearchRequestor sr = new CollectingSearchRequestor();
339             final SearchParticipant[] participants = new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()};
340             
341             final ProgressMonitorDialog dialog = new ProgressMonitorDialog(getShell());
342             
343             
344             dialog.run(true, false, new IRunnableWithProgress() {
345                 public void run(IProgressMonitor monitor) {
346                     try {
347                         engine.search(pattern, participants, scope, sr, monitor);
348                     } catch (CoreException ce) {
349                         HibernateConsolePlugin.getDefault().logErrorMessage(
350                                 "Problem while locating jdbc drivers", ce);
351                     }
352                 }
353             });
354             
355             
356             List JavaDoc resources = new ArrayList JavaDoc();
357             Iterator JavaDoc iter = sr.getResults().iterator();
358             while (iter.hasNext()) {
359                 SearchMatch match = (SearchMatch) iter.next();
360                 if(match.getResource() instanceof File) { // what happens if a actual class implements java.sql.driver ?
361
resources.add(match.getResource().getFullPath());
362                 }
363             }
364             
365             return resources;
366         } catch (InvocationTargetException JavaDoc e) {
367             HibernateConsolePlugin.getDefault().logErrorMessage(
368                     "Problem while locating jdbc drivers", e);
369             } catch (InterruptedException JavaDoc e) {
370                 HibernateConsolePlugin.getDefault().logErrorMessage(
371                         "Problem while locating jdbc drivers", e);
372         }
373         
374         
375         return Collections.EMPTY_LIST;
376     }
377     
378     IPath[] getMappingFiles() {
379         return tableItems2File(mappingFilesViewer.getTable());
380     }
381
382     IPath[] getClassPath() {
383         return tableItems2File(classPathViewer.getTable());
384     }
385     
386     private IPath[] tableItems2File(Table table) {
387         TableItem[] items = table.getItems();
388         IPath[] str = new IPath[items.length];
389         for (int i = 0; i < items.length; i++) {
390             TableItem item = items[i];
391             IPath path = (IPath) item.getData();
392             str[i] = path;
393         }
394         return str;
395     }
396
397     private void handlePropertyFileBrowse() {
398         IPath[] paths = DialogSelectionHelper.chooseFileEntries(getShell(), getPropertyFilePath(), new IPath[0], "Select property file", "Choose file to use as hibernate.properties", new String JavaDoc[] {"properties"}, false, false, true);
399         if(paths!=null && paths.length==1) {
400             propertyFileText.setText((paths[0]).toOSString());
401         }
402     }
403     
404     private void handleConfigurationFileBrowse() {
405         IPath[] paths = DialogSelectionHelper.chooseFileEntries(getShell(), getConfigurationFilePath(), new IPath[0], "Select hibernate.cfg.xml file", "Choose file to use as hibernate.cfg.xml", new String JavaDoc[] {"cfg.xml"}, false, false, true);
406         if(paths!=null && paths.length==1) {
407             configurationFileText.setText((paths[0]).toOSString());
408         }
409     }
410     
411     /**
412      * Ensures that both text fields are set.
413      */

414     
415     private void dialogChanged() {
416         String JavaDoc propertyFilename = propertyFileText.getText();
417         String JavaDoc configurationFilename = configurationFileText.getText();
418         
419         
420         if(getConfigurationName()==null || getConfigurationName().trim().length() == 0) {
421             updateStatus("A name must be specificed");
422             return;
423         } else {
424             if(oldConfiguaration==null && KnownConfigurations.getInstance().find(getConfigurationName())!=null) {
425                 updateStatus("A configuration with that name already exists!");
426                 return;
427             }
428         }
429         
430         if (propertyFilename.length() == 0 && configurationFilename.trim().length() == 0) {
431             updateStatus("Property or Configuration file must be specified");
432             return;
433         }
434         
435         if (propertyFilename.length() > 0) {
436             IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(propertyFilename);
437             String JavaDoc msg = checkForFile("Property file", resource);
438             if(msg!=null) {
439                 updateStatus(msg);
440                 return;
441             }
442         }
443         
444         if (configurationFilename.length() > 0) {
445             IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(configurationFilename);
446             String JavaDoc msg = checkForFile("Configuration file",resource);
447             if(msg!=null) {
448                 updateStatus(msg);
449                 return;
450             }
451         } else if(mappingFilesViewer.getTable().getItemCount()==0) {
452             //TODO: removed to provide a way to create a non-mapping base configuration
453
//updateStatus("Need to specify one or more mapping files");
454
//return;
455
}
456         
457         updateStatus(null);
458     }
459
460     String JavaDoc getConfigurationName() {
461         return configurationNameText.getText();
462     }
463
464     private String JavaDoc checkForFile(String JavaDoc msgPrefix, IResource resource) {
465         if(resource!=null) {
466             if(resource instanceof File) {
467                 
468                 return null;
469             } else {
470                 return msgPrefix + " is not a file";
471             }
472         } else {
473             return msgPrefix + " does not exist";
474         }
475     }
476
477     private void updateStatus(String JavaDoc message) {
478         setErrorMessage(message);
479         setPageComplete(message == null);
480     }
481     
482     public Path getPropertyFilePath() {
483         String JavaDoc p = propertyFileText.getText();
484         return pathOrNull(p);
485     }
486     private Path pathOrNull(String JavaDoc p) {
487         if(p==null || p.trim().length()==0) {
488             return null;
489         } else {
490             return new Path(p);
491         }
492     }
493
494     public Path getConfigurationFilePath() {
495         return pathOrNull(configurationFileText.getText());
496     }
497
498     /**
499      * @return
500      */

501     public EclipseConsoleConfiguration getOldConfiguration() {
502         return oldConfiguaration;
503     }
504
505 }
506
507
508
Popular Tags