1 / 45

Persistenta datelor

Persistenta datelor. Multe aplicatii doresc sa asigure persistenta datelor Metode/Tehnologii: Fisiere Serializare Baze de date Probleme: Decuplarea componentelor care fac accesul la date de celelalte parti ale aplicatiei Abstractizarea accesului la date

feng
Download Presentation

Persistenta datelor

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Persistenta datelor • Multe aplicatii doresc sa asigure persistenta datelor • Metode/Tehnologii: • Fisiere • Serializare • Baze de date • Probleme: • Decuplarea componentelor care fac accesul la date de celelalte parti ale aplicatiei • Abstractizarea accesului la date • Transformarea datelor intre OO domain model si un model de persistenta non-OO (BD relationale, fisiere diferite structuri)

  2. Continutul cursului • Tehnologii • XML • JDBC • Data Acess Patterns • Data Transfer Object • Data Access Object

  3. XML • XML este un standard pentru descrierea structurii documentelor • eXtensible Markup Language • Format text pentru descrierea datelor => simplu de utilizat • Standardizat => exista API-uri care pot fi utilizate pentru a simplifica parsing-ul (sintaxa reprezentarii datelor) • Applicatiile care utilizeaza XML trebuie sa stabileasca doar partea semantica a reprezentarii datelor

  4. XML Tags • Tags • Reprezinta Metainformatii incluse in text • Similare ca forma cu cu HTML tags • Diferenta intre HTML tags si XML tags: HTML tags contin informatii de reprezentare a datelor (ex: <B>), in timp ce XML tags contin informatii de structurare si semantica a datelor • XML tags sunt case-sensitive • Pot contine text sau alte tag-uri • Fiecare trebuie sa aiba un tag de sfarsit: • <tag> </tag> • O pereche de tag-uri fara continut se poate scrie ca si <tag /> • Tag Attributes • Defineste perechi name-value in interiorul unui tag • <dot x=“72” y=“13” />

  5. Caractere speciale • Unele caractere sunt utilizate in tag-uri si descrieri si pentru reprezentarea lor explicita se folosesc secvente: • Exemple: • < se codifica &lt; • > se codifica &gt; • & se codifica &amp; • “ se codifica &quot; • ‘ se codifica &apos;

  6. Organizarea documentelor XML • Un document XML incepe cu o declaratie: <?xml version='1.0' encoding='utf-8'?> • Forma arborescenta: • Exista exact un element radacina • Alte elemente sunt incuibate • Prin element se intelege o secventa cuprinsa intre 2 tag-uri pereche <person> <firstname>Ion</firstname> <lastname>Popescu</lastname> <age>30</age> <ssn>2711130345678</ssn> </person>

  7. Reprezentarea datelor • Dorim sa reprezentam coordonatele unor puncte in plan XML

  8. Stiluri de reprezentare a datelor: Tag-uri sau atribute ? • Dorim sa reprezentam coordonatele unor puncte in plan • Exista 2 metode de structurare si reprezentare: • Utilizand atribute: <dot x=“25" y=“33"> • Utilizand tag-uri incuibate: <dot> <x>25</x> <y>33</y> </dot> • Ce metoda de reprezentare este de preferat? • Atribute: daca datele sunt scurte: • <dot x='65' y=‘23' /> • Tag-uri: daca datele sunt lungi: • <description>Acest program este foarte util tuturor</description> • Tag-uri: daca numarul de atribute ce caracterizeaza un element nu este fix: <polygon> <point> .. </point> <point>..</point> <point>..</point> </polygon>

  9. Exemplu 1: document XML – datele reprezentate in atribute • Dots – un set de puncte in plan, caracterizate de coordonatele (x,y) • Root node: “dots” • Child nodes: “dot”, cu atributele x si y dots.xml <?xml version="1.0" encoding="UTF-8" ?> <dots> <dot x="32" y="100" /> <dot x="17" y="14" /> <dot x="18" y="58" > </dot> </dots>

  10. Exemplu 2: document XML – datele reprezentate in tag-uri incuibate • Points – un set de puncte in plan, caracterizate de coordonatele (x,y) • Root node: “points” • Child nodes: “point”, fiecare avand child nodes “x” si “y” Un document XML trebuie sa fie: Well-formed si Valid points.xml <?xml version="1.0" encoding="UTF-8" ?> -<points> <point> <x>12</x> <y>24</y> </point> <point> <x>22</x> <y>11</y> </point> </points>

  11. Documente XML: Well-formed • "well-formed": un document corect din punctul de vedere al regulilor sintactice generale XML • are exact un element radacina • fiecare element are un tag de sfarsit • elementele sunt incuibate corect • valorile atributelor sunt intre ghilimele

  12. Documente XML: ValideXML Schema • “Valid”: un document care respecta anumite reguli impuse structurii • Metode de specificare formala a structurii unui document (unei clase de documente) XML: • XML DTD (Data Type Definition): • XML Schema (XSD): un limbaj ce impune constrangeri asupra structurii documentelor XML • Pentru o clasa de documente XML, se pot impune reguli privitoare la: • Ce tag-uri sunt permise, in ce ordine pot sa apara, de cate ori, ce atribute pot sa aiba, de ce tipuri, etc. • Parserele XML cu validare verifica respectarea constrangerilor impuse de o schema specificata • XML Schema Tutorial: http://www.w3schools.com/schema/default.asp

  13. Exemplu 1 XML Schema • Pentru reprezentarea unui set de puncte in plan, se stabilesc urmatoarele reguli: • Elementul radacina este dots <xs:element name="dots"> • Acesta poate contine un numar oarecare de elemente de tip dot • Este un tip complex ptr ca contine alte elemente <xs:complexType> • Contine o secventa de alte elemente <xs:sequence> • Fiecare element dot are 2 atribute, x si y, cu valori intregi <xs:attribute name="x" type="xs:integer" />

  14. Exemplu 1 XML Schema dots.xsd <?xml version="1.0"?> <xs:schema xmlns:xs=http://www.w3.org/2001/XMLSchema> <xs:element name="dots"> <xs:complexType> <xs:sequence> <xs:element name="dot" maxOccurs="unbounded"> <xs:complexType> <xs:attribute name="x" type="xs:integer" use="required"/> <xs:attribute name="y" type="xs:integer" use="required"/> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>

  15. Exemplu: document XML cu schema dots.xml <?xml version="1.0" encoding="UTF-8" ?> <dots xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="dots.xsd">> <dot x="32" y="100" /> <dot x="17" y="14" /> <dot x="18" y="58" > </dot> </dots>

  16. Exemplu 2 XML Schema • Pentru reprezentarea unui set de puncte in plan, se stabilesc urmatoarele reguli: • Elementul radacina este points <xs:element name=“points"> • Acesta poate contine un numar oarecare de elemente de tip point • Este un tip complex ptr ca contine alte elemente <xs:complexType> • Contine o secventa de alte elemente point <xs:sequence> • Fiecare element point este de tip complex, fiind o secventa de 2 elemente x si y <xs:element name="x" type="xs:integer" /> • Elementele x si y sunt elemente simple (contine numai text, nu contine alte elemente sau atribute)

  17. Exemplu 2 XML Schema points.xsd <?xml version="1.0" encoding="utf-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="points"> <xs:complexType> <xs:sequence> <xs:element maxOccurs="unbounded" name="point"> <xs:complexType> <xs:sequence> <xs:element name="x" type="xs:integer" /> <xs:element name="y" type="xs:integer" /> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>

  18. Suport pentru editarea XML • Fisierele XML pot fi editate cu orice editor de texte (Notepad, etc) • Este recomandabila utilizarea unui XML Editor care poate ajuta la validarea unui document XML in conformitate cu o schema data si poate impune respectarea structurii permise inca din timpul editarii • XMLSpy • Mediile Integrate de Dezvoltare (IDE) curente contin diverse facilitati pentru lucrul cu XML : • NetBeans • .NET Studio • Eclipse

  19. Suport pentru prelucrarea XML in Java • JAXP (Java API for XML Processing) • http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPIntro.html • Suporta procesarea datelor XML de catre aplicatii scrise in Java • Suport pentru XML parsing: 2 standarde diferite: • SAX (Simple API for XML Parsing): in timpul operatiei de parsing se genereaza evenimente care anunta elementele identificate, este sarcina aplicatiei sa trateze acele evenimente furnizand metodele de callback (pentru a-si construi o structura de date) • DOM (Document Object Model): operatia de parsing construieste in memorie o reprezentare arborescenta a datelor din XML • Suport pentru transformarea documentelor XML: • XSLT (Extensible Stylesheet Language Transformation).

  20. SAX http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPIntro4.html

  21. Citire XML cu SAX • Exemplu: XMLDotReader - citeste date din fisierul dots.xml • // standard imports for SAX • import java.io.*; • import java.util.*; • import javax.xml.parsers.*; • import org.xml.sax.*; • import org.xml.sax.helpers.*; • // Implementing a ContentHandler to handle the SAX events • public class XMLDotReader extends DefaultHandler { • … • }

  22. Construirea parserului SAX • // create an instance of the ContentHandler • DefaultHandler handler= new XMLDotReader(); • SAXParserFactory factory = SAXParserFactory.newInstance(); • try { • // use the default non-validating parser • SAXParser saxParser = factory.newSAXParser(); • saxParser.parse(new File(“dots.xml”), handler); • } catch (Exception ex) { • ex.printStackTrace(); • }

  23. Tipuri de evenimente • public void startDocument() throws SAXException ; • public void endDocument() throws SAXException ; • // Called at start of each element • public void startElement(String namespaceURI, String localName, • String qName, Attributes atts) throws SAXException ; • // Called at the end of each element • public void endElement(java.lang.String uri, java.lang.String localName, java.lang.String qName) throws SAXException; • // Called for characters between nodes. • public void characters(char buf[], int offset, int len) throws SAXException;

  24. Tratarea evenimentelor • public class XMLDotReader extends DefaultHandler { • … • public void startElement(String namespaceURI, String localName, • String qName, Attributes atts) throws SAXException { • System.out.println("start element:" + qName); • if (qName.equals("dot")) { • x = Integer.parseInt(atts.getValue("x")); • y = Integer.parseInt(atts.getValue("y")); • System.out.println(x + ", " + y); • } • } • }

  25. Cod Sursa Exemplu1 • Vezi pagina web: XMLDotsReader.java

  26. Rezultatele rularii startDocument start element:dots start element:dot dot: 32, 100 end element:dot start element:dot dot: 17, 14 end element:dot start element:dot dot: 18, 58 end element:dot end element:dots endDocument dots.xml <?xml version="1.0" encoding="UTF-8" ?> <dots> <dot x="32" y="100" /> <dot x="17" y="14" /> <dot x="18" y="58" > </dot> </dots>

  27. Rezultatele rularii • Daca se modifica dots.xml astfel incat sa nu mai fie well-formed (lipseste inchiderea la al 2-lea tag dot) startDocument start element:dots start element:dot dot: 32, 100 end element:dot start element:dot dot: 17, 14 start element:dot dot: 18, 58 end element:dot org.xml.sax.SAXParseException: The end-tag for element type "dot" must end with a '>' delimiter. at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAX ParseException(Unknown Source)

  28. Rezultatele rularii • Daca se modifica fisierul dots.xml astfel incat sa contina si alte nume de tag-uri (se inlocuieste al doilea tag dot cu dotu), nemaifiind conform cu schema startDocument start element:dots start element:dot dot: 32, 100 end element:dot start element:dotu end element:dotu start element:dot dot: 18, 58 end element:dot end element:dots endDocument

  29. Parser cu validare • public class ValidatingXMLDotReader extends DefaultHandler { • // changes to create a validating parser • Static final String JAXP_SCHEMA_LANGUAGE= "http://java.sun.com/xml/jaxp/properties/schemaLanguage"; • static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema"; • SAXParserFactory factory = SAXParserFactory.newInstance(); • try { • factory.setValidating(true); • factory.setNamespaceAware(true); • SAXParser saxParser = factory.newSAXParser(); • saxParser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA); • saxParser.parse(new File(“dots.xml”), handler); • } catch (Exception ex) { • ex.printStackTrace(); • }

  30. Parser cu validare – evenimentul error • public void error(SAXParseException e) • throws SAXParseException • { • throw e; • }

  31. Exceptii SAX – tratare in detaliu • try { • … • }catch (SAXParseException spe) { • // Error generated by the parser • System.out.println(“Parsing Error: line ”+spe.getLineNumber()+” , ”+spe.getMessage()); • } catch (SAXException sxe) { • // Error generated by application or parser initialization • } catch (ParserConfigurationException pce) { • // parser with specified options cann’t be built • }catch (IOException ioe) { • }catch (Throwable t) { • }

  32. Cod Sursa Exemplu2 • Vezi pagina web: ValidatingXMLDotsReader.java

  33. Rezultatele rularii • Se ruleaza ValidatingXMLDotReader pe varianta modifica fisierul dots.xml care contine si alte nume de tag-uri (se inlocuieste al doilea tag dot cu dotu), nemaifiind conform cu schema startDocument start element:dots start element:dot 32, 100 end element:dot ** Parsing error, line 5, uri file:/C:/Documents%20and%20Settings/user/Desktop/x ml-marti/dots.xml cvc-complex-type.2.4.a: Invalid content was found starting with element 'dotu '. One of '{dot}' is expected. org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid content was found starting with element 'dotu'. One of '{dot}' is expected. at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAX ParseException(Unknown Source) at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(Unk nown Source)

  34. DOM http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPIntro5.html

  35. Element Node • Un element/nod corespunde unei sectiuni cuprinsa intre <tag>… </tag> • Un nod poate contine alte noduri child • Un nod poate avea atribute cu valori • Exista un nod radacina a documentului

  36. Citirea unui XML Document in DOM • // Standard imports for XML • import javax.xml.parsers.*; • import org.xml.sax.*; • import org.xml.sax.helpers.*; • import org.w3c.dom.*; • ....

  37. Construirea parserului XML DOM • DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); • try { • DocumentBuilder db = dbf.newDocumentBuilder(); • // Gets default non-validating parser • // Parse the XML to build the whole doc tree • Document doc = db.parse(new File(“dots.xml”)); • } catch (SAXParseException spe) { // Error handling code the same as with SAX • } catch (SAXException sxe) { • } catch (ParserConfigurationException pce) { • } catch (IOException ioe) { • } catch (Throwable t) { • }

  38. Traversarea DOM • // Get root node of document • Element root = doc.getDocumentElement(); • // Get list of children of given tag name • NodeList list = root.getElementsByTagName(“dot"); • // Number of children in list • int len = list.getLength(); • // Get nth child • Element elem = (Element) list.item(n); • // Get an attribute out of a element • // (returns "" if there is no such attribute) • String s = elem.getAttribute(“x");

  39. Modificarea DOM in memorie • // Create a new node (still needs to be added) • Element elem = document.createElement(“dot"); • // Append a child node to an existing node • node.appendChild(elem); • // Set an attribute/value binding in a node. • elem.setAttribute(“x”, “12”);

  40. XSLT http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPIntro6.html

  41. Scrierea DOM din memorie in XML • import javax.xml.transform.*; • import javax.xml.transform.dom.*; • import javax.xml.transform.stream.*; • // Document doc exists already in memory • try { • TransformerFactory tranFact = TransformerFactory.newInstance( ); • Transformer tran = tranFact.newTransformer( ); • DOMSource DSource = new DOMSource(doc); • StreamResult SResult = new StreamResult(new FileOutputStream(“copie.xml”)); • tran.transform(DSource, SResult); • } catch (TransformerConfigurationException tce) { • } catch (TransformerException te) { • }

  42. Cod Sursa Exemplu3 • Vezi pagina web: XMLDotsDOM.java

  43. Concluzii: XML: Avantaje si dezavantaje • Format standard • Similar fisierelor text – editabil manual, citibil direct • Big and Slow: • Reprezentarea datelor in format text ocupa foarte mult spatiu ! • Adecvat pentru reprezentarea datelor din fisiere de configurare, sau ca format de transport al datelor • NU este adecvat pentru reprezentarea continutului unei ”baze de date” de mari dimensiuni

  44. Concluzii: XML: SAX sau DOM sau ... • SAX: • mai rapid, consuma mai putina memorie • Aplicatia trebuie sa isi construiasca singura modelul de date • DOM: • construieste intai intregul model in memorie • Modelul este mai usor de transformat si salvat din nou ca XML • … Sau utilizand tool-uri care automatizeaza XML data binding: • XML data binding: procesul de reprezentare a informatiilor dintr-un document XML ca obiect in memorie • Tool-uri/API-uri care automatizeaza procesul de XML data binding: creaza automat mapari intre elementele dintr-o schema XML si campurile unei clase • Exemplu: JAXB

  45. JAXB • The Java Architecture for XML Binding (JAXB) • “provides a fast and convenient way to bind between XML schemas and Java representations” http://java.sun.com/javaee/5/docs/tutorial/doc/bnazf.html

More Related