1 23 package com.sun.enterprise.webservice; 24 25 import com.sun.enterprise.webservice.spi.ServiceDelegateCreationListener; 26 import java.lang.reflect.Method ; 27 28 import javax.xml.parsers.DocumentBuilder ; 29 import javax.xml.parsers.DocumentBuilderFactory ; 30 import javax.xml.parsers.FactoryConfigurationError ; 31 import javax.xml.parsers.ParserConfigurationException ; 32 import org.xml.sax.SAXException ; 33 import org.xml.sax.SAXParseException ; 34 import org.w3c.dom.*; 35 import javax.xml.xpath.XPathFactory ; 36 import javax.xml.xpath.XPath ; 37 import javax.xml.namespace.NamespaceContext ; 38 39 import java.io.File ; 40 import java.io.FileInputStream ; 41 import java.io.ByteArrayOutputStream ; 42 import java.io.InputStream ; 43 import java.io.OutputStream ; 44 import java.io.OutputStreamWriter ; 45 import java.io.BufferedOutputStream ; 46 import java.io.BufferedInputStream ; 47 import java.io.ByteArrayInputStream ; 48 import java.io.FileOutputStream ; 49 import java.io.IOException ; 50 51 import java.util.Iterator ; 52 import java.util.Collection ; 53 import java.util.HashSet ; 54 import java.util.Set ; 55 import java.util.Map ; 56 import java.util.List ; 57 import java.util.HashMap ; 58 import java.util.Enumeration ; 59 import java.util.ArrayList ; 60 import java.util.StringTokenizer ; 61 import java.util.LinkedList ; 62 63 import java.util.jar.JarFile ; 64 import java.util.jar.Manifest ; 65 import java.util.jar.Attributes ; 66 import java.util.zip.ZipEntry ; 67 68 import javax.xml.transform.*; 69 import javax.xml.transform.stream.*; 70 71 import java.net.URL ; 72 import java.net.URI ; 73 import java.net.URLConnection ; 74 import java.net.URLClassLoader ; 75 import java.net.JarURLConnection ; 76 import java.net.MalformedURLException ; 77 import java.net.InetAddress ; 78 79 import java.security.AccessController ; 80 import java.security.PrivilegedExceptionAction ; 81 import java.lang.reflect.InvocationTargetException ; 82 83 import org.xml.sax.InputSource ; 84 import javax.xml.namespace.QName ; 85 import javax.xml.rpc.handler.MessageContext ; 86 import javax.xml.rpc.Stub ; 87 import javax.xml.rpc.ServiceFactory ; 88 import javax.xml.rpc.handler.soap.SOAPMessageContext ; 89 import javax.xml.rpc.soap.SOAPFaultException ; 90 import javax.xml.rpc.handler.HandlerInfo ; 91 import javax.xml.rpc.handler.HandlerRegistry ; 92 93 import javax.xml.ws.soap.SOAPBinding; 94 import javax.xml.ws.http.HTTPBinding; 95 96 import javax.xml.soap.MimeHeaders ; 97 import javax.xml.soap.MimeHeader ; 98 import javax.xml.soap.MessageFactory ; 99 import javax.xml.soap.SOAPMessage ; 100 import javax.xml.soap.SOAPEnvelope ; 101 import javax.xml.soap.SOAPBody ; 102 import javax.xml.soap.SOAPBodyElement ; 103 import javax.xml.soap.SOAPPart ; 104 import javax.xml.soap.SOAPFault ; 105 import javax.xml.soap.SOAPFactory ; 106 import javax.xml.soap.SOAPException ; 107 import javax.xml.soap.Detail ; 108 109 import javax.servlet.http.HttpServletRequest ; 110 import javax.servlet.http.HttpServletResponse ; 111 112 import javax.enterprise.deploy.shared.ModuleType ; 113 114 import com.sun.enterprise.Switch; 115 import com.sun.enterprise.InjectionException; 116 117 import com.sun.enterprise.admin.common.constant.DeploymentConstants; 118 import com.sun.enterprise.deployment.Application; 119 import com.sun.enterprise.deployment.deploy.shared.AbstractArchive; 120 import com.sun.enterprise.deployment.archivist.ApplicationArchivist; 121 import com.sun.enterprise.deployment.deploy.shared.InputJarArchive; 122 import com.sun.enterprise.deployment.backend.DeploymentRequest; 123 import com.sun.enterprise.deployment.BundleDescriptor; 124 import com.sun.enterprise.deployment.EjbBundleDescriptor; 125 import com.sun.enterprise.deployment.EjbDescriptor; 126 import com.sun.enterprise.deployment.NameValuePairDescriptor; 127 import com.sun.enterprise.deployment.ServiceReferenceDescriptor; 128 import com.sun.enterprise.deployment.util.DeploymentProperties; 129 import com.sun.enterprise.deployment.util.DescriptorVisitor; 130 import com.sun.enterprise.deployment.util.ModuleDescriptor; 131 import com.sun.enterprise.deployment.util.VirtualServerInfo; 132 import com.sun.enterprise.deployment.util.WebServerInfo; 133 import com.sun.enterprise.deployment.util.WsdlFileVisitor; 134 import com.sun.enterprise.deployment.WebBundleDescriptor; 135 import com.sun.enterprise.deployment.WebComponentDescriptor; 136 import com.sun.enterprise.deployment.web.SecurityConstraint; 137 import com.sun.enterprise.deployment.WebService; 138 import com.sun.enterprise.deployment.WebServiceEndpoint; 139 import com.sun.enterprise.deployment.WebServiceHandler; 140 import com.sun.enterprise.deployment.WebServicesDescriptor; 141 import com.sun.enterprise.deployment.WebServiceHandlerChain; 142 import com.sun.enterprise.deployment.web.UserDataConstraint; 143 import com.sun.enterprise.deployment.xml.WebServicesTagNames; 144 import com.sun.enterprise.util.shared.ArchivistUtils; 145 import com.sun.enterprise.util.InjectionManagerImpl; 146 import com.sun.enterprise.util.LocalStringManagerImpl; 147 148 import com.sun.enterprise.webservice.monitoring.WebServiceEngineImpl; 149 150 import javax.enterprise.deploy.shared.ModuleType ; 152 153 import com.sun.enterprise.config.serverbeans.ServerBeansFactory; 155 import com.sun.enterprise.config.serverbeans.Domain; 156 import com.sun.enterprise.config.serverbeans.Server; 157 import com.sun.enterprise.config.serverbeans.Config; 158 import com.sun.enterprise.config.serverbeans.ApplicationRef; 159 import com.sun.enterprise.config.serverbeans.VirtualServer; 160 import com.sun.enterprise.config.serverbeans.HttpListener; 161 import com.sun.enterprise.config.serverbeans.HttpService; 162 import com.sun.enterprise.config.serverbeans.PropertyResolver; 163 import com.sun.enterprise.config.ConfigContext; 164 import com.sun.enterprise.config.ConfigException; 165 import com.sun.enterprise.server.ApplicationServer; 166 import com.sun.enterprise.config.serverbeans.ServerHelper; 167 import com.sun.enterprise.admin.server.core.AdminService; 168 import com.sun.enterprise.admin.AdminContext; 169 170 import com.sun.enterprise.admin.util.JMXConnectorConfig; 171 172 import org.w3c.dom.Element ; 173 174 import java.util.logging.Logger ; 175 import java.util.logging.Level ; 176 import java.util.Properties ; 177 import com.sun.logging.LogDomains; 178 179 import java.security.PrivilegedActionException ; 180 import com.sun.enterprise.deployment.backend.IASDeploymentException; 181 182 import javax.xml.namespace.QName ; 183 import java.io.PrintWriter ; 184 import java.io.PrintStream ; 185 186 import com.sun.xml.rpc.spi.JaxRpcObjectFactory; 188 import com.sun.xml.rpc.spi.model.Model; 189 import com.sun.xml.rpc.spi.model.ModelProperties; 190 import com.sun.xml.rpc.spi.model.Port; 191 import com.sun.xml.rpc.spi.model.Service; 192 import com.sun.xml.rpc.spi.runtime.ClientTransportFactory; 193 import com.sun.xml.rpc.spi.runtime.ClientTransportFactoryTypes; 194 import com.sun.xml.rpc.spi.runtime.SOAPConstants; 195 import com.sun.xml.rpc.spi.runtime.StreamingHandler; 196 import com.sun.xml.rpc.spi.runtime.StubBase; 197 import com.sun.xml.rpc.spi.runtime.Tie; 198 import com.sun.xml.rpc.spi.tools.WSDLUtil; 199 import com.sun.tools.ws.spi.WSToolsObjectFactory; 200 import com.sun.xml.ws.spi.runtime.WSRtObjectFactory; 201 import com.sun.xml.ws.spi.runtime.RuntimeEndpointInfo; 202 import com.sun.xml.messaging.saaj.soap.ExpressMessageFactoryImpl; 203 import com.sun.xml.bind.api.JAXBRIContext; 204 import javax.xml.ws.handler.Handler; 205 import javax.xml.ws.handler.HandlerResolver; 206 import javax.xml.ws.handler.PortInfo; 207 208 import com.sun.corba.ee.spi.codegen.Wrapper; 210 import com.sun.ejb.codegen.ClassGeneratorFactory; 211 212 import javax.xml.parsers.DocumentBuilder ; 214 import javax.xml.parsers.DocumentBuilderFactory ; 215 import javax.xml.parsers.FactoryConfigurationError ; 216 import javax.xml.parsers.ParserConfigurationException ; 217 import org.xml.sax.SAXException ; 218 import org.xml.sax.SAXParseException ; 219 import java.io.File ; 220 import java.io.IOException ; 221 import org.w3c.dom.Document ; 222 import org.w3c.dom.Node ; 223 import org.w3c.dom.NodeList ; 224 225 230 public class WsUtil { 231 232 public static final String CLIENT_TRANSPORT_LOG_PROPERTY = 234 "com.sun.enterprise.webservice.client.transport.log"; 235 236 public static final String ENDPOINT_ADDRESS_PARAM_NAME = 238 "endpointAddressParam"; 239 240 public final String WSDL_IMPORT_NAMESPACE_PARAM_NAME = 241 "wsdlImportNamespaceParam"; 242 public static final String WSDL_IMPORT_LOCATION_PARAM_NAME = 243 "wsdlImportLocationParam"; 244 public static final String WSDL_INCLUDE_LOCATION_PARAM_NAME = 245 "wsdlIncludeLocationParam"; 246 247 public final String SCHEMA_IMPORT_NAMESPACE_PARAM_NAME = 248 "schemaImportNamespaceParam"; 249 public static final String SCHEMA_IMPORT_LOCATION_PARAM_NAME = 250 "schemaImportLocationParam"; 251 public static final String SCHEMA_INCLUDE_LOCATION_PARAM_NAME = 252 "schemaIncludeLocationParam"; 253 254 public static final String SOAP11_TOKEN = "##SOAP11_HTTP"; 255 public static final String SOAP12_TOKEN = "##SOAP12_HTTP"; 256 public static final String SOAP11_MTOM_TOKEN = "##SOAP11_HTTP_MTOM"; 257 public static final String SOAP12_MTOM_TOKEN = "##SOAP12_HTTP_MTOM"; 258 public static final String XML_TOKEN = "##XML_HTTP"; 259 260 private static final String ONE_WAY_OPERATION = 263 "com.sun.xml.rpc.server.OneWayOperation"; 264 private static final String CLIENT_BAD_REQUEST = 265 "com.sun.xml.rpc.server.http.ClientBadRequest"; 266 267 private static Logger logger = 268 LogDomains.getLogger(LogDomains.EJB_LOGGER); 269 270 private static Logger deploymentLogger = 271 LogDomains.getLogger(LogDomains.DPL_LOGGER); 272 273 private JaxRpcObjectFactory rpcFactory; 274 275 public WsUtil() { 276 rpcFactory = JaxRpcObjectFactory.newInstance(); 277 } 278 279 282 public static void start() { 283 284 System.setProperty("javax.xml.ws.spi.Provider", "com.sun.enterprise.webservice.spi.ProviderImpl"); 286 WebServiceEngineImpl.getInstance(); 288 289 } 290 294 public boolean handleGet(HttpServletRequest request, 295 HttpServletResponse response, 296 WebServiceEndpoint endpoint) throws IOException { 297 298 MimeHeaders headers = getHeaders(request); 299 if( hasSomeTextXmlContent(headers) ) { 300 String message = "Received HTTP GET containing text/xml " + 301 " content for endpoint " + endpoint.getEndpointName() + 302 " at " + endpoint.getEndpointAddressUri() + 303 " . HTTP POST should be used instead."; 304 305 306 writeInvalidMethodType(response, message); 307 308 logger.info(message); 309 310 return false; 311 } 312 313 URL wsdlUrl = null; 314 315 String requestUriRaw = request.getRequestURI(); 316 String requestUri = (requestUriRaw.charAt(0) == '/') ? 317 requestUriRaw.substring(1) : requestUriRaw; 318 String queryString = request.getQueryString(); 319 320 WebService webService = endpoint.getWebService(); 321 322 if( queryString == null ) { 323 324 String wsdlPath = endpoint.getWsdlContentPath(requestUri); 326 327 if( wsdlPath != null) { 328 ModuleDescriptor module = 329 webService.getBundleDescriptor().getModuleDescriptor(); 330 331 if( wsdlPath.equals(webService.getWsdlFileUri())){ 332 wsdlUrl = webService.getWsdlFileUrl(); 335 } else if( isWsdlContent(wsdlPath, 336 webService.getBundleDescriptor()) ) { 337 URL finalWsdlUrl = webService.getWsdlFileUrl(); 343 String finalWsdlPath = finalWsdlUrl.getPath(); 344 String wsdlDirPath = finalWsdlPath.substring(0, finalWsdlPath.length()-webService.getWsdlFileUri().length()); 346 File wsdlDir = new File (wsdlDirPath); 347 File wsdlFile = new File (wsdlDir, wsdlPath.replace('/', File.separatorChar)); 348 try { 349 wsdlUrl = wsdlFile.toURL(); 350 } catch(MalformedURLException mue) { 351 logger.log(Level.INFO, "Failure serving WSDL for " + 352 webService.getName(), mue); 353 } 354 355 } 356 } 357 358 } else if( queryString.equalsIgnoreCase("WSDL") ) { 359 wsdlUrl = webService.getWsdlFileUrl(); 360 } 361 362 boolean success = false; 363 if( wsdlUrl != null ) { 364 365 InputStream is = null; 366 try { 367 response.setContentType("text/xml"); 368 response.setStatus(HttpServletResponse.SC_OK); 369 if (wsdlUrl.equals(webService.getWsdlFileUrl())) { 376 try { 378 String moduleID = endpoint.getBundleDescriptor().getApplication().getRegistrationName(); 379 WebServerInfo wsi = getWebServerInfo(moduleID, request); 380 URL url = webService.getWsdlFileUrl(); 381 File originalWsdlFile = new File (url.getPath()+"__orig"); 382 if(!originalWsdlFile.exists()) { 383 originalWsdlFile = new File (url.getPath()); 384 } 385 generateFinalWsdl(originalWsdlFile.toURL(), webService, wsi, response.getOutputStream()); 386 } catch(Exception e) { 387 URLConnection urlCon = wsdlUrl.openConnection(); 390 urlCon.setUseCaches(false); 391 is = urlCon.getInputStream(); 392 ArchivistUtils.copy(is, response.getOutputStream()); 393 } 394 } else { 395 URLConnection urlCon = wsdlUrl.openConnection(); 398 urlCon.setUseCaches(false); 399 is = urlCon.getInputStream(); 400 ArchivistUtils.copy(is, response.getOutputStream()); 401 } 402 success = true; 403 if( logger.isLoggable(Level.FINE) ) { 404 logger.fine("Serving up final wsdl " + wsdlUrl + " for " + 405 request.getRequestURL() + 406 (queryString != null ? ("?"+queryString) : "")); 407 } 408 } catch(Exception e) { 409 logger.log(Level.INFO, "Failure serving WSDL for web service " + 410 webService.getName(), e); 411 } finally { 412 if(is != null) { 413 try { 414 is.close(); 415 } catch(IOException ex) {} 416 } 417 } 418 } 419 420 if( !success ) { 421 String message = 422 "Invalid wsdl request " + request.getRequestURL() + 423 (queryString != null ? ("?"+queryString) : "") + 424 " for web service "+ webService.getName(); 425 426 logger.info(message); 427 428 writeInvalidMethodType(response, message); 429 } 430 431 return success; 432 } 433 434 439 public boolean isWsdlContent(String uri, BundleDescriptor bundle) { 440 String wsdlDir = getWsdlDir(bundle); 441 return (uri != null) && uri.startsWith(wsdlDir); 442 } 443 444 447 public String getWsdlDir(BundleDescriptor bundle) { 448 boolean isWar = (bundle instanceof WebBundleDescriptor); 449 return isWar ? "WEB-INF/wsdl" : "META-INF/wsdl"; 450 } 451 452 455 public void setClientTransportLog(ServiceReferenceDescriptor serviceRef, 456 Stub stub, String transportLogUrlStr) { 457 try { 458 459 final String logUrlString = transportLogUrlStr; 460 461 OutputStream os = (OutputStream ) 462 java.security.AccessController.doPrivileged 463 (new java.security.PrivilegedExceptionAction () { 464 public java.lang.Object run() throws Exception { 465 URL transportLogUrl = new URL (logUrlString); 466 File transportFile =new File (transportLogUrl.getFile()); 467 return new FileOutputStream (transportFile, true); 468 } 469 }); 470 471 ClientTransportFactory transportFactory = 472 rpcFactory.createClientTransportFactory( 473 ClientTransportFactoryTypes.HTTP, os); 474 475 if( stub instanceof StubBase ) { 476 ((StubBase)stub)._setTransportFactory(transportFactory); 477 logger.info("Logging client transport for service-ref " + 478 serviceRef.getName() + " to file " + 479 transportLogUrlStr); 480 } 481 482 } catch(PrivilegedActionException pae) { 483 logger.log(Level.INFO, "", pae.getCause()); 484 } catch(Throwable t) { 485 logger.log(Level.INFO, "", t); 486 } 487 } 488 489 498 private void parseRelativeImports(URL wsdlFileUrl, 499 Collection wsdlRelativeImports, 500 Collection wsdlIncludes, 501 Collection schemaRelativeImports, 502 Collection schemaIncludes) 503 throws Exception { 504 505 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 507 factory.setNamespaceAware(true); 508 509 InputStream is = null; 510 try { 511 DocumentBuilder builder = factory.newDocumentBuilder(); 512 is = wsdlFileUrl.openStream(); 513 Document document = builder.parse(is); 514 procesSchemaImports(document, schemaRelativeImports); 515 procesWsdlImports(document, wsdlRelativeImports); 516 procesSchemaIncludes(document, schemaIncludes); 517 procesWsdlIncludes(document, wsdlIncludes); 518 } catch (SAXParseException spe) { 519 logger.log(Level.SEVERE,"\n** Parsing error" + ", line " + 521 spe.getLineNumber() + ", uri " + spe.getSystemId()); 522 Exception x = spe; 524 if (spe.getException() != null) { 525 x = spe.getException(); 526 } 527 x.printStackTrace(); 528 } catch (Exception sxe) { 529 logger.log(Level.SEVERE, "Error parsing WSDL" + sxe.getMessage()); 530 } finally { 531 try { 532 if(is != null) { 533 is.close(); 534 } 535 } catch (IOException io) {} 536 } 537 } 538 539 private void addImportsAndIncludes(NodeList list, Collection result, 540 String namespace, String location) throws SAXException , 541 ParserConfigurationException , IOException , SAXParseException { 542 for(int i=0; i<list.getLength(); i++) { 543 Import imp = new Import(); 544 Node element = list.item(i); 545 NamedNodeMap attrs = element.getAttributes(); 546 Node n; 547 if(namespace != null) { 548 n = attrs.getNamedItem(namespace); 549 if(n != null) { 550 imp.setNamespace(n.getNodeValue()); 551 } 552 } 553 n = attrs.getNamedItem(location); 554 if(n != null) { 555 imp.setLocation(n.getNodeValue()); 556 result.add(imp); 557 } 558 } 559 return; 560 } 561 562 private void procesSchemaImports(Document document, Collection schemaImportCollection) throws SAXException , 563 ParserConfigurationException , IOException , SAXParseException { 564 NodeList schemaImports = 565 document.getElementsByTagNameNS("http://www.w3.org/2001/XMLSchema", "import"); 566 addImportsAndIncludes(schemaImports, schemaImportCollection, "namespace", "schemaLocation"); 567 } 568 569 private void procesWsdlImports(Document document, Collection wsdlImportCollection) throws SAXException , 570 ParserConfigurationException , IOException , SAXParseException { 571 NodeList wsdlImports = 572 document.getElementsByTagNameNS("http://schemas.xmlsoap.org/wsdl/", "import"); 573 addImportsAndIncludes(wsdlImports, wsdlImportCollection, "namespace", "location"); 574 } 575 576 private void procesSchemaIncludes(Document document, Collection schemaIncludeCollection) throws SAXException , 577 ParserConfigurationException , IOException , SAXParseException { 578 NodeList schemaIncludes = 579 document.getElementsByTagNameNS("http://www.w3.org/2001/XMLSchema", "include"); 580 addImportsAndIncludes(schemaIncludes, schemaIncludeCollection, null, "schemaLocation"); 581 } 582 583 private void procesWsdlIncludes(Document document, Collection wsdlIncludesCollection) throws SAXException , 584 ParserConfigurationException , IOException , SAXParseException { 585 NodeList wsdlIncludes = 586 document.getElementsByTagNameNS("http://schemas.xmlsoap.org/wsdl/", "import"); 587 addImportsAndIncludes(wsdlIncludes, wsdlIncludesCollection, null, "location"); 588 } 589 590 591 597 public void generateFinalWsdl(URL wsdlFileUrl, WebService webService, WebServerInfo wsi, 598 File finalWsdlFile) throws Exception { 599 600 640 641 OutputStream outputStream = 642 new BufferedOutputStream (new FileOutputStream (finalWsdlFile)); 643 generateFinalWsdl(wsdlFileUrl, webService, wsi, outputStream); 644 645 } 646 647 public void generateFinalWsdl(URL wsdlFileUrl, WebService webService, WebServerInfo wsi, 648 OutputStream outputStream) throws Exception { 649 650 Switch theSwitch = Switch.getSwitch(); 651 652 String webServiceName = webService.getName(); 653 654 Collection wsdlRelativeImports = new HashSet (); 655 Collection wsdlIncludes = new HashSet (); 656 Collection schemaRelativeImports = new HashSet (); 657 Collection schemaIncludes = new HashSet (); 658 if( webService.hasUrlPublishing() ) { 659 parseRelativeImports(wsdlFileUrl, wsdlRelativeImports, 660 wsdlIncludes, schemaRelativeImports, schemaIncludes); 661 } 662 663 Collection endpoints = webService.getEndpoints(); 664 665 Collection endpointsCopy = new ArrayList (); 676 endpointsCopy.addAll(endpoints); 677 678 BundleDescriptor bundle = webService.getBundleDescriptor(); 679 WebServicesDescriptor wsd = bundle.getWebServices(); 680 Collection webServices = wsd.getWebServices(); 681 if (webServices.size()>1) { 682 for (Iterator wsIter = webServices.iterator();wsIter.hasNext();) { 683 WebService aWS = (WebService) wsIter.next(); 684 if (webService.getName().equals(aWS.getName())) { 685 continue; 686 } 687 if (webService.getWsdlFileUri().equals(aWS.getWsdlFileUri())) { 690 endpointsCopy.addAll(aWS.getEndpoints()); 691 } 692 } 693 } 694 695 696 InputStream wsdlInputStream = new BufferedInputStream (wsdlFileUrl.openStream()); 700 Source XsltWsdlDocument = new StreamSource(wsdlInputStream); 701 Templates templates = createTemplatesFor 702 (endpointsCopy, wsdlRelativeImports, wsdlIncludes, 703 schemaRelativeImports, schemaIncludes); 704 705 Transformer transformer = templates.newTransformer(); 706 707 708 WebServiceEndpoint endpointForImport = 711 webService.pickEndpointForRelativeImports(); 712 URL root= wsi.getWebServerRootURL(endpointForImport.isSecure()); 713 URL finalWsdlUrl = endpointForImport.composeFinalWsdlUrl(root); 714 715 int wsdlImportNum = 0; 716 for(Iterator iter = wsdlRelativeImports.iterator(); iter.hasNext();){ 717 Import next = (Import) iter.next(); 718 transformer.setParameter 719 (WSDL_IMPORT_NAMESPACE_PARAM_NAME + wsdlImportNum, 720 next.getNamespace()); 721 722 URL relativeUrl = new URL (finalWsdlUrl, next.getLocation()); 725 transformer.setParameter 726 (WSDL_IMPORT_LOCATION_PARAM_NAME + wsdlImportNum, relativeUrl); 727 728 wsdlImportNum++; 729 } 730 731 int schemaImportNum = 0; 732 for(Iterator iter = schemaRelativeImports.iterator(); iter.hasNext();){ 733 Import next = (Import) iter.next(); 734 transformer.setParameter 735 (SCHEMA_IMPORT_NAMESPACE_PARAM_NAME + schemaImportNum, 736 next.getNamespace()); 737 738 URL relativeUrl = new URL (finalWsdlUrl, next.getLocation()); 741 transformer.setParameter 742 (SCHEMA_IMPORT_LOCATION_PARAM_NAME + schemaImportNum, 743 relativeUrl); 744 745 schemaImportNum++; 746 } 747 748 int wsdlIncludeNum = 0; 749 for(Iterator iter = wsdlIncludes.iterator(); iter.hasNext();){ 750 Import next = (Import) iter.next(); 751 URL relativeUrl = new URL (finalWsdlUrl, next.getLocation()); 752 transformer.setParameter 753 (WSDL_INCLUDE_LOCATION_PARAM_NAME + wsdlIncludeNum, relativeUrl); 754 wsdlIncludeNum++; 755 } 756 757 int schemaIncludeNum = 0; 758 for(Iterator iter = schemaIncludes.iterator(); iter.hasNext();){ 759 Import next = (Import) iter.next(); 760 URL relativeUrl = new URL (finalWsdlUrl, next.getLocation()); 761 transformer.setParameter 762 (SCHEMA_INCLUDE_LOCATION_PARAM_NAME + schemaIncludeNum, 763 relativeUrl); 764 schemaIncludeNum++; 765 } 766 767 int endpointNum = 0; 768 for(Iterator iter = endpointsCopy.iterator(); iter.hasNext();) { 769 WebServiceEndpoint next = (WebServiceEndpoint) iter.next(); 770 771 URL rootURL = wsi.getWebServerRootURL(next.isSecure()); 779 780 URL actualAddress = next.composeEndpointAddress(rootURL); 781 782 transformer.setParameter(ENDPOINT_ADDRESS_PARAM_NAME + endpointNum, 783 actualAddress.toExternalForm()); 784 785 String endpointType = next.implementedByEjbComponent() ? 786 "EJB" : "Servlet"; 787 788 deploymentLogger.log(Level.INFO, 789 "enterprise.deployment.endpoint.registration", 790 new Object [] { endpointType, 791 next.getEndpointName(), actualAddress }); 792 793 endpointNum++; 794 } 795 796 transformer.transform(XsltWsdlDocument, new StreamResult(outputStream)); 797 wsdlInputStream.close(); 798 outputStream.close(); 799 800 return; 801 } 802 803 public HandlerInfo createHandlerInfo(WebServiceHandler handler, 804 ClassLoader loader) 805 throws Exception { 806 807 QName [] headers = new QName [handler.getSoapHeaders().size()]; 808 int i = 0; 809 for(Iterator iter = handler.getSoapHeaders().iterator(); 810 iter.hasNext();) { 811 headers[i] = (QName ) iter.next(); 812 i++; 813 } 814 815 Map properties = new HashMap (); 816 for(Iterator iter = handler.getInitParams().iterator(); 817 iter.hasNext();) { 818 NameValuePairDescriptor next = (NameValuePairDescriptor) 819 iter.next(); 820 properties.put(next.getName(), next.getValue()); 821 } 822 823 Class handlerClass = loader.loadClass(handler.getHandlerClass()); 824 return new HandlerInfo (handlerClass, properties, headers); 825 } 826 827 831 public URL privilegedGetServiceRefWsdl 832 (ServiceReferenceDescriptor desc) throws Exception { 833 URL wsdlFileURL; 834 try { 835 final ServiceReferenceDescriptor serviceRef = desc; 836 wsdlFileURL = (URL ) java.security.AccessController.doPrivileged 837 (new java.security.PrivilegedExceptionAction () { 838 public java.lang.Object run() throws Exception { 839 URL retVal; 840 if(serviceRef.hasWsdlOverride()) { 841 retVal = serviceRef.getWsdlOverride(); 842 } else { 843 if(serviceRef.getWsdlFileUrl() != null) { 846 retVal = serviceRef.getWsdlFileUrl(); 847 } else { 848 if(serviceRef.getWsdlFileUri().startsWith("http")) { 849 retVal = new URL (serviceRef.getWsdlFileUri()); 850 } else { 851 retVal = (new File (serviceRef.getWsdlFileUri())).toURL(); 852 } 853 } 854 } 855 return retVal; 856 } 857 }); 858 } catch(PrivilegedActionException pae) { 859 logger.log(Level.WARNING, "", pae); 860 Exception e = new Exception (); 861 e.initCause(pae.getCause()); 862 throw e; 863 } 864 return wsdlFileURL; 865 } 866 867 public javax.xml.rpc.Service createConfiguredService 868 (ServiceReferenceDescriptor desc) throws Exception { 869 870 final ServiceReferenceDescriptor serviceRef = desc; 871 javax.xml.rpc.Service service = null; 872 try { 873 874 879 final URL wsdlFileURL = privilegedGetServiceRefWsdl(serviceRef); 880 final QName serviceName = serviceRef.getServiceName(); 881 final ServiceFactory serviceFactory = ServiceFactory.newInstance(); 882 883 service = (javax.xml.rpc.Service ) 884 java.security.AccessController.doPrivileged 885 (new java.security.PrivilegedExceptionAction () { 886 public java.lang.Object run() throws Exception { 887 return serviceFactory.createService 888 (wsdlFileURL, serviceName); 889 } 890 }); 891 892 } catch(PrivilegedActionException pae) { 893 logger.log(Level.WARNING, "", pae); 894 Exception e = new Exception (); 895 e.initCause(pae.getCause()); 896 throw e; 897 } 898 899 return service; 900 } 901 902 public void configureHandlerChain(ServiceReferenceDescriptor serviceRef, 903 javax.xml.rpc.Service service, 904 Iterator ports, ClassLoader loader) 905 throws Exception { 906 907 if( !serviceRef.hasHandlers() ) { 908 return; 909 } 910 911 HandlerRegistry registry = service.getHandlerRegistry(); 912 913 while(ports.hasNext()) { 914 QName nextPort = (QName ) ports.next(); 915 916 List handlerChain = registry.getHandlerChain(nextPort); 917 Collection soapRoles = new HashSet (); 918 919 for(Iterator iter = serviceRef.getHandlers().iterator(); 920 iter.hasNext();) { 921 WebServiceHandler nextHandler = (WebServiceHandler) iter.next(); 922 Collection portNames = nextHandler.getPortNames(); 923 if( portNames.isEmpty() || 924 portNames.contains(nextPort.getLocalPart()) ) { 925 soapRoles.addAll(nextHandler.getSoapRoles()); 926 HandlerInfo handlerInfo = 927 createHandlerInfo(nextHandler, loader); 928 handlerChain.add(handlerInfo); 929 } 930 } 931 } 932 } 933 934 938 private Templates createTemplatesFor(Collection endpoints, 939 Collection wsdlRelativeImports, 940 Collection wsdlIncludes, 941 Collection schemaRelativeImports, 942 Collection schemaIncludes) throws Exception { 943 944 ByteArrayOutputStream bos = new ByteArrayOutputStream (); 946 OutputStreamWriter writer = new OutputStreamWriter (bos, "UTF-8"); 947 948 writer.write("<xsl:transform version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:wsdl=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\" xmlns:soap12=\"http://schemas.xmlsoap.org/wsdl/soap12/\">\n"); 949 950 int wsdlImportNum = 0; 951 for(Iterator iter = wsdlRelativeImports.iterator(); iter.hasNext();) { 952 953 Import next = (Import) iter.next(); 954 String importNamespaceParam = 955 WSDL_IMPORT_NAMESPACE_PARAM_NAME + wsdlImportNum; 956 String importLocationParam = 957 WSDL_IMPORT_LOCATION_PARAM_NAME + wsdlImportNum; 958 writer.write("<xsl:param name=\"" + importNamespaceParam + "\"/>\n"); 959 writer.write("<xsl:param name=\"" + importLocationParam + "\"/>\n"); 960 961 writer.write("<xsl:template match=\"/\"><xsl:apply-templates mode=\"copy\"/></xsl:template>\n"); 962 writer.write("<xsl:template match=\"wsdl:definitions/wsdl:import[@location='"); 963 writer.write(next.getLocation()); 964 writer.write("']\" mode=\"copy\">"); 965 writer.write("<wsdl:import>"); 966 writer.write("<xsl:attribute name=\"namespace\"><xsl:value-of select=\"$" + importNamespaceParam + "\"/>"); 967 writer.write("</xsl:attribute>"); 968 writer.write("<xsl:attribute name=\"location\"><xsl:value-of select=\"$" + importLocationParam + "\"/>"); 969 writer.write("</xsl:attribute>"); 970 writer.write("</wsdl:import></xsl:template>"); 971 972 wsdlImportNum++; 973 } 974 975 int wsdlIncludeNum = 0; 976 for(Iterator iter = wsdlIncludes.iterator(); iter.hasNext();) { 977 978 Import next = (Import) iter.next(); 979 String importLocationParam = 980 WSDL_INCLUDE_LOCATION_PARAM_NAME + wsdlIncludeNum; 981 writer.write("<xsl:param name=\"" + importLocationParam + "\"/>\n"); 982 983 writer.write("<xsl:template match=\"/\"><xsl:apply-templates mode=\"copy\"/></xsl:template>\n"); 984 writer.write("<xsl:template match=\"wsdl:definitions/wsdl:include[@location='"); 985 writer.write(next.getLocation()); 986 writer.write("']\" mode=\"copy\">"); 987 writer.write("<wsdl:include>"); 988 writer.write("<xsl:attribute name=\"location\"><xsl:value-of select=\"$" + importLocationParam + "\"/>"); 989 writer.write("</xsl:attribute>"); 990 writer.write("</wsdl:include></xsl:template>"); 991 992 wsdlIncludeNum++; 993 } 994 995 int schemaImportNum = 0; 996 for(Iterator iter = schemaRelativeImports.iterator(); iter.hasNext();) { 997 998 Import next = (Import) iter.next(); 999 String importNamespaceParam = 1000 SCHEMA_IMPORT_NAMESPACE_PARAM_NAME + schemaImportNum; 1001 String importLocationParam = 1002 SCHEMA_IMPORT_LOCATION_PARAM_NAME + schemaImportNum; 1003 writer.write("<xsl:param name=\"" + importNamespaceParam + "\"/>\n"); 1004 writer.write("<xsl:param name=\"" + importLocationParam + "\"/>\n"); 1005 1006 writer.write("<xsl:template match=\"/\"><xsl:apply-templates mode=\"copy\"/></xsl:template>\n"); 1007 writer.write("<xsl:template match=\"wsdl:definitions/wsdl:types/xsd:schema/xsd:import[@schemaLocation='"); 1008 writer.write(next.getLocation()); 1009 writer.write("']\" mode=\"copy\">"); 1010 writer.write("<xsd:import>"); 1011 writer.write("<xsl:attribute name=\"namespace\"><xsl:value-of select=\"$" + importNamespaceParam + "\"/>"); 1012 writer.write("</xsl:attribute>"); 1013 writer.write("<xsl:attribute name=\"schemaLocation\"><xsl:value-of select=\"$" + importLocationParam + "\"/>"); 1014 writer.write("</xsl:attribute>"); 1015 writer.write("</xsd:import></xsl:template>"); 1016 1017 schemaImportNum++; 1018 } 1019 1020 int schemaIncludeNum = 0; 1021 for(Iterator iter = schemaIncludes.iterator(); iter.hasNext();) { 1022 1023 Import next = (Import) iter.next(); 1024 String importLocationParam = 1025 SCHEMA_INCLUDE_LOCATION_PARAM_NAME + schemaIncludeNum; 1026 writer.write("<xsl:param name=\"" + importLocationParam + "\"/>\n"); 1027 1028 writer.write("<xsl:template match=\"/\"><xsl:apply-templates mode=\"copy\"/></xsl:template>\n"); 1029 writer.write("<xsl:template match=\"wsdl:definitions/wsdl:types/xsd:schema/xsd:include[@schemaLocation='"); 1030 writer.write(next.getLocation()); 1031 writer.write("']\" mode=\"copy\">"); 1032 writer.write("<xsd:include>"); 1033 writer.write("<xsl:attribute name=\"schemaLocation\"><xsl:value-of select=\"$" + importLocationParam + "\"/>"); 1034 writer.write("</xsl:attribute>"); 1035 writer.write("</xsd:include></xsl:template>"); 1036 1037 schemaIncludeNum++; 1038 } 1039 1040 int endpointNum = 0; 1041 for(Iterator iter = endpoints.iterator(); iter.hasNext();) { 1042 WebServiceEndpoint endpoint = (WebServiceEndpoint) iter.next(); 1043 1044 if( !endpoint.hasWsdlPort() ) { 1045 throw new Exception ("No WSDL port specified for endpoint " + 1046 endpoint.getEndpointName()); 1047 } 1048 if( !endpoint.hasServiceName() ) { 1049 throw new Exception ("Runtime settings error. Cannot find " + 1050 "service name for endpoint " + 1051 endpoint.getEndpointName()); 1052 } 1053 1054 String actualAddressParam = 1055 ENDPOINT_ADDRESS_PARAM_NAME + endpointNum; 1056 1057 writer.write("<xsl:param name=\"" + actualAddressParam + "\"/>\n"); 1058 1059 writer.write("<xsl:template match=\"/\"><xsl:apply-templates mode=\"copy\"/></xsl:template>\n"); 1060 1061 writer.write("<xsl:template match=\"wsdl:definitions[@targetNamespace='"); 1062 writer.write(endpoint.getServiceName().getNamespaceURI()); 1063 writer.write("']/wsdl:service[@name='"); 1064 writer.write(endpoint.getServiceName().getLocalPart()); 1065 writer.write("']/wsdl:port[@name='"); 1066 writer.write(endpoint.getWsdlPort().getLocalPart()); 1067 writer.write("']/"+endpoint.getSoapAddressPrefix()+":address\" mode=\"copy\">"); 1068 writer.write("<"+endpoint.getSoapAddressPrefix()+":address><xsl:attribute name=\"location\"><xsl:value-of select=\"$" + actualAddressParam + "\"/>"); 1069 writer.write("</xsl:attribute></"+endpoint.getSoapAddressPrefix()+":address></xsl:template>"); 1070 endpointNum++; 1071 } 1072 1073 writer.write("<xsl:template match=\"@*|node()\" mode=\"copy\"><xsl:copy><xsl:apply-templates select=\"@*\" mode=\"copy\"/><xsl:apply-templates mode=\"copy\"/></xsl:copy></xsl:template>\n"); 1074 writer.write("</xsl:transform>\n"); 1075 writer.close(); 1076 byte[] stylesheet = bos.toByteArray(); 1077 1078 if( logger.isLoggable(Level.FINE) ) { 1079 logger.fine(new String (stylesheet)); 1080 } 1081 1082 Source stylesheetSource = 1083 new StreamSource(new ByteArrayInputStream (stylesheet)); 1084 TransformerFactory transformerFactory=TransformerFactory.newInstance(); 1085 Templates templates = transformerFactory.newTemplates(stylesheetSource); 1086 1087 return templates; 1088 } 1089 1090 1096 public Collection getSEIsFromGeneratedService 1097 (Class generatedServiceInterface) throws Exception { 1098 1099 Collection seis = new HashSet (); 1100 1101 Method [] declaredMethods = 1102 generatedServiceInterface.getDeclaredMethods(); 1103 1104 for(int i = 0; i < declaredMethods.length; i++) { 1106 Method next = declaredMethods[i]; 1107 Class returnType = next.getReturnType(); 1108 if( next.getName().startsWith("get") && 1109 (next.getDeclaringClass() != javax.xml.rpc.Service .class) && 1110 java.rmi.Remote .class.isAssignableFrom(returnType) ) { 1111 seis.add(returnType.getName()); 1112 } 1113 } 1114 1115 return seis; 1116 } 1117 1118 1130 public File publishFinalWsdl(URL clientPublishUrl, String finalWsdlUri, 1131 byte[] finalWsdlBytes) 1132 throws Exception 1133 { 1134 File finalWsdlFile = null; 1135 FileOutputStream fos = null; 1136 try { 1137 finalWsdlFile = new File 1138 (clientPublishUrl.getFile(), 1139 finalWsdlUri.replace('/', File.separatorChar)); 1140 File parent = finalWsdlFile.getParentFile(); 1141 if( !parent.exists() ) { 1142 boolean madeDirs = parent.mkdirs(); 1143 if( !madeDirs ) { 1144 throw new IOException ("Error creating " + parent); 1145 } 1146 } 1147 fos = new FileOutputStream (finalWsdlFile); 1148 fos.write(finalWsdlBytes, 0, finalWsdlBytes.length); 1149 } finally { 1150 if( fos != null ) { 1151 try { 1152 fos.close(); 1153 } catch(IOException ioe) { 1154 logger.log(Level.INFO, "", ioe); 1155 } 1156 } 1157 } 1158 return finalWsdlFile; 1159 } 1160 1161 1164 public Port getPortFromModel(Model model, QName portName) { 1165 1166 for(Iterator serviceIter = model.getServices(); serviceIter.hasNext();){ 1167 Service next = (Service) serviceIter.next(); 1168 for(Iterator portIter = next.getPorts(); portIter.hasNext();) { 1169 Port nextPort = (Port) portIter.next(); 1170 if( portsEqual(nextPort, portName) ) { 1171 return nextPort; 1172 } 1173 } 1174 } 1175 return null; 1176 } 1177 1178 1182 public Service getServiceForPort(Model model, QName thePortName) { 1183 1184 for(Iterator serviceIter = model.getServices(); 1185 serviceIter.hasNext();) { 1186 Service nextService = (Service) serviceIter.next(); 1187 for(Iterator portIter = nextService.getPorts(); 1188 portIter.hasNext();) { 1189 1190 Port nextPort = (Port) portIter.next(); 1191 if( portsEqual(nextPort, thePortName) ) { 1192 return nextService; 1193 } 1194 } 1195 } 1196 1197 return null; 1198 } 1199 1200 1204 public boolean portsEqual(Port port, QName candidatePortName) { 1205 1206 boolean equal = false; 1207 1208 QName portPropertyName = (QName ) port.getProperty 1212 (ModelProperties.PROPERTY_WSDL_PORT_NAME); 1213 1214 if( portPropertyName != null ) { 1215 equal = candidatePortName.equals(portPropertyName); 1216 } else { 1217 equal = candidatePortName.equals(port.getName()); 1218 } 1219 1220 return equal; 1221 } 1222 1223 public Collection getAllPorts(Model model) { 1225 Collection ports = new HashSet (); 1226 for(Iterator serviceIter = model.getServices(); 1227 serviceIter.hasNext();) { 1228 Service next = (Service) serviceIter.next(); 1229 ports.addAll(next.getPortsList()); 1230 } 1231 return ports; 1232 } 1233 1234 1238 public Method getInvMethod(Tie webServiceTie, MessageContext context) 1239 throws Exception { 1240 1241 1243 SOAPMessageContext soapMsgContext = (SOAPMessageContext ) context; 1244 SOAPMessage message = soapMsgContext.getMessage(); 1245 StreamingHandler streamingHandler = (StreamingHandler) webServiceTie; 1246 int opcode = streamingHandler.getOpcodeForRequestMessage(message); 1247 return streamingHandler.getMethodForOpcode(opcode); 1248 } 1249 1250 1253 public void throwSOAPFaultException(String faultString, com.sun.xml.ws.spi.runtime.MessageContext msgContext) { 1254 1255 SOAPMessage soapMessage = 1256 ((com.sun.xml.ws.spi.runtime.SOAPMessageContext)msgContext).getMessage(); 1257 throwSOAPFaultException(faultString, soapMessage); 1258 1259 } 1260 1261 public void throwSOAPFaultException(String faultString, MessageContext msgContext) { 1262 1263 SOAPMessage soapMessage = 1264 ((SOAPMessageContext )msgContext).getMessage(); 1265 throwSOAPFaultException(faultString, soapMessage); 1266 1267 } 1268 1269 public void throwSOAPFaultException(String faultString, 1270 SOAPMessage soapMessage) 1271 throws SOAPFaultException { 1272 1273 SOAPFaultException sfe = null; 1274 1275 try { 1276 1277 SOAPPart sp = soapMessage.getSOAPPart(); 1278 SOAPEnvelope se = sp.getEnvelope(); 1279 1280 SOAPBody sb = se.getBody(); 1282 1283 Iterator iter = sb.getChildElements(); 1285 1286 if (iter.hasNext()) { 1289 SOAPBodyElement requestBody = (SOAPBodyElement )iter.next(); 1290 requestBody.detachNode(); 1292 } 1293 1294 1295 SOAPFault soapFault = sb.addFault(); 1296 1297 se.setEncodingStyle(SOAPConstants.URI_ENCODING); 1298 1299 String faultActor = "http://schemas.xmlsoap.org/soap/actor/next"; 1300 QName faultCode = SOAPConstants.FAULT_CODE_SERVER; 1301 1302 soapFault.setFaultCode("env:" + faultCode.getLocalPart()); 1303 soapFault.setFaultString(faultString); 1304 soapFault.setFaultActor(faultActor); 1305 1306 sfe = new SOAPFaultException (faultCode, faultActor, faultString, 1307 null); 1308 } catch(SOAPException se) { 1309 logger.log(Level.FINE, "", se); 1310 } 1311 1312 if( sfe != null ) { 1313 throw sfe; 1314 } 1315 } 1316 1317 1318 void writeReply(HttpServletResponse response, 1319 com.sun.xml.rpc.spi.runtime.SOAPMessageContext messageContext) 1320 throws IOException , SOAPException 1321 { 1322 1323 if (isMessageContextPropertySet(messageContext, ONE_WAY_OPERATION)) { 1325 return; 1326 } 1327 1328 SOAPMessage reply = messageContext.getMessage(); 1329 int statusCode = 0; 1330 if (messageContext.isFailure()) { 1331 1332 if (isMessageContextPropertySet(messageContext, 1333 CLIENT_BAD_REQUEST)) { 1334 response.setStatus(HttpServletResponse.SC_BAD_REQUEST); 1335 setContentTypeAndFlush(response); 1336 return; 1337 1338 } else { 1339 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); 1340 } 1341 1342 } else { 1343 response.setStatus(HttpServletResponse.SC_OK); 1344 } 1345 1346 OutputStream os = response.getOutputStream(); 1347 String [] headers = reply.getMimeHeaders().getHeader("Content-Type"); 1348 if (headers != null && headers.length > 0) { 1349 response.setContentType(headers[0]); 1350 } else { 1351 response.setContentType("text/xml"); 1352 } 1353 1354 putHeaders(reply.getMimeHeaders(), response); 1355 1356 reply.writeTo(os); 1357 os.flush(); 1358 1359 } 1360 1361 private static void putHeaders(MimeHeaders headers, 1362 HttpServletResponse response) { 1363 headers.removeHeader("Content-Type"); 1364 headers.removeHeader("Content-Length"); 1365 Iterator it = headers.getAllHeaders(); 1366 while (it.hasNext()) { 1367 MimeHeader header = (MimeHeader )it.next(); 1368 response.setHeader(header.getName(), header.getValue()); 1369 } 1370 } 1371 1372 public static void raiseException(HttpServletResponse resp, String binding, String faultString) { 1373 1374 resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); 1375 1376 if (HTTPBinding.HTTP_BINDING.equals(binding)) { 1377 resp.setContentType("text/xml"); 1378 try { 1379 PrintWriter writer = new PrintWriter (resp.getOutputStream()); 1380 writer.println("<error>" + faultString + "</error>"); 1381 } catch(IOException ioe) { 1382 logger.log(Level.WARNING, "Cannot write out a HTTP XML exception : " + ioe.getMessage()); 1383 } 1384 } else { 1385 String protocol; 1386 if (SOAPBinding.SOAP12HTTP_BINDING.equals(binding)) { 1387 protocol = javax.xml.soap.SOAPConstants.SOAP_1_2_PROTOCOL; 1388 } else { 1389 protocol = javax.xml.soap.SOAPConstants.SOAP_1_1_PROTOCOL; 1390 } 1391 SOAPMessage fault = WsUtil.getSOAPFault(protocol, faultString); 1392 1393 if (fault!=null) { 1394 resp.setContentType("text/xml"); 1395 try { 1396 fault.writeTo(resp.getOutputStream()); 1397 } catch(Exception ex) { 1398 logger.log(Level.WARNING, "cannot write SOAPFault to the HTTP response", ex); 1399 } 1400 } 1401 } 1402 } 1403 1404 public static SOAPMessage getSOAPFault(String protocol, String faultString) { 1405 1406 if (protocol==null) { 1407 protocol = javax.xml.soap.SOAPConstants.SOAP_1_1_PROTOCOL; 1408 } 1409 try { 1410 MessageFactory factory = MessageFactory.newInstance(protocol); 1411 if (factory==null) { 1412 factory = MessageFactory.newInstance(); 1413 } 1414 SOAPMessage message = factory.createMessage(); 1415 SOAPBody body = message.getSOAPBody(); 1416 SOAPFault fault = body.addFault(); 1417 fault.setFaultString(faultString); 1418 SOAPEnvelope envelope = message.getSOAPPart().getEnvelope(); 1419 String envelopeNamespace = envelope.getNamespaceURI(); 1420 QName faultCode = new QName (envelopeNamespace, "Server", "env"); 1421 fault.setFaultCode(faultCode); 1422 return message; 1423 } catch(SOAPException e) { 1424 logger.log(Level.WARNING, "Cannot create soap fault for " + faultString); 1425 } 1426 return null; 1427 } 1428 1429 void writeInvalidContentType(HttpServletResponse response) 1430 throws SOAPException , IOException { 1431 response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); 1433 1434 setContentTypeAndFlush(response); 1435 } 1436 1437 void writeInvalidMethodType(HttpServletResponse response, 1438 String message) throws IOException { 1439 response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); 1440 response.setContentType("text/html"); 1441 PrintWriter out = response.getWriter(); 1442 out.println("<html>"); 1443 out.println("<head><title>"); 1444 1445 out.println("Invalid Method Type"); 1446 out.println("</title></head>"); 1447 out.println("<body>"); 1448 out.println(message); 1449 out.println("</body>"); 1450 out.println("</html>"); 1451 1452 } 1453 1454 private void writeNotFoundErrorPage(HttpServletResponse response, 1455 String message) throws IOException { 1456 1457 response.setStatus(HttpServletResponse.SC_NOT_FOUND); 1458 response.setContentType("text/html"); 1459 PrintWriter out = response.getWriter(); 1460 out.println("<html>"); 1461 out.println("<head><title>"); 1462 out.println("J2EE Web Services"); 1463 out.println("</title></head>"); 1464 out.println("<body>"); 1465 out.println("<h1>404 Not Found: " + message + "</h1>"); 1466 out.println("</body>"); 1467 out.println("</html>"); 1468 1469 } 1470 1471 1474 private void setContentTypeAndFlush(HttpServletResponse response) 1475 throws IOException { 1476 response.setContentType("text/xml"); 1477 response.flushBuffer(); response.getWriter().close(); 1479 } 1480 1481 boolean hasSomeTextXmlContent(MimeHeaders headers) { 1482 return ( hasTextXmlContentType(headers) && 1483 (getContentLength(headers) > 0) ); 1484 } 1485 1486 private int getContentLength(MimeHeaders headers) { 1487 String [] contentLength = headers.getHeader("Content-Length"); 1488 1489 int length = 0; 1490 1491 if ((contentLength != null) && (contentLength.length > 0)) { 1492 length = new Integer (contentLength[0]).intValue(); 1493 } 1494 1495 return length; 1496 } 1497 1498 boolean hasTextXmlContentType(MimeHeaders headers) { 1499 1500 String [] contentTypes = headers.getHeader("Content-Type"); 1501 if ((contentTypes != null) && (contentTypes.length >= 1)){ 1502 if (contentTypes[0].indexOf("text/xml") != -1){ 1503 return true; 1504 } 1505 } 1506 return false; 1507 } 1508 1509 boolean isMessageContextPropertySet 1510 (com.sun.xml.rpc.spi.runtime.SOAPMessageContext messageContext, 1511 String property){ 1512 1513 Object prop = messageContext.getProperty(property); 1514 if (prop != null) { 1515 if ( (prop instanceof String ) && 1516 ((String )prop).equalsIgnoreCase("true") ) { 1517 return true; 1518 } 1519 } 1520 1521 return false; 1522 } 1523 1524 MimeHeaders getHeaders(HttpServletRequest request) { 1525 Enumeration e = request.getHeaderNames(); 1526 MimeHeaders headers = new MimeHeaders (); 1527 1528 while (e.hasMoreElements()) { 1529 String headerName = (String )e.nextElement(); 1530 String headerValue = request.getHeader(headerName); 1531 headers.addHeader(headerName, headerValue); 1532 } 1533 1534 return headers; 1535 } 1536 1537 1540 public WebServerInfo getWebServerInfo(DeploymentRequest request) throws ConfigException { 1541 1542 1547 1548 String serverTarget = (String ) request.getOptionalArguments().get(DeploymentProperties.WSDL_TARGET_HINT); 1549 if(serverTarget == null) { 1550 return(getWebServerInfoForDAS(request)); 1551 } 1552 ConfigContext cc = AdminService.getAdminService().getAdminContext().getAdminConfigContext(); 1553 if(cc==null) { 1554 return(getWebServerInfoForDAS(request)); 1555 } 1556 Config config = ServerHelper.getConfigForServer(cc, serverTarget); 1557 JMXConnectorConfig info = ServerHelper.getJMXConnectorInfo(cc, serverTarget); 1558 if((config==null) || (info==null) ) { 1559 return(getWebServerInfoForDAS(request)); 1560 } 1561 String host = info.getHost(); 1562 return(getWebServerInfo(cc, config, null, serverTarget, host)); 1563 } 1564 1565 private WebServerInfo getWebServerInfoForDAS(DeploymentRequest request) { 1566 WebServerInfo wsi = new WebServerInfo(); 1567 wsi.setHttpVS(new VirtualServerInfo("http", request.getHttpHostName(), request.getHttpPort())); 1568 wsi.setHttpsVS(new VirtualServerInfo("https", request.getHttpsHostName(), request.getHttpsPort())); 1569 return wsi; 1570 } 1571 1572 1575 public WebServerInfo getWebServerInfo(String moduleID, HttpServletRequest request) throws ConfigException { 1576 1577 1578 ConfigContext cc = ApplicationServer.getServerContext().getConfigContext(); 1580 Server server = ServerBeansFactory.getServerBean(cc); 1581 Config config = ServerBeansFactory.getConfigBean(cc); 1582 ApplicationRef ref = server.getApplicationRefByRef(moduleID); 1583 return(getWebServerInfo(cc, config, ref.getVirtualServers(), null, null)); 1584 } 1585 1586 private WebServerInfo getWebServerInfo(ConfigContext cc, Config config, 1587 String virtualServers, String targetName, String targetHostName) throws ConfigException { 1588 HttpService httpService = config.getHttpService(); 1589 VirtualServer[] vServers = null; 1590 List httpListeners = new ArrayList (); 1591 if (virtualServers==null) { 1592 vServers = httpService.getVirtualServer(); 1593 if (vServers!=null) { 1594 for (int i=0;i<vServers.length;i++) { 1595 VirtualServer vs = vServers[i]; 1596 if (vs.getId().equals("__asadmin")) 1598 continue; 1599 1600 String httpListenersString = vs.getHttpListeners(); 1601 if (httpListenersString!=null) { 1602 String [] httpListenerIDs = httpListenersString.split(","); 1603 if (httpListenerIDs!=null) { 1604 for (int j=0;j<httpListenerIDs.length;j++) { 1605 httpListeners.add(httpService.getHttpListenerById(httpListenerIDs[j])); 1606 } 1607 } 1608 } 1609 } 1610 } 1611 } else { 1612 String virtualServerNames[] = virtualServers.split(","); 1613 if (virtualServerNames!=null) { 1614 for (int i=0;i<virtualServerNames.length;i++) { 1615 VirtualServer vs = httpService.getVirtualServerById(virtualServerNames[i]); 1616 String httpListenersString = vs.getHttpListeners(); 1617 if (httpListenersString!=null) { 1618 String [] httpListenerIDs = httpListenersString.split(","); 1619 if (httpListenerIDs!=null) { 1620 for (int j=0;j<httpListenerIDs.length;j++) { 1621 httpListeners.add(httpService.getHttpListenerById(httpListenerIDs[i])); 1622 } 1623 } 1624 } 1625 } 1626 } 1627 } 1628 1629 WebServerInfo wsi = new WebServerInfo(); 1630 for (int i=0;i<httpListeners.size();i++) { 1631 HttpListener hl = (HttpListener) httpListeners.get(i); 1632 if (!hl.isEnabled()) 1633 continue; 1634 1635 if(targetHostName == null) { 1636 targetHostName = hl.getServerName(); 1637 if (targetHostName==null || targetHostName.length()==0) { 1638 targetHostName = getDefaultHostName(); 1639 } 1640 } 1641 try { 1642 targetHostName = InetAddress.getByName(targetHostName).getCanonicalHostName(); 1643 } catch (java.net.UnknownHostException unex) { 1644 throw new ConfigException(unex.getMessage(), unex); 1645 } 1646 String redirectPortNb = hl.getRedirectPort(); 1647 String portNb; 1648 if (redirectPortNb!=null) { 1649 portNb = redirectPortNb; 1650 } else { 1651 portNb = hl.getPort(); 1652 } 1653 if(targetName == null) { 1654 targetName = ApplicationServer.getServerContext().getInstanceName(); 1655 } 1656 PropertyResolver pr = new PropertyResolver(cc, targetName); 1657 String resolvedPort = pr.resolve(portNb); 1658 1659 int port = Integer.parseInt(resolvedPort); 1660 if (hl.isSecurityEnabled()) { 1661 wsi.setHttpsVS(new VirtualServerInfo("https", targetHostName, port)); 1662 } else { 1663 wsi.setHttpVS(new VirtualServerInfo("http", targetHostName, port)); 1664 } 1665 1666 if (wsi.getHttpVS()!=null && wsi.getHttpsVS()!=null) 1667 break; 1668 } 1669 return wsi; 1670 } 1671 1672 private String getDefaultHostName() { 1673 String defaultHostName = "localhost"; 1674 try { 1675 InetAddress host = InetAddress.getLocalHost(); 1676 defaultHostName = host.getCanonicalHostName(); 1677 } catch(java.net.UnknownHostException uhe) { 1678 deploymentLogger.log(Level.FINEST, "mbean.get_local_host_error", uhe); 1679 deploymentLogger.log(Level.INFO, "mbean.use_default_host"); 1680 } 1681 return defaultHostName; 1682 } 1683 1684 private static Logger _logger = null; 1685 1686 1689 public static Logger getDefaultLogger() { 1690 return logger; 1691 } 1692 1693 static LocalStringManagerImpl localStrings = 1695 new LocalStringManagerImpl(WsUtil.class); 1696 1697 public static LocalStringManagerImpl getDefaultStringManager() { 1698 return localStrings; 1699 } 1700 1701 public void validateEjbEndpoint(WebServiceEndpoint ejbEndpoint) { 1702 EjbDescriptor ejbDescriptor = ejbEndpoint.getEjbComponentImpl(); 1703 EjbBundleDescriptor bundle = ejbDescriptor.getEjbBundleDescriptor(); 1704 WebServicesDescriptor webServices = bundle.getWebServices(); 1705 Collection endpoints = 1706 webServices.getEndpointsImplementedBy(ejbDescriptor); 1707 if( endpoints.size() == 1 ) { 1708 if( ejbDescriptor.hasWebServiceEndpointInterface() ) { 1709 if(!ejbEndpoint.getServiceEndpointInterface().equals 1710 (ejbDescriptor.getWebServiceEndpointInterfaceName())) { 1711 String msg = "Ejb " + ejbDescriptor.getName() + 1712 " service endpoint interface does not match " + 1713 " port component " + ejbEndpoint.getEndpointName(); 1714 throw new IllegalStateException (msg); 1715 } 1716 } else { 1717 String msg = "Ejb " + ejbDescriptor.getName() + 1718 " must declare <service-endpoint> interface"; 1719 throw new IllegalStateException (msg); 1720 } 1721 } else if( endpoints.size() > 1 ) { 1722 String msg = "Ejb " + ejbDescriptor.getName() + 1723 " implements " + endpoints.size() + " web service endpoints " + 1724 " but must only implement 1"; 1725 throw new IllegalStateException (msg); 1726 } 1727 } 1728 1729 public void updateServletEndpointRuntime(WebServiceEndpoint endpoint) { 1730 1731 endpoint.saveServletImplClass(); 1736 1737 WebComponentDescriptor webComp = 1738 (WebComponentDescriptor) endpoint.getWebComponentImpl(); 1739 1740 WebBundleDescriptor bundle = webComp.getWebBundleDescriptor(); 1741 WebServicesDescriptor webServices = bundle.getWebServices(); 1742 Collection endpoints = 1743 webServices.getEndpointsImplementedBy(webComp); 1744 1745 if( endpoints.size() > 1 ) { 1746 String msg = "Servlet " + endpoint.getWebComponentLink() + 1747 " implements " + endpoints.size() + " web service endpoints " + 1748 " but must only implement 1"; 1749 throw new IllegalStateException (msg); 1750 } 1751 1752 if( endpoint.getEndpointAddressUri() == null ) { 1753 Set urlPatterns = webComp.getUrlPatternsSet(); 1754 if( urlPatterns.size() == 1 ) { 1755 1756 String uri = (String ) urlPatterns.iterator().next(); 1759 endpoint.setEndpointAddressUri(uri); 1760 1761 Collection constraints = 1765 bundle.getSecurityConstraintsForUrlPattern(uri); 1766 for(Iterator i = constraints.iterator(); i.hasNext();) { 1767 SecurityConstraint next = (SecurityConstraint) i.next(); 1768 1769 UserDataConstraint dataConstraint = 1770 next.getUserDataConstraint(); 1771 String guarantee = (dataConstraint != null) ? 1772 dataConstraint.getTransportGuarantee() : null; 1773 1774 if( (guarantee != null) && 1775 ( guarantee.equals 1776 (UserDataConstraint.INTEGRAL_TRANSPORT) || 1777 guarantee.equals 1778 (UserDataConstraint.CONFIDENTIAL_TRANSPORT) ) ) { 1779 endpoint.setTransportGuarantee(guarantee); 1780 break; 1781 } 1782 } 1783 } else { 1784 String msg = "Endpoint " + endpoint.getEndpointName() + 1785 " has not been assigned an endpoint address " + 1786 " and is associated with servlet " + 1787 webComp.getCanonicalName() + " , which has " + 1788 urlPatterns.size() + " url patterns"; 1789 throw new IllegalStateException (msg); 1790 } 1791 } 1792 } 1793 1794 private boolean runWsGen(String implClass, boolean skipGenWsdl, String classPath, File stubsDir, 1795 File wsdlDir, QName sQname, QName port) { 1796 int numArgs; 1797 if(skipGenWsdl) { 1798 numArgs = 6; 1799 } else { 1800 numArgs = 13; 1801 } 1802 String [] wsgenArgs = new String [numArgs]; 1803 int argIndex= 0 ; 1804 wsgenArgs[argIndex++] = "-cp"; 1805 wsgenArgs[argIndex++] = classPath; 1806 wsgenArgs[argIndex++] = "-keep"; 1807 if(!skipGenWsdl) { 1808 wsgenArgs[argIndex++] = "-wsdl"; 1809 wsgenArgs[argIndex++] = "-r"; 1810 wsgenArgs[argIndex++] = wsdlDir.getAbsolutePath(); 1811 wsgenArgs[argIndex++] = "-servicename"; 1812 wsgenArgs[argIndex++] = sQname.toString(); 1813 wsgenArgs[argIndex++] = "-portname"; 1814 wsgenArgs[argIndex++] = port.toString(); 1815 } 1816 wsgenArgs[argIndex++] = "-d"; 1817 wsgenArgs[argIndex++] = stubsDir.getAbsolutePath(); 1818 wsgenArgs[argIndex++] = implClass; 1819 WSToolsObjectFactory wsTools = WSToolsObjectFactory.newInstance(); 1820 return(wsTools.wsgen(System.out, wsgenArgs)); 1821 } 1822 1823 private void downloadFile(URL httpUrl, File toFile) throws Exception { 1824 InputStream is = null; 1825 FileOutputStream os = null; 1826 try { 1827 if(!toFile.createNewFile()) { 1828 throw new Exception ("Unable to create new File " + toFile.getAbsolutePath()); 1829 } 1830 is = httpUrl.openStream(); 1831 os = new FileOutputStream (toFile); 1832 int readCount; 1833 int offset = 0; 1834 byte[] buffer = new byte[10240]; do { 1836 readCount = is.read(buffer, 0, 10240); 1837 os.write(buffer, offset, readCount); 1838 offset+=readCount; 1839 } while(readCount == 10240); 1840 } finally { 1841 if(is != null) { 1842 is.close(); 1843 } 1844 if(os != null) { 1845 os.flush(); 1846 os.close(); 1847 } 1848 } 1849 } 1850 1851 private void downloadWsdlsAndSchemas(WebService ws, URL httpUrl, File wsdlDir) throws Exception { 1852 wsdlDir.mkdirs(); 1854 String fileName = httpUrl.toString().substring(httpUrl.toString().lastIndexOf("/")+1); 1855 File toFile = new File (wsdlDir.getAbsolutePath()+File.separator+fileName); 1856 downloadFile(httpUrl, toFile); 1857 1858 Collection <Import> wsdlRelativeImports = new HashSet (); 1860 Collection <Import> schemaRelativeImports = new HashSet (); 1861 Collection <Import> wsdlIncludes = new HashSet (); 1862 Collection <Import> schemaIncludes = new HashSet (); 1863 parseRelativeImports(httpUrl, wsdlRelativeImports, wsdlIncludes, 1864 schemaRelativeImports, schemaIncludes); 1865 wsdlRelativeImports.addAll(wsdlIncludes); 1866 schemaRelativeImports.addAll(schemaIncludes); 1867 1868 String urlWithoutFileName = httpUrl.toString().substring(0, httpUrl.toString().lastIndexOf("/")); 1870 for(Import next : schemaRelativeImports) { 1871 String location = next.getLocation(); 1872 location.replaceAll("/", "\\"+File.separator); 1873 if(location.lastIndexOf(File.separator) != -1) { 1874 File newDir = new File (wsdlDir.getAbsolutePath()+File.separator+ 1875 location.substring(0, location.lastIndexOf(File.separator))); 1876 newDir.mkdirs(); 1877 } 1878 downloadFile(new URL (urlWithoutFileName+"/"+next.getLocation()), 1879 new File (wsdlDir.getAbsolutePath()+File.separator+location)); 1880 } 1881 1882 for(Import next : wsdlRelativeImports) { 1884 String newWsdlLocation = next.getLocation(); 1885 newWsdlLocation.replaceAll("/", "\\"+File.separator); 1886 File newWsdlDir; 1887 if(newWsdlLocation.lastIndexOf(File.separator) != -1) { 1888 newWsdlDir = new File (wsdlDir.getAbsolutePath() + File.separator + 1889 newWsdlLocation.substring(0, newWsdlLocation.lastIndexOf(File.separator))); 1890 } else { 1891 newWsdlDir = wsdlDir; 1892 } 1893 downloadWsdlsAndSchemas(ws, new URL (urlWithoutFileName+"/"+next.getLocation()), newWsdlDir); 1894 } 1895 return; 1896 } 1897 1898 private String addJarsToClassPath(String cp, String dirName) throws IASDeploymentException { 1899 try { 1900 File dir = new File (dirName); 1901 if(dir.exists()) { 1902 Iterator fileSetIter = com.sun.enterprise.util.FileUtil.getAllFilesUnder(dir, null, false).iterator(); 1903 while(fileSetIter.hasNext()) { 1904 cp+=(File.pathSeparator+((File )fileSetIter.next()).getAbsolutePath()); 1905 } 1906 } 1907 } catch (IOException ioex) { 1908 throw new IASDeploymentException("IOException : " + ioex.getMessage() + 1909 " when trying to get list of files under " + dirName); 1910 } 1911 return cp; 1912 } 1913 1914 private String getWsgenClassPath(File classesDir, String webinfLibDir, 1915 String appLibDirPath, String moduleDir) throws IASDeploymentException { 1916 String classpath = classesDir.getAbsolutePath(); 1918 1919 if(webinfLibDir != null) { 1921 classpath = addJarsToClassPath(classpath, webinfLibDir); 1922 } 1923 1924 if(appLibDirPath != null) { 1926 classpath = addJarsToClassPath(classpath, appLibDirPath); 1927 } 1928 1929 FileInputStream is = null; 1931 try { 1932 File mfFile = new File (moduleDir+File.separator+"META-INF"+ 1933 File.separator+"MANIFEST.MF"); 1934 if(mfFile.exists()) { 1935 is = new FileInputStream (mfFile); 1936 Manifest ms = new Manifest (is); 1937 Attributes attrMap = ms.getMainAttributes(); 1938 String mfCp = attrMap.getValue(Attributes.Name.CLASS_PATH); 1939 if(mfCp != null && mfCp.length() != 0) { 1940 StringTokenizer strTok = new StringTokenizer (mfCp, " \t"); 1941 while(strTok.hasMoreTokens()) { 1942 String givenCP = strTok.nextToken(); 1943 if(!givenCP.startsWith(File.separator)) { 1945 givenCP = moduleDir+File.separator+givenCP; 1946 } 1947 classpath+=(File.pathSeparator+givenCP); 1948 } 1949 } 1950 } 1951 } catch (Exception e) { 1952 throw new IASDeploymentException("Exception : " + e.getMessage() + 1953 " when trying to process MANIFEST file under " + moduleDir); 1954 } finally { 1955 if(is != null) { 1956 try { 1957 is.close(); 1958 } catch(IOException t) {} 1959 } 1960 } 1961 return classpath; 1962 } 1963 1964 1968 public void genWSInfo(Application app, DeploymentRequest request) throws IASDeploymentException { 1969 1970 Set <BundleDescriptor> bundles = (Set <BundleDescriptor>) app.getBundleDescriptors(); 1971 for(BundleDescriptor bundle : bundles) { 1972 WebServicesDescriptor wsDesc = bundle.getWebServices(); 1973 for (WebService ws : wsDesc.getWebServices()) { 1974 1975 File moduleDir = request.getDeployedDirectory(); 1979 File wsdlDir = request.getGeneratedXMLDirectory(); 1980 File stubsDir = request.getStubsDirectory(); 1981 1982 if(request.isApplication()) { 1983 String subDirName = bundle.getModuleDescriptor().getArchiveUri(); 1984 moduleDir = new File (moduleDir, subDirName.replaceAll("\\.", "_")); 1985 wsdlDir = new File (wsdlDir, subDirName.replaceAll("\\.", "_")); 1986 } 1987 File classesDir; 1988 String webinfLibDir = null; 1989 if (ModuleType.WAR.equals(bundle.getModuleType())) { 1990 classesDir = new File (moduleDir, "WEB-INF"+File.separator+"classes"); 1991 webinfLibDir = moduleDir.getAbsolutePath() + File.separator + "WEB-INF"+File.separator+"lib"; 1992 } else if (ModuleType.EJB.equals(bundle.getModuleType())) { 1993 classesDir = moduleDir; 1994 } else { 1995 continue; 1997 } 1998 wsdlDir = new File (wsdlDir, bundle.getWsdlDir().replaceAll("/", "\\"+File.separator)); 1999 2000 String wsdlFileUri; 2002 File wsdlFile; 2003 checkCatalog(bundle, ws, moduleDir); 2004 if (ws.hasWsdlFile()) { 2005 if (ws.getWsdlFileUri().startsWith("http")) { 2007 try { 2008 downloadWsdlsAndSchemas(ws, new URL (ws.getWsdlFileUri()), wsdlDir); 2009 } catch(Exception e) { 2010 throw new IASDeploymentException(e.toString(), e); 2011 } 2012 wsdlFileUri = ws.getWsdlFileUri().substring(ws.getWsdlFileUri().lastIndexOf("/")+1); 2013 wsdlFile = new File (wsdlDir, wsdlFileUri); 2014 2015 ws.setWsdlFileUri(null); 2019 2020 } else { 2021 wsdlFileUri = ws.getWsdlFileUri(); 2022 if(wsdlFileUri.startsWith("/")) { 2023 wsdlFile = new File (wsdlFileUri); 2024 } else { 2025 wsdlFile = new File (moduleDir, wsdlFileUri); 2026 } 2027 if (!wsdlFile.exists()) { 2028 throw new IASDeploymentException("WebService " + ws.getName() + " wsdl file " 2029 + ws.getWsdlFileUri() + " not found in archive " 2030 + bundle.getModuleDescriptor().getArchiveUri()); 2031 } 2032 } 2033 2034 } else { 2035 wsdlFileUri = JAXBRIContext.mangleNameToClassName(ws.getName()) + ".wsdl"; 2037 wsdlDir.mkdirs(); 2038 wsdlFile = new File (wsdlDir, wsdlFileUri); 2039 } 2040 2041 2042 for (WebServiceEndpoint endpoint : ws.getEndpoints()) { 2043 2044 String implClassName; 2045 boolean jaxwsEndPtFound = false; 2046 boolean jaxrpcEndPtFound = false; 2047 if (endpoint.implementedByEjbComponent()) { 2048 implClassName = endpoint.getEjbComponentImpl().getEjbClassName(); 2049 } else { 2050 implClassName = endpoint.getWebComponentImpl().getWebComponentImplementation(); 2051 } 2052 2053 Class implClass; 2055 try { 2056 implClass = app.getClassLoader().loadClass(implClassName); 2057 } catch(Exception e) { 2058 throw new IASDeploymentException("WebService " + ws.getName() + "implementation " 2059 + implClassName + " not found in archive " 2060 + bundle.getModuleDescriptor().getArchiveUri()); 2061 } 2062 2063 if (implClass!=null) { 2064 if(implClass.getAnnotation(javax.xml.ws.WebServiceProvider.class) != null) { 2065 if(jaxrpcEndPtFound) { 2068 throw new IASDeploymentException("WebService " + ws.getName() + 2069 "has a JAXWS and a JAXRPC endpoint; this is not supported now"); 2070 } 2071 jaxwsEndPtFound = true; 2074 continue; 2075 } 2076 if(implClass.getAnnotation(javax.jws.WebService.class) != null) { 2077 2078 if(jaxrpcEndPtFound) { 2081 throw new IASDeploymentException("WebService " + ws.getName() + 2082 "has a JAXWS and a JAXRPC endpoint; this is not supported now"); 2083 } 2084 jaxwsEndPtFound = true; 2086 String wsgenClassPath = getWsgenClassPath(classesDir, webinfLibDir, 2087 request.getDeployedDirectory().getAbsolutePath()+File.separator+app.getLibraryDirectory(), 2088 moduleDir.getAbsolutePath()); 2089 boolean wsgenDone = 2090 runWsGen(implClassName, wsdlFile.exists(), wsgenClassPath, 2091 stubsDir, wsdlDir, endpoint.getServiceName(), endpoint.getWsdlPort()); 2092 if(!wsgenDone) { 2093 throw new IASDeploymentException("WSGEN FAILED"); 2094 } 2095 try { 2096 endpoint.getWebService().setWsdlFileUrl(wsdlFile.toURI().toURL()); 2097 } catch(java.net.MalformedURLException mue) { 2098 throw new IASDeploymentException("WSGEN Failed"); 2099 } 2100 logger.log(Level.INFO, "wsgen successful"); 2101 } else { 2102 if(jaxwsEndPtFound) { 2106 throw new IASDeploymentException("WebService " + ws.getName() + 2107 "has a JAXWS and a JAXRPC endpoint; this is not supported now"); 2108 } 2109 jaxrpcEndPtFound = true; 2113 ws.getWebServicesDescriptor().setSpecVersion("1.1"); 2114 } 2115 } 2116 } 2117 } 2118 } 2119 } 2120 2121 public URL resolveCatalog(File catalogFile, String wsdlFile, WebService ws) throws IASDeploymentException { 2122 try { 2123 URL retVal = null; 2124 org.xml.sax.EntityResolver resolver = 2126 WSRtObjectFactory.newInstance().createEntityResolver(catalogFile.toURL()); 2127 org.xml.sax.InputSource source = resolver.resolveEntity(null, wsdlFile); 2128 if(source != null) { 2129 String mappedEntry = source.getSystemId(); 2130 if(mappedEntry.startsWith("file:")) { 2133 File f = new File (mappedEntry.substring(mappedEntry.indexOf(":")+1)); 2134 if(!f.exists()) { 2135 throw new IASDeploymentException("File " + mappedEntry + " not found"); 2136 } 2137 retVal = f.toURI().toURL(); 2138 if(ws != null) { 2139 ws.setWsdlFileUri(f.getAbsolutePath()); 2140 ws.setWsdlFileUrl(retVal); 2141 } 2142 } else if(mappedEntry.startsWith("http")) { 2143 retVal = new URL (mappedEntry); 2144 if(ws != null) { 2145 ws.setWsdlFileUrl(retVal); 2146 } 2147 } 2148 } 2149 return retVal; 2150 } catch (Throwable t) { 2151 throw new IASDeploymentException("Exception while processing catalog " 2152 + catalogFile.getAbsolutePath() + "; Reason " + t.getMessage()); 2153 } 2154 } 2155 2156 private void checkCatalog(BundleDescriptor bundle, WebService ws, File moduleDir) 2159 throws IASDeploymentException { 2160 File catalogFile = new File (moduleDir, 2162 bundle.getDeploymentDescriptorDir() + 2163 File.separator + "jax-ws-catalog.xml"); 2164 if(!catalogFile.exists()) { 2165 return; 2166 } 2167 resolveCatalog(catalogFile, ws.getWsdlFileUri(), ws); 2168 } 2169 2170 public static Class generateAndLoad(ClassGeneratorFactory cgf, 2171 ClassLoader loader) { 2172 2173 cgf.evaluate(); 2174 2175 Properties props = new Properties(); 2176 if( logger.isLoggable(Level.FINE) ) { 2177 2178 props.put(Wrapper.DUMP_AFTER_SETUP_VISITOR, "true"); 2179 props.put(Wrapper.TRACE_BYTE_CODE_GENERATION, "true"); 2180 props.put(Wrapper.USE_ASM_VERIFIER, "true"); 2181 2182 try { 2183 2184 ByteArrayOutputStream baos = new ByteArrayOutputStream (); 2185 PrintStream ps = new PrintStream (baos); 2186 2187 Wrapper._sourceCode(ps, props); 2188 logger.log(Level.FINE,baos.toString()); 2189 2190 } catch(Exception e) { 2191 logger.log(Level.FINE, "exception generating src", e); 2192 } 2193 2194 } 2195 2196 return Wrapper._generate(loader, null, props); 2197 2198 } 2199 2200 2203 public void doPostConstruct(Class impl, Object implObj) { 2204 invokeServiceMethod(javax.annotation.PostConstruct.class, impl, 2205 implObj); 2206 } 2207 2208 2211 public void doPreDestroy(WebServiceEndpoint ep, ClassLoader loader) { 2212 try { 2214 Class impl = Class.forName(ep.getServletImplClass(), 2215 true, loader); 2216 invokeServiceMethod(javax.annotation.PreDestroy.class, impl, 2217 impl.newInstance()); 2218 } catch (Throwable ex) { 2219 logger.log(Level.SEVERE, "Class " + ep.getServletImplClass() + 2220 "not found during PreDestroy processing", ex); 2221 } 2222 2223 if(!ep.hasHandlerChain()) { 2225 return; 2226 } 2227 for(Iterator <WebServiceHandlerChain> hc = ep.getHandlerChain().iterator(); 2228 hc.hasNext();) { 2229 WebServiceHandlerChain thisHc = hc.next(); 2230 for(Iterator <WebServiceHandler> h = thisHc.getHandlers().iterator(); 2231 h.hasNext();) { 2232 WebServiceHandler thisHandler = h.next(); 2233 try { 2234 Class handlerClass = Class.forName(thisHandler.getHandlerClass(), 2235 true, loader); 2236 invokeServiceMethod(javax.annotation.PreDestroy.class, handlerClass, 2237 handlerClass.newInstance()); 2238 } catch (Throwable ex) { 2239 logger.log(Level.SEVERE, "Handler class " + thisHandler.getHandlerClass() + 2240 "not found during PreDestroy processing", ex); 2241 } 2242 } 2243 } 2244 } 2245 2246 2249 private void invokeServiceMethod(Class annType, Class impl, final Object implObj) { 2250 Method [] methods = impl.getDeclaredMethods(); 2251 for(final Method method : methods) { 2254 if (method.getAnnotation(annType) != null) { 2255 try { 2256 AccessController.doPrivileged(new PrivilegedExceptionAction () { 2257 public Object run() throws IllegalAccessException , 2258 InvocationTargetException { 2259 if (!method.isAccessible()) { 2260 method.setAccessible(true); 2261 } 2262 method.invoke(implObj, new Object []{}); 2263 return null; 2264 } 2265 }); 2266 } catch(Throwable e) { 2267 logger.log(Level.SEVERE, 2269 "Failure while calling PostConstruct/PreDestroy method", e); 2270 } 2271 break; 2272 } 2273 } 2274 } 2275 2276 private boolean matchQNamePatterns(QName cfgQName, QName givenPattern) { 2277 if (givenPattern.getNamespaceURI().equals(cfgQName.getNamespaceURI())) { 2278 String expr = givenPattern.getLocalPart().replaceAll("\\*", ".*"); 2279 return java.util.regex.Pattern.matches(expr, cfgQName.getLocalPart()); 2280 } 2281 return false; 2282 } 2283 2284 private boolean patternsMatch(WebServiceHandlerChain hc, QName svcName, 2285 QName portName, String bindingId) { 2286 if(hc.getServiceNamePattern() != null && svcName != null) { 2289 QName svcPattern = QName.valueOf(hc.getServiceNamePattern()); 2290 if(!matchQNamePatterns(svcName, svcPattern)) { 2291 return false; 2292 } 2293 } 2294 2295 if(hc.getPortNamePattern() != null && portName != null) { 2298 QName portPattern = QName.valueOf(hc.getPortNamePattern()); 2299 if(!matchQNamePatterns(portName, portPattern)) { 2300 return false; 2301 } 2302 } 2303 2304 if(hc.getProtocolBindings() != null && bindingId != null) { 2307 String givenBindings = hc.getProtocolBindings(); 2308 if( (bindingId.equals(HTTPBinding.HTTP_BINDING)) && 2309 ((givenBindings.indexOf(HTTPBinding.HTTP_BINDING) != -1) || 2310 (givenBindings.indexOf(XML_TOKEN) != -1))) { 2311 return true; 2312 } 2313 if( (bindingId.equals(SOAPBinding.SOAP11HTTP_BINDING)) && 2314 ((givenBindings.indexOf(SOAPBinding.SOAP11HTTP_BINDING) != -1) || 2315 (givenBindings.indexOf(SOAP11_TOKEN) != -1))) { 2316 return true; 2317 } 2318 if( (bindingId.equals(SOAPBinding.SOAP12HTTP_BINDING)) && 2319 ((givenBindings.indexOf(SOAPBinding.SOAP12HTTP_BINDING) != -1) || 2320 (givenBindings.indexOf(SOAP12_TOKEN) != -1))) { 2321 return true; 2322 } 2323 if( (bindingId.equals(SOAPBinding.SOAP11HTTP_MTOM_BINDING)) && 2324 ((givenBindings.indexOf(SOAPBinding.SOAP11HTTP_MTOM_BINDING) != -1) || 2325 (givenBindings.indexOf(SOAP11_MTOM_TOKEN) != -1))) { 2326 return true; 2327 } 2328 if( (bindingId.equals(SOAPBinding.SOAP12HTTP_MTOM_BINDING)) && 2329 ((givenBindings.indexOf(SOAPBinding.SOAP12HTTP_MTOM_BINDING) != -1) || 2330 (givenBindings.indexOf(SOAP12_MTOM_TOKEN) != -1))) { 2331 return true; 2332 } 2333 } 2334 return true; 2335 } 2336 2337 private List <Handler> processConfiguredHandlers(List <WebServiceHandler> handlersList, Set <String > roles) { 2338 List <Handler> handlerChain = new ArrayList <Handler>(); 2339 for(WebServiceHandler h : handlersList) { 2340 Handler handler = null; 2341 Map <String , Object > params = new HashMap <String , Object >(); 2342 ClassLoader loader = Thread.currentThread().getContextClassLoader(); 2343 Class handlerClass; 2345 try { 2346 handlerClass = Class.forName(h.getHandlerClass(), true, loader); 2347 handler = (Handler)handlerClass.newInstance(); 2348 } catch (Throwable t) { 2349 logger.log(Level.SEVERE, "Unable to load handler class " + 2350 h.getHandlerClass()); 2351 t.printStackTrace(); 2352 continue; 2353 } 2354 2355 try { 2357 new InjectionManagerImpl().injectInstance(handler); 2358 } catch(InjectionException e) { 2359 logger.severe("Handler " + h.getHandlerClass() + 2360 " instance injection failed : " + e.getMessage()); 2361 continue; 2362 } 2363 2364 doPostConstruct(handlerClass, handler); 2366 2367 Collection <String > rolesColl = h.getSoapRoles(); 2369 roles.addAll(rolesColl); 2370 2371 handlerChain.add(handler); 2373 } 2374 return handlerChain; 2375 } 2376 2377 public void configureJAXWSServiceHandlers(WebServiceEndpoint ep, RuntimeEndpointInfo jaxwsInfo) { 2378 if(!ep.hasHandlerChain()) { 2380 return; 2381 } 2382 LinkedList handlerChainList = ep.getHandlerChain(); 2383 List <Handler> finalHandlerList = new ArrayList <Handler>(); 2384 Set <String > roles = new HashSet (); 2385 String bindingId = 2386 ((com.sun.xml.ws.binding.BindingImpl)jaxwsInfo.getBinding()).getBindingId(); 2387 for(Iterator <WebServiceHandlerChain> i = handlerChainList.iterator(); i.hasNext();) { 2388 WebServiceHandlerChain hc = i.next(); 2389 2390 if(!patternsMatch(hc, ep.getServiceName(), ep.getWsdlPort(), bindingId)) { 2393 continue; 2394 } 2395 2396 List <Handler> handlerInfo = processConfiguredHandlers(hc.getHandlers(), roles); 2399 finalHandlerList.addAll(handlerInfo); 2400 } 2401 jaxwsInfo.getBinding().setHandlerChain(finalHandlerList); 2404 if(jaxwsInfo.getBinding() instanceof javax.xml.ws.soap.SOAPBinding) { 2406 ((javax.xml.ws.soap.SOAPBinding)jaxwsInfo.getBinding()).setRoles(roles); 2407 } 2408 } 2409 2410 public void configureJAXWSClientHandlers(javax.xml.ws.Service svcClass, ServiceReferenceDescriptor desc) { 2411 2412 2414 HandlerResolverImpl resolver = 2418 JAXWSSystemHandlerDelegateFactory.getHandlerResolverImpl(svcClass,desc); 2419 2420 if (resolver == null) { 2421 if (desc.hasHandlerChain()) { 2425 resolver = new HandlerResolverImpl(); 2426 } else { 2427 return; 2428 } 2429 } 2430 2431 Set <String > roles = new HashSet (); 2432 2433 Iterator <QName > ports = svcClass.getPorts(); 2434 2435 while(ports.hasNext()) { 2437 QName nextPort = ports.next(); 2438 LinkedList handlerChainList = desc.getHandlerChain(); 2439 for(Iterator <WebServiceHandlerChain> i = handlerChainList.iterator(); i.hasNext();) { 2440 WebServiceHandlerChain hc = i.next(); 2441 if(!patternsMatch(hc, desc.getServiceName(), nextPort, null)) { 2444 continue; 2445 } 2446 ArrayList <String > protocols = new ArrayList <String >(); 2448 if(hc.getProtocolBindings() == null) { 2449 protocols.add(SOAP11_TOKEN); 2452 protocols.add(SOAP12_TOKEN); 2453 protocols.add(SOAP11_MTOM_TOKEN); 2454 protocols.add(SOAP12_MTOM_TOKEN); 2455 protocols.add(XML_TOKEN); 2456 protocols.add(HTTPBinding.HTTP_BINDING); 2457 protocols.add(SOAPBinding.SOAP11HTTP_BINDING); 2458 protocols.add(SOAPBinding.SOAP12HTTP_BINDING); 2459 protocols.add(SOAPBinding.SOAP11HTTP_MTOM_BINDING); 2460 protocols.add(SOAPBinding.SOAP12HTTP_MTOM_BINDING); 2461 } else { 2462 String specifiedProtocols = hc.getProtocolBindings(); 2464 if((specifiedProtocols.indexOf(HTTPBinding.HTTP_BINDING) != -1) || 2465 (specifiedProtocols.indexOf(XML_TOKEN) != -1)) { 2466 protocols.add(XML_TOKEN); 2467 protocols.add(HTTPBinding.HTTP_BINDING); 2468 } 2469 if((specifiedProtocols.indexOf(SOAPBinding.SOAP11HTTP_BINDING) != -1) || 2470 (specifiedProtocols.indexOf(SOAP11_TOKEN) != -1)) { 2471 protocols.add(SOAP11_TOKEN); 2472 protocols.add(SOAPBinding.SOAP11HTTP_BINDING); 2473 } 2474 if((specifiedProtocols.indexOf(SOAPBinding.SOAP12HTTP_BINDING) != -1) || 2475 (specifiedProtocols.indexOf(SOAP12_TOKEN) != -1)) { 2476 protocols.add(SOAP12_TOKEN); 2477 protocols.add(SOAPBinding.SOAP12HTTP_BINDING); 2478 } 2479 if((specifiedProtocols.indexOf(SOAPBinding.SOAP11HTTP_MTOM_BINDING) != -1) || 2480 (specifiedProtocols.indexOf(SOAP11_MTOM_TOKEN) != -1)) { 2481 protocols.add(SOAP11_MTOM_TOKEN); 2482 protocols.add(SOAPBinding.SOAP11HTTP_MTOM_BINDING); 2483 } 2484 if((specifiedProtocols.indexOf(SOAPBinding.SOAP12HTTP_MTOM_BINDING) != -1) || 2485 (specifiedProtocols.indexOf(SOAP12_MTOM_TOKEN) != -1)) { 2486 protocols.add(SOAP12_MTOM_TOKEN); 2487 protocols.add(SOAPBinding.SOAP12HTTP_MTOM_BINDING); 2488 } 2489 } 2490 List <WebServiceHandler> handlersList = hc.getHandlers(); 2492 for(WebServiceHandler thisOne : handlersList) { 2495 Collection portNames = thisOne.getPortNames(); 2496 if(!portNames.isEmpty() && 2497 !portNames.contains(nextPort.getLocalPart())) { 2498 handlersList.remove(thisOne); 2499 } 2500 } 2501 List <Handler> handlerInfo = processConfiguredHandlers(handlersList, roles); 2503 for(Iterator <String > s = protocols.iterator(); s.hasNext();) { 2506 javax.xml.ws.handler.PortInfo portInfo = 2507 new PortInfoImpl(s.next(), nextPort, desc.getServiceName()); 2508 resolver.setHandlerChain(portInfo, handlerInfo); 2509 } 2510 } 2511 } 2512 2515 2520 svcClass.setHandlerResolver(resolver); 2521 2522 } 2524 2525 2536 public void setMtom(javax.xml.ws.Binding bnd, WebServiceEndpoint ep) { 2537 String currentBinding = ep.getProtocolBinding(); 2538 if((ep.getMtomEnabled() == null) && 2539 (SOAPBinding.SOAP11HTTP_MTOM_BINDING.equals(currentBinding) || 2540 SOAPBinding.SOAP12HTTP_MTOM_BINDING.equals(currentBinding) || 2541 SOAP11_MTOM_TOKEN.equals(currentBinding) || 2542 SOAP12_MTOM_TOKEN.equals(currentBinding))) { 2543 ((SOAPBinding)bnd).setMTOMEnabled(true); 2544 } 2545 if((new Boolean (ep.getMtomEnabled())).booleanValue() && 2546 (SOAPBinding.SOAP11HTTP_BINDING.equals(currentBinding) || 2547 SOAPBinding.SOAP12HTTP_BINDING.equals(currentBinding) || 2548 SOAP11_TOKEN.equals(currentBinding) || 2549 SOAP12_TOKEN.equals(currentBinding) || 2550 SOAPBinding.SOAP11HTTP_MTOM_BINDING.equals(currentBinding) || 2551 SOAPBinding.SOAP12HTTP_MTOM_BINDING.equals(currentBinding) || 2552 SOAP11_MTOM_TOKEN.equals(currentBinding) || 2553 SOAP12_MTOM_TOKEN.equals(currentBinding))) { 2554 ((SOAPBinding)bnd).setMTOMEnabled(true); 2555 } 2556 } 2557 2558 public static SOAPMessage getMessage 2562 (javax.xml.rpc.handler.soap.SOAPMessageContext c) { 2563 return c.getMessage(); 2565 } 2566 2567 private static boolean readProperty = true; 2568 private static ExpressMessageFactoryImpl soapMsgFactory = null; 2569 private static final String EXPRESS_MSG_FACTORY = 2570 "com.sun.enterprise.webservice.expressMsgFactory"; 2571 2572 private static SOAPMessage getFactoryMessage 2573 (com.sun.xml.ws.spi.runtime.SOAPMessageContext c, boolean nameKnown) { 2574 2575 synchronized (WsUtil.class) { 2576 if (readProperty) { 2577 try { 2578 soapMsgFactory = (ExpressMessageFactoryImpl) 2579 java.security.AccessController.doPrivileged 2580 (new java.security.PrivilegedExceptionAction () { 2581 public Object run() throws Exception { 2582 ExpressMessageFactoryImpl emfi = null; 2583 if (System.getProperty 2584 (EXPRESS_MSG_FACTORY) != null) { 2585 emfi = new ExpressMessageFactoryImpl(); 2586 } 2587 return emfi; 2588 } 2589 }); 2590 } catch (Exception e) { 2591 soapMsgFactory = null; 2594 } 2595 readProperty = false; 2596 } 2597 } 2598 2599 SOAPMessage message = null; 2600 2601 if (soapMsgFactory != null) { 2602 try { 2603 message = soapMsgFactory.createMessage(c,nameKnown); 2604 } catch (Exception e) { 2605 message = null; 2607 } 2608 } 2609 2610 2614 return message; 2615 } 2616 2617 private static synchronized SOAPMessage getMessage 2621 (javax.xml.ws.handler.soap.SOAPMessageContext c, boolean nameKnown) { 2622 2623 SOAPMessage message = null; 2624 2625 if (c instanceof com.sun.xml.ws.spi.runtime.SOAPMessageContext) { 2626 2627 com.sun.xml.ws.spi.runtime.SOAPMessageContext spiC = 2628 (com.sun.xml.ws.spi.runtime.SOAPMessageContext) c; 2629 2630 if (spiC.isAlreadySoap()) { 2631 message = spiC.getMessage(); 2632 } else { 2633 message = getFactoryMessage(spiC,nameKnown); 2634 } 2635 } 2636 if (message == null) { 2638 message = c.getMessage(); 2639 } 2640 2641 return message; 2642 } 2643 2644 public static synchronized SOAPMessage getMessage 2646 (javax.xml.ws.handler.soap.SOAPMessageContext c) { 2647 return getMessage(c,true); 2648 } 2649 2650 public static synchronized SOAPMessage getMessageWithName 2653 (javax.xml.ws.handler.soap.SOAPMessageContext c) { 2654 return getMessage(c,false); 2655 } 2656} 2657 2658 2659 2660 2661 2662 2663 | Popular Tags |