KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > j2ee > persistence > wizard > Util


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.j2ee.persistence.wizard;
21
22 import java.awt.Component JavaDoc;
23 import java.beans.PropertyChangeEvent JavaDoc;
24 import java.beans.PropertyChangeListener JavaDoc;
25 import javax.swing.JButton JavaDoc;
26 import javax.swing.JLabel JavaDoc;
27 import java.awt.Container JavaDoc;
28 import java.io.IOException JavaDoc;
29 import java.net.URL JavaDoc;
30 import java.util.ArrayList JavaDoc;
31 import javax.swing.JComponent JavaDoc;
32 import java.util.Vector JavaDoc;
33 import java.util.Iterator JavaDoc;
34 import java.util.Collection JavaDoc;
35 import java.util.Collections JavaDoc;
36 import java.util.HashMap JavaDoc;
37 import java.util.HashSet JavaDoc;
38 import java.util.List JavaDoc;
39 import java.util.Map JavaDoc;
40 import java.util.Set JavaDoc;
41 import org.netbeans.api.java.classpath.ClassPath;
42 import org.netbeans.api.java.project.JavaProjectConstants;
43 import org.netbeans.api.java.queries.UnitTestForSourceQuery;
44 import org.netbeans.api.project.Project;
45 import org.netbeans.api.project.ProjectUtils;
46 import org.netbeans.api.project.SourceGroup;
47 import org.netbeans.api.project.libraries.Library;
48 import org.netbeans.modules.j2ee.persistence.dd.persistence.model_1_0.PersistenceUnit;
49 import org.netbeans.modules.j2ee.persistence.provider.InvalidPersistenceXmlException;
50 import org.netbeans.modules.j2ee.persistence.provider.ProviderUtil;
51 import org.netbeans.modules.j2ee.persistence.spi.moduleinfo.JPAModuleInfo;
52 import org.netbeans.modules.j2ee.persistence.unit.PUDataObject;
53 import org.netbeans.modules.j2ee.persistence.wizard.entity.WrapperPanel;
54 import org.netbeans.modules.j2ee.persistence.wizard.unit.PersistenceUnitWizardPanel.TableGeneration;
55 import org.netbeans.modules.j2ee.persistence.wizard.unit.PersistenceUnitWizardPanel;
56 import org.netbeans.modules.j2ee.persistence.wizard.unit.PersistenceUnitWizardPanelDS;
57 import org.netbeans.modules.j2ee.persistence.wizard.unit.PersistenceUnitWizardPanelJdbc;
58 import org.netbeans.spi.java.classpath.support.ClassPathSupport;
59 import org.netbeans.spi.java.project.classpath.ProjectClassPathExtender;
60 import org.openide.DialogDescriptor;
61 import org.openide.DialogDisplayer;
62 import org.openide.ErrorManager;
63 import org.openide.WizardDescriptor;
64 import org.openide.filesystems.FileObject;
65 import org.openide.filesystems.URLMapper;
66 import org.openide.util.NbBundle;
67
68 /**
69  * Copy of j2ee/utilities Util class
70  */

71 public class Util {
72     
73     /*
74      * Changes the text of a JLabel in component from oldLabel to newLabel
75      */

76     public static void changeLabelInComponent(JComponent JavaDoc component, String JavaDoc oldLabel, String JavaDoc newLabel) {
77         JLabel JavaDoc label = findLabel(component, oldLabel);
78         if(label != null) {
79             label.setText(newLabel);
80         }
81     }
82     
83     /*
84      * Hides a JLabel and the component that it is designated to labelFor, if any
85      */

86     public static void hideLabelAndLabelFor(JComponent JavaDoc component, String JavaDoc lab) {
87         JLabel JavaDoc label = findLabel(component, lab);
88         if(label != null) {
89             label.setVisible(false);
90             Component JavaDoc c = label.getLabelFor();
91             if(c != null) {
92                 c.setVisible(false);
93             }
94         }
95     }
96     
97     /*
98      * Recursively gets all components in the components array and puts it in allComponents
99      */

100     public static void getAllComponents( Component JavaDoc[] components, Collection JavaDoc allComponents ) {
101         for( int i = 0; i < components.length; i++ ) {
102             if( components[i] != null ) {
103                 allComponents.add( components[i] );
104                 if( ( ( Container JavaDoc )components[i] ).getComponentCount() != 0 ) {
105                     getAllComponents( ( ( Container JavaDoc )components[i] ).getComponents(), allComponents );
106                 }
107             }
108         }
109     }
110     
111     /*
112      * Recursively finds a JLabel that has labelText in comp
113      */

114     public static JLabel JavaDoc findLabel(JComponent JavaDoc comp, String JavaDoc labelText) {
115         Vector JavaDoc allComponents = new Vector JavaDoc();
116         getAllComponents(comp.getComponents(), allComponents);
117         Iterator JavaDoc iterator = allComponents.iterator();
118         while(iterator.hasNext()) {
119             Component JavaDoc c = (Component JavaDoc)iterator.next();
120             if(c instanceof JLabel JavaDoc) {
121                 JLabel JavaDoc label = (JLabel JavaDoc)c;
122                 if(label.getText().equals(labelText)) {
123                     return label;
124                 }
125             }
126         }
127         return null;
128     }
129     
130     /**
131      * Returns the simple class for the passed fully-qualified class name.
132      */

133     public static String JavaDoc getClassName(String JavaDoc fqClassName) {
134         int dot = fqClassName.lastIndexOf("."); // NOI18N
135
if (dot >= 0 && dot < fqClassName.length() - 1) {
136             return fqClassName.substring(dot + 1);
137         } else {
138             return fqClassName;
139         }
140     }
141     
142     /**
143      * Returns the package name of the passed fully-qualified class name.
144      */

145     public static String JavaDoc getPackageName(String JavaDoc fqClassName) {
146         int dot = fqClassName.lastIndexOf("."); // NOI18N
147
if (dot >= 0 && dot < fqClassName.length() - 1) {
148             return fqClassName.substring(0, dot);
149         } else {
150             return ""; // NOI18N
151
}
152     }
153     
154     /**
155      * Returns the SourceGroup of the passesd project which contains the
156      * fully-qualified class name.
157      */

158     public static SourceGroup getClassSourceGroup(Project project, String JavaDoc fqClassName) {
159         String JavaDoc classFile = fqClassName.replace('.', '/') + ".java"; // NOI18N
160
SourceGroup[] sourceGroups = ProjectUtils.getSources(project).getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
161         
162         for (SourceGroup sourceGroup : sourceGroups) {
163             FileObject classFO = sourceGroup.getRootFolder().getFileObject(classFile);
164             if (classFO != null) {
165                 return sourceGroup;
166             }
167         }
168         return null;
169     }
170     
171     /**
172      * Returns Java source groups for all source packages in given project.<br>
173      * Doesn't include test packages.
174      *
175      * @param project Project to search
176      * @return Array of SourceGroup. It is empty if any probelm occurs.
177      */

178     public static SourceGroup[] getJavaSourceGroups(Project project) {
179         SourceGroup[] sourceGroups = ProjectUtils.getSources(project).getSourceGroups(
180                 JavaProjectConstants.SOURCES_TYPE_JAVA);
181         Set JavaDoc testGroups = getTestSourceGroups(project, sourceGroups);
182         List JavaDoc result = new ArrayList JavaDoc();
183         for (int i = 0; i < sourceGroups.length; i++) {
184             if (!testGroups.contains(sourceGroups[i])) {
185                 result.add(sourceGroups[i]);
186             }
187         }
188         return (SourceGroup[]) result.toArray(new SourceGroup[result.size()]);
189     }
190     
191     private static Set JavaDoc/*<SourceGroup>*/ getTestSourceGroups(Project project, SourceGroup[] sourceGroups) {
192         Map JavaDoc foldersToSourceGroupsMap = createFoldersToSourceGroupsMap(sourceGroups);
193         Set JavaDoc testGroups = new HashSet JavaDoc();
194         for (int i = 0; i < sourceGroups.length; i++) {
195             testGroups.addAll(getTestTargets(sourceGroups[i], foldersToSourceGroupsMap));
196         }
197         return testGroups;
198     }
199     
200     private static Map JavaDoc createFoldersToSourceGroupsMap(final SourceGroup[] sourceGroups) {
201         Map JavaDoc result;
202         if (sourceGroups.length == 0) {
203             result = Collections.EMPTY_MAP;
204         } else {
205             result = new HashMap JavaDoc(2 * sourceGroups.length, .5f);
206             for (int i = 0; i < sourceGroups.length; i++) {
207                 SourceGroup sourceGroup = sourceGroups[i];
208                 result.put(sourceGroup.getRootFolder(), sourceGroup);
209             }
210         }
211         return result;
212     }
213     
214     private static List JavaDoc/*<FileObject>*/ getFileObjects(URL JavaDoc[] urls) {
215         List JavaDoc result = new ArrayList JavaDoc();
216         for (int i = 0; i < urls.length; i++) {
217             FileObject sourceRoot = URLMapper.findFileObject(urls[i]);
218             if (sourceRoot != null) {
219                 result.add(sourceRoot);
220             } else {
221                 int severity = ErrorManager.INFORMATIONAL;
222                 if (ErrorManager.getDefault().isNotifiable(severity)) {
223                     ErrorManager.getDefault().notify(severity, new IllegalStateException JavaDoc(
224                             "No FileObject found for the following URL: " + urls[i])); //NOI18N
225
}
226             }
227         }
228         return result;
229     }
230     
231     private static List JavaDoc/*<SourceGroup>*/ getTestTargets(SourceGroup sourceGroup, Map JavaDoc foldersToSourceGroupsMap) {
232         final URL JavaDoc[] rootURLs = UnitTestForSourceQuery.findUnitTests(sourceGroup.getRootFolder());
233         if (rootURLs.length == 0) {
234             return new ArrayList JavaDoc();
235         }
236         List JavaDoc result = new ArrayList JavaDoc();
237         List JavaDoc sourceRoots = getFileObjects(rootURLs);
238         for (int i = 0; i < sourceRoots.size(); i++) {
239             FileObject sourceRoot = (FileObject) sourceRoots.get(i);
240             SourceGroup srcGroup = (SourceGroup) foldersToSourceGroupsMap.get(sourceRoot);
241             if (srcGroup != null) {
242                 result.add(srcGroup);
243             }
244         }
245         return result;
246     }
247     
248     public static ClassPath getFullClasspath(FileObject fo) {
249         FileObject[] sourceRoots = ClassPath.getClassPath(fo, ClassPath.SOURCE).getRoots();
250         FileObject[] bootRoots = ClassPath.getClassPath(fo, ClassPath.BOOT).getRoots();
251         FileObject[] compileRoots = ClassPath.getClassPath(fo, ClassPath.COMPILE).getRoots();
252         FileObject[] roots = new FileObject[sourceRoots.length + bootRoots.length + compileRoots.length];
253         for (int i = 0; i < sourceRoots.length; i++) {
254             roots[i] = sourceRoots[i];
255         }
256         for (int i = 0; i < bootRoots.length; i++) {
257             roots[sourceRoots.length + i] = bootRoots[i];
258         }
259         for (int i = 0; i < compileRoots.length; i++) {
260             roots[sourceRoots.length + bootRoots.length + i] = compileRoots[i];
261         }
262         return ClassPathSupport.createClassPath(roots);
263     }
264     
265     // from ejbcore utils
266

267     private static final String JavaDoc WIZARD_PANEL_CONTENT_DATA = "WizardPanel_contentData"; // NOI18N
268
private static final String JavaDoc WIZARD_PANEL_CONTENT_SELECTED_INDEX = "WizardPanel_contentSelectedIndex"; //NOI18N;
269

270     public static void mergeSteps(WizardDescriptor wizard, WizardDescriptor.Panel[] panels, String JavaDoc[] steps) {
271         Object JavaDoc prop = wizard.getProperty(WIZARD_PANEL_CONTENT_DATA);
272         String JavaDoc[] beforeSteps;
273         int offset;
274         if (prop instanceof String JavaDoc[]) {
275             beforeSteps = (String JavaDoc[]) prop;
276             offset = beforeSteps.length;
277             if (offset > 0 && ("...".equals(beforeSteps[offset - 1]))) {// NOI18N
278
offset--;
279             }
280         } else {
281             beforeSteps = null;
282             offset = 0;
283         }
284         String JavaDoc[] resultSteps = new String JavaDoc[ (offset) + panels.length];
285         for (int i = 0; i < offset; i++) {
286             resultSteps[i] = beforeSteps[i];
287         }
288         setSteps(panels, steps, resultSteps, offset);
289     }
290     
291     private static void setSteps(WizardDescriptor.Panel[] panels, String JavaDoc[] steps, String JavaDoc[] resultSteps, int offset) {
292         int n = steps == null ? 0 : steps.length;
293         for (int i = 0; i < panels.length; i++) {
294             final JComponent JavaDoc component = (JComponent JavaDoc) panels[i].getComponent();
295             String JavaDoc step = i < n ? steps[i] : null;
296             if (step == null) {
297                 step = component.getName();
298             }
299             component.putClientProperty(WIZARD_PANEL_CONTENT_DATA, resultSteps);
300             component.putClientProperty(WIZARD_PANEL_CONTENT_SELECTED_INDEX, new Integer JavaDoc(i));
301             component.getAccessibleContext().setAccessibleDescription(step);
302             resultSteps[i + offset] = step;
303         }
304     }
305     
306     public static void setSteps(WizardDescriptor.Panel[] panels, String JavaDoc[] steps) {
307         setSteps(panels, steps, steps, 0);
308     }
309     
310     public static boolean isSupportedJavaEEVersion(Project project) {
311         JPAModuleInfo moduleInfo = project.getLookup().lookup(JPAModuleInfo.class);
312         if (moduleInfo == null){
313             return false;
314         }
315         if (JPAModuleInfo.ModuleType.EJB == moduleInfo.getType()
316                 && "3.0".equals(moduleInfo.getVersion())){
317             return true;
318         }
319         if (JPAModuleInfo.ModuleType.WEB == moduleInfo.getType()
320                 && "2.5".equals(moduleInfo.getVersion())){
321             return true;
322         }
323         return false;
324     }
325     
326     public static boolean isEjbModule(Project project) {
327         JPAModuleInfo moduleInfo = project.getLookup().lookup(JPAModuleInfo.class);
328         if (moduleInfo == null){
329             return false;
330         }
331         return JPAModuleInfo.ModuleType.EJB == moduleInfo.getType();
332     }
333     
334     
335     public static boolean isEjb21Module(Project project) {
336         JPAModuleInfo moduleInfo = project.getLookup().lookup(JPAModuleInfo.class);
337         if (moduleInfo == null){
338             return false;
339         }
340         
341         return JPAModuleInfo.ModuleType.EJB == moduleInfo.getType()
342                 && "2.1".equals(moduleInfo.getVersion());
343     }
344     
345     /**
346      * @return true if given this data object's project's enviroment is Java SE, false otherwise.
347      */

348     public static boolean isJavaSE(Project project){
349         return project.getLookup().lookup(JPAModuleInfo.class) == null;
350     }
351     
352     /**
353      * Builds a persistence unit using wizard. Does not save the created persistence unit
354      * nor create the persistence.xml file if it does not exist.
355      * @param project the current project
356      * @param preselectedDB the name of the database connection that should be preselected in the wizard.
357      * @tableGeneration the table generation strategy that should be preselected in the wizard.
358      * @return the created PersistenceUnit or null if nothing was created, for example
359      * if wizard was cancelled.
360      */

361     public static PersistenceUnit buildPersistenceUnitUsingWizard(Project project,
362             String JavaDoc preselectedDB, TableGeneration tableGeneration){
363         
364         boolean isContainer = Util.isSupportedJavaEEVersion(project);
365         PersistenceUnitWizardPanel panel;
366         if (isContainer) {
367             panel = new PersistenceUnitWizardPanelDS(project, null, true, tableGeneration);
368         } else {
369             panel = new PersistenceUnitWizardPanelJdbc(project, null, true, tableGeneration);
370         }
371         if (preselectedDB != null) {
372             panel.setPreselectedDB(preselectedDB);
373         }
374         
375         final JButton JavaDoc createPUButton = new JButton JavaDoc(NbBundle.getMessage(Util.class,"LBL_CreatePersistenceUnitButton"));
376         createPUButton.getAccessibleContext().setAccessibleDescription(NbBundle.getMessage(Util.class,"ACSD_CreatePersistenceUnitButton"));
377         Object JavaDoc[] buttons = new Object JavaDoc[] { createPUButton, DialogDescriptor.CANCEL_OPTION };
378         
379         final DialogDescriptor nd = new DialogDescriptor(
380                 new WrapperPanel(panel),
381                 NbBundle.getMessage(Util.class, "LBL_CreatePersistenceUnit"),
382                 true,
383                 buttons,
384                 DialogDescriptor.OK_OPTION,
385                 DialogDescriptor.DEFAULT_ALIGN,
386                 null,
387                 null
388                 );
389         panel.addPropertyChangeListener(new PropertyChangeListener JavaDoc() {
390             public void propertyChange(PropertyChangeEvent JavaDoc evt) {
391                 if (evt.getPropertyName().equals(PersistenceUnitWizardPanel.IS_VALID)) {
392                     Object JavaDoc newvalue = evt.getNewValue();
393                     if ((newvalue != null) && (newvalue instanceof Boolean JavaDoc)) {
394                         nd.setValid(((Boolean JavaDoc)newvalue).booleanValue());
395                         createPUButton.setEnabled(((Boolean JavaDoc)newvalue).booleanValue());
396                     }
397                 }
398             }
399         });
400         if (!panel.isValidPanel()) {
401             nd.setValid(false);
402             createPUButton.setEnabled(false);
403         }
404         Object JavaDoc result = DialogDisplayer.getDefault().notify(nd);
405         if (result == createPUButton) {
406             PersistenceUnit punit = new PersistenceUnit();
407             if (isContainer) {
408                 PersistenceUnitWizardPanelDS puPanel = (PersistenceUnitWizardPanelDS) panel;
409                 if (puPanel.getDatasource() != null && !"".equals(puPanel.getDatasource().trim())){
410                     if (puPanel.isJTA()) {
411                         punit.setJtaDataSource(puPanel.getDatasource());
412                     } else {
413                         if (puPanel.isNonDefaultProviderEnabled()) {
414                             punit.setNonJtaDataSource(puPanel.getDatasource());
415                         }
416                         punit.setTransactionType("RESOURCE_LOCAL");
417                     }
418                 }
419                 if (puPanel.isNonDefaultProviderEnabled()) {
420                     punit.setProvider(puPanel.getNonDefaultProvider());
421                 }
422             } else {
423                 PersistenceUnitWizardPanelJdbc puJdbc = (PersistenceUnitWizardPanelJdbc) panel;
424                 punit = ProviderUtil.buildPersistenceUnit(puJdbc.getPersistenceUnitName(), puJdbc.getSelectedProvider(), puJdbc.getPersistenceConnection());
425                 punit.setTransactionType("RESOURCE_LOCAL"); //NO18N
426
if (puJdbc.getPersistenceLibrary() != null){
427                     addLibraryToProject(project, puJdbc.getPersistenceLibrary());
428                 }
429             }
430             punit.setName(panel.getPersistenceUnitName());
431             ProviderUtil.setTableGeneration(punit, panel.getTableGeneration(), project);
432             return punit;
433         }
434         return null;
435         
436     }
437
438     /**
439      * Creates a persistence unit using the PU wizard and adds the created
440      * persistence unit to the given project's <code>PUDataObject</code> and saves it.
441      *
442      * @param project the project to which the created persistence unit is to be created.
443      * @param preselectedDB the name of the db connection that should be preselected, or null if none needs
444      * to be preselected.
445      * @param tableGeneration the table generation strategy for the persistence unit.
446      *
447      * @return true if the creation of the persistence unit was successful, false otherwise.
448      *
449      * @throws InvalidPersistenceXmlException if the persistence.xml file in the given
450      * project is not valid.
451      *
452      */

453     public static boolean createPersistenceUnitUsingWizard(Project project,
454             String JavaDoc preselectedDB, TableGeneration tableGeneration) throws InvalidPersistenceXmlException {
455         
456         PersistenceUnit punit = buildPersistenceUnitUsingWizard(project, preselectedDB, tableGeneration);
457         if (punit == null){
458             return false;
459         }
460         PUDataObject pud = ProviderUtil.getPUDataObject(project);
461         pud.addPersistenceUnit(punit);
462         pud.save();
463         return true;
464     }
465     
466     /**
467      * Creates a persistence unit with the default table generation strategy using the PU wizard and adds the created
468      * persistence unit to the given project's <code>PUDataObject</code> and saves it.
469      *
470      * @param project the project to which the created persistence unit is to be created.
471      * @param preselectedDB the name of the db connection that should be preselected, or null if none needs
472      * to be preselected.
473      *
474      * @return true if the creation of the persistence unit was successful, false otherwise.
475      *
476      * @throws InvalidPersistenceXmlException if the persistence.xml file in the given
477      * project is not valid.
478      *
479      */

480     public static boolean createPersistenceUnitUsingWizard(Project project, String JavaDoc preselectedDB) throws InvalidPersistenceXmlException {
481         return createPersistenceUnitUsingWizard(project, preselectedDB, TableGeneration.CREATE);
482     }
483     
484     public static void addLibraryToProject(Project project, Library library) {
485         ProjectClassPathExtender pcpe = (ProjectClassPathExtender) project.getLookup().lookup(ProjectClassPathExtender.class);
486         if (pcpe != null) {
487             try {
488                 pcpe.addLibrary(library);
489             } catch (IOException JavaDoc ex) {
490                 ErrorManager.getDefault().notify(ex);
491             }
492         }
493     }
494     
495     public static String JavaDoc simpleClassName(String JavaDoc fqn) {
496         int lastDot = fqn.lastIndexOf('.');
497         return lastDot > 0 ? fqn.substring(lastDot + 1) : fqn;
498     }
499     
500 }
501
Popular Tags