Tue, 09 Apr 2013 14:51:13 +0100
8010393: Update JAX-WS RI to 2.2.9-b12941
Reviewed-by: alanb, erikj
Contributed-by: miroslav.kos@oracle.com, martin.grebac@oracle.com
1 /*
2 * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
26 package com.sun.xml.internal.ws.util.pipe;
28 import com.sun.istack.internal.NotNull;
29 import com.sun.istack.internal.Nullable;
30 import com.sun.xml.internal.stream.buffer.XMLStreamBufferResult;
31 import com.sun.xml.internal.ws.api.WSBinding;
32 import com.sun.xml.internal.ws.api.message.Message;
33 import com.sun.xml.internal.ws.api.message.Packet;
34 import com.sun.xml.internal.ws.api.pipe.Tube;
35 import com.sun.xml.internal.ws.api.pipe.TubeCloner;
36 import com.sun.xml.internal.ws.api.pipe.helper.AbstractFilterTubeImpl;
37 import com.sun.xml.internal.ws.api.server.DocumentAddressResolver;
38 import com.sun.xml.internal.ws.api.server.SDDocument;
39 import com.sun.xml.internal.ws.api.server.SDDocumentSource;
40 import com.sun.xml.internal.ws.developer.SchemaValidationFeature;
41 import com.sun.xml.internal.ws.developer.ValidationErrorHandler;
42 import com.sun.xml.internal.ws.server.SDDocumentImpl;
43 import com.sun.xml.internal.ws.util.ByteArrayBuffer;
44 import com.sun.xml.internal.ws.util.xml.XmlUtil;
45 import com.sun.xml.internal.ws.wsdl.SDDocumentResolver;
46 import com.sun.xml.internal.ws.wsdl.parser.WSDLConstants;
47 import org.w3c.dom.*;
48 import org.w3c.dom.ls.LSInput;
49 import org.w3c.dom.ls.LSResourceResolver;
50 import org.xml.sax.SAXException;
51 import org.xml.sax.helpers.NamespaceSupport;
53 import javax.xml.XMLConstants;
54 import javax.xml.namespace.QName;
55 import javax.xml.transform.Source;
56 import javax.xml.transform.Transformer;
57 import javax.xml.transform.TransformerException;
58 import javax.xml.transform.dom.DOMResult;
59 import javax.xml.transform.dom.DOMSource;
60 import javax.xml.transform.stream.StreamSource;
61 import javax.xml.validation.SchemaFactory;
62 import javax.xml.validation.Validator;
63 import javax.xml.ws.WebServiceException;
64 import java.io.IOException;
65 import java.io.InputStream;
66 import java.io.Reader;
67 import java.io.StringReader;
68 import java.net.MalformedURLException;
69 import java.net.URI;
70 import java.net.URL;
71 import java.util.*;
72 import java.util.logging.Level;
73 import java.util.logging.Logger;
75 /**
76 * {@link Tube} that does the schema validation.
77 *
78 * @author Jitendra Kotamraju
79 */
80 public abstract class AbstractSchemaValidationTube extends AbstractFilterTubeImpl {
82 private static final Logger LOGGER = Logger.getLogger(AbstractSchemaValidationTube.class.getName());
84 protected final WSBinding binding;
85 protected final SchemaValidationFeature feature;
86 protected final DocumentAddressResolver resolver = new ValidationDocumentAddressResolver();
87 protected final SchemaFactory sf;
89 public AbstractSchemaValidationTube(WSBinding binding, Tube next) {
90 super(next);
91 this.binding = binding;
92 feature = binding.getFeature(SchemaValidationFeature.class);
93 sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
94 }
96 protected AbstractSchemaValidationTube(AbstractSchemaValidationTube that, TubeCloner cloner) {
97 super(that, cloner);
98 this.binding = that.binding;
99 this.feature = that.feature;
100 this.sf = that.sf;
101 }
103 protected abstract Validator getValidator();
105 protected abstract boolean isNoValidation();
107 private static class ValidationDocumentAddressResolver implements DocumentAddressResolver {
109 @Nullable
110 @Override
111 public String getRelativeAddressFor(@NotNull SDDocument current, @NotNull SDDocument referenced) {
112 LOGGER.log(Level.FINE, "Current = {0} resolved relative={1}", new Object[]{current.getURL(), referenced.getURL()});
113 return referenced.getURL().toExternalForm();
114 }
115 }
117 private Document createDOM(SDDocument doc) {
118 // Get infoset
119 ByteArrayBuffer bab = new ByteArrayBuffer();
120 try {
121 doc.writeTo(null, resolver, bab);
122 } catch (IOException ioe) {
123 throw new WebServiceException(ioe);
124 }
126 // Convert infoset to DOM
127 Transformer trans = XmlUtil.newTransformer();
128 Source source = new StreamSource(bab.newInputStream(), null); //doc.getURL().toExternalForm());
129 DOMResult result = new DOMResult();
130 try {
131 trans.transform(source, result);
132 } catch(TransformerException te) {
133 throw new WebServiceException(te);
134 }
135 return (Document)result.getNode();
136 }
138 protected class MetadataResolverImpl implements SDDocumentResolver, LSResourceResolver {
140 // systemID --> SDDocument
141 final Map<String, SDDocument> docs = new HashMap<String, SDDocument>();
143 // targetnamespace --> SDDocument
144 final Map<String, SDDocument> nsMapping = new HashMap<String, SDDocument>();
146 public MetadataResolverImpl() {
147 }
149 public MetadataResolverImpl(Iterable<SDDocument> it) {
150 for(SDDocument doc : it) {
151 if (doc.isSchema()) {
152 docs.put(doc.getURL().toExternalForm(), doc);
153 nsMapping.put(((SDDocument.Schema)doc).getTargetNamespace(), doc);
154 }
155 }
156 }
158 void addSchema(Source schema) {
159 assert schema.getSystemId() != null;
161 String systemId = schema.getSystemId();
162 try {
163 XMLStreamBufferResult xsbr = XmlUtil.identityTransform(schema, new XMLStreamBufferResult());
164 SDDocumentSource sds = SDDocumentSource.create(new URL(systemId), xsbr.getXMLStreamBuffer());
165 SDDocument sdoc = SDDocumentImpl.create(sds, new QName(""), new QName(""));
166 docs.put(systemId, sdoc);
167 nsMapping.put(((SDDocument.Schema)sdoc).getTargetNamespace(), sdoc);
168 } catch(Exception ex) {
169 LOGGER.log(Level.WARNING, "Exception in adding schemas to resolver", ex);
170 }
171 }
173 void addSchemas(Collection<? extends Source> schemas) {
174 for(Source src : schemas) {
175 addSchema(src);
176 }
177 }
179 @Override
180 public SDDocument resolve(String systemId) {
181 SDDocument sdi = docs.get(systemId);
182 if (sdi == null) {
183 SDDocumentSource sds;
184 try {
185 sds = SDDocumentSource.create(new URL(systemId));
186 } catch(MalformedURLException e) {
187 throw new WebServiceException(e);
188 }
189 sdi = SDDocumentImpl.create(sds, new QName(""), new QName(""));
190 docs.put(systemId, sdi);
191 }
192 return sdi;
193 }
195 @Override
196 public LSInput resolveResource(String type, String namespaceURI, String publicId, final String systemId, final String baseURI) {
197 if (LOGGER.isLoggable(Level.FINE)) {
198 LOGGER.log(Level.FINE, "type={0} namespaceURI={1} publicId={2} systemId={3} baseURI={4}", new Object[]{type, namespaceURI, publicId, systemId, baseURI});
199 }
200 try {
201 final SDDocument doc;
202 if (systemId == null) {
203 doc = nsMapping.get(namespaceURI);
204 } else {
205 URI rel = (baseURI != null)
206 ? new URI(baseURI).resolve(systemId)
207 : new URI(systemId);
208 doc = docs.get(rel.toString());
209 }
210 if (doc != null) {
211 return new LSInput() {
213 @Override
214 public Reader getCharacterStream() {
215 return null;
216 }
218 @Override
219 public void setCharacterStream(Reader characterStream) {
220 throw new UnsupportedOperationException();
221 }
223 @Override
224 public InputStream getByteStream() {
225 ByteArrayBuffer bab = new ByteArrayBuffer();
226 try {
227 doc.writeTo(null, resolver, bab);
228 } catch (IOException ioe) {
229 throw new WebServiceException(ioe);
230 }
231 return bab.newInputStream();
232 }
234 @Override
235 public void setByteStream(InputStream byteStream) {
236 throw new UnsupportedOperationException();
237 }
239 @Override
240 public String getStringData() {
241 return null;
242 }
244 @Override
245 public void setStringData(String stringData) {
246 throw new UnsupportedOperationException();
247 }
249 @Override
250 public String getSystemId() {
251 return doc.getURL().toExternalForm();
252 }
254 @Override
255 public void setSystemId(String systemId) {
256 throw new UnsupportedOperationException();
257 }
259 @Override
260 public String getPublicId() {
261 return null;
262 }
264 @Override
265 public void setPublicId(String publicId) {
266 throw new UnsupportedOperationException();
267 }
269 @Override
270 public String getBaseURI() {
271 return doc.getURL().toExternalForm();
272 }
274 @Override
275 public void setBaseURI(String baseURI) {
276 throw new UnsupportedOperationException();
277 }
279 @Override
280 public String getEncoding() {
281 return null;
282 }
284 @Override
285 public void setEncoding(String encoding) {
286 throw new UnsupportedOperationException();
287 }
289 @Override
290 public boolean getCertifiedText() {
291 return false;
292 }
294 @Override
295 public void setCertifiedText(boolean certifiedText) {
296 throw new UnsupportedOperationException();
297 }
298 };
299 }
300 } catch(Exception e) {
301 LOGGER.log(Level.WARNING, "Exception in LSResourceResolver impl", e);
302 }
303 if (LOGGER.isLoggable(Level.FINE)) {
304 LOGGER.log(Level.FINE, "Don''t know about systemId={0} baseURI={1}", new Object[]{systemId, baseURI});
305 }
306 return null;
307 }
309 }
311 private void updateMultiSchemaForTns(String tns, String systemId, Map<String, List<String>> schemas) {
312 List<String> docIdList = schemas.get(tns);
313 if (docIdList == null) {
314 docIdList = new ArrayList<String>();
315 schemas.put(tns, docIdList);
316 }
317 docIdList.add(systemId);
318 }
320 /*
321 * Using the following algorithm described in the xerces discussion thread:
322 *
323 * "If you're synthesizing schema documents to glue together the ones in
324 * the WSDL then you may not even need to use "honour-all-schemaLocations".
325 * Create a schema document for each namespace with <xs:include>s
326 * (for each schema document in the WSDL with that target namespace)
327 * and then combine those together with <xs:import>s for each of those
328 * namespaces in a "master" schema document.
329 *
330 * That should work with any schema processor, not just those which
331 * honour multiple imports for the same namespace."
332 */
333 protected Source[] getSchemaSources(Iterable<SDDocument> docs, MetadataResolverImpl mdresolver) {
334 // All schema fragments in WSDLs are put inlinedSchemas
335 // systemID --> DOMSource
336 Map<String, DOMSource> inlinedSchemas = new HashMap<String, DOMSource>();
338 // Consolidates all the schemas(inlined and external) for a tns
339 // tns --> list of systemId
340 Map<String, List<String>> multiSchemaForTns = new HashMap<String, List<String>>();
342 for(SDDocument sdoc: docs) {
343 if (sdoc.isWSDL()) {
344 Document dom = createDOM(sdoc);
345 // Get xsd:schema node from WSDL's DOM
346 addSchemaFragmentSource(dom, sdoc.getURL().toExternalForm(), inlinedSchemas);
347 } else if (sdoc.isSchema()) {
348 updateMultiSchemaForTns(((SDDocument.Schema)sdoc).getTargetNamespace(), sdoc.getURL().toExternalForm(), multiSchemaForTns);
349 }
350 }
351 if (LOGGER.isLoggable(Level.FINE)) {
352 LOGGER.log(Level.FINE, "WSDL inlined schema fragment documents(these are used to create a pseudo schema) = {0}", inlinedSchemas.keySet());
353 }
354 for(DOMSource src: inlinedSchemas.values()) {
355 String tns = getTargetNamespace(src);
356 updateMultiSchemaForTns(tns, src.getSystemId(), multiSchemaForTns);
357 }
359 if (multiSchemaForTns.isEmpty()) {
360 return new Source[0]; // WSDL doesn't have any schema fragments
361 } else if (multiSchemaForTns.size() == 1 && multiSchemaForTns.values().iterator().next().size() == 1) {
362 // It must be a inlined schema, otherwise there would be at least two schemas
363 String systemId = multiSchemaForTns.values().iterator().next().get(0);
364 return new Source[] {inlinedSchemas.get(systemId)};
365 }
367 // need to resolve these inlined schema fragments
368 mdresolver.addSchemas(inlinedSchemas.values());
370 // If there are multiple schema fragments for the same tns, create a
371 // pseudo schema for that tns by using <xsd:include> of those.
372 // tns --> systemId of a pseudo schema document (consolidated for that tns)
373 Map<String, String> oneSchemaForTns = new HashMap<String, String>();
374 int i = 0;
375 for(Map.Entry<String, List<String>> e: multiSchemaForTns.entrySet()) {
376 String systemId;
377 List<String> sameTnsSchemas = e.getValue();
378 if (sameTnsSchemas.size() > 1) {
379 // SDDocumentSource should be changed to take String systemId
380 // String pseudoSystemId = "urn:x-jax-ws-include-"+i++;
381 systemId = "file:x-jax-ws-include-"+i++;
382 Source src = createSameTnsPseudoSchema(e.getKey(), sameTnsSchemas, systemId);
383 mdresolver.addSchema(src);
384 } else {
385 systemId = sameTnsSchemas.get(0);
386 }
387 oneSchemaForTns.put(e.getKey(), systemId);
388 }
390 // create a master pseudo schema with all the different tns
391 Source pseudoSchema = createMasterPseudoSchema(oneSchemaForTns);
392 return new Source[] { pseudoSchema };
393 }
395 private @Nullable void addSchemaFragmentSource(Document doc, String systemId, Map<String, DOMSource> map) {
396 Element e = doc.getDocumentElement();
397 assert e.getNamespaceURI().equals(WSDLConstants.NS_WSDL);
398 assert e.getLocalName().equals("definitions");
400 NodeList typesList = e.getElementsByTagNameNS(WSDLConstants.NS_WSDL, "types");
401 for(int i=0; i < typesList.getLength(); i++) {
402 NodeList schemaList = ((Element)typesList.item(i)).getElementsByTagNameNS(WSDLConstants.NS_XMLNS, "schema");
403 for(int j=0; j < schemaList.getLength(); j++) {
404 Element elem = (Element)schemaList.item(j);
405 NamespaceSupport nss = new NamespaceSupport();
406 // Doing this because transformer is not picking up inscope namespaces
407 // why doesn't transformer pickup the inscope namespaces ??
408 buildNamespaceSupport(nss, elem);
409 patchDOMFragment(nss, elem);
410 String docId = systemId+"#schema"+j;
411 map.put(docId, new DOMSource(elem, docId));
412 }
413 }
414 }
417 /*
418 * Recursively visit ancestors and build up {@link org.xml.sax.helpers.NamespaceSupport} object.
419 */
420 private void buildNamespaceSupport(NamespaceSupport nss, Node node) {
421 if (node==null || node.getNodeType()!=Node.ELEMENT_NODE) {
422 return;
423 }
425 buildNamespaceSupport( nss, node.getParentNode() );
427 nss.pushContext();
428 NamedNodeMap atts = node.getAttributes();
429 for( int i=0; i<atts.getLength(); i++ ) {
430 Attr a = (Attr)atts.item(i);
431 if( "xmlns".equals(a.getPrefix()) ) {
432 nss.declarePrefix( a.getLocalName(), a.getValue() );
433 continue;
434 }
435 if( "xmlns".equals(a.getName()) ) {
436 nss.declarePrefix( "", a.getValue() );
437 //continue;
438 }
439 }
440 }
442 /**
443 * Adds inscope namespaces as attributes to <xsd:schema> fragment nodes.
444 *
445 * @param nss namespace context info
446 * @param elem that is patched with inscope namespaces
447 */
448 private @Nullable void patchDOMFragment(NamespaceSupport nss, Element elem) {
449 NamedNodeMap atts = elem.getAttributes();
450 for( Enumeration en = nss.getPrefixes(); en.hasMoreElements(); ) {
451 String prefix = (String)en.nextElement();
453 for( int i=0; i<atts.getLength(); i++ ) {
454 Attr a = (Attr)atts.item(i);
455 if (!"xmlns".equals(a.getPrefix()) || !a.getLocalName().equals(prefix)) {
456 if (LOGGER.isLoggable(Level.FINE)) {
457 LOGGER.log(Level.FINE, "Patching with xmlns:{0}={1}", new Object[]{prefix, nss.getURI(prefix)});
458 }
459 elem.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:"+prefix, nss.getURI(prefix));
460 }
461 }
462 }
463 }
465 /*
466 * Creates a pseudo schema for the WSDL schema fragments that have the same
467 * targetNamespace.
468 *
469 * <xsd:schema targetNamespace="X">
470 * <xsd:include schemaLocation="Y1"/>
471 * <xsd:include schemaLocation="Y2"/>
472 * </xsd:schema>
473 *
474 * @param tns targetNamespace of the the schema documents
475 * @param docs collection of systemId for the schema documents that have the
476 * same tns, the collection must have more than one document
477 * @param psuedoSystemId for the created pseudo schema
478 * @return Source of pseudo schema that can be used multiple times
479 */
480 private @Nullable Source createSameTnsPseudoSchema(String tns, Collection<String> docs, String pseudoSystemId) {
481 assert docs.size() > 1;
483 final StringBuilder sb = new StringBuilder("<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'");
484 if (!tns.equals("")) {
485 sb.append(" targetNamespace='").append(tns).append("'");
486 }
487 sb.append(">\n");
488 for(String systemId : docs) {
489 sb.append("<xsd:include schemaLocation='").append(systemId).append("'/>\n");
490 }
491 sb.append("</xsd:schema>\n");
492 if (LOGGER.isLoggable(Level.FINE)) {
493 LOGGER.log(Level.FINE, "Pseudo Schema for the same tns={0}is {1}", new Object[]{tns, sb});
494 }
496 // override getReader() so that the same source can be used multiple times
497 return new StreamSource(pseudoSystemId) {
498 @Override
499 public Reader getReader() {
500 return new StringReader(sb.toString());
501 }
502 };
503 }
505 /*
506 * Creates a master pseudo schema importing all WSDL schema fragments with
507 * different tns+pseudo schema for same tns.
508 * <xsd:schema targetNamespace="urn:x-jax-ws-master">
509 * <xsd:import schemaLocation="Y1" namespace="X1"/>
510 * <xsd:import schemaLocation="Y2" namespace="X2"/>
511 * </xsd:schema>
512 *
513 * @param pseudo a map(tns-->systemId) of schema documents
514 * @return Source of pseudo schema that can be used multiple times
515 */
516 private Source createMasterPseudoSchema(Map<String, String> docs) {
517 final StringBuilder sb = new StringBuilder("<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema' targetNamespace='urn:x-jax-ws-master'>\n");
518 for(Map.Entry<String, String> e : docs.entrySet()) {
519 String systemId = e.getValue();
520 String ns = e.getKey();
521 sb.append("<xsd:import schemaLocation='").append(systemId).append("'");
522 if (!ns.equals("")) {
523 sb.append(" namespace='").append(ns).append("'");
524 }
525 sb.append("/>\n");
526 }
527 sb.append("</xsd:schema>");
528 if (LOGGER.isLoggable(Level.FINE)) {
529 LOGGER.log(Level.FINE, "Master Pseudo Schema = {0}", sb);
530 }
532 // override getReader() so that the same source can be used multiple times
533 return new StreamSource("file:x-jax-ws-master-doc") {
534 @Override
535 public Reader getReader() {
536 return new StringReader(sb.toString());
537 }
538 };
539 }
541 protected void doProcess(Packet packet) throws SAXException {
542 getValidator().reset();
543 Class<? extends ValidationErrorHandler> handlerClass = feature.getErrorHandler();
544 ValidationErrorHandler handler;
545 try {
546 handler = handlerClass.newInstance();
547 } catch(Exception e) {
548 throw new WebServiceException(e);
549 }
550 handler.setPacket(packet);
551 getValidator().setErrorHandler(handler);
552 Message msg = packet.getMessage().copy();
553 Source source = msg.readPayloadAsSource();
554 try {
555 // Validator javadoc allows ONLY SAX, and DOM Sources
556 // But the impl seems to handle all kinds.
557 getValidator().validate(source);
558 } catch(IOException e) {
559 throw new WebServiceException(e);
560 }
561 }
563 private String getTargetNamespace(DOMSource src) {
564 Element elem = (Element)src.getNode();
565 return elem.getAttribute("targetNamespace");
566 }
568 // protected static void printSource(Source src) {
569 // try {
570 // ByteArrayBuffer bos = new ByteArrayBuffer();
571 // StreamResult sr = new StreamResult(bos );
572 // Transformer trans = TransformerFactory.newInstance().newTransformer();
573 // trans.transform(src, sr);
574 // LOGGER.info("**** src ******"+bos.toString());
575 // bos.close();
576 // } catch(Exception e) {
577 // e.printStackTrace();
578 // }
579 // }
581 }