Parsing and Application



Hasonló dokumentumok
MVC Java EE Java EE Kliensek JavaBeanek Java EE komponensek Web-alkalmazások Fejlesztői környezet. Java Web technológiák

Hello World Servlet. Készítsünk egy szervletet, amellyel összeadhatunk két számot, és meghívásakor üdvözlőszöveget ír a konzolra.

Széchenyi István Egyetem

Üdvözli Önöket A PGY3 tantárgy! Bakay Árpád dr. NETvisor kft (30) arpad.bakay@netvisor.hu

Bevezető. Servlet alapgondolatok

Using the CW-Net in a user defined IP network

JAVA webes alkalmazások

A WEB programozása - JSP1 dr.gál Tibor őszi félév

XML adatkezelés I. Az SAX szabvány. Dr. Kovács László Miskolci Egyetem Általános Informatikai Tanszék. XML adatok kezelési lehetőségei

JEE tutorial. Zsíros Levente, 2012

Web-fejlesztés NGM_IN002_1

Java Servlet technológia

Web-fejlesztés NGM_IN002_1

Szervlet-JSP együttműködés

Osztott alkalmazások fejlesztési technológiái Áttekintés

Ficsor Lajos Általános Informatikai Tanszék Miskolci Egyetem

Osztott rendszerek, Java EE. Általános bevezető

Adatbázis-kezelés ODBC driverrel

Szoftver-technológia II. Tervezési minták. Irodalom. Szoftver-technológia II.

Java technológiák - ANTAL Margit. komponensek. A HTTP protokoll. Webkonténerek és szervletek. Egyszerű HTTP. ANTAL Margit.

Cloud computing. Cloud computing. Dr. Bakonyi Péter.

Biztonság java web alkalmazásokban

A Java EE 5 plattform

JNDI - alapok. Java Naming and Directory Interface

1. Gyakorlat: Telepítés: Windows Server 2008 R2 Enterprise, Core, Windows 7

Cloud computing Dr. Bakonyi Péter.

Webes alkalmazások fejlesztése 8. előadás. Webszolgáltatások megvalósítása (ASP.NET WebAPI)

Symfony kurzus 2014/2015 I. félév. Controller, Routing

(NGB_TA024_1) MÉRÉSI JEGYZŐKÖNYV

Oracle Containers for Java - j2ee alkalmazás szerver funkciók. Molnár Balázs Oracle Hungary

SAS Enterprise BI Server

JavaServer Pages (JSP) (folytatás)

Create & validate a signature

discosnp demo - Peterlongo Pierre 1 DISCOSNP++: Live demo

Website review acci.hu

MVC desktop alkalmazás esetén. MVC Model-View-Controller. eredete: Model View Controller (MVC) elv Java EE Java alapú Web alkalmazások

SQL/PSM kurzorok rész

A Web réteg architektúrája A JSF web alkalmazás keretrendszer. Bakay Árpád dr. NETvisor kft (30)

4. Gyakorlat: Csoportházirend beállítások

Eseményvezérelt alkalmazások fejlesztése II 12. előadás. Objektumrelációs adatkezelés (ADO.NET) Giachetta Roberto

A J2EE fejlesztési si platform (application. model) 1.4 platform. Ficsor Lajos Általános Informatikai Tanszék Miskolci Egyetem

eseményvezérelt megoldások Vizuális programozás 5. előadás

Stateless Session Bean

SOPHOS simple + secure. A dobozba rejtett biztonság UTM 9. Kókai Gábor - Sophos Advanced Engineer Balogh Viktor - Sophos Architect SOPHOS

Java Web technológiák

EN United in diversity EN A8-0206/419. Amendment

PHP II. WEB technológiák. Tóth Zsolt. Miskolci Egyetem. Tóth Zsolt (Miskolci Egyetem) PHP II / 19

Web Services. (webszolgáltatások): egy osztott alkalmazásfejlesztési plattform

MVC Java EE Java EE Kliensek JavaBeanek Java EE komponensek Web-alkalmazások Fejlesztői környezet

Teszt topológia E1/1 E1/0 SW1 E1/0 E1/0 SW3 SW2. Kuris Ferenc - [HUN] Cisco Blog -

10. Gyakorlat: Alkalmazások publikálása Remote Desktop Szervízen keresztül

XML dokumentumok feldolgozása. DOM, SAX, StAX

USER MANUAL Guest user

ios alkalmazásfejlesztés Koltai Róbert

T Á J É K O Z T A T Ó. A 1108INT számú nyomtatvány a webcímen a Letöltések Nyomtatványkitöltő programok fülön érhető el.

Előszó. Bevezetés. Java objektumok leképzése relációs adatbázisokra OJB-vel Viczián István Viczián István

Enterprise JavaBeans. Ficsor Lajos Általános Informatikai Tanszék Miskolci Egyetem. Az Enterprise JavaBeans

Webfejlesztés alapjai

Java bevezet o Kab odi L aszl o Kab odi L aszl o Java bevezet o

5. rész: A Java EE és az Enterprise Bean réteg. Bakay Árpád dr. NETvisor kft (30)

Enterprise JavaBeans 1.4 platform (EJB 2.0)

Java Server Pages - JSP. Web Technológiák. Java Server Pages - JSP. JSP lapok életciklusa

Correlation & Linear Regression in SPSS

Csatlakozás a BME eduroam hálózatához Setting up the BUTE eduroam network

Rétegezett architektúra HTTP. A hálózatfejlesztés motorját a hálózati alkalmazások képezik. TCP/IP protokoll készlet

Computer Architecture

Cluster Analysis. Potyó László

Mobil webszerverek. Márton Gábor Nokia Research Center. W3C Mobilweb Műhelykonferencia, Budapest október 18.

C#, OOP. Osztályok tervezése C#-ban

Java. Perzisztencia. ANTAL Margit. Java Persistence API. Object Relational Mapping. Perzisztencia. Entity components. ANTAL Margit.

Utasítások. Üzembe helyezés

Collections. Összetett adatstruktúrák

Komponens modellek. 3. Előadás (első fele)

Könnyen bevezethető ITIL alapú megoldások a Novell ZENworks segítségével. Hargitai Zsolt Sales Support Manager Novell Hungary

11. Gyakorlat: Certificate Authority (CA), FTP site-ok

CREATE TABLE student ( id int NOT NULL GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name varchar(100) NOT NULL, address varchar(100) NOT NULL )

Nemzetközi vállalat - a vállalati szoftvermegoldások egyik vezető szállítója

Bánsághi Anna

Modellalkotás UML-ben

Lexington Public Schools 146 Maple Street Lexington, Massachusetts 02420

Angol Középfokú Nyelvvizsgázók Bibliája: Nyelvtani összefoglalás, 30 kidolgozott szóbeli tétel, esszé és minta levelek + rendhagyó igék jelentéssel

Construction of a cube given with its centre and a sideline

Proxer 7 Manager szoftver felhasználói leírás

Perzisztencia. ANTAL Margit. Sapientia - EMTE. ANTAL Margit Java technológiák 11. előadás Perzisztencia

Cashback 2015 Deposit Promotion teljes szabályzat

ENROLLMENT FORM / BEIRATKOZÁSI ADATLAP

Földtani térképek kartografálásának segítése térinformatikai módszerekkel

Mapping Sequencing Reads to a Reference Genome

1. Ismerkedés a Hyper-V-vel, virtuális gépek telepítése és konfigurálása

Elosztott rendszerek: Alapelvek és paradigmák Distributed Systems: Principles and Paradigms

Java Development Alapképzés

Excel vagy Given-When-Then? Vagy mindkettő?

WWW Kliens-szerver Alapfogalmak Technológiák Terv. Web programozás 1 / 31

Java servlet technológia 1 / 40

Szálkezelés. Melyik az a hívás, amelynek megtörténtekor már biztosak lehetünk a deadlock kialakulásában?

4. rész: Java Enterprise Edition bevezetı. Bakay Árpád dr. NETvisor kft (30)

Budapest By Vince Kiado, Klösz György

WCF, Entity Framework, ASP.NET, WPF 1. WCF service-t (adatbázissal Entity Framework) 2. ASP.NET kliens 3. WPF kliens

SIP. Jelzés a telefóniában. Session Initiation Protocol

Java Business Integration szolgáltatásalapú architektúra JavaEE környezetben. Simon Géza Zsemlye Tamás

Átírás:

XML Parsing - SAX 1

Parsing and Application Parsing Well-formed ness checking & Validating Reading Application Manipulating Creating Writing and Sending 2

SAX Historical Background Simple API for XML Started as community-driven project xml-dev mailing list Originally designed as Java API Others (C++, Python, Perl) are now supported SAX 2 Namespaces 3

SAX Features Event-driven You provide event handlers Fast and lightweight Document does not have to be entirely in memory Sequential read access only One-time access Does not support modification of document 4

SAX Operational Model Input Events XML Document Parser Provided Handler 5

SAX Programming Collection of Java interfaces and classes org.xml.sax package Interfaces Parser XMLReader Event handlers ContentHandler 6

SAX Programming Procedures Create XML Parser XMLReader parser = XMLReaderFactory.createXMLReader(); Create Event Handler myhandler handler = new myhandler(); Call Parser and Set Event Handler parser.parse(args[0]); Parse Handling SAX parser calls methods on the event handler Event Handler Processing public void startdocument(){ } System.out.println( XML Document Start ); 7

XMLReader Interface Represents SAX parser SAX2 parser implementation has to implement this interface Methods for Registering event handlers Initiating parsing Configuring features and properties Validation on and off 8

XMLReader Interface public interface XMLReader{ public boolean getfeature (String name) throws SAXNotRecognizedException, SAXNotSupportedException; public void setfeature (String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException; public Object getproperty (String name) throws SAXNotRecognizedException, SAXNotSupportedException; public void setproperty (String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException; public void setentityresolver (EntityResolver resolver); public EntityResolver getentityresolver (); public void setdtdhandler (DTDHandler handler); public DTDHandler getdtdhandler (); public void setcontenthandler (ContentHandler handler); public ContentHandler getcontenthandler (); public void seterrorhandler (ErrorHandler handler); public ErrorHandler geterrorhandler (); public void parse (InputSource input) throws IOException, SAXException; public void parse (String systemid) throws IOException, SAXException; } 9

XMLReader Instance Concrete implementation instance bound to XMLReader interface Has to be created before parsing Gets created by using static method of createxmlreader() method of helper class XMLReaderFactory 10

XMLReader Example XMLReader parser = null; try { // Get SAX parser instance reading org.xml.sax.driver // system property. parser = XMLReaderFactory.createXMLReader(); // Parse the document }catch(saxexception ex){ // Couldn t create XMLReader // either because org.xml.sax.driver system property // was not set or set incorrectly. } 11

Setting Features setfeature(string, boolean) method of XMLReader interface Features General features SAX features DOM features 12

Features General Features http://xml.org/sax/features/validation http://xml.org/sax/features/namespaces http://apache.org/xml/features/validation/schema http://apache.org/xml/features/continue-after-fatal-error SAX Features http://xml.org/sax/features/namespace-prefixes 13

Example XMLReader parser = null; try { // Create an instance of Apache s Crimson SAX parser parser = XMLReaderFactory.createXMLReader(); // Set features parser.setfeature("http://xml.org/sax/features/validation", true); // Parse the document }catch(saxexception ex){ } 14

Parse Methods void parse(string uri) throws SAXException, IOException void parse(inputsource source) throws SAXException, IOException 15

XMLReader parser = null; try { parser = XMLReaderFactory.createXMLReader(); Example // Parse the document parser.parse( http://www.slashdot.org/slashdot.xml ); // Capture SAX events }catch(saxexception ex){ // exception occurs maybe because document // is malformed } 16

XMLReader parser = null; try { parser = XMLReaderFactory.createXMLReader(); Example // Parse the document in File URI form parser.parse( file:/tmp/people.xml ); // Capture SAX events }catch(saxexception ex){ // exception occurs maybe because document // is malformed } 17

InputSource Objects Encapsulates information about an input source as a single object Passed to the XMLReader.parse() method May include the following: Public identifier System identifier A byte stream A character stream 18

Parser Behavior on InputSource If character stream is available, parser will read that stream directly Else if byte stream is available, parser will read byte stream Else open URI connection to resource specified in System identifier 19

SAX Event Handlers Interfaces ContentHandler ErrorHandler DTDHandler EntityResolver Attributes Class DefaultHandler 20

SAX Event Handlers <<interface>> ContentHandler Implements <<interface>> ErrorHandler DefaultHandler <<interface>> DTDHandler <<interface>> EntityResolver 21

ContentHandler Interface public interface ContentHandler{ void startdocument () throws SAXException; void enddocument() throws SAXException; void startelement(string namespace, String name, String qname, Attributes atts) throws SAXException; void endelement(string namespace, String name, String qname) throws SAXException; void characters(char [ ] ch, int start, int length) throws SAXException; void ignorablewhitespace(char [ ]ch, int start, int length) throws SAXException; void processinginstruction(string target, String data) throws SAXException; void setdocumentlocator(locator locator); void startprefixmapping(string prefix, String uri) throws SAXException; void endprefixmapping(string prefix) throws SAXException; void skippedentity(string name) throws SAXException; } 22

Simple SAX Example: Parser XMLReader parser = null; try { // Create XML (non-validating) parser parser = XMLReaderFactory.createXMLReader(); // Create event handler mycontenthandler handler = new mycontenthandler(); parser.setcontenthandler(handler); // Call parsing method parser.parse(args[0]); }catch(saxexception ex){ System.err.println(ex.getMessage()); }catch(exception ex){ System.err.println(ex.getMessage()); } 23

Simple SAX Example: Event Handler class mycontenthandler implements ContentHandler { // ContentHandler methods public void startdocument(){ System.out.println( XML Document START ); } public void enddocument(){ System.out.println( XML Document END ); } public void startelement(string namespace, String name, String qname, Attributes atts){ System.out.println( < + qname + > ); } public void endelement(string namespace, String name, String qname){ System.out.println( </ + qname + >); } public void characters(char[] chars, int start, int length){ System.out.println(new String(chars, start, length); } 24

Character Data Character data void characters(char [ ] ch, int start, int length) throws SAXException Parsers are allowed to break up character data any way desired Character data are in Unicode regardless of encoding scheme specified in XML document 25

White Space White space Nonvalidating parser void characters(char [ ] ch, int start, int length) throws SAXException Validating parser void ignorablewhitespace(char [ ]ch, int start, int length) throws SAXException Ignorable white space includes spaces, tabs and newlines 26

Attributes Interface public interface Attributes{ public abstract int getlength(); public abstract int getindex(string qname); public abstract int getindex(string namespace, String name) public abstract String getlocalname(int index) public abstract String getqname(int index) public abstract String gettype(int index) public abstract String gettype(string qname) public abstract String gettype(string namespace, String name) public abstract String getvalue(string qname) public abstract String getvalue(string namespace, String name) public abstract String getvalue(int index) public abstract String geturi(int index) } 27

Locator Interface Tells application where events occurred public interface Locator{ public int getlinenumber(); public int getcolumnnumber(); public String getpublicid(); public String getsystemid(); } 28

Locator Interface SAX parser passes implementation instance of Locator interface to the ContentHandler.setDocumentLocator() It should be saved to a local reference if the application needs it 29

Locator Example Locator loc; public void setdocumentlocator(locator loc){ this.loc = loc; } public void startelement(string namespace, String name, String qname, Attributes a){ System.out.println(name); System.out.println( line: + loc.getlinenumber()); System.out.println( ID: + loc.getsystemid()); } 30

ErrorHandler Interface public interface ErrorHandler{ void error(saxparserexception e) throws SAXException void fatalerror(saxparseexception e) throws SAXException void warning(saxparseexception e) throws SAXException } 31

DTDHandler Methods Public interface DTDHandler{ void notationdecl(string name, String publicid, String systemid) throws SAXException void unparsedentitydecl(string name, String publicid, String systemid, String notationname) throws SAXException } 32

EntityResolver Interface Public interface EntityResolver{ InputSource resolveentity(string publicid, String systemid) throws SAXException } This method is used to return an InputSource so the content of the external entity can be read An external entity External Parsed Entities Unparsed Entities 33

DefaultHandler Class Helper class Implements ContentHandler ErrorHandler DTDHandler EntityResolver Just subclass and override the methods you are interested in. Completely optional for use 34

JAXP/SAX Code Sample 01 import javax.xml.parsers.*; 02 import org.xml.sax.*; 03 04 SAXParserFactory factory = 05 SAXParserFactory.newInstance(); 06 07 factory.setvalidating(true); 08 SAXParser parser = factory.newsaxparser(); 09 10 // can also parse InputStreams, Files, and 11 // SAX input sources 12 parser.parse("http://foo.com/bar.xml", 13 mysaxeventhandler); 14.. 35

Benefits Of SAX It is very simple It is very fast Useful when custom data structures are needed to model the XML document Can parse files of any size without impacting memory usage Can be used to gather a subset of a document s information 36

Drawbacks Of SAX SAX provides read-only access No random access to documents Searching of documents is not easy 37

DOM (Document Object Model) 38

Historical Background DOM is a standard defined by the W3C, just like XML DOM was not designed specifically for Java technology (unlike SAX) DOM is cross-platform and cross-language Uses OMG s IDL to define interfaces IDL to language binding 39

DOM Characteristics Access XML document as a tree structure Composed of mostly element nodes and text nodes Can walk the tree back and forth Larger memory requirements Fairly heavyweight to load and store Use it when for walking and modifying the tree 40

DOM in Action XML Document Input Parser Creates Tree 41

DOM Tree and Nodes XML document is represented as a tree A tree is made of nodes There are 12 different node types Nodes may contain other nodes (depending on node types) parent node contains child nodes 42

Node Types Document node Document Fragment node Element node Attribute node Text node Comment node Processing instruction node Document type node Entity node Entity reference node CDATA section node Notation node 43

JDOM a DOM API for Java JDOM is an open source API designed to represent an XML document and its contents to the typical Java developer in an intuitive and straightforward way. Java optimized. It behaves like Java, it uses Java collections, and it provides a low-cost entry point for using XML. JDOM users don't need to have tremendous expertise in XML to be productive and get their jobs done. JDOM interoperates well with existing standards such as the Simple API for XML (SAX) and the Document Object Model (DOM). 44

Java EE 45

Alapfogalmak Java = Objektumorientált programozási nyelv Hordozható byte code A byte code-ot futtató virtuális gép (jvm) Standard API-k gyűjteménye A Java platform kiadásai Micro Edition (Java ME) Mobiltelefonok, set-top-box-ok, PDA-k Standard Edition (Java SE) Egy felhasználó elé kerülő desktop alkalmazások fejlesztése Enterprise Edition (Java EE) Vállalati szintű, többrétegű, sokfelhasználós alkalmazások 46

A Java EE platform alapgondolata A platform felelőssége A fejlesztő felelőssége Konkurrencia Biztonság Rendelkezésre állás Skálázhatóság Perzisztencia Tranzakciók Életciklus menedzsment Felügyelet A prezentációs logika Az üzleti logika (A teszt logika) Ismerni a platform nyújtotta összes szolgáltatást :-) 47

Miért Java EE? Szabvány A platformfüggetlen Java SE környezetre épülő API-k és konténerek összessége A gyártók együttműködnek a specifikációk készítésénél és többnyire csak az implementációk minősége, szolgáltatásai terén versenyeznek A sokezer USD/CPU-s terméktől a nyílt forrású Java EE kiszolgálóig széles a termékek palettája A fejlesztők szabadon választhatnak a Java EE szabvány adott verzióját implementáló futtatókörnyezetek között Java EE kompatibilitás Alkalmazás hordozhatóság gyártói platformok között 48

Java EE 5 A Java Standard Edition (leánykorában J2SE) 5-ös változata jelentős nyelvi változásokat hozott a Java világba Generikus típusok (ami nagyon más, mint a C++ template-ek) Annotációk (címkék a kódban, melyek belefordulnak a byte code-ba és dinamikusan felderíthetőek futás közben) Az annotációk segítségével a Java EE fejlesztés jelentősen egyszerűsödik XML alapú deployment descriptor-ok helyett a.java forrásba írt annotációk írják le a fejlesztett komponens és a kiszolgáló által nyújtott konténer közötti kapcsolatot 49

Java EE API-k 50

Gyakran használt Java EE API-k Java Message Service üzenetek küldése/fogadása Java Transaction API JavaMail API e-mail üzenetek kezelése Java API for XML Web Services Java Architecture for XML Binding SOAP with Attachments API J2EE Connector Architecture Java Naming and Directory Interface Java Authentication and Authorization Service 51

Java EE rétegek 52

Java EE konténerek 53

Java EE konténerek Web konténer A HTTP kérések kiszolgálását végző Java EE komponens Feladatkör: webalkalmazások, webszolgáltatások kezelése EJB konténer Az Enterprise JavaBean technológiát alkalmazó komponensek futtatására képes Java EE komponens Feladatkör: üzleti logika, objektum perzisztencia, üzenetküldés, kapcsolódás EIS rendszerekhez Application client container Az alkalmazásszervert elérő, a kliensen futó standalone Java alkalmazások futtatási környezete 54

Konténerek szolgáltatásai Komponensek és erőforrások felderítése JNDI API Komponensek életciklusának menedzselése Alkalmazások, modulok telepítése (deploy), törlése (undeploy) Alkalmazások elindítása, megállítása Egyebek Monitoring (JMX) Naplózás (java.util.logging) 55

Alkalmazáscsomagok Standard könyvtárstruktúrák.ear (enterprise archive).war (web archive).rar (resource archive) Standard és gyártófüggő alkalmazásleírók (deployment descriptor) application.xml web.xml ejb-jar.xml 56

Perzisztencia Egy objektum által tárolt információ elmentése valamilyen háttértárba Sok lehetséges megoldása létezik a problémának Objektumszerializáció XML szerializáció (JAXB) Objektum-relációs leképezés (ORM) Korábbi szabványok (EJB 2.1 Entity Beans, JDO) Open source framework-ök tömkelege (pl Hibernate, Torque) Kereskedelmi szoftverek (pl Toplink) Java EE 5: Java Persistence API Az egyre népszerűbb, open source framework-ök által megcélzott útvonal beemelése a Java EE szabványokba 57

Java Persistence API Könnyebb fejlesztés és deployment az előd EJB Entity API-hoz képest A perzisztálandó objektumok között öröklődési kapcsolat lehet, polimorfizmus megengedett Használható Java EE konténereken kívül is (nem kell hozzá alkalmazásszerver könnyíti a unit testinget is) Az entitások egyszerű, megfelelően annotált Java osztályok 58

Java Persistence API @Entity public class Customer { private Long id; private String name; private Address address; private Collection<Order> orders = new HashSet(); public Customer() {} @Id public Long getid() { return id; } protected void setid (Long id) { this.id = id; } 59

Java Persistence API // Relationship between Customer and Orders @OneToMany public Collection<Order> getorders() { return orders; } public void setorders(collection<order> orders) { this.orders = orders; } 60

Entity használata @Stateless public class OrderEntry { // Dependency injection of Entity Manager for // the given persistence unit @PersistenceContext EntityManager em; public void enterorder(int custid, Order neworder){ // Use find method to locate customer entity Customer c = em.find(customer.class, custid); // Add a new order to the Orders c.getorders().add(neworder); neworder.setcustomer(c); } } 61

A JPA Entity-k életciklusa 62

Az üzleti logika rétege Java EE módon: EJB 3.0 Lightweight módon: A web rétegben egyszerű Java osztályokban Spring A programozó felelőssége ezek életciklusának felügyelete, tranzakciók kezelése, jogosultságvizsgálatok lefolytatása, stb Az Inversion of Control és a Dependency Injection tervezési mintákat implementáló, J2EE környezetben, vagy anélkül is használható keretrendszer XML konfigurációs file-ok alapján konfigurált alkalmazások 63

EJB 3.0 Enterprise JavaBeans Maguk az üzleti logikát implementáló osztályok Két típusa létezik Session Bean-ek (stateless/stateful) Message Driven Bean A konténer gondoskodik az erőforrások eléréséről, a szálkezelésről (az EJB-k thread safe objektumok), az authorizációról, a tranzakciókról (akár XA, two phase commit), stb ennek konfigurációja annotációkkal történik: @MessageDriven(mappedName="jms/Queue") public class SimpleMessageBean implements MessageListener { @Resource private MessageDrivenContext mdc; 64

Session Bean Session Bean interfész Local vagy Remote elérés @Remote public interface Converter { public BigDecimal dollartoyen(bigdecimal dollars); public BigDecimal yentoeuro(bigdecimal yen); } Session Bean osztály POJO, ami az interfészt implementálja @Stateless public class ConverterBean implements Converter { public BigDecimal dollartoyen(bigdecimal dollars) { BigDecimal result = dollars.multiply(yenrate); return result.setscale(2, BigDecimal.ROUND_UP); } 65

A Session Bean-t használó kliens public class ConverterClient { @EJB private static Converter converter; public ConverterClient(String[] args) { } public static void main(string[] args) { } ConverterClient client = new ConverterClient(args); client.doconversion(); public void doconversion() { try { BigDecimal param = new BigDecimal("100.00"); BigDecimal yenamount = converter.dollartoyen(param); 66

Session Bean Egyetlen kliens session-jét reprezentáló objektum Két típusa van: Állapotmentes (Stateless) A bean esetleges attribútumai nem őriződnek meg a kliens két hívása között Az állapotmentesség miatt jobban skálázható a stateless session bean-eket használó alkalmazás Csak állapotmentes session bean lehet webszolgáltatás végpont Állapottal rendelkező (Stateful) Két hívás között, a kliens és a bean közötti kapcsolat lezáródásáig megörződik a bean állapota, attribútumainak értéke Bizonyos körülmények között a konténer kiíhatja az állapotot valamilyen háttértárba (passziválás) 67

Webes keretrendszerek Az alapok: a Servlet API, JSP, MVC Kérés-válasz alapú keretrendszerek Struts Komponens alapú keretrendszerek JSF Wicket 68

Az alapok: a Servlet API, JSP, MVC Web Tier EJB Tier 69

A Servlet Java objektum, ami a servlet keretrendszert és API-t használja és egy HTTP kiszolgáló funkcionalitását bővíti Nagyon sikeres API (gyakorlatilag minden más web framework erre épül) public class HelloServlet extends HttpServlet { } public void doget(httpservletrequest request, HttpServletResponse response){ response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println("<title>hello World!</title>"); }... 70

Servlet életciklus service( ) init( ) Init parameters Ready destroy( ) doget( ) dopost( ) Request parameters 71

Webalkalmazások (.war) struktúrája 72

CGI modell vs Servlet modell CGI Servlet Bármely nyelven írható Nehezen skálázható, felügyelhető Gyakori biztonsági hibák Pazarlóan bánik az erőforrásokkal (fork()) Platform és alkalmazás specifikus Java objektum Erős, megbízható és hatékony Skálázható, újrahasznosítható A Java beépített biztonsági modelljét használja Platformfüggetlen 73

CGI modell vs Servlet modell Request Request CGI1 CGI1 Request Request CGI2 CGI2 Request Request CGI1 CGI1 CGI CGI Based Based Webserver Webserver Child Child for for CGI1 CGI1 Child Child for for CGI2 CGI2 Child Child for for CGI1 CGI1 Request Request Servlet1 Servlet1 Servlet Servlet Based Based Webserver Webserver Request Request Servlet2 Servlet2 Request Servlet1 JVM JVM Servlet1 Servlet1 Servlet2 Servlet2 74

A Servletek tulajdonságai Többszálú végrehajtás egyetlen objektumon Beépített HTTP session kezelés (cookie vagy GET paraméter alapon) Beépített (container managed) authentikáció (basic, form, digest, cert) ContextListener-eken keresztül a kérések, session kezelése több ponton befolyásolható A web container újraindítás nélkül képes a web alkalmazások életciklusát kezelni 75

Objektumok láthatósága Web context (ServletConext) Egyazon webalkalmazásban lévő összes servlet összes kliense eléri (Application scope) Session Egyazon webalkalmazásban lévő összes servlet egyetlen kliense éri el Request Az adott kérést kiszolgáló komponens éri el 76

Java Server Pages Lehetővé teszi a prezentációs logika elválasztását magától a prezentációtól A prezentáció HTML és/vagy XML/XSLT A prezentációs logikát Java osztályok vagy custom tag-ek valósítják meg a prezentáción belül Az eredmény egy fokkal jobban karbantartható, mint ha egy servlet-ből out.println( <html> )-eznénk Minden.jsp oldalból a deployment során valójában egy out.println()-eket tartalmazó servlet generálódik 77

Java Server Pages Egy szöveges file, ami egy dinamikus tartalmat ír le arról, hogy mit is generálunk vissza a böngésző felé <html> Hello World! <br> <jsp:usebean id="clock" class= calendar.jspcalendar /> Today is <ul> <li>day of month: <%= clock.getdayofmonth() %> <li>year: <%= clock.getyear() %> </ul> </html> 78

Servlet vs JSP Servlet JSP HTML Java-ba ágyazva Nehezen karbantartható a statikus tartalom Java kód HTML-be ágyazva Könnyen karbantartható statikus (HTML) tartalom Futás időben servletként fut, viselkedik 79

Servlet, vagy JSP? A gyakorlatban a kettőt együtt használják MVC (Model, View, Controller) architektúra A Controller általában egy Servlet A JSP egy lehetséges technológia a View megvalósítására 80

JSTL Szabványos tag library Alapfunkcionalitást tartalmaz gyakori JSP elemekre Iteráció és feltételes végrehajtás XML kezelés Direkt adatbázis elérés Lokalizáció Java kód nélküli deklaratív prezentációs logika létrehozását teszi lehetővé 81

JSTL példa <c:set var="customertable" scope="application"> <table border="1"> <c:foreach var="customer" items="${customers}"> <tr> <td>${customer.lastname}</td> <td><c:out value="${customer.address}" default="no address specified"/></td> <td> <c:out value="${customer.address}"> <font color="red">no address specified</font> </c:out></td> </tr> </c:foreach> </table> </c:set> 82

Komponens alapú A fő ígéret: framework-ök Kérés-válasz és oldalakban gondolkodó alkalmazások helyett valódi objektumorientált alkalmazások fejlesztése Magasabb fokú újrahasznosítás, jobb programozók:) Gyorsabb fejlesztési ciklus, ugyanakkor kevésbé skálázódó alkalmazások Több megközelítés létezik: Echo2, RIFE, Tapestry, Wicket 83

Web programming in Java 84

Web Application & Components Web Application is a deployable package Web components (Servlets and JSP's) Static resource files such as images Helper classes Libraries Deployment descriptor (web.xml file) Web Application can be represented as A hierarchy of directories and files (unpacked form) or *.WAR file reflecting the same hierarchy (packed form) 85

Web Application Development and Deployment Steps 1.Write (and compile) the Web component code (Servlet or JSP) and helper classes referenced by the web component code 2.Create any static resources (for example, images or HTML pages) 3.Create deployment descriptor (web.xml) 4.Build the Web application (*.war file or deploymentready directory) 5.Deploy the web application into a Web container Web clients are now ready to access them via URL 86

1. Write and compile the Web component code Create development tree structure Write either servlet code or JSP pages along with related helper code Create build.xml for Ant-based build (and other application development life-cycle management) process IDE (i.e. NetBeans) handles all these chores 87

Development Tree Structure Keep Web application source separate from compiled files facilitate iterative development Root directory (example from hello2 sample code from J2EE 1.4 tutorial) build.xml: Ant build file src: Java source of servlets and JavaBeans components web: JSP pages and HTML pages, images 88

Example: hello2 Tree Structure (before ant build command) Hello2 src/servlets GreetingServlet.java ResponseServlet.java web WEB-INF web.xml duke.waving.gif build.xml 89

2. Create any static resources HTML pages Custom pages Login pages Error pages Image files that are used by HTML pages or JSP pages Example: duke.waving.gif 90

3. Create deployment descriptor (web.xml) Deployment descriptor contains deployment time runtime instructions to the Web container URL that the client uses to access the web component Every web application has to have it 91

4. Build the Web application Either *.WAR file or unpacked form of *.WAR file Build process is made of create build directory (if it is not present) and its subdirectories compile Java code into build/web-inf/classes directory Java classes reside under./web-inf/classes directory copy web.xml file into build/web-inf directory copy image files into build directory 92

Example: hello2 Tree Structure (after asant build command) Hello1 src web build.xml build WEB-INF classes GreetingServlet.class ResponseServlet.class web.xml duke.waving.gif 93

5. Deploy Web application Deploy the application over deployment platform such as Tomcat 94

6. Perform Client Access to Web Application From a browser, go to URL of the Web application 95

http://localhost:8080/hello1/greeting 96

Running Web Application 97

Web Application Web application can be deployed in two different forms a *.war file or an unpacked directory laid out in the same format as a *.war file (build directory) Use *.war file when you have to deploy on a remote machine 98

What is *.WAR file? Ready to deploy'able package over web container Similar to *.jar file Contains things to be deployed Web components (servlets or JSP's) Server-side utility classes Static Web presentation content (HTML, image, etc) Client-side classes (applets and utility classes) Reflects contents in build directory 99

Document Root & Context Document Root of the Web application Top-level directory of WAR Contains JSP pages, client-side classes and archives, and static Web resources are stored Also contains WEB-INF directory A context is a name that gets mapped to the document root of a Web application /hello1 is context for hello1 example Distinguishes a Web application in a single Web container Has to be specified as part of client URL 100

Directory Structure of *.WAR file 101

Directory Structure of *.WAR file 102

How to Create *.WAR file? 3 different ways Use IDE (NetBeans) Use ant tool after putting proper build instruction in build.xml file asant create-war (under J2EE 1.4 tutorial) Use jar cvf <filename>.war. command under build directory 103

Example: Creating hello2.war via asant create-war command C:\j2eetutorial14\examples\web\hello2>asant create-war Buildfile: build.xml... create-war: [echo] Creating the WAR... [delete] Deleting: C:\j2eetutorial14\examples\web\hello2\assemble\war\hello2.war [delete] Deleting directory C:\j2eetutorial14\examples\web\hello2\assemble\war\WEB-INF [copy] Copying 1 file to C:\j2eetutorial14\examples\web\hello2\assemble\war\WEB- INF [copy] Copying 2 files to C:\j2eetutorial14\examples\web\hello2\assemble\war\WEB- INF\classes [war] Building war: C:\j2eetutorial14\examples\web\hello2\assemble\war\hello2.war [copy] Copying 1 file to C:\j2eetutorial14\examples\web\hello2 104

Example: Creating hello2.war via jar command C:\j2eetutorial14\examples\web\hello2\build>jar cvf hello2.war. added manifest adding: duke.waving.gif(in = 1305) (out= 1295)(deflated 0%) adding: servlets/(in = 0) (out= 0)(stored 0%) adding: servlets/greetingservlet.class(in = 1680) (out= 887)(deflated 47%) adding: servlets/responseservlet.class(in = 1090) (out= 572)(deflated 47%) C:\j2eetutorial14\examples\web\hello2\build>jar xvf hello2.war created: META-INF/ extracted: META-INF/MANIFEST.MF extracted: duke.waving.gif created: servlets/ extracted: servlets/greetingservlet.class extracted: servlets/responseservlet.class 105

WEB-INF Directory Subdirectory of Document root Contains web.xml : Web application deployment descriptor JSP tag library descriptor files classes : A directory that contains server-side classes: servlets, utility classes, and JavaBeans components lib : A directory that contains JAR archives of libraries (tag libraries and any utility libraries called by serverside classes) 106

HTTP request URL & Web component URL (alias) & Context Request URL: User specified access point of a web resource http://[host]:[port]/[request path]?[query string] [request path] is made of context and web component's URL http://localhost:8080/hello1/greeting?username=monica Context: Name of the root document of a web application Identifies a particular application on that server /hello1 is context 107

Configuring Web Application Configuration information is specified in web.xml (Web Applications Deployment Descriptor) 108

Web Applications Deployment Descriptor (web.xml) Prolog Alias Paths Context and Initialization Parameters Event Listeners Filter Mappings Error Mappings Reference to Environment Entries, Resource environment entries, or Resources 109

Web Applications Deployment Descriptor (web.xml) Case sensitive Order sensitive (in the following order) icon, display-name, description, distributable context-param, filter, filter-mapping listener, servet, servlet-mapping, session-config mime-mapping, welcome-file-list error-page, taglib, resource-env-ref, resource-ref security-constraint, login-config, security-role env-entry, ejb-ref, ejb-local-ref 110

Prolog (of web.xml) Every XML document needs a prolog <?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> 111

Alias Paths (of web.xml) When a request is received by Servlet container, it must determine which Web component in a which web application should handle the request. It does so by mapping the URL path contained in the request to a Web component A URL path contains the context root and alias path http://<host>:8080/context_root/alias_path Alias Path can be in the form of either /alias-string (for servlet) or /*.jsp (for JSP) 112

Alias Paths (of web.xml) <servlet> <servlet-name>greeting</servlet-name> <display-name>greeting</display-name> <description>no description</description> <servlet-class>greetingservlet</servlet-class> </servlet> <servlet> <servlet-name>response</servlet-name> <display-name>response</display-name> <description>no description</description> <servlet-class>responseservlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>greeting</servlet-name> <url-pattern>/greeting</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>response</servlet-name> <url-pattern>/response</url-pattern> </servlet-mapping> 113

Context and Initialization Parameters (of web.xml) Represents application context Can be shared among Web components in a WAR file <web-app>... <context-param> <param-name> javax.servlet.jsp.jstl.fmt.localizationcontext </param-name> <param-value>messages.bookstoremessages</param-value> </context-param>... </web-app> 114

Event Listeners (of web.xml) Receives servlet life-cycle events <listener> <listener-class>listeners.contextlistener</listener-class> </listener> 115

Filter Mappings (of web.xml) Specify which filters are applied to a request, and in what order <filter> <filter-name>orderfilter<filter-name> <filter-class>filters.orderfilter<filter-class> </filter> <filter-mapping> <filter-name>orderfilter</filter-name> <url-pattern>/receipt</url-pattern> </filter-mapping> 116

Error Mappings (of web.xml) Maps status code returled in an HTTP response to a Java programming language exception returled by any Web component and a Web resource <error-page> <exception-type>exception.orderexception</exception-type> <location>/errorpage.html</location> </error-page> 117

References (of web.xml) Need when web components make references to environment entries, resource environment entries, or resources such as databases Example: declare a reference to the data source <resource-ref> <res-ref-name>jdbc/bookdb</res-ref-name> <res-type>javax.sql.datasource</res-type> <res-auth>container</res-auth> </resource-ref> 118

Example web.xml of hello2 <?xml version="1.0" encoding="utf-8"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>hello2</display-name> <servlet> <display-name>greetingservlet</display-name> <servlet-name>greetingservlet</servlet-name> <servlet-class>servlets.greetingservlet</servlet-class> </servlet> <servlet> <display-name>responseservlet</display-name> <servlet-name>responseservlet</servlet-name> <servlet-class>servlets.responseservlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>greetingservlet</servlet-name> <url-pattern>/greeting</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>responseservlet</servlet-name> <url-pattern>/response</url-pattern> </servlet-mapping> </web-app> 119

Servlet Request and Response Model Servlet Container Request Browser HTTP Request Servlet Response Web Server Response 120

What does Servlet Do? Receives client request (mostly in the form of HTTP request) Extract some information from the request Do content generation or business logic process (possibly by accessing database, invoking EJBs, etc) Create and send response to client (mostly in the form of HTTP response) or forward the request to another servlet or JSP page 121

Requests and Responses What is a request? Information that is sent from client to a server Who made the request What user-entered data is sent Which HTTP headers are sent What is a response? Information that is sent to client from a server Text(html, plain) or binary(image) data HTTP headers, cookies, etc 122

HTTP HTTP request contains header a method Get: Input form data is passed as part of URL Post: Input form data is passed within message body Put Header request data 123

HTTP GET and POST The most common client requests HTTP GET & HTTP POST GET requests: User entered information is appended to the URL in a query string Can only send limited amount of data.../servlet/viewcourse?firstname=sang&lastname=shin POST requests: User entered information is sent as data (not appended to URL) Can send any amount of data 124

First Servlet import javax.servlet.*; import javax.servlet.http.*; import java.io.*; Public class HelloServlet extends HttpServlet { public void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println("<title>first Servlet</title>"); out.println("<big>hello Code Camp!</big>"); } } 125

Servlet Interfaces & Classes Servlet GenericServlet HttpSession HttpServlet ServletRequest ServletResponse HttpServletRequest HttpServletResponse 126

Servlet Life-Cycle Is Servlet Loaded? Http request No Load Invoke Http response Yes Servlet Container Run Servlet Client Server 127

Servlet Life Cycle Methods service( ) init( ) Init parameters Ready destroy( ) doget( ) dopost( ) Request parameters 128

Servlet Life Cycle Methods Invoked by container Container controls life cycle of a servlet Defined in javax.servlet.genericservlet class or init() destroy() service() - this is an abstract method javax.servlet.http.httpservlet class doget(), dopost(), doxxx() service() - implementation 129

Servlet Life Cycle Methods init() Invoked once when the servlet is first instantiated Perform any set-up in this method destroy() Setting up a database connection Invoked before servlet instance is removed Perform any clean-up Closing a previously created database connection 130

service() & doget()/dopost() service() methods take generic requests and responses: service(servletrequest request, ServletResponse response) doget() or dopost() take HTTP requests and responses: doget(httpservletrequest request, HttpServletResponse response) dopost(httpservletrequest request, HttpServletResponse response) 131

Example: Sophisticated doget() // Get the identifier of the book to display (Get HTTP parameter) String bookid = request.getparameter("bookid"); if (bookid!= null) { // and the information about the book (Perform business logic) try { BookDetails bd = bookdb.getbookdetails(bookid); Currency c = (Currency)session.getAttribute("currency"); if (c == null) { c = new Currency(); c.setlocale(request.getlocale()); session.setattribute("currency", c); } c.setamount(bd.getprice()); // Print out the information obtained out.println("..."); } catch (BookNotFoundException ex) { response.resetbuffer(); throw new ServletException(ex); } } } out.println("</body></html>"); out.close(); 132

Example: Sophisticated doget() public void doget (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Read session-scope attribute message HttpSession session = request.getsession(true); ResourceBundle messages = (ResourceBundle)session.getAttribute("messages"); // Set headers and buffer size before accessing the Writer response.setcontenttype("text/html"); response.setbuffersize(8192); PrintWriter out = response.getwriter(); // Then write the response (Populate the header part of the response) out.println("<html>" + "<head><title>" + messages.getstring("titlebookdescription") + "</title></head>"); // Get the dispatcher; it gets the banner to the user RequestDispatcher dispatcher = getservletcontext().getrequestdispatcher("/banner"); if (dispatcher!= null) dispatcher.include(request, response); 133

Steps of Populating HTTP Response Fill Response headers Set some properties of the response Buffer size Get an output stream object from the response Write body content to the output stream 134

Example: Simple Response Public class HelloServlet extends HttpServlet { public void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { } } // Fill response headers response.setcontenttype("text/html"); // Set buffer size response.setbuffersize(8192); // Get an output stream object from the response PrintWriter out = response.getwriter(); // Write body content to output stream out.println("<title>first Servlet</title>"); out.println("<big>hello J2EE Programmers! </big>"); 135

Scope Objects Enables sharing information among collaborating web components via attributes maintained in Scope objects Attributes are name/object pairs Attributes maintained in the Scope objects are accessed with getattribute() & setattribute() 4 Scope objects are defined Web context, session, request, page 136

Four Scope Objects: Accessibility Web context (ServletConext) Accessible from Web components within a Web context Session Accessible from Web components handling a request that belongs to the session Request Accessible from Web components handling the request Page Accessible from JSP page that creates the object 137

Four Scope Objects: Class Web context javax.servlet.servletcontext Session javax.servlet.http.httpsession Request subtype of javax.servlet.servletrequest: javax.servlet.http.httpservletrequest Page javax.servlet.jsp.pagecontext 138

Service() Method Server GenericServlet subclass Request Sub c lass o f Ge ne ricse rv le t c lass Service( ) Response Key: Implemented by subclass 139

doget() and dopost() Methods Server HttpServlet subclass Request doget( ) Service( ) Response dopost( ) Key: Implemented by subclass 140

Things You Do in doget() & dopost() Extract client-sent information (HTTP parameter) from HTTP request Set (Save) and get (read) attributes to/from Scope objects Perform some business logic or access database Optionally forward the request to other Web components (Servlet or JSP) Populate HTTP response message and send it to client 141

Example: Simple doget() import javax.servlet.*; import javax.servlet.http.*; import java.io.*; Public class HelloServlet extends HttpServlet { public void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { } } // Just send back a simple HTTP response response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println("<title>first Servlet</title>"); out.println("<big>hello J2EE Programmers! </big>"); 142

Getting around in Javaland 143

IDEs We were using NetBeans IDE during this week Developed by Sun mainly in Prague www.netbeans.org Another common IDE is Eclipse Another open source IDE originally developed by IBM www.eclipse.org IntelliJ IDEA Commercial Java IDE 144

Java resources java.sun.com Java Language Specification Tutorial books: http://java.sun.com/docs/books/jls/ http://java.sun.com/docs/books/javatutorial/tutorial-all.html Tutorials for each standard API http://java.sun.com/docs/books/tutorial/ http://java.sun.com/javaee/5/docs/tutorial/doc/ Bruce Eckel's Thinking in Java book http://www.mindview.net/books/tij/ 145

Java portals http://www.javagrund.hu http://www.javaforum.hu http://www.theserverside.com http://www.infoq.com http://www.java.net 146