1 / 56

Persistenta datelor

Metode/Tehnologii: Fisiere Serializare Baze de date. Probleme: Decuplarea componentelor care fac accesul la date(specifice unei anumite tehnologii) de celelalte parti ale aplicatiei Abstractizarea accesului la date

lel
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. Metode/Tehnologii: Fisiere Serializare Baze de date Probleme: Decuplarea componentelor care fac accesul la date(specifice unei anumite tehnologii) 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) Persistenta datelor • Multe aplicatii doresc sa asigure persistenta datelor

  2. Continutul cursurilor • Tehnologii • XML : • JAXP: Java API for XML Procesing (SAX, DOM) • JAXB: Java Architecture for XML Binding • JDBC: API in Java care permite unui program Java sa interactioneze (query, update) cu baze de date relationale • Pattern for mapping object oriented to relational concepts • OO concepts: aggregation, inheritance, association • Relational model: tables, foreign key references to other tables • Data Acess Patterns: • Modul in care se face accesul la date depinde de • tipul sursei de date: baze de date, fisiere • implementarea concreta a acestui tip de sursa de date • Se doreste decuplarea componentelor care fac accesul la date (puternic dependente de API-ul tehnologiei folosite) de restul componentelor de business • Data Access Object Pattern • Variante (Data mapper, Table data gateway, Active record)

  3. Tehnologii XML pentru Java • JAXP: Java API for XML Procesing (SAX, DOM) • Bibliografie: • Tutorial Sun: http://download.oracle.com/javase/tutorial/jaxp/index.html • JAXB: Java Architecture for XML Binding • Bibliografie: • http://download.oracle.com/javase/6/docs/technotes/guides/xml/jaxb/index.html

  4. 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

  5. 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” />

  6. 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;

  7. 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>

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

  9. 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>

  10. 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>

  11. 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>

  12. 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

  13. 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

  14. 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" />

  15. 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>

  16. 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>

  17. 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)

  18. 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>

  19. 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

  20. Suport pentru prelucrarea XML in Java • JAXP (Java API for XML Processing) • 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).

  21. SAX http://download.oracle.com/javase/tutorial/jaxp/intro/simple.html

  22. 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 { • … • }

  23. 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(); • }

  24. 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;

  25. 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); • } • } • }

  26. Cod Sursa Exemplu1 • Vezi pagina web a cursului: XMLDotsReader.java

  27. 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>

  28. 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)

  29. 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

  30. 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(); • }

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

  32. 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) { • }

  33. Cod Sursa Exemplu2 • Vezi pagina web a cursului: ValidatingXMLDotsReader.java

  34. 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)

  35. DOM http://download.oracle.com/javase/tutorial/jaxp/intro/dom.html

  36. 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

  37. 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.*; • ....

  38. 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) { • }

  39. 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");

  40. 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”);

  41. XSLT API lets you transform XML into other forms A TransformerFactory object is instantiated and used to create a Transformer. The source object is the input to the transformation process. A source object can be created from a SAX reader, from a DOM, or from an input stream. The result object is the result of the transformation process. That object can be a SAX event handler, a DOM, or an output stream. XSLT (The Extensible Stylesheet Language Transformations APIs ) http://download.oracle.com/javase/tutorial/jaxp/xslt/index.html

  42. 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 at this point … • 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) { • }

  43. Cod Sursa Exemplu3 • Vezi pagina web a cursului: XMLDotsDOM.java

  44. 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

  45. Concluzii: SAX vs DOM • SAX: • “de facto standard” elaborat de comunitatea XML-DEV http://www.saxproject.org/ • Parsarea se face “online” pe masura ce se citeste documentul XML • Parsarea se face mai rapid, consuma mai putina memorie • Aplicatia trebuie sa isi construiasca singura modelul de date • Adecvat pentru procesari de tip state-independent, dificil de folosit pentru procesari state-dependent • DOM: • Model standard definit de W3C (model independent de limbaj si platforma) http://www.w3.org/DOM/ • Parsarea construieste intai intregul model al documentului XML in memorie => mai incet, mai multa memorie • Modelul din memorie este mai usor de transformat si salvat din nou ca XML

  46. Concluzii: JAXP • JAXP: Java API for XML processing: • http://download.oracle.com/javase/tutorial/jaxp/index.html • Transpune diferitele modele de referinta existente pentru procesarea XML in API-uri Java • Pentru fiecare model, ofera un API uniform de parsing care constituie o interfata ce trebuie respectata de diferitii furnizori de parsere concrete • Nu impune anumite implementari concrete pentru parsere ! (ParserFactory-urile pot fi configurate cu system property-urile javax.xml.parsers.SAXParserFactory si javax.xml.parsers.DocumentBuilderFactory )

  47. Concluzii: XML: SAX sau DOM sau ... • Alte modalitati pentru XML parsing in Java: • StAX: • Standard JSR 173: Streaming API for XML http://jcp.org/en/jsr/detail?id=173 • Implementat si el in JAXP incepand cu Java 1.4 http://download.oracle.com/javase/tutorial/jaxp/stax/index.html • Este un model event-driven, ca si SAX • Produce output in mod incremental; mod de lucru adecvat si cand sursa de date este dinamica (din retea) • Spre deosebire de SAX (care este de tip push-parsing) StAX este un model de tip pull-parsing • Bidirectional: suporta atat citirea (parsarea) cat si scrierea(generarea) documentelor XML • JDOM: http://jdom.org/ • DOM4J: http://dom4j.sourceforge.net/

  48. Concluzii: XML parsing sau ... • In contextul in care XML e folosit ca modalitate de a asigura persistenta datelor: • Starea obiectelor trebuie salvata respectiv reconstituita din date XML => acest lucru se poate face prin parsarea respectiv generarea XML • Problema: trebuie scris mult cod cu un continut standard => procesul se poate automatiza Class Dots Class Dots instance XML Dots schema XML file complying with Dots Schema

  49. 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 Class Dots Class Dots instance XML Dots schema XML file complying with Dots Schema

  50. JAXB • The Java Architecture for XML Binding (JAXB) • “provides a fast and convenient way to bind between XML schemas and Java representations” • http://download.oracle.com/javase/6/docs/technotes/guides/xml/jaxb/index.html http://www.oracle.com/technetwork/articles/javase/index-140168.html

More Related