KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > websvc > core > jaxws > actions > JaxWsCodeGenerator


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.websvc.core.jaxws.actions;
21
22 import com.sun.source.tree.AnnotationTree;
23 import com.sun.source.tree.ClassTree;
24 import com.sun.source.tree.CompilationUnitTree;
25 import com.sun.source.tree.ExpressionTree;
26 import com.sun.source.tree.ModifiersTree;
27 import com.sun.source.tree.Tree;
28 import com.sun.source.tree.VariableTree;
29 import com.sun.source.util.TreePath;
30 import java.io.IOException JavaDoc;
31 import java.io.StringWriter JavaDoc;
32 import java.io.Writer JavaDoc;
33 import java.text.MessageFormat JavaDoc;
34 import java.util.ArrayList JavaDoc;
35 import java.util.Arrays JavaDoc;
36 import java.util.Collections JavaDoc;
37 import java.util.HashSet JavaDoc;
38 import java.util.Iterator JavaDoc;
39 import java.util.List JavaDoc;
40 import java.util.Set JavaDoc;
41 import java.util.StringTokenizer JavaDoc;
42 import javax.lang.model.element.Modifier;
43 import javax.lang.model.element.TypeElement;
44 import javax.swing.JEditorPane JavaDoc;
45 import javax.swing.text.BadLocationException JavaDoc;
46 import javax.swing.text.Document JavaDoc;
47 import javax.swing.text.StyledDocument JavaDoc;
48 import org.netbeans.api.java.source.CancellableTask;
49 import org.netbeans.api.java.source.CompilationController;
50 import org.netbeans.api.java.source.JavaSource;
51 import org.netbeans.api.java.source.TreeMaker;
52 import org.netbeans.modules.websvc.core.InvokeOperationCookie;
53 import static org.netbeans.api.java.source.JavaSource.Phase;
54 import static com.sun.source.tree.Tree.Kind.*;
55 import org.netbeans.api.java.source.WorkingCopy;
56 import org.netbeans.api.project.FileOwnerQuery;
57 import org.netbeans.api.project.Project;
58
59 import org.netbeans.modules.editor.NbEditorUtilities;
60 import org.netbeans.modules.j2ee.common.queries.api.InjectionTargetQuery;
61 import org.netbeans.modules.j2ee.common.source.SourceUtils;
62 import org.netbeans.modules.j2ee.deployment.devmodules.api.J2eeModule;
63 import org.netbeans.modules.j2ee.deployment.devmodules.spi.J2eeModuleProvider;
64 import org.netbeans.modules.websvc.api.jaxws.project.config.Client;
65 import org.netbeans.modules.websvc.api.jaxws.wsdlmodel.WsdlOperation;
66 import org.netbeans.modules.websvc.api.jaxws.wsdlmodel.WsdlParameter;
67 import org.netbeans.modules.websvc.api.jaxws.wsdlmodel.WsdlPort;
68 import org.netbeans.modules.websvc.api.jaxws.wsdlmodel.WsdlService;
69 import org.netbeans.modules.websvc.core.JaxWsUtils;
70 import org.netbeans.modules.websvc.core.jaxws.nodes.OperationNode;
71 import org.openide.DialogDisplayer;
72 import org.openide.ErrorManager;
73 import org.openide.NotifyDescriptor;
74 import org.openide.cookies.EditorCookie;
75 import org.openide.filesystems.FileObject;
76 import org.openide.loaders.DataObject;
77 import org.openide.nodes.Node;
78 import org.openide.text.IndentEngine;
79 import org.openide.text.NbDocument;
80 import org.openide.util.NbBundle;
81
82 /** JaxWsCodeGenerator.java
83  *
84  * Created on March 2, 2006
85  *
86  * @author mkuchtiak
87  */

88 public class JaxWsCodeGenerator {
89     
90     private static final List JavaDoc IMPLICIT_JSP_OBJECTS = Arrays.asList(new String JavaDoc[]{
91         "request","response","session","out","page","config","application","pageContext" //NOI18N
92
});
93     
94     private static final String JavaDoc HINT_INIT_ARGUMENTS=" // TODO initialize WS operation arguments here\n"; //NOI18N
95

96     // {0} = service java name (as variable, e.g. "AddNumbersService")
97
// {1} = port java name (e.g. "AddNumbersPort")
98
// {2} = port getter method (e.g. "getAddNumbersPort")
99
// {3} = argument initialization part (e.g. "int x=0; int y=0;")
100
// {4} = java result type (e.g. "int")
101
// {5} = operation java method name (e.g. "add")
102
// {6} = java method arguments (e.g. "int x, int y")
103
// {7} = service field name
104
private static final String JavaDoc JAVA_TRY =
105             "\ntry '{' // Call Web Service Operation\n"; //NOI18N
106
private static final String JavaDoc JAVA_SERVICE_DEF =
107             " {0} {7} = new {0}();\n"; //NOI18N
108
private static final String JavaDoc JAVA_PORT_DEF =
109             " {1} port = {7}.{2}();\n"; //NOI18N
110
private static final String JavaDoc JAVA_RESULT =
111             " {3}" + //NOI18N
112
" // TODO process result here\n" + //NOI18N
113
" {4} result = port.{5}({6});\n"; //NOI18N
114
private static final String JavaDoc JAVA_VOID =
115             " {3}" + //NOI18N
116
" port.{5}({6});\n"; //NOI18N
117
private static final String JavaDoc JAVA_OUT =
118             " {8}.println(\"Result = \"+result);\n"; //NOI18N
119
private static final String JavaDoc JAVA_CATCH =
120             "'}' catch (Exception ex) '{'\n" + //NOI18N
121
" // TODO handle custom exceptions here\n" + //NOI18N
122
"'}'"; //NOI18N
123

124     // {0} = service java name (as variable, e.g. "AddNumbersService")
125
// {1} = port java name (e.g. "AddNumbersPort")
126
// {2} = port getter method (e.g. "getAddNumbersPort")
127
// {3} = argument initialization part (e.g. "int x=0; int y=0;")
128
// {4} = java result type (e.g. "int")
129
// {5} = operation java method name (e.g. "add")
130
// {6} = java method arguments (e.g. "int x, int y")
131
private static final String JavaDoc JAVA_STATIC_STUB_ASYNC_POLLING =
132             "\ntry '{' // Call Web Service Operation(async. polling)\n" + //NOI18N
133
" {0} service = new {0}();\n" + //NOI18N
134
" {1} port = service.{2}();\n" + //NOI18N
135
" {3}" + //NOI18N
136
" // TODO process asynchronous response here\n" + //NOI18N
137
" {4} resp = port.{5}({6});\n" + //NOI18N
138
" while(!resp.isDone()) '{'\n" + //NOI18N
139
" // do something\n" + //NOI18N
140
" Thread.sleep(100);\n" + //NOI18N
141
" '}'\n" + //NOI18N
142
" System.out.println(\"Result = \"+resp.get());\n" + //NOI18N
143
"'}' catch (Exception ex) '{'\n" + //NOI18N
144
" // TODO handle custom exceptions here\n" + //NOI18N
145
"'}'"; //NOI18N
146

147     // {0} = service java name (as variable, e.g. "AddNumbersService")
148
// {1} = port java name (e.g. "AddNumbersPort")
149
// {2} = port getter method (e.g. "getAddNumbersPort")
150
// {3} = argument initialization part (e.g. "int x=0; int y=0;")
151
// {4} = java result type (e.g. "int")
152
// {5} = operation java method name (e.g. "add")
153
// {6} = java method arguments (e.g. "int x, int y")
154
// {7} = response type (e.g. FooResponse)
155
private static final String JavaDoc JAVA_STATIC_STUB_ASYNC_CALLBACK =
156             "\ntry '{' // Call Web Service Operation(async. callback)\n" + //NOI18N
157
" {0} service = new {0}();\n" + //NOI18N
158
" {1} port = service.{2}();\n" + //NOI18N
159
" {3}" + //NOI18N
160
" public void handleResponse(javax.xml.ws.Response<{7}> response) '{'\n" + //NOI18N
161
" try '{'\n" + //NOI18N
162
" // TODO process asynchronous response here\n" + //NOI18N
163
" System.out.println(\"Result = \"+ response.get());\n" + //NOI18N
164
" '}' catch(Exception ex) '{'\n" + //NOI18N
165
" // TODO handle exception\n" + //NOI18N
166
" '}'\n" + //NOI18N
167
" '}'\n" + //NOI18N
168
" '}';\n" + //NOI18N
169
" {4} result = port.{5}({6});\n" + //NOI18N
170
" while(!result.isDone()) '{'\n" + //NOI18N
171
" // do something\n" + //NOI18N
172
" Thread.sleep(100);\n" + //NOI18N
173
" '}'\n" + //NOI18N
174
"'}' catch (Exception ex) '{'\n" + //NOI18N
175
" // TODO handle custom exceptions here\n" + //NOI18N
176
"'}'\n"; //NOI18N
177

178     // {0} = service java name (as variable, e.g. "AddNumbersService")
179
// {1} = port java name (e.g. "AddNumbersPort")
180
// {2} = port getter method (e.g. "getAddNumbersPort")
181
// {3} = argument initialization part (e.g. "int x=0; int y=0;")
182
// {4} = java result type (e.g. "int")
183
// {5} = operation java method name (e.g. "add")
184
// {6} = java method arguments (e.g. "int x, int y")
185
private static final String JavaDoc JSP_STATIC_STUB =
186             " <%-- start web service invocation --%><hr/>\n" + //NOI18N
187
" <%\n" + //NOI18N
188
" try '{'\n" + //NOI18N
189
"\t{0} service = new {0}();\n" + //NOI18N
190
"\t{1} port = service.{2}();\n" + //NOI18N
191
"{3}" + //NOI18N
192
"\t// TODO process result here\n" + //NOI18N
193
"\t{4} result = port.{5}({6});\n" + //NOI18N
194
"\tout.println(\"Result = \"+result);\n" + //NOI18N
195
" '}' catch (Exception ex) '{'\n" + //NOI18N
196
"\t// TODO handle custom exceptions here\n" + //NOI18N
197
" '}'\n" + //NOI18N
198
" %>\n" + //NOI18N
199
" <%-- end web service invocation --%><hr/>\n"; //NOI18N
200

201     // {0} = service java name (as variable, e.g. "AddNumbersService")
202
// {1} = port java name (e.g. "AddNumbersPort")
203
// {2} = port getter method (e.g. "getAddNumbersPort")
204
// {3} = argument initialization part (e.g. "int x=0; int y=0;")
205
// {5} = operation java method name (e.g. "add")
206
// {6} = java method arguments (e.g. "int x, int y")
207
private static final String JavaDoc JSP_STATIC_STUB_VOID =
208             " <%-- start web service invocation --%><hr/>\n" + //NOI18N
209
" <%\n" + //NOI18N
210
" try '{'\n" + //NOI18N
211
"\t{0} service = new {0}();\n" + //NOI18N
212
"\t{1} port = service.{2}();\n" + //NOI18N
213
"{3}" + //NOI18N
214
"\tport.{5}({6});\n" + //NOI18N
215
" '}' catch (Exception ex) '{'\n" + //NOI18N
216
"\t// TODO handle custom exceptions here\n" + //NOI18N
217
" '}'\n" + //NOI18N
218
" %>\n" + //NOI18N
219
" <%-- end web service invocation --%><hr/>\n"; //NOI18N
220

221     // {0} = service java name (as variable, e.g. "AddNumbersService")
222
// {1} = port java name (e.g. "AddNumbersPort")
223
// {2} = port getter method (e.g. "getAddNumbersPort")
224
// {3} = argument initialization part (e.g. "int x=0; int y=0;")
225
// {4} = java result type (e.g. "int")
226
// {5} = operation java method name (e.g. "add")
227
// {6} = java method arguments (e.g. "int x, int y")
228
private static final String JavaDoc JSP_STATIC_STUB_ASYNC_POLLING =
229             " <%-- start web service invocation(async. polling) --%><hr/>\n" + //NOI18N
230
" <%\n" + //NOI18N
231
" try '{'\n" + //NOI18N
232
"\t{0} service = new {0}();\n" + //NOI18N
233
"\t{1} port = service.{2}();\n" + //NOI18N
234
"{3}" + //NOI18N
235
"\t// TODO process asynchronous response here\n" + //NOI18N
236
"\t{4} resp = port.{5}({6});\n" + //NOI18N
237
"\twhile(!resp.isDone()) '{'\n" + //NOI18N
238
"\t\t// do something\n" + //NOI18N
239
"\t\tThread.sleep(100);\n" + //NOI18N
240
"\t'}'\n" + //NOI18N
241
"\tout.println(\"Result = \"+resp.get());\n" + //NOI18N
242
" '}' catch (Exception ex) '{'\n" + //NOI18N
243
"\t// TODO handle custom exceptions here\n" + //NOI18N
244
" '}'\n" + //NOI18N
245
" %>\n" + //NOI18N
246
" <%-- end web service invocation(async. polling) --%><hr/>\n"; //NOI18N
247

248     // {0} = service java name (as variable, e.g. "AddNumbersService")
249
// {1} = port java name (e.g. "AddNumbersPort")
250
// {2} = port getter method (e.g. "getAddNumbersPort")
251
// {3} = argument initialization part (e.g. "int x=0; int y=0;")
252
// {4} = java result type (e.g. "int")
253
// {5} = operation java method name (e.g. "add")
254
// {6} = java method arguments (e.g. "int x, int y")
255
private static final String JavaDoc JSP_STATIC_STUB_ASYNC_CALLBACK =
256             " <%-- start web service invocation(async. callback) --%><hr/>\n" + //NOI18N
257
" <%\n" + //NOI18N
258
" try '{'\n" + //NOI18N
259
"\t{0} service = new {0}();\n" + //NOI18N
260
"\t{1} port = service.{2}();\n" + //NOI18N
261
"{3}" + //NOI18N
262
"\t// TODO process asynchronous response here\n" + //NOI18N
263
"\t{4} result = port.{5}({6});\n" + //NOI18N
264
"\twhile(!result.isDone()) '{'\n" + //NOI18N
265
"\t\t// do something\n" + //NOI18N
266
"\t\tThread.sleep(100);\n" + //NOI18N
267
"\t'}'\n" + //NOI18N
268
"\tout.println(\"Result = \"+asyncHandler.getResponse());\n" + //NOI18N
269
" '}' catch (Exception ex) '{'\n" + //NOI18N
270
"\t// TODO handle custom exceptions here\n" + //NOI18N
271
" '}'\n" + //NOI18N
272
" %>\n" + //NOI18N
273
" <%-- end web service invocation(async. callback) --%><hr/>\n"; //NOI18N
274

275     // {0} = handler name (as type, e.g. "FooCallbackHandler")
276
// {1} = response type (e.g. FooResponse)
277
private static final String JavaDoc JSP_CALLBACK_HANDLER =
278             "<%!\n" + //NOI18N
279
"class {0} implements javax.xml.ws.AsyncHandler<{1}> '{'\n" + //NOI18N
280
" private {1} output;\n" + //NOI18N
281
"\n" + //NOI18N
282
" public void handleResponse(javax.xml.ws.Response<{1}> response) '{'\n" + //NOI18N
283
" try '{'\n" + //NOI18N
284
" output = response.get();\n" + //NOI18N
285
" '}' catch(Exception ex) '{'\n" + //NOI18N
286
" // TODO handle exception\n" + //NOI18N
287
" '}'\n" + //NOI18N
288
" '}'\n" + //NOI18N
289
"\n" + //NOI18N
290
" {1} getResponse() '{'\n" + //NOI18N
291
" return output;\n" + //NOI18N
292
" '}'\n" + //NOI18N
293
"'}'\n" + //NOI18N
294
"%>\n"; //NOI18N
295

296     public static void insertMethodCall(int targetSourceType, DataObject dataObj, Node sourceNode, Node operationNode) {
297         EditorCookie cookie = (EditorCookie)sourceNode.getCookie(EditorCookie.class);
298         boolean inJsp = InvokeOperationCookie.TARGET_SOURCE_JSP==targetSourceType;
299         // First, collect name of method, port, and service:
300

301         Node serviceNode, portNode, wsdlNode;
302         String JavaDoc wsdlUrl;
303         String JavaDoc serviceFieldName;
304         final String JavaDoc serviceJavaName;
305         String JavaDoc portJavaName, portGetterMethod, operationJavaName, returnTypeName;
306         String JavaDoc responseType="Object"; //NOI18N
307
String JavaDoc callbackHandlerName = "javax.xml.ws.AsyncHandler"; //NOI18N
308
String JavaDoc argumentInitializationPart, argumentDeclarationPart;
309         WsdlOperation operation;
310         Client client;
311         
312         try {
313             serviceFieldName="service"; //NOI18N
314
portNode = operationNode.getParentNode();
315             serviceNode = portNode.getParentNode();
316             wsdlNode = serviceNode.getParentNode();
317             operation = (WsdlOperation)operationNode.getLookup().lookup(WsdlOperation.class);
318             WsdlPort port = (WsdlPort)portNode.getLookup().lookup(WsdlPort.class);
319             WsdlService service = (WsdlService)serviceNode.getLookup().lookup(WsdlService.class);
320             
321             client = (Client)wsdlNode.getLookup().lookup(Client.class);
322             wsdlUrl = client.getWsdlUrl();
323             operationJavaName = operation.getJavaName();
324             portJavaName = port.getJavaName();
325             portGetterMethod = port.getPortGetter();
326             serviceJavaName = service.getJavaName();
327             List JavaDoc arguments = operation.getParameters();
328             returnTypeName = operation.getReturnTypeName();
329             StringBuffer JavaDoc argumentBuffer1=new StringBuffer JavaDoc();
330             StringBuffer JavaDoc argumentBuffer2=new StringBuffer JavaDoc();
331             for (int i=0;i<arguments.size();i++) {
332                 String JavaDoc argumentTypeName = ((WsdlParameter)arguments.get(i)).getTypeName();
333                 if (argumentTypeName.startsWith("javax.xml.ws.AsyncHandler")) { //NOI18N
334
responseType = resolveResponseType(argumentTypeName);
335                     if (inJsp) argumentTypeName = pureJavaName(portJavaName)+"CallbackHandler"; //NOI18N
336
callbackHandlerName = argumentTypeName;
337                 }
338                 String JavaDoc argumentName = ((WsdlParameter)arguments.get(i)).getName();
339                 if (inJsp && IMPLICIT_JSP_OBJECTS.contains(argumentName)) {
340                     argumentName=argumentName+"_1"; //NOI18N
341
}
342                 String JavaDoc argumentDeclaration = argumentTypeName+" "+argumentName;
343                 argumentBuffer1.append("\t"+argumentTypeName+" "+argumentName+" = "+resolveInitValue(argumentTypeName, dataObj.getPrimaryFile())+"\n"); //NOI18N
344
argumentBuffer2.append(i>0?", "+argumentName:argumentName); //NOI18N
345
}
346             argumentInitializationPart=(argumentBuffer1.length()>0?"\t"+HINT_INIT_ARGUMENTS+argumentBuffer1.toString():"");
347             argumentDeclarationPart=argumentBuffer2.toString();
348             
349         } catch (NullPointerException JavaDoc npe) {
350             // !PW notify failure to extract service information.
351
npe.printStackTrace();
352             String JavaDoc message = NbBundle.getMessage(JaxWsCodeGenerator.class, "ERR_FailedUnexpectedWebServiceDescriptionPattern"); // NOI18N
353
NotifyDescriptor desc = new NotifyDescriptor.Message(message, NotifyDescriptor.Message.ERROR_MESSAGE);
354             DialogDisplayer.getDefault().notify(desc);
355             return;
356         }
357         
358         // Collect up any and all errors for display in case of problem
359
List JavaDoc errors = new ArrayList JavaDoc();
360         
361         boolean success=false;
362         
363         // including code to JSP
364
if (inJsp) {
365             final javax.swing.text.StyledDocument JavaDoc document = cookie.getDocument();
366             String JavaDoc invocationBody = "";
367             // invocation
368
Object JavaDoc[] args = new Object JavaDoc [] {
369                 serviceJavaName,
370                 portJavaName,
371                 portGetterMethod,
372                 argumentInitializationPart,
373                 returnTypeName,
374                 operationJavaName,
375                 argumentDeclarationPart
376             };
377             switch (operation.getOperationType()) {
378                 case WsdlOperation.TYPE_NORMAL : {
379                     if ("void".equals(returnTypeName))
380                         invocationBody = MessageFormat.format(JSP_STATIC_STUB_VOID, args);
381                     else
382                         invocationBody = MessageFormat.format(JSP_STATIC_STUB, args);
383                     break;
384                 }
385                 case WsdlOperation.TYPE_ASYNC_POLLING : {
386                     invocationBody = MessageFormat.format(JSP_STATIC_STUB_ASYNC_POLLING, args);
387                     break;
388                 }
389                 case WsdlOperation.TYPE_ASYNC_CALLBACK : {
390                     invocationBody = MessageFormat.format(JSP_STATIC_STUB_ASYNC_CALLBACK, args);
391                     break;
392                 }
393             }
394             
395             try {
396                 String JavaDoc content = document.getText(0, document.getLength());
397                 int pos = content.lastIndexOf("</body>"); //NOI18N
398
if (pos<0) pos = content.lastIndexOf("</html>"); //NOI18N
399
if (pos>=0) { //find where line begins
400
while (pos>0 && content.charAt(pos-1)!='\n' && content.charAt(pos-1)!='\r') {
401                         pos--;
402                     }
403                 } else pos = document.getLength();
404                 
405                 if (WsdlOperation.TYPE_ASYNC_CALLBACK==operation.getOperationType()) {
406                     Object JavaDoc[] args1 = new Object JavaDoc [] {
407                         callbackHandlerName,
408                         responseType
409                     };
410                     final String JavaDoc methodBody = MessageFormat.format(JSP_CALLBACK_HANDLER, args1);
411                     final String JavaDoc invocationPart = invocationBody;
412                     final int position = pos;
413                     // insert 2 parts in one atomic action
414
NbDocument.runAtomic(document, new Runnable JavaDoc() {
415                         public void run() {
416                             try {
417                                 document.insertString(document.getLength(),methodBody,null);
418                                 document.insertString(position,invocationPart,null);
419                             } catch (javax.swing.text.BadLocationException JavaDoc ex) {}
420                         }
421                     });
422                 } else {
423                     document.insertString(pos,invocationBody,null);
424                 }
425                 success=true;
426             } catch (javax.swing.text.BadLocationException JavaDoc ex) {}
427         } else {
428 //
429
// // including code to java class
430
//
431
EditorCookie ec = (EditorCookie)dataObj.getCookie(EditorCookie.class);
432             JEditorPane JavaDoc pane = ec.getOpenedPanes()[0];
433             int pos = pane.getCaretPosition();
434         
435             JavaSource targetSource = JavaSource.forFileObject(dataObj.getPrimaryFile());
436             
437             final boolean[] insertServiceDef = {true};
438             final String JavaDoc[] printerName = {"System.out"}; // NOI18N
439
final String JavaDoc[] argumentInitPart = {argumentInitializationPart};
440             final String JavaDoc[] argumentDeclPart = {argumentDeclarationPart};
441             final String JavaDoc[] serviceFName = {serviceFieldName};
442             final boolean[] generateWsRefInjection = {false};
443             CancellableTask<CompilationController> task = new CancellableTask<CompilationController>() {
444                 public void run(CompilationController controller) throws IOException JavaDoc {
445                     controller.toPhase(Phase.ELEMENTS_RESOLVED);
446                     CompilationUnitTree cut = controller.getCompilationUnit();
447
448                     SourceUtils srcUtils = SourceUtils.newInstance(controller);
449                     if (srcUtils!=null) {
450                         ClassTree javaClass = srcUtils.getClassTree();
451                         // find if class is Injection Target
452
TypeElement thisTypeEl = srcUtils.getTypeElement();
453                         generateWsRefInjection[0] = InjectionTargetQuery.isInjectionTarget(controller, thisTypeEl);
454                         insertServiceDef[0] = !generateWsRefInjection[0];
455                         if (isServletClass(controller, javaClass)) {
456                             // PENDING Need to compute pronter name from the method
457
printerName[0]="out";
458                             argumentInitPart[0] = fixNamesInInitializationPart(argumentInitPart[0]);
459                             argumentDeclPart[0] = fixNamesInDeclarationPart(argumentDeclPart[0]);
460                         }
461                         // compute the service field name
462
if (generateWsRefInjection[0]) {
463                             Set JavaDoc<String JavaDoc> serviceFieldNames = new HashSet JavaDoc<String JavaDoc>();
464                             boolean injectionExists=false;
465                             int memberOrder=0;
466                             for (Tree member : javaClass.getMembers()) {
467                                 // for the first inner class in top level
468
++memberOrder;
469                                 if (VARIABLE == member.getKind()) {
470                                     // get variable type
471
VariableTree var = (VariableTree)member;
472                                     Tree typeTree = var.getType();
473                                     TreePath typeTreePath = controller.getTrees().getPath(cut, typeTree);
474                                     TypeElement typeEl = (TypeElement)controller.getTrees().getElement(typeTreePath);
475                                     if (typeEl!=null) {
476                                         String JavaDoc variableType = typeEl.getQualifiedName().toString();
477                                         if (serviceJavaName.equals(variableType)) {
478                                             serviceFName[0]=var.getName().toString();
479                                             generateWsRefInjection[0]=false;
480                                             injectionExists=true;
481                                             break;
482                                         }
483                                     }
484                                     serviceFieldNames.add(var.getName().toString());
485                                 }
486                             }
487                             if (!injectionExists) {
488                                 serviceFName[0] = findProperServiceFieldName(serviceFieldNames);
489                             }
490                         }
491                     }
492                 }
493                 public void cancel() {}
494             };
495             try {
496                 targetSource.runUserActionTask(task, true);
497
498                 // create & format inserted text
499
Document JavaDoc document = pane.getDocument();
500                 IndentEngine eng = IndentEngine.find(document);
501                 StringWriter JavaDoc textWriter = new StringWriter JavaDoc();
502                 Writer JavaDoc indentWriter = eng.createWriter(document, pos, textWriter);
503
504                 // create the inserted text
505
String JavaDoc invocationBody = getJavaInvocationBody(
506                         operation,
507                         insertServiceDef[0],
508                         serviceJavaName,
509                         portJavaName,
510                         portGetterMethod,
511                         argumentInitPart[0],
512                         returnTypeName,
513                         operationJavaName,
514                         argumentDeclPart[0],
515                         serviceFName[0],
516                         printerName[0],
517                         responseType);
518
519                 indentWriter.write(invocationBody);
520                 indentWriter.close();
521                 String JavaDoc textToInsert = textWriter.toString();
522
523                 try {
524                     document.insertString(pos, textToInsert, null);
525                 } catch (BadLocationException JavaDoc badLoc) {
526                     document.insertString(pos + 1, textToInsert, null);
527                 }
528
529                 // @insert WebServiceRef injection
530
if (generateWsRefInjection[0]) {
531                     if (wsdlUrl.startsWith("file:")) { //NOI18N
532
DataObject dObj = (DataObject) sourceNode.getCookie(DataObject.class);
533                         if (dObj!=null)
534                             wsdlUrl = findWsdlLocation(client,dObj.getPrimaryFile());
535                     }
536                     final String JavaDoc localWsdlUrl = wsdlUrl;
537                     CancellableTask<WorkingCopy> modificationTask = new CancellableTask<WorkingCopy>() {
538                         public void run(WorkingCopy workingCopy) throws IOException JavaDoc {
539                             workingCopy.toPhase(Phase.RESOLVED);
540
541                             TreeMaker make = workingCopy.getTreeMaker();
542
543                             SourceUtils srcUtils = SourceUtils.newInstance(workingCopy);
544                             if (srcUtils!=null) {
545                                 ClassTree javaClass = srcUtils.getClassTree();
546                                 VariableTree serviceRefInjection = generateServiceRefInjection(workingCopy, make, serviceFName[0], serviceJavaName, localWsdlUrl);
547                                 ClassTree modifiedClass = make.insertClassMember(javaClass, 0, serviceRefInjection);
548                                 workingCopy.rewrite(javaClass, modifiedClass);
549                             }
550                         }
551                         public void cancel() {}
552                     };
553                     targetSource.runModificationTask(modificationTask).commit();
554                     success=true;
555                 }
556             } catch (BadLocationException JavaDoc badLoc) {
557                 ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, badLoc);
558             } catch (IOException JavaDoc ioe) {
559                 ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ioe);
560             }
561         }
562         if (errors.size() > 0) {
563             // At least one error was encountered during code insertion. Display the list of messages.
564
StringBuffer JavaDoc buf = new StringBuffer JavaDoc(errors.size() * 100);
565             buf.append(NbBundle.getMessage(JaxWsCodeGenerator.class, "ERR_FailedWebServiceInvocationCreation")); // NOI18N
566
buf.append("\n"); // NOI18N
567
for(Iterator JavaDoc iter = errors.iterator(); iter.hasNext(); ) {
568                 buf.append(iter.next().toString());
569                 buf.append("\n"); // NOI18N
570
}
571             NotifyDescriptor desc = new NotifyDescriptor.Message(buf.toString(), NotifyDescriptor.Message.ERROR_MESSAGE);
572             DialogDisplayer.getDefault().notify(desc);
573         }
574         
575         if (success) { // managed to insert string
576
Node clientNode = operationNode.getParentNode().getParentNode().getParentNode();
577             FileObject srcRoot = (FileObject)clientNode.getLookup().lookup(FileObject.class);
578             Project clientProject = FileOwnerQuery.getOwner(srcRoot);
579             DataObject dObj = (DataObject) sourceNode.getCookie(DataObject.class);
580             if (dObj!=null) {
581                 JaxWsUtils.addProjectReference(clientProject, FileOwnerQuery.getOwner(dObj.getPrimaryFile()));
582             }
583         }
584     }
585     
586     /**
587      * Determines the initialization value of a variable of type "type"
588      * @param type Type of the variable
589      * @param targetFile FileObject containing the class that declares the type
590      */

591     private static String JavaDoc resolveInitValue(String JavaDoc type, FileObject targetFile) {
592         if ("int".equals(type) || "long".equals(type) || "short".equals(type) || "byte".equals(type)) //NOI18N
593
return "0;"; //NOI18N
594
if ("boolean".equals(type)) //NOI18N
595
return "false;"; //NOI18N
596
if ("float".equals(type) || "double".equals(type)) //NOI18N
597
return "0.0;"; //NOI18N
598
if ("java.lang.String".equals(type)) //NOI18N
599
return "\"\";"; //NOI18N
600
if (type.endsWith("CallbackHandler")) { //NOI18N
601
return "new "+type+"();"; //NOI18N
602
}
603         if (type.startsWith("javax.xml.ws.AsyncHandler")) { //NOI18N
604
return "new "+type+"() {"; //NOI18N
605
}
606
607 // Retouche
608
// if(targetFile != null && !isEnum(type)){
609
// JavaClass jc = JMIUtils.findClass(type, targetFile);
610
// if(jc != null){
611
// if(hasDefaultConstructor(jc) || !hasExplicitConstructor(jc)){
612
// return "new " + type+ "();";//NOI18N
613
// }
614
// }
615
// }
616
return "null;"; //NOI18N
617
}
618 // Retouche
619
// private static boolean isEnum(String typeName){
620
// Type type = JavaModel.getDefaultExtent().getType().resolve(typeName);
621
// if(type != null){
622
// return (type instanceof JavaEnum);
623
// }
624
// return false;
625
// }
626
//
627
// /**
628
// * Determines if a Java class has an explicit constructor definition
629
// */
630
// private static boolean hasExplicitConstructor(JavaClass jc){
631
// List<ClassMember> members = jc.getContents();
632
// for(ClassMember member: members){
633
// if(member instanceof Constructor){
634
// return true;
635
// }
636
// }
637
// return false;
638
// }
639
//
640
// /**
641
// * Determines if a Java class has a no-arg constructor
642
// */
643
// private static boolean hasDefaultConstructor(JavaClass jc){
644
// return jc.getConstructor(Collections.emptyList(), false) != null;
645
// }
646

647     private static String JavaDoc resolveResponseType(String JavaDoc argumentType) {
648         int start = argumentType.indexOf("<");
649         int end = argumentType.indexOf(">");
650         if (start>0 && end>0 && start<end) {
651             return argumentType.substring(start+1,end);
652         } else return "javax.xml.ws.Response"; //NOI18N
653
}
654     
655     private static String JavaDoc pureJavaName(String JavaDoc javaNameWithPackage) {
656         int index = javaNameWithPackage.lastIndexOf(".");
657         return index>=0?javaNameWithPackage.substring(index+1):javaNameWithPackage;
658     }
659     
660     public static void insertMethod(final Document JavaDoc document, final int pos, OperationNode operationNode) {
661         
662         boolean inJsp = "text/x-jsp".equals(document.getProperty("mimeType")); //NOI18N
663
// First, collect name of method, port, and service:
664

665         Node serviceNode, portNode, wsdlNode;
666         String JavaDoc wsdlUrl;
667         final String JavaDoc serviceJavaName;
668         String JavaDoc serviceFieldName;
669         String JavaDoc portJavaName, portGetterMethod, operationJavaName, returnTypeName;
670         String JavaDoc responseType="Object"; //NOI18N
671
String JavaDoc callbackHandlerName = "javax.xml.ws.AsyncHandler"; //NOI18N
672
String JavaDoc argumentInitializationPart, argumentDeclarationPart;
673         WsdlOperation operation;
674         Client client;
675         
676         try {
677             serviceFieldName="service"; //NOI18N
678
portNode = operationNode.getParentNode();
679             serviceNode = portNode.getParentNode();
680             wsdlNode = serviceNode.getParentNode();
681             operation = (WsdlOperation)operationNode.getLookup().lookup(WsdlOperation.class);
682             WsdlPort port = (WsdlPort)portNode.getLookup().lookup(WsdlPort.class);
683             WsdlService service = (WsdlService)serviceNode.getLookup().lookup(WsdlService.class);
684             
685             client = (Client)wsdlNode.getLookup().lookup(Client.class);
686             wsdlUrl = client.getWsdlUrl();
687             operationJavaName = operation.getJavaName();
688             portJavaName = port.getJavaName();
689             portGetterMethod = port.getPortGetter();
690             serviceJavaName = service.getJavaName();
691             List JavaDoc arguments = operation.getParameters();
692             returnTypeName = operation.getReturnTypeName();
693             StringBuffer JavaDoc argumentBuffer1=new StringBuffer JavaDoc();
694             StringBuffer JavaDoc argumentBuffer2=new StringBuffer JavaDoc();
695             for (int i=0;i<arguments.size();i++) {
696                 String JavaDoc argumentTypeName = ((WsdlParameter)arguments.get(i)).getTypeName();
697                 if (argumentTypeName.startsWith("javax.xml.ws.AsyncHandler")) { //NOI18N
698
responseType = resolveResponseType(argumentTypeName);
699                     if (inJsp) argumentTypeName = pureJavaName(portJavaName)+"CallbackHandler"; //NOI18N
700
callbackHandlerName = argumentTypeName;
701                 }
702                 String JavaDoc argumentName = ((WsdlParameter)arguments.get(i)).getName();
703                 if (inJsp && IMPLICIT_JSP_OBJECTS.contains(argumentName)) {
704                     argumentName=argumentName+"_1"; //NOI18N
705
}
706                 String JavaDoc argumentDeclaration = argumentTypeName+" "+argumentName;
707                 argumentBuffer1.append("\t"+argumentTypeName+" "+argumentName+" = "+resolveInitValue(argumentTypeName,
708                         NbEditorUtilities.getFileObject(document))+"\n"); //NOI18N
709
argumentBuffer2.append(i>0?", "+argumentName:argumentName); //NOI18N
710
}
711             argumentInitializationPart=(argumentBuffer1.length()>0?"\t"+HINT_INIT_ARGUMENTS+argumentBuffer1.toString():"");
712             argumentDeclarationPart=argumentBuffer2.toString();
713             
714         } catch (NullPointerException JavaDoc npe) {
715             // !PW notify failure to extract service information.
716
npe.printStackTrace();
717             String JavaDoc message = NbBundle.getMessage(JaxWsCodeGenerator.class, "ERR_FailedUnexpectedWebServiceDescriptionPattern"); // NOI18N
718
NotifyDescriptor desc = new NotifyDescriptor.Message(message, NotifyDescriptor.Message.ERROR_MESSAGE);
719             DialogDisplayer.getDefault().notify(desc);
720             return;
721         }
722         
723         // including code to JSP
724
if (inJsp) {
725             String JavaDoc invocationBody = "";
726             // invocation
727
Object JavaDoc[] args = new Object JavaDoc [] {
728                 serviceJavaName,
729                 portJavaName,
730                 portGetterMethod,
731                 argumentInitializationPart,
732                 returnTypeName,
733                 operationJavaName,
734                 argumentDeclarationPart
735             };
736             switch (operation.getOperationType()) {
737                 case WsdlOperation.TYPE_NORMAL : {
738                     if ("void".equals(returnTypeName))
739                         invocationBody = MessageFormat.format(JSP_STATIC_STUB_VOID, args);
740                     else
741                         invocationBody = MessageFormat.format(JSP_STATIC_STUB, args);
742                     break;
743                 }
744                 case WsdlOperation.TYPE_ASYNC_POLLING : {
745                     invocationBody = MessageFormat.format(JSP_STATIC_STUB_ASYNC_POLLING, args);
746                     break;
747                 }
748                 case WsdlOperation.TYPE_ASYNC_CALLBACK : {
749                     invocationBody = MessageFormat.format(JSP_STATIC_STUB_ASYNC_CALLBACK, args);
750                     break;
751                 }
752             }
753             
754             try {
755                 if (WsdlOperation.TYPE_ASYNC_CALLBACK==operation.getOperationType()) {
756                     Object JavaDoc[] args1 = new Object JavaDoc [] {
757                         callbackHandlerName,
758                         responseType
759                     };
760                     final String JavaDoc methodBody = MessageFormat.format(JSP_CALLBACK_HANDLER, args1);
761                     final String JavaDoc invocationPart = invocationBody;
762                     // insert 2 parts in one atomic action
763
NbDocument.runAtomic((StyledDocument JavaDoc)document, new Runnable JavaDoc() {
764                         public void run() {
765                             try {
766                                 document.insertString(document.getLength(),methodBody,null);
767                                 document.insertString(pos,invocationPart,null);
768                             } catch (javax.swing.text.BadLocationException JavaDoc ex) {}
769                         }
770                     });
771                 } else {
772                     document.insertString(pos,invocationBody,null);
773                 }
774                 
775                 
776             } catch (javax.swing.text.BadLocationException JavaDoc ex) {}
777             
778             return;
779         }
780         
781         // including code to java class
782
FileObject targetFo = NbEditorUtilities.getFileObject(document);
783         
784         JavaSource targetSource = JavaSource.forFileObject(targetFo);
785         String JavaDoc respType = responseType;
786         final boolean[] insertServiceDef = {true};
787         final String JavaDoc[] printerName = {"System.out"}; // NOI18N
788
final String JavaDoc[] argumentInitPart = {argumentInitializationPart};
789         final String JavaDoc[] argumentDeclPart = {argumentDeclarationPart};
790         final String JavaDoc[] serviceFName = {serviceFieldName};
791         final boolean[] generateWsRefInjection = {false};
792         CancellableTask<CompilationController> task = new CancellableTask<CompilationController>() {
793             public void run(CompilationController controller) throws IOException JavaDoc {
794                 controller.toPhase(Phase.ELEMENTS_RESOLVED);
795                 CompilationUnitTree cut = controller.getCompilationUnit();
796                 
797                 SourceUtils srcUtils = SourceUtils.newInstance(controller);
798                 if (srcUtils!=null) {
799                     ClassTree javaClass = srcUtils.getClassTree();
800                     // find if class is Injection Target
801
TypeElement thisTypeEl = srcUtils.getTypeElement();
802                     generateWsRefInjection[0] = InjectionTargetQuery.isInjectionTarget(controller, thisTypeEl);
803                     insertServiceDef[0] = !generateWsRefInjection[0];
804                     if (isServletClass(controller, javaClass)) {
805                         printerName[0]="out";
806                         argumentInitPart[0] = fixNamesInInitializationPart(argumentInitPart[0]);
807                         argumentDeclPart[0] = fixNamesInDeclarationPart(argumentDeclPart[0]);
808                     }
809                     // compute the service field name
810
if (generateWsRefInjection[0]) {
811                         Set JavaDoc<String JavaDoc> serviceFieldNames = new HashSet JavaDoc<String JavaDoc>();
812                         boolean injectionExists=false;
813                         int memberOrder=0;
814                         for (Tree member : javaClass.getMembers()) {
815                             // for the first inner class in top level
816
++memberOrder;
817                             if (VARIABLE == member.getKind()) {
818                                 // get variable type
819
VariableTree var = (VariableTree)member;
820                                 Tree typeTree = var.getType();
821                                 TreePath typeTreePath = controller.getTrees().getPath(cut, typeTree);
822                                 TypeElement typeEl = (TypeElement)controller.getTrees().getElement(typeTreePath);
823                                 if (typeEl!=null) {
824                                     String JavaDoc variableType = typeEl.getQualifiedName().toString();
825                                     if (serviceJavaName.equals(variableType)) {
826                                         serviceFName[0]=var.getName().toString();
827                                         generateWsRefInjection[0]=false;
828                                         injectionExists=true;
829                                         break;
830                                     }
831                                 }
832                                 serviceFieldNames.add(var.getName().toString());
833                             }
834                         }
835                         if (!injectionExists) {
836                             serviceFName[0] = findProperServiceFieldName(serviceFieldNames);
837                         }
838                     }
839                 }
840             }
841             public void cancel() {}
842         };
843         
844
845
846         try {
847             targetSource.runUserActionTask(task, true);
848             
849             // create & format inserted text
850
IndentEngine eng = IndentEngine.find(document);
851             StringWriter JavaDoc textWriter = new StringWriter JavaDoc();
852             Writer JavaDoc indentWriter = eng.createWriter(document, pos, textWriter);
853
854             // create the inserted text
855
String JavaDoc invocationBody = getJavaInvocationBody(
856                     operation,
857                     insertServiceDef[0],
858                     serviceJavaName,
859                     portJavaName,
860                     portGetterMethod,
861                     argumentInitPart[0],
862                     returnTypeName,
863                     operationJavaName,
864                     argumentDeclPart[0],
865                     serviceFName[0],
866                     printerName[0],
867                     respType);
868
869             indentWriter.write(invocationBody);
870             indentWriter.close();
871             String JavaDoc textToInsert = textWriter.toString();
872
873             try {
874                 document.insertString(pos, textToInsert, null);
875             } catch (BadLocationException JavaDoc badLoc) {
876                 document.insertString(pos + 1, textToInsert, null);
877             }
878             
879             // @insert WebServiceRef injection
880
if (generateWsRefInjection[0]) {
881                 if (wsdlUrl.startsWith("file:")) { //NOI18N
882
wsdlUrl = findWsdlLocation(client, targetFo);
883                 }
884                 final String JavaDoc localWsdlUrl = wsdlUrl;
885                 CancellableTask<WorkingCopy> modificationTask = new CancellableTask<WorkingCopy>() {
886                     public void run(WorkingCopy workingCopy) throws IOException JavaDoc {
887                         workingCopy.toPhase(Phase.RESOLVED);
888
889                         TreeMaker make = workingCopy.getTreeMaker();
890                         
891                         SourceUtils srcUtils = SourceUtils.newInstance(workingCopy);
892                         if (srcUtils!=null) {
893                             ClassTree javaClass = srcUtils.getClassTree();
894                             VariableTree serviceRefInjection = generateServiceRefInjection(workingCopy, make, serviceFName[0], serviceJavaName, localWsdlUrl);
895                             ClassTree modifiedClass = make.insertClassMember(javaClass, 0, serviceRefInjection);
896                             workingCopy.rewrite(javaClass, modifiedClass);
897                         }
898                     }
899                     public void cancel() {}
900                 };
901                 targetSource.runModificationTask(modificationTask).commit();
902             }
903         } catch (BadLocationException JavaDoc badLoc) {
904             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, badLoc);
905         } catch (IOException JavaDoc ioe) {
906             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ioe);
907         }
908     }
909     
910     private static VariableTree generateServiceRefInjection(
911             WorkingCopy workingCopy,
912             TreeMaker make,
913             String JavaDoc fieldName,
914             String JavaDoc fieldType,
915             String JavaDoc wsdlUrl) {
916         TypeElement wsRefElement = workingCopy.getElements().getTypeElement("javax.xml.ws.WebServiceRef"); //NOI18N
917

918         AnnotationTree wsRefAnnotation = make.Annotation(
919                 make.QualIdent(wsRefElement),
920                 Collections.<ExpressionTree>singletonList(make.Assignment(make.Identifier("wsdlLocation"), make.Literal(wsdlUrl)))
921         );
922         // create method modifier: public and no annotation
923
ModifiersTree methodModifiers = make.Modifiers(
924             Collections.<Modifier>singleton(Modifier.PUBLIC),
925             Collections.<AnnotationTree>singletonList(wsRefAnnotation)
926         );
927         TypeElement typeElement = workingCopy.getElements().getTypeElement(fieldType);
928         return make.Variable(
929             methodModifiers,
930             fieldName,
931             make.Type(typeElement.asType()),
932             null
933         );
934     }
935     
936     private static String JavaDoc findProperServiceFieldName(Set JavaDoc serviceFieldNames) {
937         String JavaDoc name="service";
938         int i=0;
939         while (serviceFieldNames.contains(name)) {
940             name="service_"+String.valueOf(++i);
941         }
942         return name; //NOI18N
943
}
944     
945     private static boolean isServletClass(CompilationController controller, ClassTree classTree) {
946         SourceUtils srcUtils = SourceUtils.newInstance(controller, classTree);
947         return srcUtils.isSubtype("javax.servlet.http.HttpServlet");
948     }
949     
950     private static String JavaDoc getJavaInvocationBody(
951             WsdlOperation operation,
952             boolean insertServiceDef,
953             String JavaDoc serviceJavaName,
954             String JavaDoc portJavaName,
955             String JavaDoc portGetterMethod,
956             String JavaDoc argumentInitializationPart,
957             String JavaDoc returnTypeName,
958             String JavaDoc operationJavaName,
959             String JavaDoc argumentDeclarationPart,
960             String JavaDoc serviceFieldName,
961             String JavaDoc printerName,
962             String JavaDoc responseType) {
963         String JavaDoc invocationBody="";
964         Object JavaDoc [] args = new Object JavaDoc [] {
965             serviceJavaName,
966             portJavaName,
967             portGetterMethod,
968             argumentInitializationPart,
969             returnTypeName,
970             operationJavaName,
971             argumentDeclarationPart,
972             serviceFieldName,
973             printerName
974         };
975         switch (operation.getOperationType()) {
976             case WsdlOperation.TYPE_NORMAL : {
977                 if ("void".equals(returnTypeName)) { //NOI18N
978
String JavaDoc body =
979                             JAVA_TRY+
980                             (insertServiceDef?JAVA_SERVICE_DEF:"")+
981                             JAVA_PORT_DEF+
982                             JAVA_VOID+
983                             JAVA_CATCH;
984                     invocationBody = MessageFormat.format(body, args);
985                 } else {
986                     String JavaDoc body =
987                             JAVA_TRY+
988                             (insertServiceDef?JAVA_SERVICE_DEF:"")+
989                             JAVA_PORT_DEF+
990                             JAVA_RESULT+
991                             JAVA_OUT+
992                             JAVA_CATCH;
993                     invocationBody = MessageFormat.format(body, args);
994                 } break;
995             }
996             case WsdlOperation.TYPE_ASYNC_POLLING : {
997                 invocationBody = MessageFormat.format(JAVA_STATIC_STUB_ASYNC_POLLING, args);
998                 break;
999             }
1000            case WsdlOperation.TYPE_ASYNC_CALLBACK : {
1001                args[7] = responseType;
1002                invocationBody = MessageFormat.format(JAVA_STATIC_STUB_ASYNC_CALLBACK, args);
1003                break;
1004            }
1005        }
1006        return invocationBody;
1007    }
1008    
1009    private static String JavaDoc fixNamesInDeclarationPart(String JavaDoc argumentDeclarationPart) {
1010        StringTokenizer JavaDoc tok = new StringTokenizer JavaDoc(argumentDeclarationPart," ,"); //NOI18N
1011
StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
1012        int i=0;
1013        while (tok.hasMoreTokens()) {
1014            String JavaDoc token = tok.nextToken();
1015            String JavaDoc newName=null;
1016            if ("request".equals(token)) newName="request_1"; //NOI18N
1017
else if ("response".equals(token)) newName="response_1"; //NOI18N
1018
else if ("out".equals(token)) newName="out_1"; //NOI18N
1019
else newName=token;
1020            buf.append(i>0?", "+newName:newName); //NOI18N
1021
i++;
1022        }
1023        return buf.toString();
1024    }
1025    
1026    private static String JavaDoc fixNamesInInitializationPart(String JavaDoc argumentInitializationPart) {
1027        return argumentInitializationPart.replaceFirst(" request ", //NOI18N
1028
" request_1 ").replaceFirst(" response ", //NOI18N
1029
" response_1 ").replaceFirst(" out "," out_1 "); //NOI18N
1030
}
1031// Retouche
1032
// private static String findPrinter(Method m) {
1033
// List childrens = m.getChildren();
1034
// boolean foundPrinter=false;
1035
// for (int i=0;i<childrens.size();i++) {
1036
// Object o = childrens.get(i);
1037
// if (o instanceof Parameter) {
1038
// Parameter param = (Parameter)o;
1039
// if ("java.io.PrintWriter".equals(param.getType().getName())) { //NOI18N
1040
// return param.getName();
1041
// }
1042
// }
1043
// if (o instanceof StatementBlock) {
1044
// List<Statement> statements = ((StatementBlock)o).getStatements();
1045
// for (Statement st:statements) {
1046
// if (st instanceof LocalVarDeclaration) {
1047
// List<Variable> variables = ((LocalVarDeclaration)st).getVariables();
1048
// for (Variable var:variables) {
1049
// if ("java.io.PrintWriter".equals(var.getType().getName())) { //NOI18N
1050
// return var.getName();
1051
// }
1052
// }
1053
// }
1054
// }
1055
// }
1056
// }
1057
// return null;
1058
// }
1059

1060    private static String JavaDoc findWsdlLocation(Client client, FileObject targetFo) {
1061        Project targetProject = FileOwnerQuery.getOwner(targetFo);
1062        J2eeModuleProvider moduleProvider = (J2eeModuleProvider)targetProject.getLookup().lookup(J2eeModuleProvider.class);
1063        if (moduleProvider!=null && J2eeModule.WAR.equals(moduleProvider.getJ2eeModule().getModuleType())) {
1064            return "WEB-INF/wsdl/client/"+client.getName()+"/"+client.getLocalWsdlFile(); //NOI18N
1065
} else {
1066            return "META-INF/wsdl/client/"+client.getName()+"/"+client.getLocalWsdlFile(); //NOI18N
1067
}
1068    }
1069}
1070
Popular Tags