KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > xml > wsdl > validator > WSDLInlineSchemaValidator


1 package org.netbeans.modules.xml.wsdl.validator;
2
3 import java.io.File JavaDoc;
4 import java.io.FileInputStream JavaDoc;
5 import java.io.FileNotFoundException JavaDoc;
6 import java.io.InputStream JavaDoc;
7 import java.io.Reader JavaDoc;
8 import java.io.StringReader JavaDoc;
9 import java.net.URI JavaDoc;
10 import java.net.URISyntaxException JavaDoc;
11 import java.util.ArrayList JavaDoc;
12 import java.util.Collection JavaDoc;
13 import java.util.Collections JavaDoc;
14 import java.util.Iterator JavaDoc;
15 import java.util.List JavaDoc;
16 import java.util.Map JavaDoc;
17 import java.util.Vector JavaDoc;
18 import java.util.logging.Level JavaDoc;
19 import java.util.logging.Logger JavaDoc;
20 import java.util.regex.Matcher JavaDoc;
21 import java.util.regex.Pattern JavaDoc;
22
23 import javax.swing.text.BadLocationException JavaDoc;
24 import javax.swing.text.Document JavaDoc;
25 import javax.xml.XMLConstants JavaDoc;
26 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
27 import javax.xml.parsers.ParserConfigurationException JavaDoc;
28 import javax.xml.transform.Source JavaDoc;
29 import javax.xml.transform.sax.SAXSource JavaDoc;
30 import javax.xml.validation.Schema JavaDoc;
31 import javax.xml.validation.SchemaFactory JavaDoc;
32 import org.netbeans.modules.xml.schema.model.SchemaModel;
33
34 import org.netbeans.modules.xml.schema.model.SchemaModelFactory;
35 import org.netbeans.modules.xml.wsdl.model.Definitions;
36 import org.netbeans.modules.xml.wsdl.model.Types;
37 import org.netbeans.modules.xml.wsdl.model.WSDLModel;
38 import org.netbeans.modules.xml.wsdl.model.extensions.xsd.WSDLSchema;
39 import org.netbeans.modules.xml.xam.Model;
40 import org.netbeans.modules.xml.xam.ModelSource;
41 import org.netbeans.modules.xml.xam.Model.State;
42 import org.netbeans.modules.xml.xam.dom.AbstractDocumentComponent;
43 import org.netbeans.modules.xml.xam.dom.DocumentModel;
44 import org.netbeans.modules.xml.xam.locator.CatalogModel;
45 import org.netbeans.modules.xml.xam.locator.CatalogModelException;
46 import org.netbeans.modules.xml.xam.locator.CatalogModelFactory;
47 import org.netbeans.modules.xml.xam.spi.Validation;
48 import org.netbeans.modules.xml.xam.spi.ValidationResult;
49 import org.netbeans.modules.xml.xam.spi.Validator;
50 import org.netbeans.modules.xml.xam.spi.XsdBasedValidator;
51 import org.netbeans.modules.xml.xam.spi.Validation.ValidationType;
52 import org.w3c.dom.DOMImplementation JavaDoc;
53 import org.w3c.dom.ls.DOMImplementationLS JavaDoc;
54 import org.w3c.dom.ls.LSInput JavaDoc;
55 import org.w3c.dom.ls.LSResourceResolver JavaDoc;
56 import org.xml.sax.InputSource JavaDoc;
57 import org.xml.sax.SAXException JavaDoc;
58
59 public class WSDLInlineSchemaValidator extends XsdBasedValidator {
60     
61     @SuppressWarnings JavaDoc("unchecked")
62     public static final ValidationResult EMPTY_RESULT =
63         new ValidationResult( Collections.EMPTY_SET,
64                 Collections.EMPTY_SET);
65
66     public String JavaDoc getName() {
67        return "WSDLInlineSchemaValidator";//NOI18N
68
}
69
70     @Override JavaDoc
71     public ValidationResult validate(Model model, Validation validation,
72             ValidationType validationType) {
73         if (model instanceof WSDLModel) {
74             WSDLModel wsdlModel = (WSDLModel) model;
75
76             List JavaDoc<Model> validatedModels = new ArrayList JavaDoc<Model>();
77             Vector JavaDoc<ResultItem> resultItems = new Vector JavaDoc<ResultItem>();
78             if (validationType.equals(ValidationType.COMPLETE) ||
79                     validationType.equals(ValidationType.PARTIAL)) {
80                 
81                 if (wsdlModel.getState() == State.NOT_WELL_FORMED) {
82                     return EMPTY_RESULT;
83                 }
84                 
85                 Definitions def = wsdlModel.getDefinitions();
86                 Map JavaDoc<String JavaDoc, String JavaDoc> prefixes = ((AbstractDocumentComponent)def).getPrefixes();
87                 String JavaDoc systemId = getSystemId(wsdlModel);
88                 Types types = def.getTypes();
89                 if (types != null) {
90                     Collection JavaDoc<WSDLSchema> schemas = types.getExtensibilityElements(WSDLSchema.class);
91                     
92                     String JavaDoc text = getWSDLText(wsdlModel);
93                     
94                     assert text != null : "there is no content in the wsdl document or couldnt be read";
95                     
96                     List JavaDoc<Integer JavaDoc> linePositions = setupLinePositions(text);
97                     
98                     WSDLLSResourceResolver resolver = new WSDLLSResourceResolver(wsdlModel,
99                                                                                  systemId,
100                                                                                  text,
101                                                                                  prefixes,
102                                                                                  linePositions);
103            
104                     for (WSDLSchema schema : schemas) {
105                         Reader JavaDoc in = createInlineSchemaSource(text, prefixes, linePositions, schema);
106                         if(in != null) {
107                             SAXSource JavaDoc source = new SAXSource JavaDoc(new InputSource JavaDoc(in));
108                             source.setSystemId(systemId);
109                             int start = schema.findPosition();
110                             int lineNumber = getLineNumber(start, linePositions); //where the schema starts in the wsdl document
111

112                             //validate the source
113
Handler handler = new InlineSchemaValidatorHandler(wsdlModel, lineNumber);
114                             validate(wsdlModel, source, handler, resolver);
115                             resultItems.addAll(handler.getResultItems());
116                         }
117                     }
118                     
119                     
120                     validatedModels.add(model);
121                     return new ValidationResult(resultItems, validatedModels);
122                 }
123             }
124         }
125         return new ValidationResult(new ArrayList JavaDoc<ResultItem>(), new ArrayList JavaDoc<Model>());
126     }
127     
128     private String JavaDoc getSystemId(WSDLModel model) {
129         Source JavaDoc source = (Source JavaDoc) model.getModelSource().getLookup().lookup(Source JavaDoc.class);
130
131         // Try to get Source via File from lookup.
132
if(source == null) {
133             File JavaDoc file = (File JavaDoc) model.getModelSource().getLookup().lookup(File JavaDoc.class);
134             if(file != null) {
135                 try {
136                     source = new SAXSource JavaDoc(new InputSource JavaDoc(new FileInputStream JavaDoc(file)));
137                 } catch (FileNotFoundException JavaDoc ex) {
138                     Logger.getLogger(getClass().getName()).log(Level.SEVERE, "getSystemId", ex); //NOI18N
139
}
140             }
141         }
142         
143         if (source != null) {
144             return source.getSystemId();
145         }
146         return null;
147         
148     }
149
150     private void validate(WSDLModel model,
151                           Source JavaDoc saxSource,
152                           XsdBasedValidator.Handler handler,
153                           LSResourceResolver JavaDoc resolver) {
154         try {
155             SchemaFactory JavaDoc sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
156             if (resolver != null) {
157                 sf.setResourceResolver(resolver);
158             }
159             sf.setErrorHandler(handler);
160             if (saxSource == null) {
161                 return;
162             }
163             sf.newSchema(saxSource);
164         } catch(SAXException JavaDoc sax) {
165             //already processed by handler
166
} catch(Exception JavaDoc ex) {
167             handler.logValidationErrors(Validator.ResultType.ERROR, ex.getMessage());
168         }
169     }
170     
171     /**
172      * {<one or more space}{anyNonSpace + schema}{zero or more space}
173      * it can be <xsd:schema> or <xsd:schema blah-blah>
174      */

175     Pattern JavaDoc pattern = Pattern.compile("(<\\s*)(\\S*schema)(\\s*)");
176     
177     private String JavaDoc getEndTag(String JavaDoc startTag) {
178         Matcher JavaDoc matcher = pattern.matcher(startTag);
179         if (matcher.find()) {
180             return "</" + matcher.group(2) + ">"; //get the schema with prefix and create a end tag
181
}
182         return null;
183     }
184     
185     private List JavaDoc<Integer JavaDoc> setupLinePositions(String JavaDoc str) {
186         List JavaDoc<Integer JavaDoc> linePositions = new ArrayList JavaDoc<Integer JavaDoc>();
187         String JavaDoc[] lines = str.split("\n"); //NOI18N
188
linePositions.add(Integer.valueOf(-1));
189         int pos = 0;
190         for (String JavaDoc line : lines) {
191             linePositions.add(pos);
192             pos += line.length() + 1; // make sure we also count the \n
193
}
194         return linePositions;
195     }
196     
197     private int getLineNumber(int position, List JavaDoc<Integer JavaDoc> linePositions) {
198         for (int i = 0; i < linePositions.size(); i++) {
199             if (position < linePositions.get(i).intValue()) {
200                 return i - 1;
201             }
202         }
203         return -1;
204         
205     }
206
207     
208     class InlineSchemaValidatorHandler extends XsdBasedValidator.Handler {
209         int startingLineNumber;
210         public InlineSchemaValidatorHandler(Model model, int lineNumber) {
211             super(model);
212             startingLineNumber = lineNumber - 1;
213         }
214
215         @Override JavaDoc
216         public void logValidationErrors(ResultType resultType, String JavaDoc errorDescription, int lineNumber, int columnNumber) {
217             super.logValidationErrors(resultType, errorDescription, startingLineNumber + lineNumber,
218                     columnNumber);
219         }
220         
221         
222
223     }
224
225     @Override JavaDoc
226     protected Schema JavaDoc getSchema(Model model) {
227         //not used.
228
return null;
229     }
230     
231     private String JavaDoc getWSDLText(WSDLModel model) {
232         javax.swing.text.Document JavaDoc d = (Document JavaDoc) model.getModelSource().getLookup().lookup(Document JavaDoc.class);
233         try {
234             return d.getText(0, d.getLength());
235         } catch (BadLocationException JavaDoc e) {
236             //log this..
237
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "getWSDLText", e); //NOI18N
238
}
239         return null;
240     }
241     
242     @Override JavaDoc
243     public DocumentModel resolveResource(String JavaDoc systemId, Model currentModel) {
244         if (currentModel instanceof WSDLModel && systemId.equals(getSystemId((WSDLModel)currentModel))) {
245             return (WSDLModel) currentModel;
246         }
247         try {
248             CatalogModel cm = (CatalogModel) currentModel.getModelSource().getLookup()
249                 .lookup(CatalogModel.class);
250             ModelSource ms = cm.getModelSource(new URI JavaDoc(systemId));
251             if (ms != null) {
252                 return SchemaModelFactory.getDefault().getModel(ms);
253             }
254         } catch(URISyntaxException JavaDoc ex) {
255             Logger.getLogger(getClass().getName()).log(Level.FINE, "resolveResource", ex); //NOI18N
256
} catch(CatalogModelException ex) {
257             Logger.getLogger(getClass().getName()).log(Level.FINE, "resolveResource", ex); //NOI18N
258
}
259         return null;
260     }
261  
262     private Reader JavaDoc createInlineSchemaSource(String JavaDoc wsdlText,
263                                             Map JavaDoc<String JavaDoc, String JavaDoc> wsdlPrefixes,
264                                             List JavaDoc<Integer JavaDoc> wsdlLinePositions,
265                                             WSDLSchema oneInlineSchema) {
266         Reader JavaDoc source = null;
267         int start = oneInlineSchema.findPosition();
268         int lineNumber = getLineNumber(start, wsdlLinePositions); //where the schema starts in the wsdl document
269
String JavaDoc schemaString = oneInlineSchema.getContentFragment(); // get inner text content of schema.
270
int index = wsdlText.indexOf(schemaString, start);
271         if (schemaString != null && schemaString.trim().length() > 0) { //else if its schema with no contents
272
assert index != -1 : "the text content under schema couldnt be found in the wsdl document";
273             String JavaDoc schemaTop = wsdlText.substring(start, index); //get the schema definition.
274
String JavaDoc[] splits = schemaTop.split(">");
275             StringBuffer JavaDoc strBuf = new StringBuffer JavaDoc();
276             if (splits.length > 0) {
277                 strBuf.append(splits[0]);
278                 Map JavaDoc<String JavaDoc, String JavaDoc> schemaPrefixes = ((AbstractDocumentComponent)oneInlineSchema.getSchemaModel().getSchema()).getPrefixes();
279                 for (String JavaDoc prefix : wsdlPrefixes.keySet()) {
280                     if (!(prefix == null || prefix.length() == 0 || schemaPrefixes.containsKey(prefix))) {
281                         strBuf.append(" ").append("xmlns:").append(prefix).append("=\"").append(wsdlPrefixes.get(prefix)).append("\"");
282                     }
283                 }
284
285                 for (int i = 1; i < splits.length; i++) {
286                     strBuf.append(">").append(splits[i]);
287                 }
288                 strBuf.append(">");
289                 strBuf.append(schemaString).append(getEndTag(splits[0]));
290                 schemaString = null;
291                 splits = null;
292                 schemaTop = null;
293             }
294
295
296             source = new StringReader JavaDoc(strBuf.toString());
297 // source = new SAXSource(new InputSource(new StringReader(strBuf.toString())));
298
strBuf = null;
299         }
300         
301         return source;
302     }
303                         
304     class WSDLLSResourceResolver implements LSResourceResolver JavaDoc {
305         
306         private WSDLModel mModel;
307                 
308         private LSResourceResolver JavaDoc mDelegate;
309         
310         private String JavaDoc mWsdlSystemId;
311         private String JavaDoc mWsdlText;
312         private Map JavaDoc<String JavaDoc, String JavaDoc> mWsdlPrefixes;
313         private List JavaDoc<Integer JavaDoc> mWsdlLinePositions;
314                 
315         public WSDLLSResourceResolver(WSDLModel wsdlmodel,
316                                       String JavaDoc wsdlSystemId,
317                                       String JavaDoc wsdlText,
318                                       Map JavaDoc<String JavaDoc, String JavaDoc> wsdlPrefixes,
319                                       List JavaDoc<Integer JavaDoc> wsdlLinePositions) {
320              mModel = wsdlmodel;
321              mWsdlSystemId = wsdlSystemId;
322              mWsdlText = wsdlText;
323              mWsdlPrefixes = wsdlPrefixes;
324              mWsdlLinePositions = wsdlLinePositions;
325
326              mDelegate = CatalogModelFactory.getDefault().getLSResourceResolver();
327            
328         }
329         public LSInput JavaDoc resolveResource(String JavaDoc type,
330                                        String JavaDoc namespaceURI,
331                                        String JavaDoc publicId,
332                                        String JavaDoc systemId,
333                                        String JavaDoc baseURI) {
334             
335              LSInput JavaDoc lsi = mDelegate.resolveResource(type, namespaceURI, publicId, systemId, baseURI);
336              if(lsi == null) {
337                  //if we can not get an input from catalog, then it could that
338
//there as a schema in types section which refer to schema compoment from other inline schema
339
//so we try to check in other inline schema.
340
WSDLSchema schema = findSchema(namespaceURI);
341                 if(schema != null) {
342                     Reader JavaDoc in = createInlineSchemaSource(mWsdlText, mWsdlPrefixes, mWsdlLinePositions, schema);
343                     if(in != null) {
344                         //create LSInput object
345
DOMImplementation JavaDoc domImpl = null;
346                         try {
347                             domImpl = DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation();
348                         } catch (ParserConfigurationException JavaDoc ex) {
349                              Logger.getLogger(getClass().getName()).log(Level.SEVERE, "resolveResource", ex); //NOI18N
350
return null;
351                         }
352                         
353                         DOMImplementationLS JavaDoc dols = (DOMImplementationLS JavaDoc) domImpl.getFeature("LS","3.0");
354                         lsi = dols.createLSInput();
355                         if(in != null) {
356                             lsi.setCharacterStream(in);
357                         }
358                         
359                         if(mWsdlSystemId != null) {
360                             lsi.setSystemId(mWsdlSystemId);
361                         }
362                     return lsi;
363                     }
364                 }
365              }
366              return lsi;
367         }
368
369         private WSDLSchema findSchema(String JavaDoc namespaceURI) {
370                 WSDLSchema schema = null;
371                 Definitions def = mModel.getDefinitions();
372                 Types types = def.getTypes();
373                 if (types != null) {
374                     Collection JavaDoc<WSDLSchema> schemas = types.getExtensibilityElements(WSDLSchema.class);
375                     Iterator JavaDoc<WSDLSchema> it = schemas.iterator();
376                     while(it.hasNext()) {
377                         WSDLSchema sch = it.next();
378                         SchemaModel model = sch.getSchemaModel();
379                         if(model != null) {
380                             org.netbeans.modules.xml.schema.model.Schema s = model.getSchema();
381                             if(s != null && s.getTargetNamespace() != null && s.getTargetNamespace().equals(namespaceURI)) {
382                                 schema = sch;
383                                 break;
384                             }
385                         }
386                     }
387                 }
388                 
389                 return schema;
390         }
391         
392     }
393 }
394
Popular Tags