1 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 ; 31 import java.io.StringWriter ; 32 import java.io.Writer ; 33 import java.text.MessageFormat ; 34 import java.util.ArrayList ; 35 import java.util.Arrays ; 36 import java.util.Collections ; 37 import java.util.HashSet ; 38 import java.util.Iterator ; 39 import java.util.List ; 40 import java.util.Set ; 41 import java.util.StringTokenizer ; 42 import javax.lang.model.element.Modifier; 43 import javax.lang.model.element.TypeElement; 44 import javax.swing.JEditorPane ; 45 import javax.swing.text.BadLocationException ; 46 import javax.swing.text.Document ; 47 import javax.swing.text.StyledDocument ; 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 88 public class JaxWsCodeGenerator { 89 90 private static final List IMPLICIT_JSP_OBJECTS = Arrays.asList(new String []{ 91 "request","response","session","out","page","config","application","pageContext" }); 93 94 private static final String HINT_INIT_ARGUMENTS=" // TODO initialize WS operation arguments here\n"; 96 private static final String JAVA_TRY = 105 "\ntry '{' // Call Web Service Operation\n"; private static final String JAVA_SERVICE_DEF = 107 " {0} {7} = new {0}();\n"; private static final String JAVA_PORT_DEF = 109 " {1} port = {7}.{2}();\n"; private static final String JAVA_RESULT = 111 " {3}" + " // TODO process result here\n" + " {4} result = port.{5}({6});\n"; private static final String JAVA_VOID = 115 " {3}" + " port.{5}({6});\n"; private static final String JAVA_OUT = 118 " {8}.println(\"Result = \"+result);\n"; private static final String JAVA_CATCH = 120 "'}' catch (Exception ex) '{'\n" + " // TODO handle custom exceptions here\n" + "'}'"; 124 private static final String JAVA_STATIC_STUB_ASYNC_POLLING = 132 "\ntry '{' // Call Web Service Operation(async. polling)\n" + " {0} service = new {0}();\n" + " {1} port = service.{2}();\n" + " {3}" + " // TODO process asynchronous response here\n" + " {4} resp = port.{5}({6});\n" + " while(!resp.isDone()) '{'\n" + " // do something\n" + " Thread.sleep(100);\n" + " '}'\n" + " System.out.println(\"Result = \"+resp.get());\n" + "'}' catch (Exception ex) '{'\n" + " // TODO handle custom exceptions here\n" + "'}'"; 147 private static final String JAVA_STATIC_STUB_ASYNC_CALLBACK = 156 "\ntry '{' // Call Web Service Operation(async. callback)\n" + " {0} service = new {0}();\n" + " {1} port = service.{2}();\n" + " {3}" + " public void handleResponse(javax.xml.ws.Response<{7}> response) '{'\n" + " try '{'\n" + " // TODO process asynchronous response here\n" + " System.out.println(\"Result = \"+ response.get());\n" + " '}' catch(Exception ex) '{'\n" + " // TODO handle exception\n" + " '}'\n" + " '}'\n" + " '}';\n" + " {4} result = port.{5}({6});\n" + " while(!result.isDone()) '{'\n" + " // do something\n" + " Thread.sleep(100);\n" + " '}'\n" + "'}' catch (Exception ex) '{'\n" + " // TODO handle custom exceptions here\n" + "'}'\n"; 178 private static final String JSP_STATIC_STUB = 186 " <%-- start web service invocation --%><hr/>\n" + " <%\n" + " try '{'\n" + "\t{0} service = new {0}();\n" + "\t{1} port = service.{2}();\n" + "{3}" + "\t// TODO process result here\n" + "\t{4} result = port.{5}({6});\n" + "\tout.println(\"Result = \"+result);\n" + " '}' catch (Exception ex) '{'\n" + "\t// TODO handle custom exceptions here\n" + " '}'\n" + " %>\n" + " <%-- end web service invocation --%><hr/>\n"; 201 private static final String JSP_STATIC_STUB_VOID = 208 " <%-- start web service invocation --%><hr/>\n" + " <%\n" + " try '{'\n" + "\t{0} service = new {0}();\n" + "\t{1} port = service.{2}();\n" + "{3}" + "\tport.{5}({6});\n" + " '}' catch (Exception ex) '{'\n" + "\t// TODO handle custom exceptions here\n" + " '}'\n" + " %>\n" + " <%-- end web service invocation --%><hr/>\n"; 221 private static final String JSP_STATIC_STUB_ASYNC_POLLING = 229 " <%-- start web service invocation(async. polling) --%><hr/>\n" + " <%\n" + " try '{'\n" + "\t{0} service = new {0}();\n" + "\t{1} port = service.{2}();\n" + "{3}" + "\t// TODO process asynchronous response here\n" + "\t{4} resp = port.{5}({6});\n" + "\twhile(!resp.isDone()) '{'\n" + "\t\t// do something\n" + "\t\tThread.sleep(100);\n" + "\t'}'\n" + "\tout.println(\"Result = \"+resp.get());\n" + " '}' catch (Exception ex) '{'\n" + "\t// TODO handle custom exceptions here\n" + " '}'\n" + " %>\n" + " <%-- end web service invocation(async. polling) --%><hr/>\n"; 248 private static final String JSP_STATIC_STUB_ASYNC_CALLBACK = 256 " <%-- start web service invocation(async. callback) --%><hr/>\n" + " <%\n" + " try '{'\n" + "\t{0} service = new {0}();\n" + "\t{1} port = service.{2}();\n" + "{3}" + "\t// TODO process asynchronous response here\n" + "\t{4} result = port.{5}({6});\n" + "\twhile(!result.isDone()) '{'\n" + "\t\t// do something\n" + "\t\tThread.sleep(100);\n" + "\t'}'\n" + "\tout.println(\"Result = \"+asyncHandler.getResponse());\n" + " '}' catch (Exception ex) '{'\n" + "\t// TODO handle custom exceptions here\n" + " '}'\n" + " %>\n" + " <%-- end web service invocation(async. callback) --%><hr/>\n"; 275 private static final String JSP_CALLBACK_HANDLER = 278 "<%!\n" + "class {0} implements javax.xml.ws.AsyncHandler<{1}> '{'\n" + " private {1} output;\n" + "\n" + " public void handleResponse(javax.xml.ws.Response<{1}> response) '{'\n" + " try '{'\n" + " output = response.get();\n" + " '}' catch(Exception ex) '{'\n" + " // TODO handle exception\n" + " '}'\n" + " '}'\n" + "\n" + " {1} getResponse() '{'\n" + " return output;\n" + " '}'\n" + "'}'\n" + "%>\n"; 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 301 Node serviceNode, portNode, wsdlNode; 302 String wsdlUrl; 303 String serviceFieldName; 304 final String serviceJavaName; 305 String portJavaName, portGetterMethod, operationJavaName, returnTypeName; 306 String responseType="Object"; String callbackHandlerName = "javax.xml.ws.AsyncHandler"; String argumentInitializationPart, argumentDeclarationPart; 309 WsdlOperation operation; 310 Client client; 311 312 try { 313 serviceFieldName="service"; 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 arguments = operation.getParameters(); 328 returnTypeName = operation.getReturnTypeName(); 329 StringBuffer argumentBuffer1=new StringBuffer (); 330 StringBuffer argumentBuffer2=new StringBuffer (); 331 for (int i=0;i<arguments.size();i++) { 332 String argumentTypeName = ((WsdlParameter)arguments.get(i)).getTypeName(); 333 if (argumentTypeName.startsWith("javax.xml.ws.AsyncHandler")) { responseType = resolveResponseType(argumentTypeName); 335 if (inJsp) argumentTypeName = pureJavaName(portJavaName)+"CallbackHandler"; callbackHandlerName = argumentTypeName; 337 } 338 String argumentName = ((WsdlParameter)arguments.get(i)).getName(); 339 if (inJsp && IMPLICIT_JSP_OBJECTS.contains(argumentName)) { 340 argumentName=argumentName+"_1"; } 342 String argumentDeclaration = argumentTypeName+" "+argumentName; 343 argumentBuffer1.append("\t"+argumentTypeName+" "+argumentName+" = "+resolveInitValue(argumentTypeName, dataObj.getPrimaryFile())+"\n"); argumentBuffer2.append(i>0?", "+argumentName:argumentName); } 346 argumentInitializationPart=(argumentBuffer1.length()>0?"\t"+HINT_INIT_ARGUMENTS+argumentBuffer1.toString():""); 347 argumentDeclarationPart=argumentBuffer2.toString(); 348 349 } catch (NullPointerException npe) { 350 npe.printStackTrace(); 352 String message = NbBundle.getMessage(JaxWsCodeGenerator.class, "ERR_FailedUnexpectedWebServiceDescriptionPattern"); NotifyDescriptor desc = new NotifyDescriptor.Message(message, NotifyDescriptor.Message.ERROR_MESSAGE); 354 DialogDisplayer.getDefault().notify(desc); 355 return; 356 } 357 358 List errors = new ArrayList (); 360 361 boolean success=false; 362 363 if (inJsp) { 365 final javax.swing.text.StyledDocument document = cookie.getDocument(); 366 String invocationBody = ""; 367 Object [] args = new Object [] { 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 content = document.getText(0, document.getLength()); 397 int pos = content.lastIndexOf("</body>"); if (pos<0) pos = content.lastIndexOf("</html>"); if (pos>=0) { 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 [] args1 = new Object [] { 407 callbackHandlerName, 408 responseType 409 }; 410 final String methodBody = MessageFormat.format(JSP_CALLBACK_HANDLER, args1); 411 final String invocationPart = invocationBody; 412 final int position = pos; 413 NbDocument.runAtomic(document, new Runnable () { 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 ex) {} 420 } 421 }); 422 } else { 423 document.insertString(pos,invocationBody,null); 424 } 425 success=true; 426 } catch (javax.swing.text.BadLocationException ex) {} 427 } else { 428 EditorCookie ec = (EditorCookie)dataObj.getCookie(EditorCookie.class); 432 JEditorPane 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 [] printerName = {"System.out"}; final String [] argumentInitPart = {argumentInitializationPart}; 440 final String [] argumentDeclPart = {argumentDeclarationPart}; 441 final String [] serviceFName = {serviceFieldName}; 442 final boolean[] generateWsRefInjection = {false}; 443 CancellableTask<CompilationController> task = new CancellableTask<CompilationController>() { 444 public void run(CompilationController controller) throws IOException { 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 TypeElement thisTypeEl = srcUtils.getTypeElement(); 453 generateWsRefInjection[0] = InjectionTargetQuery.isInjectionTarget(controller, thisTypeEl); 454 insertServiceDef[0] = !generateWsRefInjection[0]; 455 if (isServletClass(controller, javaClass)) { 456 printerName[0]="out"; 458 argumentInitPart[0] = fixNamesInInitializationPart(argumentInitPart[0]); 459 argumentDeclPart[0] = fixNamesInDeclarationPart(argumentDeclPart[0]); 460 } 461 if (generateWsRefInjection[0]) { 463 Set <String > serviceFieldNames = new HashSet <String >(); 464 boolean injectionExists=false; 465 int memberOrder=0; 466 for (Tree member : javaClass.getMembers()) { 467 ++memberOrder; 469 if (VARIABLE == member.getKind()) { 470 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 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 Document document = pane.getDocument(); 500 IndentEngine eng = IndentEngine.find(document); 501 StringWriter textWriter = new StringWriter (); 502 Writer indentWriter = eng.createWriter(document, pos, textWriter); 503 504 String 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 textToInsert = textWriter.toString(); 522 523 try { 524 document.insertString(pos, textToInsert, null); 525 } catch (BadLocationException badLoc) { 526 document.insertString(pos + 1, textToInsert, null); 527 } 528 529 if (generateWsRefInjection[0]) { 531 if (wsdlUrl.startsWith("file:")) { DataObject dObj = (DataObject) sourceNode.getCookie(DataObject.class); 533 if (dObj!=null) 534 wsdlUrl = findWsdlLocation(client,dObj.getPrimaryFile()); 535 } 536 final String localWsdlUrl = wsdlUrl; 537 CancellableTask<WorkingCopy> modificationTask = new CancellableTask<WorkingCopy>() { 538 public void run(WorkingCopy workingCopy) throws IOException { 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 badLoc) { 557 ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, badLoc); 558 } catch (IOException ioe) { 559 ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ioe); 560 } 561 } 562 if (errors.size() > 0) { 563 StringBuffer buf = new StringBuffer (errors.size() * 100); 565 buf.append(NbBundle.getMessage(JaxWsCodeGenerator.class, "ERR_FailedWebServiceInvocationCreation")); buf.append("\n"); for(Iterator iter = errors.iterator(); iter.hasNext(); ) { 568 buf.append(iter.next().toString()); 569 buf.append("\n"); } 571 NotifyDescriptor desc = new NotifyDescriptor.Message(buf.toString(), NotifyDescriptor.Message.ERROR_MESSAGE); 572 DialogDisplayer.getDefault().notify(desc); 573 } 574 575 if (success) { 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 591 private static String resolveInitValue(String type, FileObject targetFile) { 592 if ("int".equals(type) || "long".equals(type) || "short".equals(type) || "byte".equals(type)) return "0;"; if ("boolean".equals(type)) return "false;"; if ("float".equals(type) || "double".equals(type)) return "0.0;"; if ("java.lang.String".equals(type)) return "\"\";"; if (type.endsWith("CallbackHandler")) { return "new "+type+"();"; } 603 if (type.startsWith("javax.xml.ws.AsyncHandler")) { return "new "+type+"() {"; } 606 607 return "null;"; } 618 647 private static String resolveResponseType(String 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"; } 654 655 private static String pureJavaName(String javaNameWithPackage) { 656 int index = javaNameWithPackage.lastIndexOf("."); 657 return index>=0?javaNameWithPackage.substring(index+1):javaNameWithPackage; 658 } 659 660 public static void insertMethod(final Document document, final int pos, OperationNode operationNode) { 661 662 boolean inJsp = "text/x-jsp".equals(document.getProperty("mimeType")); 665 Node serviceNode, portNode, wsdlNode; 666 String wsdlUrl; 667 final String serviceJavaName; 668 String serviceFieldName; 669 String portJavaName, portGetterMethod, operationJavaName, returnTypeName; 670 String responseType="Object"; String callbackHandlerName = "javax.xml.ws.AsyncHandler"; String argumentInitializationPart, argumentDeclarationPart; 673 WsdlOperation operation; 674 Client client; 675 676 try { 677 serviceFieldName="service"; 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 arguments = operation.getParameters(); 692 returnTypeName = operation.getReturnTypeName(); 693 StringBuffer argumentBuffer1=new StringBuffer (); 694 StringBuffer argumentBuffer2=new StringBuffer (); 695 for (int i=0;i<arguments.size();i++) { 696 String argumentTypeName = ((WsdlParameter)arguments.get(i)).getTypeName(); 697 if (argumentTypeName.startsWith("javax.xml.ws.AsyncHandler")) { responseType = resolveResponseType(argumentTypeName); 699 if (inJsp) argumentTypeName = pureJavaName(portJavaName)+"CallbackHandler"; callbackHandlerName = argumentTypeName; 701 } 702 String argumentName = ((WsdlParameter)arguments.get(i)).getName(); 703 if (inJsp && IMPLICIT_JSP_OBJECTS.contains(argumentName)) { 704 argumentName=argumentName+"_1"; } 706 String argumentDeclaration = argumentTypeName+" "+argumentName; 707 argumentBuffer1.append("\t"+argumentTypeName+" "+argumentName+" = "+resolveInitValue(argumentTypeName, 708 NbEditorUtilities.getFileObject(document))+"\n"); argumentBuffer2.append(i>0?", "+argumentName:argumentName); } 711 argumentInitializationPart=(argumentBuffer1.length()>0?"\t"+HINT_INIT_ARGUMENTS+argumentBuffer1.toString():""); 712 argumentDeclarationPart=argumentBuffer2.toString(); 713 714 } catch (NullPointerException npe) { 715 npe.printStackTrace(); 717 String message = NbBundle.getMessage(JaxWsCodeGenerator.class, "ERR_FailedUnexpectedWebServiceDescriptionPattern"); NotifyDescriptor desc = new NotifyDescriptor.Message(message, NotifyDescriptor.Message.ERROR_MESSAGE); 719 DialogDisplayer.getDefault().notify(desc); 720 return; 721 } 722 723 if (inJsp) { 725 String invocationBody = ""; 726 Object [] args = new Object [] { 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 [] args1 = new Object [] { 757 callbackHandlerName, 758 responseType 759 }; 760 final String methodBody = MessageFormat.format(JSP_CALLBACK_HANDLER, args1); 761 final String invocationPart = invocationBody; 762 NbDocument.runAtomic((StyledDocument )document, new Runnable () { 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 ex) {} 769 } 770 }); 771 } else { 772 document.insertString(pos,invocationBody,null); 773 } 774 775 776 } catch (javax.swing.text.BadLocationException ex) {} 777 778 return; 779 } 780 781 FileObject targetFo = NbEditorUtilities.getFileObject(document); 783 784 JavaSource targetSource = JavaSource.forFileObject(targetFo); 785 String respType = responseType; 786 final boolean[] insertServiceDef = {true}; 787 final String [] printerName = {"System.out"}; final String [] argumentInitPart = {argumentInitializationPart}; 789 final String [] argumentDeclPart = {argumentDeclarationPart}; 790 final String [] serviceFName = {serviceFieldName}; 791 final boolean[] generateWsRefInjection = {false}; 792 CancellableTask<CompilationController> task = new CancellableTask<CompilationController>() { 793 public void run(CompilationController controller) throws IOException { 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 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 if (generateWsRefInjection[0]) { 811 Set <String > serviceFieldNames = new HashSet <String >(); 812 boolean injectionExists=false; 813 int memberOrder=0; 814 for (Tree member : javaClass.getMembers()) { 815 ++memberOrder; 817 if (VARIABLE == member.getKind()) { 818 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 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 IndentEngine eng = IndentEngine.find(document); 851 StringWriter textWriter = new StringWriter (); 852 Writer indentWriter = eng.createWriter(document, pos, textWriter); 853 854 String 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 textToInsert = textWriter.toString(); 872 873 try { 874 document.insertString(pos, textToInsert, null); 875 } catch (BadLocationException badLoc) { 876 document.insertString(pos + 1, textToInsert, null); 877 } 878 879 if (generateWsRefInjection[0]) { 881 if (wsdlUrl.startsWith("file:")) { wsdlUrl = findWsdlLocation(client, targetFo); 883 } 884 final String localWsdlUrl = wsdlUrl; 885 CancellableTask<WorkingCopy> modificationTask = new CancellableTask<WorkingCopy>() { 886 public void run(WorkingCopy workingCopy) throws IOException { 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 badLoc) { 904 ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, badLoc); 905 } catch (IOException ioe) { 906 ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ioe); 907 } 908 } 909 910 private static VariableTree generateServiceRefInjection( 911 WorkingCopy workingCopy, 912 TreeMaker make, 913 String fieldName, 914 String fieldType, 915 String wsdlUrl) { 916 TypeElement wsRefElement = workingCopy.getElements().getTypeElement("javax.xml.ws.WebServiceRef"); 918 AnnotationTree wsRefAnnotation = make.Annotation( 919 make.QualIdent(wsRefElement), 920 Collections.<ExpressionTree>singletonList(make.Assignment(make.Identifier("wsdlLocation"), make.Literal(wsdlUrl))) 921 ); 922 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 findProperServiceFieldName(Set serviceFieldNames) { 937 String name="service"; 938 int i=0; 939 while (serviceFieldNames.contains(name)) { 940 name="service_"+String.valueOf(++i); 941 } 942 return name; } 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 getJavaInvocationBody( 951 WsdlOperation operation, 952 boolean insertServiceDef, 953 String serviceJavaName, 954 String portJavaName, 955 String portGetterMethod, 956 String argumentInitializationPart, 957 String returnTypeName, 958 String operationJavaName, 959 String argumentDeclarationPart, 960 String serviceFieldName, 961 String printerName, 962 String responseType) { 963 String invocationBody=""; 964 Object [] args = new Object [] { 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)) { String 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 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 fixNamesInDeclarationPart(String argumentDeclarationPart) { 1010 StringTokenizer tok = new StringTokenizer (argumentDeclarationPart," ,"); StringBuffer buf = new StringBuffer (); 1012 int i=0; 1013 while (tok.hasMoreTokens()) { 1014 String token = tok.nextToken(); 1015 String newName=null; 1016 if ("request".equals(token)) newName="request_1"; else if ("response".equals(token)) newName="response_1"; else if ("out".equals(token)) newName="out_1"; else newName=token; 1020 buf.append(i>0?", "+newName:newName); i++; 1022 } 1023 return buf.toString(); 1024 } 1025 1026 private static String fixNamesInInitializationPart(String argumentInitializationPart) { 1027 return argumentInitializationPart.replaceFirst(" request ", " request_1 ").replaceFirst(" response ", " response_1 ").replaceFirst(" out "," out_1 "); } 1031 1060 private static String 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(); } else { 1066 return "META-INF/wsdl/client/"+client.getName()+"/"+client.getLocalWsdlFile(); } 1068 } 1069} 1070 | Popular Tags |