KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > web > struts > StrutsConfigUtilities


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.web.struts;
21
22 import java.io.IOException JavaDoc;
23 import java.util.ArrayList JavaDoc;
24 import java.util.Collections JavaDoc;
25 import java.util.List JavaDoc;
26 import java.util.StringTokenizer JavaDoc;
27 import javax.lang.model.element.TypeElement;
28 import javax.lang.model.util.Elements;
29 import org.netbeans.api.java.classpath.ClassPath;
30 import org.netbeans.api.java.source.ClasspathInfo;
31 import org.netbeans.api.java.source.CompilationController;
32 import org.netbeans.api.java.source.CompilationInfo;
33 import org.netbeans.api.java.source.JavaSource;
34 import org.netbeans.api.java.source.JavaSource.Phase;
35 import org.netbeans.api.project.FileOwnerQuery;
36 import org.netbeans.api.project.Project;
37 import org.netbeans.api.project.ProjectUtils;
38 import org.netbeans.api.project.SourceGroup;
39 import org.netbeans.api.project.Sources;
40 import org.netbeans.modules.j2ee.common.source.AbstractTask;
41 import org.netbeans.modules.j2ee.dd.api.common.InitParam;
42 import org.netbeans.modules.j2ee.dd.api.web.DDProvider;
43 import org.netbeans.modules.j2ee.dd.api.web.ServletMapping;
44 import org.netbeans.modules.j2ee.dd.api.web.WebApp;
45 import org.netbeans.modules.j2ee.dd.api.web.Servlet;
46 import org.netbeans.modules.web.api.webmodule.WebModule;
47 import org.netbeans.modules.web.api.webmodule.WebProjectConstants;
48 import org.netbeans.modules.web.struts.config.model.Action;
49 import org.netbeans.modules.web.struts.config.model.ActionMappings;
50 import org.netbeans.modules.web.struts.config.model.MessageResources;
51 import org.netbeans.modules.web.struts.config.model.StrutsConfig;
52 import org.netbeans.modules.web.struts.config.model.FormBeans;
53 import org.netbeans.modules.web.struts.config.model.FormBean;
54 import org.openide.ErrorManager;
55 import org.openide.filesystems.FileObject;
56 import org.openide.filesystems.FileUtil;
57 import org.openide.loaders.DataObject;
58 import org.openide.loaders.DataObjectNotFoundException;
59
60 /**
61  *
62  * @author petr
63  */

64 public class StrutsConfigUtilities {
65     
66     public static String JavaDoc DEFAULT_MODULE_NAME = "config"; //NOI18N
67
private static final int TYPE_ACTION=0;
68     private static final int TYPE_FORM_BEAN=1;
69     private static final int TYPE_MESSAGE_RESOURCES=2;
70     
71     public static List JavaDoc getAllActionsInModule(StrutsConfigDataObject data){
72         return createConfigElements(TYPE_ACTION,data);
73     }
74     
75     public static List JavaDoc getAllFormBeansInModule(StrutsConfigDataObject data){
76         return createConfigElements(TYPE_FORM_BEAN,data);
77     }
78     
79     public static List JavaDoc getAllMessageResourcesInModule(StrutsConfigDataObject data){
80         return createConfigElements(TYPE_MESSAGE_RESOURCES,data);
81     }
82     
83     private static List JavaDoc createConfigElements(int elementType, StrutsConfigDataObject data) {
84         FileObject config = data.getPrimaryFile();
85         ArrayList JavaDoc list = new ArrayList JavaDoc();
86         WebModule wm = WebModule.getWebModule(config);
87         if (wm != null){
88             FileObject ddFo = wm.getDeploymentDescriptor();
89             if (ddFo != null){
90                 String JavaDoc moduleName = getModuleName(config, ddFo);
91                 if (moduleName == null){
92                     // the conf file is not in any module (is not declared in the web.xml)
93
try{
94                         StrutsConfig sConfig = data.getStrutsConfig(true);
95                         switch (elementType) {
96                             case TYPE_ACTION : addActions(list, sConfig);break;
97                             case TYPE_FORM_BEAN : addFormBeans(list, sConfig);break;
98                             case TYPE_MESSAGE_RESOURCES : addMessageResource(list, sConfig);break;
99                         }
100                     } catch (java.io.IOException JavaDoc e){
101                         // Do nothing
102
}
103                 } else {
104                     // the config file is in a Struts module, returns all actions from the
105
// conf files in the module
106
FileObject[] configs = getConfigFiles(moduleName, ddFo);
107                     DataObject dOb;
108                     for (int i = 0; i < configs.length; i++){
109                         try{
110                             dOb = DataObject.find(configs[i]);
111                         } catch (DataObjectNotFoundException e){
112                             dOb = null;
113                         }
114                         if (dOb !=null && dOb instanceof StrutsConfigDataObject){
115                             StrutsConfigDataObject con = (StrutsConfigDataObject)dOb;
116                             // the conf file is not in any module (is not declared in the web.xml)
117
try{
118                                 StrutsConfig sConfig = con.getStrutsConfig(true);
119                                 switch (elementType) {
120                                     case TYPE_ACTION : addActions(list, sConfig);break;
121                                     case TYPE_FORM_BEAN : addFormBeans(list, sConfig);break;
122                                     case TYPE_MESSAGE_RESOURCES : addMessageResource(list, sConfig);break;
123                                 }
124                             } catch (java.io.IOException JavaDoc e){
125                                 // Do nothing
126
}
127                         }
128                     }
129                 }
130             }
131         }
132         return list;
133     }
134
135     private static void addActions(List JavaDoc list, StrutsConfig sConfig) {
136         ActionMappings mappings = sConfig.getActionMappings();
137         if (mappings==null) return;
138         Action [] actions = mappings.getAction();
139         for (int j = 0; j < actions.length; j++)
140             list.add(actions[j]);
141     }
142     
143     private static void addFormBeans(List JavaDoc list, StrutsConfig sConfig) {
144         FormBeans formBeans = sConfig.getFormBeans();
145         if (formBeans==null) return;
146         FormBean [] beans = formBeans.getFormBean();
147         for (int j = 0; j < beans.length; j++)
148             list.add(beans[j]);
149     }
150     
151     private static void addMessageResource(List JavaDoc list, StrutsConfig sConfig) {
152         MessageResources[] rosources = sConfig.getMessageResources();
153         for (int j = 0; j < rosources.length; j++)
154             list.add(rosources[j]);
155     }
156     
157     
158     /** Returns all configuration files for the module
159      **/

160     public static FileObject[] getConfigFiles(String JavaDoc module, FileObject dd){
161         FileObject docBase = WebModule.getWebModule(dd).getDocumentBase();
162         if (docBase == null)
163             return null;
164         Servlet servlet = getActionServlet(dd);
165         InitParam param = null;
166         if (module.equals(DEFAULT_MODULE_NAME))
167             param = (InitParam)servlet.findBeanByName("InitParam", "ParamName", DEFAULT_MODULE_NAME);
168         else
169             param = (InitParam)servlet.findBeanByName("InitParam", "ParamName", DEFAULT_MODULE_NAME+"/"+module);
170         FileObject[] configs = null;
171         if (param != null){
172             StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(param.getParamValue(), ",");
173             configs = new FileObject[st.countTokens()];
174             int index = 0;
175             while (st.hasMoreTokens()){
176                 String JavaDoc name = st.nextToken().trim();
177                 configs[index] = docBase.getFileObject(name);
178                 index++;
179             }
180         }
181         return configs;
182     }
183     
184     
185     
186     /** Returns name of Struts module, which contains the configuration file.
187      */

188     public static String JavaDoc getModuleName(FileObject config, FileObject dd){
189         String JavaDoc moduleName = null;
190         if (dd != null) {
191             Servlet servlet = getActionServlet(dd);
192             if (servlet != null){
193                 InitParam [] param = servlet.getInitParam();
194                 StringTokenizer JavaDoc st = null;
195                 int index = 0;
196
197                 while (moduleName == null && index < param.length){
198                     if(param[index].getParamName().trim().startsWith(DEFAULT_MODULE_NAME)){
199                         String JavaDoc[] files = param[index].getParamValue().split(","); //NOI18N
200
for (int i = 0; i < files.length; i++){
201                             String JavaDoc file = files[i];
202                             if (config.getPath().endsWith(file)){
203                                 if (!param[index].getParamName().trim().equals(DEFAULT_MODULE_NAME)){
204                                     moduleName = param[index].getParamName().trim()
205                                     .substring(DEFAULT_MODULE_NAME.length()+1);
206                                 } else{
207                                     moduleName = DEFAULT_MODULE_NAME;
208                                 }
209                                 break;
210                             }
211                         }
212
213                     }
214                     index++;
215                 }
216             }
217         }
218         return moduleName;
219     }
220     
221     public static Servlet getActionServlet(FileObject dd) {
222         if (dd == null) {
223             return null;
224         }
225         try {
226             WebApp webApp = DDProvider.getDefault().getDDRoot(dd);
227             Servlet servlet = (Servlet) webApp
228                     .findBeanByName("Servlet", "ServletClass", "org.apache.struts.action.ActionServlet"); //NOI18N;
229
if (servlet == null){
230                 // check whether a servler class doesn't extend org.apache.struts.action.ActionServlet
231
final Servlet[] servlets = webApp.getServlet();
232
233                 ClasspathInfo cpi = ClasspathInfo.create(dd);
234                 JavaSource js = JavaSource.create(cpi, Collections.EMPTY_LIST);
235                 final int[] index = new int[]{-1};
236                 js.runUserActionTask( new AbstractTask <CompilationController>(){
237                     public void run(CompilationController cc) throws Exception JavaDoc {
238                         Elements elements = cc.getElements();
239                         TypeElement strutsServletElement = elements.getTypeElement("org.apache.struts.action.ActionServlet"); //NOI18N
240
TypeElement servletElement;
241                         if (strutsServletElement != null){
242                             for (int i = 0; i < servlets.length; i++) {
243                                 servletElement = elements.getTypeElement(servlets[i].getServletClass());
244                                 if (servletElement != null
245                                         && cc.getTypes().isSubtype(servletElement.asType(),strutsServletElement.asType())){
246                                     index[0] = i;
247                                     continue;
248                                 }
249                             }
250                         }
251                     }
252                     
253                 },false);
254     
255                 
256                 if (index[0] > -1 )
257                     servlet = servlets[index[0]];
258             }
259             return servlet;
260         } catch (java.io.IOException JavaDoc e) {
261             ErrorManager.getDefault().notify(e);
262             return null;
263         }
264     }
265     
266     /** Returns the mapping for the Struts Action Servlet.
267      */

268     public static String JavaDoc getActionServletMapping(FileObject dd){
269         Servlet servlet = getActionServlet(dd);
270         if (servlet != null){
271             try{
272                 WebApp webApp = DDProvider.getDefault().getDDRoot(dd);
273                 ServletMapping[] mappings = webApp.getServletMapping();
274                 for (int i = 0; i < mappings.length; i++){
275                     if (mappings[i].getServletName().equals(servlet.getServletName()))
276                         return mappings[i].getUrlPattern();
277                 }
278             } catch (java.io.IOException JavaDoc e) {
279                 
280             }
281         }
282         return null;
283     }
284     
285     /** Returns relative path for all struts configuration files in the web module
286      */

287     public static String JavaDoc[] getConfigFiles(FileObject dd){
288         if (dd != null){
289             Servlet servlet = getActionServlet(dd);
290             if (servlet!=null) {
291                 InitParam[] params = servlet.getInitParam();
292                 List JavaDoc list = new ArrayList JavaDoc();
293                 for (int i=0;i<params.length;i++) {
294                     String JavaDoc paramName=params[i].getParamName();
295                     if (paramName!=null) {
296                         if (paramName.startsWith(DEFAULT_MODULE_NAME)){
297                             String JavaDoc[] files = params[i].getParamValue().split(","); //NOI18N
298
for (int j = 0; j < files.length; j++)
299                                 list.add(files[j]);
300                         }
301                     }
302                 }
303                 String JavaDoc[] result = new String JavaDoc[list.size()];
304                 list.toArray(result);
305                 return result;
306             }
307         }
308         return new String JavaDoc[]{};
309     }
310     
311     /** Returns all configuration files in the web module
312      */

313     public static FileObject[] getConfigFilesFO(FileObject dd){
314         if (dd != null){
315             FileObject docBase = WebModule.getWebModule(dd).getDocumentBase();
316             if (docBase == null)
317                 return null;
318             Servlet servlet = getActionServlet(dd);
319             if (servlet!=null) {
320                 InitParam[] params = servlet.getInitParam();
321                 List JavaDoc list = new ArrayList JavaDoc();
322                 FileObject file;
323                 for (int i=0;i<params.length;i++) {
324                     String JavaDoc paramName=params[i].getParamName();
325                     if (paramName!=null) {
326                         if (paramName.startsWith(DEFAULT_MODULE_NAME)){ //NOI18N
327
String JavaDoc[] files = params[i].getParamValue().split(","); //NOI18N
328
for (int j = 0; j < files.length; j++){
329                                 file = docBase.getFileObject(files[j]);
330                                 if (file != null)
331                                     list.add(file);
332                             }
333                         }
334                     }
335                 }
336                 FileObject[] result = new FileObject[list.size()];
337                 list.toArray(result);
338                 return result;
339             }
340         }
341         return new FileObject[]{};
342     }
343     
344     /** Returns WebPages for the project, where the fo is located.
345      */

346     public static SourceGroup[] getDocBaseGroups(FileObject fo) throws java.io.IOException JavaDoc {
347         Project proj = FileOwnerQuery.getOwner(fo);
348         if (proj==null) return new SourceGroup[]{};
349         Sources sources = ProjectUtils.getSources(proj);
350         return sources.getSourceGroups(WebProjectConstants.TYPE_DOC_ROOT);
351     }
352     
353     public static String JavaDoc getResourcePath(SourceGroup[] groups, FileObject fo, char separator, boolean withExt) {
354         for (int i=0;i<groups.length;i++) {
355             FileObject root = groups[i].getRootFolder();
356             if (FileUtil.isParentOf(root,fo)) {
357                 String JavaDoc relativePath = FileUtil.getRelativePath(root,fo);
358                 if (relativePath!=null) {
359                     if (separator!='/') relativePath = relativePath.replace('/',separator);
360                     if (!withExt) {
361                         int index = relativePath.lastIndexOf((int)'.');
362                         if (index>0) relativePath = relativePath.substring(0,index);
363                     }
364                     return relativePath;
365                 } else {
366                     return "";
367                 }
368             }
369         }
370         return "";
371     }
372     
373     
374     public static String JavaDoc getActionAsResource (WebModule wm, String JavaDoc action){
375         String JavaDoc resource = "";
376         String JavaDoc mapping = StrutsConfigUtilities.getActionServletMapping(wm.getDeploymentDescriptor());
377         if (mapping != null && mapping.length()>0){
378             if (mapping.startsWith("*."))
379                 resource = action + mapping.substring(1);
380             else
381                 if (mapping.endsWith("/*"))
382                     resource = mapping.substring(0,mapping.length()-2) + action;
383         }
384         return resource;
385     }
386     
387     public static String JavaDoc getActionAsResource(String JavaDoc mapping, String JavaDoc action){
388         String JavaDoc resource = "";
389         if (mapping != null && mapping.length()>0){
390             if (mapping.startsWith("*."))
391                 resource = action + mapping.substring(1);
392             else
393                 if (mapping.endsWith("/*"))
394                     resource = mapping.substring(0,mapping.length()-2) + action;
395         }
396         return resource;
397     }
398     
399     public static MessageResources getDefatulMessageResource(FileObject dd){
400         FileObject [] files = getConfigFilesFO(dd);
401         MessageResources resource = null;
402         int index = 0;
403         DataObject configDO;
404         try {
405             while (resource == null && index < files.length){
406                 configDO = DataObject.find(files[index]);
407                 if (configDO != null && configDO instanceof StrutsConfigDataObject){
408                     StrutsConfig strutsConfig = ((StrutsConfigDataObject)configDO).getStrutsConfig();
409                     // we need to chech, whether the config is parseable
410
if (strutsConfig != null){
411                         MessageResources[] resources = strutsConfig.getMessageResources();
412                         for (int i = 0; i < resources.length; i++){
413                             if (resources[i].getAttributeValue("key") == null) { //NOI18N
414
resource = resources[i];
415                                 break;
416                             }
417                         }
418                     }
419                 }
420                 index++;
421             }
422         } catch (DataObjectNotFoundException ex) {
423             ErrorManager.getDefault().notify(ErrorManager.WARNING, ex);
424         } catch (IOException JavaDoc ex) {
425             ErrorManager.getDefault().notify(ErrorManager.WARNING, ex);
426         }
427         return resource;
428     }
429 }
430
Popular Tags