KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > websvc > wsitconf > wizard > STSWizardCreator


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

19
20 package org.netbeans.modules.websvc.wsitconf.wizard;
21
22 import com.sun.source.tree.AnnotationTree;
23 import com.sun.source.tree.ClassTree;
24 import com.sun.source.tree.ExpressionTree;
25 import com.sun.source.tree.MethodTree;
26 import com.sun.source.tree.ModifiersTree;
27 import com.sun.source.tree.TypeParameterTree;
28 import com.sun.source.tree.VariableTree;
29 import java.io.File JavaDoc;
30 import java.net.URL JavaDoc;
31 import java.util.ArrayList JavaDoc;
32 import java.util.Collections JavaDoc;
33 import java.util.List JavaDoc;
34 import java.util.Map JavaDoc;
35 import javax.lang.model.element.Modifier;
36 import javax.lang.model.element.TypeElement;
37 import org.netbeans.api.java.classpath.ClassPath;
38 import org.netbeans.api.java.source.CancellableTask;
39 import org.netbeans.api.java.source.JavaSource;
40 import org.netbeans.api.java.source.JavaSource.Phase;
41 import org.netbeans.api.java.source.TreeMaker;
42 import org.netbeans.api.java.source.WorkingCopy;
43 import org.netbeans.api.progress.ProgressHandle;
44 import org.netbeans.api.progress.ProgressHandleFactory;
45 import org.netbeans.api.project.Project;
46 import org.netbeans.modules.j2ee.api.ejbjar.EjbJar;
47 import org.netbeans.modules.j2ee.deployment.devmodules.api.Deployment;
48 import org.netbeans.modules.j2ee.deployment.devmodules.api.J2eeModule;
49 import org.netbeans.modules.j2ee.deployment.devmodules.api.J2eePlatform;
50 import org.netbeans.modules.j2ee.deployment.devmodules.spi.J2eeModuleProvider;
51 import org.netbeans.modules.web.api.webmodule.WebModule;
52 import org.netbeans.modules.websvc.api.jaxws.wsdlmodel.WsdlModel;
53 import org.netbeans.modules.websvc.api.jaxws.wsdlmodel.WsdlModelListener;
54 import org.netbeans.modules.websvc.api.jaxws.wsdlmodel.WsdlModeler;
55 import org.netbeans.modules.websvc.api.jaxws.wsdlmodel.WsdlPort;
56 import org.netbeans.modules.websvc.api.jaxws.wsdlmodel.WsdlService;
57 import org.netbeans.modules.websvc.jaxws.api.JAXWSSupport;
58 import org.netbeans.modules.websvc.wsitconf.util.GenerationUtils;
59 import org.netbeans.spi.project.ui.templates.support.Templates;
60 import org.openide.DialogDisplayer;
61 import org.openide.ErrorManager;
62 import org.openide.NotifyDescriptor;
63 import org.openide.WizardDescriptor;
64 import org.openide.cookies.EditorCookie;
65 import org.openide.filesystems.FileObject;
66 import org.openide.filesystems.FileUtil;
67 import org.openide.loaders.DataObject;
68 import org.openide.util.NbBundle;
69 import org.openide.util.RequestProcessor;
70
71 public class STSWizardCreator {
72
73     protected static final int JSE_PROJECT_TYPE = 0;
74     protected static final int WEB_PROJECT_TYPE = 1;
75     protected static final int EJB_PROJECT_TYPE = 2;
76
77     private int projectType;
78
79     private Project project;
80     private WizardDescriptor wiz;
81
82     public boolean jwsdpSupported, wsitSupported, jsr109Supported, jsr109oldSupported;
83
84     public STSWizardCreator(Project project, WizardDescriptor wiz) {
85         this.project = project;
86         this.wiz = wiz;
87     }
88     
89     public STSWizardCreator(Project project) {
90         this.project = project;
91     }
92     
93     public void createSTS() {
94         final ProgressHandle handle = ProgressHandleFactory.createHandle(
95                 NbBundle.getMessage(STSWizardCreator.class, "TXT_WebServiceGeneration")); //NOI18N
96

97         initProjectInfo(project);
98         
99         Runnable JavaDoc r = new Runnable JavaDoc() {
100             public void run() {
101                 try {
102                     handle.start(100);
103                     generateWsFromWsdl15(handle);
104                 } catch (Exception JavaDoc e) {
105                     //finish progress bar
106
handle.finish();
107                     String JavaDoc message = e.getLocalizedMessage();
108                     if(message != null) {
109                         ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
110                         NotifyDescriptor nd = new NotifyDescriptor.Message(message, NotifyDescriptor.ERROR_MESSAGE);
111                         DialogDisplayer.getDefault().notify(nd);
112                     } else {
113                         ErrorManager.getDefault().notify(ErrorManager.EXCEPTION, e);
114                     }
115                 }
116             }
117         };
118         RequestProcessor.getDefault().post(r);
119     }
120     
121     private void initProjectInfo(Project project) {
122         JAXWSSupport wss = JAXWSSupport.getJAXWSSupport(project.getProjectDirectory());
123         if (wss != null) {
124             Map JavaDoc properties = wss.getAntProjectHelper().getStandardPropertyEvaluator().getProperties();
125             String JavaDoc serverInstance = (String JavaDoc)properties.get("j2ee.server.instance"); //NOI18N
126
if (serverInstance != null) {
127                 J2eePlatform j2eePlatform = Deployment.getDefault().getJ2eePlatform(serverInstance);
128                 if (j2eePlatform != null) {
129                     jwsdpSupported = j2eePlatform.isToolSupported(J2eePlatform.TOOL_JWSDP);
130                     wsitSupported = j2eePlatform.isToolSupported(J2eePlatform.TOOL_WSIT);
131                     jsr109Supported = j2eePlatform.isToolSupported(J2eePlatform.TOOL_JSR109);
132                     jsr109oldSupported = j2eePlatform.isToolSupported(J2eePlatform.TOOL_WSCOMPILE);
133                 }
134             }
135         }
136         
137         WebModule wm = WebModule.getWebModule(project.getProjectDirectory());
138         EjbJar em = EjbJar.getEjbJar(project.getProjectDirectory());
139         if (em != null)
140             projectType = EJB_PROJECT_TYPE;
141         else if (wm != null)
142             projectType = WEB_PROJECT_TYPE;
143         else
144             projectType = JSE_PROJECT_TYPE;
145     }
146     
147     private void generateWsFromWsdl15(final ProgressHandle handle) throws Exception JavaDoc {
148         String JavaDoc wsdlFilePath = (String JavaDoc) wiz.getProperty(WizardProperties.WSDL_FILE_PATH);
149         File JavaDoc normalizedWsdlFilePath = FileUtil.normalizeFile(new File JavaDoc(wsdlFilePath));
150         //convert to URI first to take care of spaces
151
final URL JavaDoc wsdlURL = normalizedWsdlFilePath.toURI().toURL();
152         final WsdlService service = (WsdlService) wiz.getProperty(WizardProperties.WSDL_SERVICE);
153         if (service==null) {
154             handle.finish();
155             return;
156         } else {
157             final WsdlPort port = (WsdlPort) wiz.getProperty(WizardProperties.WSDL_PORT);
158             //String portJavaName = port.getJavaName();
159
WsdlModeler wsdlModeler = (WsdlModeler) wiz.getProperty(WizardProperties.WSDL_MODELER);
160             // don't set the packageName for modeler (use the default one generated from target Namespace)
161
wsdlModeler.generateWsdlModel(new WsdlModelListener() {
162                 public void modelCreated(WsdlModel model) {
163                     WsdlService service1 = model.getServiceByName(service.getName());
164                     WsdlPort port1 = service1.getPortByName(port.getName());
165                     port1.setSOAPVersion(port.getSOAPVersion());
166                     FileObject targetFolder = Templates.getTargetFolder(wiz);
167                     String JavaDoc targetName = Templates.getTargetName(wiz);
168                     try {
169                         generateProviderImplClass(project, targetFolder, targetName, service1, port1, wsdlURL);
170                         handle.finish();
171                     } catch (Exception JavaDoc ex) {
172                         handle.finish();
173                         ErrorManager.getDefault().notify(ErrorManager.EXCEPTION, ex);
174                     }
175                 }
176             });
177         }
178     }
179     
180     public void generateProviderImplClass(Project project, FileObject targetFolder,
181             String JavaDoc targetName, final WsdlService service, final WsdlPort port, URL JavaDoc wsdlURL) throws Exception JavaDoc{
182         initProjectInfo(project);
183         
184         String JavaDoc serviceID = service.getName();
185         
186         JAXWSSupport jaxWsSupport = JAXWSSupport.getJAXWSSupport(project.getProjectDirectory());
187             
188         FileObject implClassFo = GenerationUtils.createClass(targetFolder, targetName, null);
189         ClassPath classPath = ClassPath.getClassPath(implClassFo, ClassPath.SOURCE);
190         String JavaDoc serviceImplPath = classPath.getResourceName(implClassFo, '.', false);
191         String JavaDoc portJavaName = port.getJavaName();
192         String JavaDoc artifactsPckg = portJavaName.substring(0, portJavaName.lastIndexOf("."));
193
194         serviceID = jaxWsSupport.addService(targetName, serviceImplPath, wsdlURL.toString(), service.getName(), port.getName(), artifactsPckg, jsr109Supported && isJavaEE5orHigher(project));
195         final String JavaDoc wsdlLocation = jaxWsSupport.getWsdlLocation(serviceID);
196                        
197         JavaSource targetSource = JavaSource.forFileObject(implClassFo);
198         CancellableTask<WorkingCopy> task = new CancellableTask<WorkingCopy>() {
199
200             public void run(WorkingCopy workingCopy) throws java.io.IOException JavaDoc {
201                 workingCopy.toPhase(Phase.RESOLVED);
202                 GenerationUtils genUtils = GenerationUtils.newInstance(workingCopy);
203                 if (genUtils!=null) {
204                     TreeMaker make = workingCopy.getTreeMaker();
205                     ClassTree javaClass = genUtils.getClassTree();
206
207                     // add implementation clause
208
// TODO - retouche - this should return <Source>, not sure how to do it with retouche yet
209
ClassTree modifiedClass = genUtils.addImplementsClause(javaClass, "javax.xml.ws.Provider");
210
211                     //add @WebServiceProvider annotation
212
TypeElement WSAn = workingCopy.getElements().getTypeElement("javax.xml.ws.WebServiceProvider"); //NOI18N
213
List JavaDoc<ExpressionTree> attrs = new ArrayList JavaDoc<ExpressionTree>();
214                     attrs.add(
215                         make.Assignment(make.Identifier("serviceName"), make.Literal(service.getName()))); //NOI18N
216
attrs.add(
217                         make.Assignment(make.Identifier("portName"), make.Literal(port.getName()))); //NOI18N
218
attrs.add(
219                         make.Assignment(make.Identifier("targetNamespace"), make.Literal(port.getNamespaceURI()))); //NOI18N
220
attrs.add(
221                         make.Assignment(make.Identifier("wsdlLocation"), make.Literal(wsdlLocation))); //NOI18N
222
AnnotationTree WSAnnotation = make.Annotation(
223                         make.QualIdent(WSAn),
224                         attrs
225                     );
226                     modifiedClass = genUtils.addAnnotation(modifiedClass, WSAnnotation);
227
228                     //add @WebServiceProvider annotation
229
TypeElement modeAn = workingCopy.getElements().getTypeElement("javax.xml.ws.ServiceMode"); //NOI18N
230
List JavaDoc<ExpressionTree> attrsM = new ArrayList JavaDoc<ExpressionTree>();
231                                         
232                     attrsM.add(
233                         make.Assignment(make.Identifier("value"), make.Identifier("Mode.PAYLOAD"))); //NOI18N
234
AnnotationTree modeAnnot = make.Annotation(
235                         make.QualIdent(modeAn),
236                         attrsM
237                     );
238                     modifiedClass = genUtils.addAnnotation(modifiedClass, modeAnnot);
239
240                     // add @Stateless annotation
241
if (projectType == EJB_PROJECT_TYPE) {//EJB project
242
TypeElement StatelessAn = workingCopy.getElements().getTypeElement("javax.ejb.Stateless"); //NOI18N
243
AnnotationTree StatelessAnnotation = make.Annotation(
244                             make.QualIdent(StatelessAn),
245                             Collections.<ExpressionTree>emptyList()
246                         );
247                         modifiedClass = genUtils.addAnnotation(modifiedClass, StatelessAnnotation);
248                     }
249
250                     // create parameters
251
List JavaDoc<VariableTree> params = new ArrayList JavaDoc<VariableTree>();
252                     // final ObjectOutput arg0
253
params.add(make.Variable(
254                             make.Modifiers(
255                                 Collections.<Modifier>emptySet(),
256                                 Collections.<AnnotationTree>emptyList()
257                             ),
258                             "source", // name
259
make.Identifier("javax.xml.transform.Source"), // parameter type
260
null // initializer - does not make sense in parameters.
261
));
262
263                     // create method
264
ModifiersTree methodModifiers = make.Modifiers(
265                         Collections.<Modifier>singleton(Modifier.PUBLIC),
266                         Collections.<AnnotationTree>emptyList()
267                     );
268                     
269                     List JavaDoc<ExpressionTree> exc = new ArrayList JavaDoc<ExpressionTree>();
270                     
271                     MethodTree method = make.Method(
272                             methodModifiers, // public
273
"invoke", // operation name
274
make.Identifier("javax.xml.transform.Source"), // return type
275
Collections.<TypeParameterTree>emptyList(), // type parameters - none
276
params,
277                             exc, // throws
278
"{ //TODO implement this method\nthrow new UnsupportedOperationException(\"Not implemented yet.\") }", // body text
279
null // default value - not applicable here, used by annotations
280
);
281                     modifiedClass = make.addClassMember(modifiedClass, method);
282                     workingCopy.rewrite(javaClass, modifiedClass);
283                 }
284             }
285
286             public void cancel() {
287             }
288         };
289         
290         targetSource.runModificationTask(task).commit();
291             
292         //open in the editor
293
DataObject dobj = DataObject.find(implClassFo);
294         openFileInEditor(dobj);
295     }
296
297     private static void openFileInEditor(DataObject dobj){
298         final EditorCookie ec = (EditorCookie)dobj.getCookie(EditorCookie.class);
299         RequestProcessor.getDefault().post(new Runnable JavaDoc(){
300             public void run(){
301                 ec.open();
302             }
303         }, 1000);
304     }
305     
306     /**
307      * Is J2EE version of a given project JavaEE 5 or higher?
308      *
309      * @param project J2EE project
310      * @return true if J2EE version is JavaEE 5 or higher; otherwise false
311      */

312     public static boolean isJavaEE5orHigher(Project project) {
313         if (project == null) {
314             return false;
315         }
316         J2eeModuleProvider j2eeModuleProvider = (J2eeModuleProvider) project.getLookup().lookup(J2eeModuleProvider.class);
317         if (j2eeModuleProvider != null) {
318             J2eeModule j2eeModule = j2eeModuleProvider.getJ2eeModule();
319             if (j2eeModule != null) {
320                 Object JavaDoc type = j2eeModule.getModuleType();
321                 double version = Double.parseDouble(j2eeModule.getModuleVersion());
322                 if (J2eeModule.EJB.equals(type) && (version > 2.1)) {
323                     return true;
324                 };
325                 if (J2eeModule.WAR.equals(type) && (version > 2.4)) {
326                     return true;
327                 }
328                 if (J2eeModule.CLIENT.equals(type) && (version > 1.4)) {
329                     return true;
330                 }
331             }
332         }
333         return false;
334     }
335     
336 }
337
Popular Tags