KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > test > j2ee > lib > J2eeProjectSupport


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.test.j2ee.lib;
21
22 import java.beans.PropertyChangeEvent JavaDoc;
23 import java.beans.PropertyChangeListener JavaDoc;
24 import java.io.File JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.util.HashSet JavaDoc;
27 import java.util.Iterator JavaDoc;
28 import java.util.Set JavaDoc;
29 import org.netbeans.api.project.Project;
30 import org.netbeans.api.project.ProjectManager;
31 import org.netbeans.api.project.ProjectUtils;
32 import org.netbeans.junit.ide.ProjectSupport;
33 import org.netbeans.modules.j2ee.deployment.impl.ServerRegistry;
34 import org.netbeans.modules.j2ee.earproject.EarProjectGenerator;
35 import org.netbeans.modules.j2ee.ejbjarproject.api.EjbJarProjectGenerator;
36 import org.netbeans.modules.java.j2seproject.J2SEProjectGenerator;
37 import org.netbeans.modules.project.ui.OpenProjectList;
38 import org.netbeans.modules.web.api.webmodule.WebModule;
39 import org.netbeans.modules.web.project.api.WebProjectUtilities;
40 import org.openide.ErrorManager;
41 import org.openide.filesystems.FileObject;
42 import org.openide.filesystems.FileUtil;
43 import org.openide.util.Mutex;
44
45 /**
46  *
47  * @author jungi
48  */

49 public class J2eeProjectSupport {
50     
51     public static final int J2SE_PROJECT = 0;
52     public static final int WEB_PROJECT = 1;
53     public static final int EJB_PROJECT = 2;
54     public static final int J2EE_PROJECT = 3;
55     
56     public static final String JavaDoc DEFAULT_J2EE_LEVEL
57             = WebModule.J2EE_14_LEVEL;
58     
59     public static final String JavaDoc DEFAULT_APPSRV_ID;
60     static {
61         String JavaDoc location = System.getProperty("com.sun.aas.installRoot");
62         if (location != null) {
63             location = new File JavaDoc(location).getAbsolutePath();
64         }
65         DEFAULT_APPSRV_ID = "[" + location + "]deployer:Sun:AppServer::localhost:4848";
66     }
67     
68     public static final String JavaDoc DEFAULT_SRC_STRUCTURE
69             = WebProjectUtilities.SRC_STRUCT_BLUEPRINTS;
70     
71     public static final int WAIT_APPSRV_INSTALL = 30000;
72     
73     /** Creates a new instance of J2eeProjectSupport */
74     private J2eeProjectSupport() {
75         throw new UnsupportedOperationException JavaDoc("It is just a helper class.");
76     }
77     
78     public static boolean waitForAppServerInstall() {
79        long t1 = System.currentTimeMillis();
80        while (ServerRegistry.getInstance().getServerInstance(DEFAULT_APPSRV_ID) == null && System.currentTimeMillis() - t1 < WAIT_APPSRV_INSTALL) {
81            try {
82                Thread.sleep(500);
83            } catch (InterruptedException JavaDoc e) {}
84        }
85        return ServerRegistry.getInstance().getServerInstance(DEFAULT_APPSRV_ID) != null;
86     }
87     
88     /** Opens project in specified directory.
89      * @param projectDir a directory with project to open
90      * @return Project instance of opened project
91      */

92     public static Object JavaDoc openProject(File JavaDoc projectDir) {
93         final ProjectOpenListener listener = new ProjectOpenListener();
94         try {
95             // open project
96
final Project project = OpenProjectList.fileToProject(projectDir);
97             // posting the to AWT event thread
98
Mutex.EVENT.writeAccess(new Runnable JavaDoc() {
99                 public void run() {
100                     OpenProjectList.getDefault().addPropertyChangeListener(listener);
101                     OpenProjectList.getDefault().open(project);
102                     // Set main? Probably user should do this if he wants.
103
// OpenProjectList.getDefault().setMainProject(project);
104
}
105             });
106             // WAIT PROJECT OPEN - start
107
// We need to wait until project is open and then we can start to
108
// wait when scanning finishes. If we don't wait, scanning is started
109
// too early and finishes immediatelly.
110
Thread JavaDoc waitThread = new Thread JavaDoc(new Runnable JavaDoc() {
111                 public void run() {
112                     while(!listener.projectOpened) {
113                         try {
114                             Thread.sleep(50);
115                         } catch (Exception JavaDoc e) {
116                             ErrorManager.getDefault().notify(ErrorManager.EXCEPTION, e);
117                         }
118                     }
119                 }
120             });
121             waitThread.start();
122             try {
123                 waitThread.join(60000L); // wait 1 minute at the most
124
} catch (InterruptedException JavaDoc iex) {
125                 ErrorManager.getDefault().notify(ErrorManager.EXCEPTION, iex);
126             }
127             if (waitThread.isAlive()) {
128                 // time-out expired, project not opened -> interrupt the wait thread
129
ErrorManager.getDefault().log(ErrorManager.USER, "Project not opened in 60 second.");
130                 waitThread.interrupt();
131             }
132             // WAIT PROJECT OPEN - end
133
// wait until metadata scanning is finished
134
waitScanFinished();
135             return project;
136         } catch (Exception JavaDoc ex) {
137             ErrorManager.getDefault().notify(ErrorManager.EXCEPTION, ex);
138             return null;
139         } finally {
140             OpenProjectList.getDefault().removePropertyChangeListener(listener);
141         }
142     }
143     
144     /** Opens project on specified path.
145      * @param projectPath path to a directory with project to open
146      * @return Project instance of opened project
147      */

148     public static Object JavaDoc openProject(String JavaDoc projectPath) {
149         return openProject(new File JavaDoc(projectPath));
150     }
151     
152     /** Creates an empty Java project in specified directory and opens it.
153      * Its name is defined by name parameter.
154      * @param projectParentPath path to directory where to create name subdirectory and
155      * new project structure in that subdirectory.
156      * @param name name of the project
157      * @return Project instance of created project
158      */

159     public static Object JavaDoc createProject(String JavaDoc projectParentPath, String JavaDoc name) {
160         return createProject(new File JavaDoc(projectParentPath), name, J2SE_PROJECT, null);
161     }
162     
163     /** Creates an empty project in specified directory and opens it.
164      * Its name is defined by name parameter.
165      * @param projectParentDir directory where to create name subdirectory and
166      * new project structure in that subdirectory.
167      * @param name name of the project
168      * @param type type of project
169      * @param params parameters passed to created project
170      */

171     public static Object JavaDoc createProject(File JavaDoc projectParentDir, String JavaDoc name,
172             int type, String JavaDoc[] params) {
173         String JavaDoc mainClass = null;
174         try {
175             File JavaDoc projectDir = new File JavaDoc(projectParentDir, name);
176             switch (type) {
177                 case J2SE_PROJECT:
178                     J2SEProjectGenerator.createProject(projectDir, name, mainClass, null);
179                     break;
180                 case WEB_PROJECT:
181                     //params[0] = serverInstanceID
182
//params[1] = sourceStructure
183
//params[2] = j2eeLevel
184
if (params == null){
185                         params = new String JavaDoc[] {DEFAULT_APPSRV_ID, DEFAULT_SRC_STRUCTURE, DEFAULT_J2EE_LEVEL};
186                     }
187                     WebProjectUtilities.createProject(projectDir, name, params[0], params[1], params[2], name);
188                     break;
189                 case EJB_PROJECT:
190                     //params[0] = j2eeLevel
191
//params[1] = serverInstanceID
192
if (params == null){
193                         params = new String JavaDoc[] {DEFAULT_J2EE_LEVEL, DEFAULT_APPSRV_ID};
194                     }
195                     EjbJarProjectGenerator.createProject(projectDir, name, params[0], params[1]);
196                     break;
197                 case J2EE_PROJECT:
198                     //params[0] = j2eeLevel
199
//params[1] = serverInstanceID
200
//params[2] = sourceLevel
201
if (params == null){
202                         params = new String JavaDoc[] {DEFAULT_J2EE_LEVEL, DEFAULT_APPSRV_ID, null};
203                     }
204                     EarProjectGenerator.createProject(projectDir, name, params[0], params[1], params[2]);
205                     break;
206                 default:
207                     throw new IllegalArgumentException JavaDoc("Invalid project type.");
208             }
209             return openProject(projectDir);
210         } catch (IOException JavaDoc e) {
211             ErrorManager.getDefault().notify(ErrorManager.EXCEPTION, e);
212             return null;
213         }
214     }
215     
216     /** Closes project with system or display name equals to given name.
217      * @param name system or display name of project to be closed.
218      * @return true if project is closed, false otherwise (i.e. project was
219      * not found).
220      */

221     public static boolean closeProject(String JavaDoc name) {
222         Project[] projects = OpenProjectList.getDefault().getOpenProjects();
223         for(int i=0;i<projects.length;i++) {
224             final Project project = projects[i];
225             if(ProjectUtils.getInformation(project).getDisplayName().equals(name) ||
226                     ProjectUtils.getInformation(project).getName().equals(name)) {
227                 // posting the to AWT event thread
228
Mutex.EVENT.writeAccess(new Runnable JavaDoc() {
229                     public void run() {
230                         OpenProjectList.getDefault().close( new Project[] { project }, true);
231                     }
232                 });
233                 return true;
234             }
235         }
236         // project not found
237
return false;
238     }
239     
240     /** Waits until metadata scanning is finished. */
241     public static void waitScanFinished() {
242             ProjectSupport.waitScanFinished();
243     }
244     
245     /**
246      *
247      * @return set of file names under the project root
248      */

249     public static Set JavaDoc getFileSet(Project p) {
250         File JavaDoc f = FileUtil.toFile(p.getProjectDirectory());
251         Set JavaDoc dummy = new HashSet JavaDoc();
252         visitAllDirsAndFiles(f, dummy);
253         Set JavaDoc retVal = new HashSet JavaDoc(dummy.size());
254         Iterator JavaDoc i = dummy.iterator();
255         while (i.hasNext()) {
256             String JavaDoc s = ((String JavaDoc) i.next()).substring(f.getAbsolutePath().length() + 1);
257             if (s.length() > 2) {
258                 retVal.add(s);
259             }
260         }
261         return retVal;
262     }
263     
264     public static Set JavaDoc getFileSet(String JavaDoc projectRoot) {
265         File JavaDoc f = new File JavaDoc(projectRoot);
266         Set JavaDoc dummy = new HashSet JavaDoc();
267         visitAllDirsAndFiles(f, dummy);
268         Set JavaDoc retVal = new HashSet JavaDoc(dummy.size());
269         Iterator JavaDoc i = dummy.iterator();
270         while (i.hasNext()) {
271             String JavaDoc s = ((String JavaDoc) i.next()).substring(f.getAbsolutePath().length() + 1);
272             if (s.length() > 2) {
273                 retVal.add(s);
274             }
275         }
276         return retVal;
277     }
278     
279     public static Project getProject(File JavaDoc wd, String JavaDoc relativePath) throws Exception JavaDoc {
280         File JavaDoc f = new File JavaDoc(wd, relativePath);
281         f = f.getCanonicalFile();
282         FileObject fo = FileUtil.toFileObject(f);
283         return ProjectManager.getDefault().findProject(fo);
284     }
285     
286     // Process all files and directories under dir and put their names to given set
287
private static void visitAllDirsAndFiles(File JavaDoc dir, Set JavaDoc s) {
288         s.add(dir.isDirectory() ? dir.getPath() + File.separatorChar : dir.getPath());
289         if (dir.isDirectory()) {
290             String JavaDoc[] children = dir.list();
291             for (int i=0; i<children.length; i++) {
292                 visitAllDirsAndFiles(new File JavaDoc(dir, children[i]), s);
293             }
294         }
295     }
296     
297     /** Listener for project open. */
298     static class ProjectOpenListener implements PropertyChangeListener JavaDoc {
299         public boolean projectOpened = false;
300         
301         /** Listen for property which changes when project is hopefully opened. */
302         public void propertyChange(PropertyChangeEvent JavaDoc evt) {
303             if(OpenProjectList.PROPERTY_OPEN_PROJECTS.equals(evt.getPropertyName())) {
304                 projectOpened = true;
305             }
306         }
307     }
308 }
309
Popular Tags