informática enterprise integration - técnico lisboa - … · informática enterprise integration...
TRANSCRIPT
DepartamentodeEngenhariaInformática
EnterpriseIntegrationXMLTutorial
IE2016
IST/DEI Pág.1de13
Inthistutorial1,wewillcreateanXMLschemainJDeveloper11g.WewillthencreateanXMLdocument from the schemaandvalidate theXML instance. The code listingbelowpresentstheXMLschema:
<?xmlversion="1.0"encoding="UTF-8"?><xsd:schemaxmlns:xsd="http://www.w3.org/2001/XMLSchema"xmlns:tns="http://www.example.org"targetNamespace="http://www.example.org"elementFormDefault="qualified"><xsd:complexTypename="taxSubjectType"><xsd:sequence><xsd:elementname="name"type="xsd:string"/><xsd:elementname="address"type="xsd:string"/></xsd:sequence><xsd:attributename="tax-id"type="xsd:integer"use="required"/></xsd:complexType><xsd:complexTypename="totalsType"><xsd:sequence><xsd:elementname="value"type="xsd:decimal"/><xsd:elementname="tax"type="xsd:decimal"/></xsd:sequence></xsd:complexType><xsd:complexTypename="itemType"><xsd:sequence><xsd:elementname="value"type="xsd:decimal"/><xsd:elementname="desc"type="xsd:string"/></xsd:sequence></xsd:complexType><xsd:complexTypename="itemsType"><xsd:sequence><xsd:elementname="item"type="tns:itemType"minOccurs="0"maxOccurs="unbounded"/></xsd:sequence></xsd:complexType><xsd:complexTypename="invoiceType"><xsd:sequence><xsd:elementname="seller"type="tns:taxSubjectType"/><xsd:elementname="buyer"type="tns:taxSubjectType"/><xsd:elementname="totals"type="tns:totalsType"/><xsd:elementname="items"type="tns:itemsType"/></xsd:sequence><xsd:attributename="nr"type="xsd:integer"/><xsd:attributename="date"type="xsd:dateTime"/></xsd:complexType><xsd:elementname="invoice"type="tns:invoiceType"/></xsd:schema>
1 The code listings in this tutorial is based on the examples from the book Deepak Vohra. Processing XML documents with Oracle JDeveloper 11g. Packt Publishing, 2009.
SystemsIntegration
IST/DEI Pág.2de13
CreatinganXMLSchema1. OpenJDeveloperandusethe“DefaultRole”.2. Createanapplicationandprojectbyfollowingthesesteps:
• Inthemenu,selectFile->New...• IntheCategoriespane,selectGeneral.• ClickonGenericApplicationandontheOKbutton.• In theCreateGeneric Applicationwindow, change theApplicationName to
SIExampleandclickonNext.
• InStep2oftheCreateGenericApplicationwindow,changetheProjectNametoXMLExample.
• Within the Project Technologies tab, click on XML and on the right arrowbutton(i.e,“>”).
i. XMLshouldappearintheSelectedpaneasshownbelow.
SystemsIntegration
IST/DEI Pág.3de13
• ClickonFinish.
3. In the Application Navigator pane, right-click on the XML node and then click onNew...
4. SelecttheAllTechnologiestabwithintheNewGallerywindow.
5. SelectGeneral|XML intheCategoriespaneandclickonXMLSchemas intheItems
pane(asshownbelow).ClickontheOKbutton.
SystemsIntegration
IST/DEI Pág.4de13
6. IntheCreateXMLschemawindow,changetheFileNametoinvoice.xsdandclickOK.• AnXMLschemagetsaddedtotheXMLproject.• In theDesign view, thedifferentcomponentsof theschemaaredisplayed In
theschemavisualeditor(asshownbelow).• IntheSourceview,theschemadocumentsourceislisted.
7. DeletetheexampleElement(right-clickonexampleElemetandclickonDelete).
8. Right-clickonthe<schema>nodeintheDesignview.Select Insert insideschema->
complexType.• The<schema>nodeistherootnodeofeveryXMLschema.
SystemsIntegration
IST/DEI Pág.5de13
• The complexType is an element that contains other elements and/orattributes.
• Componentsmaybe added to anXML schema from theComponentPalettetoo.
9. ChangethenameofthecomplexTypetotaxSubjectTypeinthePropertyInspector.
10. Right-click on the taxSubjectType and select Insert inside complexType -
taxSubjectType->sequence.• The sequence element in a complexType is used to add child elements that
mustappearinthesameorderastheyaredeclared.
SystemsIntegration
IST/DEI Pág.6de13
11. Right-clickonthesequencenodeandselectInsertinsidesequence->element.
12. InthePropertyInspectoroftheelement,changethenametonameandthetypetoxsd:string.
13. Addanotherelementtothesequencenodeandchangethefollowingproperties:• name=address• type=xsd:string
14. Right-click on the taxSubjectType and select Insert inside complexType -taxSubjectType->attributeinordertoaddanattributetothecomplexType.
15. In theProperty Inspector of the attribute, change the name to tax-id, the type to
xsd:integerandtheusetorequired.
SystemsIntegration
IST/DEI Pág.7de13
16. SwitchtotheSourceviewandchangethefollowingxmlnsattributeof<schema>:
• xmlns=”http://example.org”toxmlns:tns=”http://example.org”• Wehaveaddedaprefixtoanamespacethatwillbeusedinthenextstep.
17. Switch back to the Design view and add the following complexType nodes to
<schema>:
• complexType name = totalsType with the following elements within asequence:
i. elementname=valueandtype=xsd:decimalii. elementname=taxandtype=xsd:decimal
• complexTypename=itemTypewiththefollowingelementswithinasequence:i. elementname=valueandtype=xsd:decimalii. elementname=descandtype=xsd:string
• complexType name = itemsType with the following elements within a
sequence:i. element name = item, type = tns:itemType, minOccurs = 0 and
maxOccurs=unbounded
• complexTypename=invoiceTypewiththefollowingattributes:i. attributename=nr,type=xsd:integeranduse=requiredii. attributename=date,type=xsd:dateTimeanduse=required
andthefollowingelementswithinasequence:iii. elementname=sellerandtype=tns:taxSubjectTypeiv. elementname=buyerandtype=tns:taxSubjectTypev. elementname=totalsandtype=tns:totalsTypevi. elementname=itemsandtype=tns:itemsType
18. Finally,addanelementnodeto<schema>withthefollowingproperties:
• name=invoice• type=tns:invoiceType
SystemsIntegration
IST/DEI Pág.8de13
CreatinganXMLinstanceIn this section, we shall create an instance of an XML document that conforms to theschemacreatedinthelastsection(invoice.xsd).19. In the Application Navigator pane, right-click on the XML node and then click on
New...IntheNewGallerywindow(AllTechnologiestab),selectGeneral|XMLintheCategoriespaneandclickonXMLDocumentfromXMLSchemaintheItemspane(asshownbelow).ClickontheOKbutton.
20. Change theXML File to invoice.xml, select the optionUse File System Schema andclickontheBrowse…button.
21. IntheOpenwindow,selectinvoice.xsdandclickontheOpenbutton.22. ClickontheNextbutton.
23. ClickontheNextbutton.
SystemsIntegration
IST/DEI Pág.9de13
24. InStep2of2,clickontheFinishbutton.25. AnXMLinstancehasbeencreated.ValidatetheXMLbyselectingSource->Validate
XMLinthemenu.Arethereanyerrors?Why?
26. WewillnowaddvaluestotheXML.SelectthesellernodeintheStructureviewaddthefollowingvaluesinthePropertyInspector:
• Tax-id=123456789• Name=MaryBenisch• Address=23MainRoadApt3NJ
27. SelectthebuyernodeintheStructureviewaddthefollowingvaluesinthePropertyInspector:
• Tax-id=987654321• Name=JohnSmith• Address=34AbbyRoadApt1NJ
28. Expand the items node in the Structure view, select the item node and add the
followingvaluesinthePropertyInspector:• value=10• desc=Shirt
29. Wewillnowaddanotheritemtoitems intheXMLinstance.Right-clickontheitems
node in the Structure view, click on the Insert inside items -> item and add thefollowingvaluesintheitemwindow:
• value=20• desc=Pants
30. SelectthetotalsnodeandaddthefollowingvaluesinthePropertyInspector:
• value=30• tax=6.9
SystemsIntegration
IST/DEI Pág.10de13
31. Validate theXMLagainby selectingSource ->ValidateXML in themenu.Are there
anyerrors?Why?Fixtheerrors.YourXMLinstanceshouldlooklikethis:
<?xmlversion="1.0"encoding="UTF-8"?><invoicexmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.example.orginvoice.xsd"xmlns="http://www.example.org" nr="11111" date="2015-07-22T11:05:00"><sellertax-id="123456789"><name>MaryBenisch</name><address>23MainRoadApt3NJ</address></seller><buyertax-id="987654321"><name>JohnSmith</name><address>34AbbyRoadApt1NJ</address></buyer><totals><value>30</value><tax>6.9</tax></totals><items><item><value>10</value><desc>shirt</desc></item><item><value>20</value><desc>pants</desc></item></items></invoice>
CreatinganXMLschemavalidatorwithJavaInthissection,wewillcreateaJavaclassforschemavalidationandusetheXMLschema(invoice.xsd)tovalidatetheXMLinstancecreatedintheprevioussection.32. Wewillfirstaddalibraryandjarfiletoourproject.Right-clickXMLintheApplication
NavigatorandselectProjectProperties.33. SelectLibrariesandClasspathandclickontheAddLibrarybutton.34. SelectOracleXMLParserv2andclickontheOKbutton.
SystemsIntegration
IST/DEI Pág.11de13
35. ClickontheAddJar/Directorybutton.36. Selectajarfilecalledxml.jar(/oracle/jdevhome/oracle_common/modules/oracle.xdk
11.1.0/xml.jar).ClickontheSelectbutton.
37. ClickontheOKbutton
38. We will now create a Java classes for schema validation. Select File -> New,
subsequentlyCategories->General->JavaandItems->JavaClassintheNewGallerywindow.ClickontheOKbutton.
39. IntheCreateJavaClasswindow,changetheNametoXMLSchemaValidatorandclick
ontheOKbutton.
SystemsIntegration
IST/DEI Pág.12de13
40. EdittheXMLSchemaValidatorclasswithfollowingcode:packagexml;importjava.io.*;importoracle.xml.schemavalidator.XSDValidator;importoracle.xml.parser.schema.*;importoracle.xml.parser.v2.XMLError;importorg.xml.sax.SAXException;importorg.xml.sax.SAXParseException;importorg.xml.sax.InputSource;importorg.xml.sax.helpers.DefaultHandler;publicclassXMLSchemaValidator{publicXMLSchemaValidator(){super();}//Thisinnerclassdefinesacustomerrorhandler//forhandlingerrorsintheXMLdocument.////TheDefaultHandlerclassimplementstheErrorHandler//interface,whichisthebasicerrorhandlerforSAX//parsing(mostXMLparsing,includingDOMparsing,//isbasedonSAXparsing)privateclassCustomErrorHandlerextendsDefaultHandler{protectedbooleanhasValidationError=false;protectedSAXParseExceptionsaxParseException=null;//overridingmethodsofDefaultHandler//methodsareinvokedwhenavalidationerrorisgeneratedpublicvoiderror(SAXParseExceptionexception){hasValidationError=true;saxParseException=exception;}publicvoidfatalError(SAXParseExceptionexception){hasValidationError=true;saxParseException=exception;}publicvoidwarning(SAXParseExceptionexception){}}//methodforvalidatingXMLDocumentpublicvoidvalidateXMLDocument(InputStreamxmlInput,InputStreamxsdInput){try{//TheXSDValidatorclassisusedtovalidateanXML//documentthathasbeenbuiltintoaDOMtreeXSDValidatorxsdValidator=newXSDValidator();//ThesetSchemamethodisusedtospecifytheschemadocumentXMLSchemaschema=getXMLSchema(xsdInput);xsdValidator.setSchema(schema);//CreatingthecustomerrorhandlerCustomErrorHandlererrorHandler=newCustomErrorHandler();XMLErrorxmlError=newXMLError();xmlError.setErrorHandler(errorHandler);
SystemsIntegration
IST/DEI Pág.13de13
xsdValidator.setError(xmlError);//ValidatingtheXMLDocumentxsdValidator.validate(xmlInput);//Usesthecustomerrorhandlertocheck//ifanerroroccuredif(errorHandler.hasValidationError==true)System.err.println("XMLDocumenthasValidationError:"+errorHandler.saxParseException.getMessage());elseSystem.out.println("XMLDocumentvalidateswithXMLschema");}catch(IOExceptione){System.err.println("IOException"+e.getMessage());}catch(SAXExceptione){System.err.println("SAXException"+e.getMessage());}catch(XSDExceptione){System.err.println("XSDException"+e.getMessage());}}//MethodforcreatinganXMLSchemaobject//(representsaschemadocumentasaDOMtree)publicXMLSchemagetXMLSchema(InputStreamxsdInput){try{XSDBuilderbuilder=newXSDBuilder();InputSourceinputSource=newInputSource(xsdInput);XMLSchemaschema=builder.build(inputSource);returnschema;}catch(XSDExceptione){System.err.println("XSDException"+e.getMessage());}returnnull;}publicstaticvoidmain(String[]argv){try{InputStreamxmlInput=newFileInputStream(newFile("invoice.xml"));InputStreamxsdInput=newFileInputStream(newFile("invoice.xsd"));XMLSchemaValidatorvalidator=newXMLSchemaValidator();validator.validateXMLDocument(xmlInput,xsdInput);}catch(FileNotFoundExceptione){System.err.println("FileNotFoundException"+e.getMessage());}}}
41. In the Application Navigator view, right-click XMLSchemaValidator.java and select
Run.
42. AddanerrorintheXMLdocumentandrunthecodeagain.