KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > junit > CreateTestAction


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-2007 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.junit;
21
22 import java.util.*;
23 import javax.swing.Action JavaDoc;
24 import org.netbeans.api.java.classpath.ClassPath;
25 import org.netbeans.api.project.FileOwnerQuery;
26 import org.netbeans.api.project.Project;
27 import org.netbeans.api.project.SourceGroup;
28 import org.netbeans.modules.junit.plugin.JUnitPlugin;
29 import org.netbeans.modules.junit.plugin.JUnitPlugin.CreateTestParam;
30 import org.netbeans.spi.java.classpath.support.ClassPathSupport;
31 import org.openide.DialogDisplayer;
32 import org.openide.NotifyDescriptor;
33 import org.openide.filesystems.FileObject;
34 import org.openide.loaders.DataObject;
35 import org.openide.loaders.DataObjectNotFoundException;
36 import org.openide.nodes.Node;
37 import org.openide.util.HelpCtx;
38 import org.openide.util.NbBundle;
39 import org.openide.cookies.EditorCookie;
40
41 /** Action sensitive to some cookie that does something useful.
42  *
43  * @author vstejskal, David Konecny
44  * @author Marian Petras
45  * @author Ondrej Rypacek
46  */

47 public final class CreateTestAction extends TestAction {
48         
49     public CreateTestAction() {
50         putValue("noIconInMenu", Boolean.TRUE); //NOI18N
51
}
52
53     /* public members */
54     public String JavaDoc getName() {
55         return NbBundle.getMessage(CreateTestAction.class,
56                                    "LBL_Action_CreateTest"); //NOI18N
57
}
58
59     public HelpCtx getHelpCtx() {
60         return new HelpCtx(CreateTestAction.class);
61     }
62
63     protected void initialize() {
64         super.initialize();
65         putProperty(Action.SHORT_DESCRIPTION,
66                     NbBundle.getMessage(CreateTestAction.class,
67                                         "HINT_Action_CreateTest")); //NOI18N
68
}
69
70     protected String JavaDoc iconResource() {
71         return "org/netbeans/modules/junit/resources/" //NOI18N
72
+ "CreateTestActionIcon.gif"; //NOI18N
73
}
74
75     /**
76      * Checks that the selection of nodes the dialog is invoked on is valid.
77      * @return String message describing the problem found or null, if the
78      * selection is ok
79      */

80     private static String JavaDoc checkNodesValidity(Node[] nodes) {
81         FileObject[] files = getFiles(nodes);
82
83         Project project = getProject(files);
84         if (project == null) {
85             return NbBundle.getMessage(CreateTestAction.class,
86                                        "MSG_multiproject_selection"); //NOI18N
87
}
88
89         if (!checkPackages(files)) {
90             return NbBundle.getMessage(CreateTestAction.class,
91                                        "MSG_invalid_packages"); //NOI18N
92
}
93
94         return null;
95     }
96
97     /**
98      * Check that all the files (folders or java files) have correct java
99      * package names.
100      * @return true if all are fine
101      */

102     private static boolean checkPackages(FileObject[] files) {
103         if (files.length == 0) {
104             return true;
105         } else {
106             Project project = FileOwnerQuery.getOwner(files[0]);
107             for (int i = 0 ; i < files.length; i++) {
108                 String JavaDoc packageName = getPackage(project, files[i]);
109                 if ((packageName == null)
110                         || !TestUtil.isValidPackageName(packageName)) {
111                     return false;
112                 }
113             }
114             return true;
115         }
116     }
117
118     /**
119      * Get the package name of <code>file</code>.
120      *
121      * @param project owner of the file (for performance reasons)
122      * @param file the FileObject whose packagename to get
123      * @return package name of the file or null if it cannot be retrieved
124      */

125     private static String JavaDoc getPackage(Project project, FileObject file) {
126         SourceGroup srcGrp = TestUtil.findSourceGroupOwner(project, file);
127         if (srcGrp!= null) {
128             ClassPath cp = ClassPathSupport.createClassPath(
129                     new FileObject [] {srcGrp.getRootFolder()});
130             return cp.getResourceName(file, '.', false);
131         } else {
132             return null;
133         }
134     }
135
136
137     private static FileObject[] getFiles(Node[] nodes) {
138         FileObject[] ret = new FileObject[nodes.length];
139         for (int i = 0 ; i < nodes.length ; i++) {
140             ret[i] = TestUtil.getFileObjectFromNode(nodes[i]);
141         }
142         return ret;
143     }
144
145     /**
146      * Get the single project for <code>nodes</code> if there is such.
147      * If the nodes belong to different projects or some of the nodes doesn't
148      * have a project, return null.
149      */

150     private static Project getProject(FileObject[] files) {
151         Project project = null;
152         for (int i = 0 ; i < files.length; i++) {
153             Project nodeProject = FileOwnerQuery.getOwner(files[i]);
154             if (project == null) {
155                 project = nodeProject;
156             } else if (project != nodeProject) {
157                 return null;
158             }
159         }
160         return project;
161     }
162
163     @Override JavaDoc
164     protected void performAction(Node[] nodes) {
165         String JavaDoc problem;
166         if ((problem = checkNodesValidity(nodes)) != null) {
167             // TODO report problem
168
NotifyDescriptor msg = new NotifyDescriptor.Message(
169                                 problem, NotifyDescriptor.WARNING_MESSAGE);
170             DialogDisplayer.getDefault().notify(msg);
171             return;
172         }
173
174         // show configuration dialog
175
// when dialog is canceled, escape the action
176
JUnitCfgOfCreate cfg = new JUnitCfgOfCreate(nodes);
177         if (!cfg.configure()) {
178             return;
179         }
180
181         /* Store the configuration data: */
182         final boolean singleClass = cfg.isSingleClass();
183         final Map<CreateTestParam, Object JavaDoc> params
184                 = TestUtil.getSettingsMap(!singleClass);
185         if (singleClass) {
186             params.put(CreateTestParam.CLASS_NAME, cfg.getTestClassName());
187         }
188         final FileObject targetFolder = cfg.getTargetFolder();
189         cfg = null;
190
191         FileObject[] filesToTest = getFileObjectsFromNodes(nodes);
192         if (filesToTest == null) {
193             return; //XXX: display some message
194
}
195
196         /* Determine the plugin to be used: */
197         final JUnitPlugin plugin = TestUtil.getPluginForProject(
198                 FileOwnerQuery.getOwner(filesToTest[0]));
199
200         /* Now create the tests: */
201         final FileObject[] testFileObjects
202                 = JUnitPluginTrampoline.DEFAULT.createTests(
203                         plugin,
204                         filesToTest,
205                         targetFolder,
206                         params);
207
208         /* Open the created/updated test class if appropriate: */
209         if (testFileObjects.length == 1) {
210             try {
211                 DataObject dobj = DataObject.find(testFileObjects[0]);
212                 EditorCookie ec = dobj.getCookie(EditorCookie.class);
213                 if (ec != null) {
214                     ec.open();
215                 }
216             } catch (DataObjectNotFoundException ex) {
217                 ex.printStackTrace();
218             }
219         }
220     }
221
222     /**
223      * Extracts {@code FileObject}s from the given nodes.
224      * Nodes that have (direct or indirect) parent nodes among the given
225      * nodes are ignored.
226      *
227      * @return a non-empty array of {@code FileObject}s
228      * represented by the given nodes;
229      * or {@code null} if no {@code FileObject} was found;
230      */

231     private static FileObject[] getFileObjectsFromNodes(final Node[] nodes){
232         FileObject[] fileObjects = new FileObject[nodes.length];
233         List<FileObject> fileObjectsList = null;
234
235         for (int i = 0; i < nodes.length; i++) {
236             final Node node = nodes[i];
237             final FileObject fo;
238             if (!hasParentAmongNodes(nodes, i)
239                     && ((fo = getTestFileObject(node)) != null)) {
240                 if (fileObjects != null) {
241                     fileObjects[i] = fo;
242                 } else {
243                     if (fileObjectsList == null) {
244                         fileObjectsList = new ArrayList<FileObject>(
245                                                         nodes.length - i);
246                     }
247                     fileObjectsList.add(fo);
248                 }
249             } else {
250                 fileObjects = null; //signs that some FOs were skipped
251
}
252         }
253         if (fileObjects == null) {
254             if (fileObjectsList != null) {
255                 fileObjects = fileObjectsList.toArray(
256                         new FileObject[fileObjectsList.size()]);
257                 fileObjectsList = null;
258             }
259         }
260
261         return fileObjects;
262     }
263
264     /**
265      * Grabs and checks a <code>FileObject</code> from the given node.
266      * If either the file could not be grabbed or the file does not pertain
267      * to any project, a message is displayed.
268      *
269      * @param node node to get a <code>FileObject</code> from.
270      * @return the grabbed <code>FileObject</code>,
271      * or <code>null</code> in case of failure
272      */

273     private static FileObject getTestFileObject(final Node node) {
274         final FileObject fo = TestUtil.getFileObjectFromNode(node);
275         if (fo == null) {
276             TestUtil.notifyUser(NbBundle.getMessage(
277                     CreateTestAction.class,
278                     "MSG_file_from_node_failed")); //NOI18N
279
return null;
280         }
281         ClassPath cp = ClassPath.getClassPath(fo, ClassPath.SOURCE);
282         if (cp == null) {
283             TestUtil.notifyUser(NbBundle.getMessage(
284                     CreateTestAction.class,
285                     "MSG_no_project", //NOI18N
286
fo));
287             return null;
288         }
289         return fo;
290     }
291
292     private static boolean hasParentAmongNodes(final Node[] nodes,
293                                                final int idx) {
294         Node node;
295
296         node = nodes[idx].getParentNode();
297         while (null != node) {
298             for (int i = 0; i < nodes.length; i++) {
299                 if (i == idx) {
300                     continue;
301                 }
302                 if (node == nodes[i]) {
303                     return true;
304                 }
305             }
306             node = node.getParentNode();
307         }
308         return false;
309     }
310
311 }
312
Popular Tags