Вы находитесь на странице: 1из 640

.

Java EE 7
. , . , . , .





32.973.2-018.1

.
.
.
.
.
.

004.43

65

Java EE 7. .: , 2014. 640 .: .

ISBN 978-5-496-00942-3
Java Enterprise Edition (Java EE) Java.
,
Java EE 7.
. GlassFish,
.
Java EE, Java Community Process (JCP).
, Java .
Java EE; API EJB JPA -, - ,
, ; API -,
JSF, Facelet Expression Language; - SOAP RESTful,
, Java EE; ,
Java-.

12+ ( 29 2010 . 436-.)


ISBN 978-1430246268 .
ISBN 978-5-496-00942-3

Copyright 2013 by Antonio Goncalves


, 2014
,
, 2014

Apress. .
.
, , , . , , ,
.

, 192102, -, . (. ), . 3, , . 7.
005-93, 2; 95 3005 .
23.05.14. 70100/16. . . . 51,600. 1000. 0000.

. 180004, , . , 34.


................................................................................................................. 15
....................................................................................................................... 16
............................................................................................ 17
.............................................................................................................. 18
....................................................................................................................... 19
.............................................................................................................. 20
................................................................................................ 21
.............................................................................................................. 21
.............................................................................................................. 21
1. Java EE7.................................................................................... 22
Java EE.......................................................................................................... 22
.............................................................................................................. 23
.............................................................................................................. 24
.............................................................................................................. 25
................................................................................................................... 26
.................................................................................................. 27
................................................................................................................... 28
................................................................ 30
................................................................................................................ 32
JCP........................................................................................................................... 33
......................................................................................................... 33
...................................................................................... 34
Java Standard Edition7..................................................................................................... 35
................................................................................................. 36
............................................................................................... 36
try-with-resources.................................................................................. 37
Multicatch-.............................................................................................. 38
NIO.2......................................................................................................................... 38
Java EE.......................................................................................... 39
Java EE........................................................................................... 39
................................................................................................................ 41
Java EE7........................................................................................... 42
-7.................................................................................. 45
CD-BookStore.............................................................................................. 46
........................................................................................................................... 47
2. ................................................................. 49
...................................................................................................... 49
......................................................................................... 50
................................................................................ 51
................................................................................. 52
................................................................................................................... 52
................................................................. 53
...................................................................................... 53
CDI........................................................................................... 54
CDI.......................................................................... 54

CDI 1.1.................................................................................................. 55
................................................................................................. 55
CDI............................................................................................... 55
CDI................................................................. 56
......................................................................................... 56
........................................................................................................... 64
............................................................................................. 65
............................................................................................................. 68
.................................................................................................. 69
............................................................................... 73
.................................................................................................................. 73
................................................................................. 74
............................................................................................... 76
................................................................................. 78
................................................................. 80
.................................................................................... 80
.............................................................. 82
..................................................................................................................... 83
.......................................................................................................................... 84
...................................................................................................................... 87
Book BookService..................................................................... 88
NumberGenerator........................................................................ 89
...................................................................................... 90
....................................................................... 90
Main............................................................................................. 91
CDI beans.xml.................................................................... 92
Maven........................................................... 92
Main................................................................................................... 94
BookServiceIT............................................................................... 94
beans.xml .
.......................................................................... 95
.................................................................................. 95
........................................................................................................................... 96
3. ................................................................................... 97
............................................................................ 97
.............................................................................................................. 98
.............................................................................................................. 99
...................................................................................................................... 99
............................................................................................ 100
.............................................................. 100
............................................................... 101
Bean Validation1.1.................................................. 101
.......................................................................................... 102
................................................................................................ 102
.................................................................... 103
........................................................................................ 106
................................................................. 107
............................................................................................................. 115
ConstraintValidator.................................................................................... 117
.................................................................................................................... 119
.................................................................................. 120
................................................................................................ 121
API................................................................................................ 122
......................................................................................... 125

7
................................................................................................. 126
............................................................................................... 126
................................................................................................ 127
..................................................................................................... 127
.................................................................................................................... 128
Customer............................................................................ 130
Address.............................................................................. 130
@Email.............................................................................. 131
@ZipCode.......................................................................... 131
CustomerIT AddressIT..................................... 133
Maven...................................................................... 134
......................................................................................................................... 136
4. Java Persistence API......................................................................................... 137
....................................................................................................... 138
................................................................................................ 139
- ..................................................................... 140
........................................................................ 143
......................................................................................... 146
....................................................... 146
Bean Validation................................................................................... 148
JPA.............................................................................................. 148
JPA............................................................................................... 149
JPA2.1................................................................................................ 150
............................................................................................ 150
.................................................................................................................... 151
Book...................................................................................... 152
Main........................................................................................... 152
BookIT.............................................................. 153
....................................................................... 155
SQL- ....................................................... 156
Maven........................................... 157
Main Maven................................................. 160
.......................................................................... 161
......................................................................................................................... 162
5. - ............................................................. 163
......................................................................................... 163
.................................................................................................................. 164
.................................................................................................... 166
................................................................................................................ 171
............................................................................................................. 177
....................................................................................... 180
................................................................................... 181
XML............................................................................ 183
................................................................................................. 186
..................................................................................................... 189
........................................................................ 191
....................................................................................... 192
...................................................................................................... 203
............................................................................................. 205
.......................................................................................... 208
........................................................................................ 208
.................................................................. 217
......................................................................................................................... 221

6. .............................................................. 222
.................................................................................................... 223
........................................................................... 225
............................................................................................. 227
............................................................................... 230
JPQL.............................................................................................................................. 240
SELECT................................................................................................................... 242
FROM...................................................................................................................... 244
WHERE.................................................................................................................... 244
ORDER BY............................................................................................................... 245
GROUP BY HAVING................................................................................................ 246
................................................................................................ 246
............................................................................................ 247
........................................................................................................................ 247
.......................................................................................... 250
............................................................................................ 252
Criteria API ( - )............................................ 254
.................................................................................................. 257
........................................................................... 258
Cache API...................................................................................................................... 261
.................................................................................................... 264
..................................................................................................... 266
................................................................................. 267
............................................................................... 269
............................................................................................ 270
.......................................................................................................... 272
.................................................................................................................... 275
......................................................................................................................... 279
7. EJB-.................................................................... 281
EJB-.................................................................... 282
EJB-........................................................................................... 283
........................................................................... 284
, .................................................................. 285
EJB Lite................................................................................................................... 286
EJB............................................................................................. 287
EJB....................................................................... 288
EJB3.2................................................................................................ 289
............................................................................................ 290
EJB-................................................................ 290
EJB-...................................................................................... 291
EJB-............................................................................................ 292
, ..... 292
-.......................................................................................... 295
JNDI-.......................................................................................... 296
EJB- ........................................................... 297
EJB- ............................................................ 301
EJB-................................................................................... 304
................................................................................... 306
EJB- ............................................. 306
.................................................................................................... 307
, .................................................. 308
, EJB-.......................................... 309
.............. 310

9
.............................................................................................. 311
API- SessionContext................................................................................ 312
.............................................................................................. 313
.................................................................................... 315
................................................................................... 317
................................................................................................................. 318
EJB-............................................................................. 319
EJB-....................................................................... 321
....................................................................... 321
CDI.................................................................................. 322
JNDI................................................................................ 323
......................................................................................................................... 324
8. , ........................... 325
..................................................................... 325
, , ................................................. 326
, ................................................................................ 327
............................................................................................. 329
............................................................................................................ 332
............................................................................ 333
.......................................................................... 335
............................................................................ 336
.................................................................................................................. 338
................................................................................... 338
..................................................................................... 341
.................................................................................................................... 343
Entity..................................................................................... 343
BookEJB, ............ 345
CDI DatabaseProducer............................................................................ 346
BookEJB.................................................................................... 347
DatabasePopulator ............................. 348
BookEJBIT......................................................... 349
, Maven....................................... 351
GlassFish.................................................................................... 353
Main........................................................................................... 353
......................................................................................................................... 354
9. ..................................................................................................... 355
................................................................................................. 355
ACID.......................................................................................................... 356
................................................................................................ 356
.................................................................................. 357
JTA...................................................................................... 357
XA........................................................................... 358
......................................................... 360
JTA............................................................................................... 361
1.2 JTA.................................................................................... 361
............................................................................................. 362
EJB........................................................................................ 362
CMT ....................................................................... 366
............................................................................................. 367
Managed Beans...................................................................... 371
......................................................................................................................... 373

10

10. JavaServer Faces........................................................................................... 374


-................................................................................................ 374
HTML...................................................................................................................... 375
XHTML.................................................................................................................... 377
CSS......................................................................................................................... 378
DOM....................................................................................................................... 381
JavaScript................................................................................................................ 381
JSF.............................................................................................................. 384
FacesServlet............................................................................................................ 385
......................................................................................... 385
Facelets................................................................................................................... 387
.......................................................................................................... 387
............................................................................. 387
- ........................................................................ 388
..................................................................................................... 389
AJAX..................................................................................................... 390
JSF.............................................................................................. 390
-......................................................................... 390
JSF............................................................................................... 391
JSF2.2................................................................................................ 392
........................................................................................... 393
JSF- .......................................................................... 393
JSF......................................................................................... 393
............................................................................................................... 395
Body....................................................................................................................... 395
..................................................................................................... 398
JSF..................................................................................... 400
HTML- JSF.................................................................................................. 400
................................................................................................................. 401
....................................................................................................................... 402
.................................................................................................. 402
................................................................................................ 403
............................................................................................... 404
.................................................................................................................. 406
...................................................................................................... 406
.......................................................................................... 407
.................................................................................................................... 408
................................................................................................... 409
JSF........................................................................................................ 409
JSF........................................................................................................ 410
JSTL....................................................................................................................... 412
................................................................................................ 413
..................................................................................... 414
.................................................................................................. 416
.......................................................................................................... 417
................................................................................................. 419
......................................................................................................................... 424
11. ................................................................................. 425
MVC................................................................................................................. 425
FacesServlet............................................................................................................ 426
FacesContext........................................................................................................... 429
Faces-config.xml...................................................................................................... 430
-................................................................................. 431

11

-................................................................................. 432
......................................................................................................... 434
....................................... 435
...................................................................... 436
JSF EJB.......................................................................................... 439
..................................................................................................................... 439
..................................................................................................... 440
................................................................................................. 441
.................................................................................... 443
......................................................................................... 444
................................................................................................... 445
....................................................................... 447
............................................................................................................ 449
............................................................................... 450
Bean Validation................................................................................... 451
AJAX.............................................................................................................................. 451
....................................................................................................... 452
JSF..................................................................................................... 453
.................................................................................................................... 455
Book...................................................................................... 457
BookEJB................................................................................................ 458
- BookController.................................................... 458
layout.xhtml............................................................................. 459
newBook.xhtml....................................................................... 460
viewBook.xhtml....................................................................... 462
Maven.............................................................. 463
GlassFish.................................................................................... 464
...................................................................................................... 465
......................................................................................................................... 466
12. XML JSON................................................................................. 467
XML........................................................................................... 467
XML-......................................................................................................... 468
XML.............................................................................................. 469
SAX DOM....................................................................................... 472
DOM....................................................................................................................... 472
SAX......................................................................................................................... 472
XPath................................................................. 473
XSLT........................................................................... 473
XML............................................................................................. 475
XML-...................................................................... 475
XML Java...................................................................................... 476
............................................................................................. 477
Java XML............................................................................ 477
JAXP......................................................................................... 478
JAXP SAX.............................................................................................................. 479
JAXP DOM............................................................................................................ 482
JAXP XSLT............................................................................................................. 483
Java XML.......................................................................... 484
............................................................................................................ 486
.............................................................................................................. 487
JSON........................................................................................... 490
JSON........................................................................................... 492
JSON-P................................................................................................................... 493
................................................................................................ 493

12

JSON........................................................................................................... 493
JSON................................................................................................... 494
JSON........................................................................................................... 495
JSON...................................................................................................... 497
.................................................................................................................... 498
CreditCard.................................................................................. 499
CreditCardXMLTest........................................................................ 499
CreditCardJSonTest....................................................................... 500
......................................................................................................................... 501
13. .................................................................................... 502
............................................................... 502
...................................................................................................... 504
-............................................................................................. 505
.................................................................................. 506
, ............................................................... 506
................................................................. 507
.................................................................. 507
JMS 2.0............................................................................................... 508
EJB 3.2................................................................................................ 508
............................................................................................. 508
Java Messaging Service API............................................................................................ 509
API.................................................................................................... 510
ConnectionFactory................................................................................................... 510
................................................................................................... 511
............................................................................................................ 511
...................................................................................................................... 512
............................................................................................................. 512
............................................................................................................... 512
................................................................................................................ 514
...................................................................................................... 514
API.................................. 514
API..................................................................................................... 516
JMSContext............................................................................................................. 517
JMSProducer........................................................................................................... 519
JMSConsumer......................................................................................................... 519
........................................................................ 520
.............................................................. 520
......................................................... 521
CDI................................ 522
............................................................................ 523
.............................................................................................. 523
............................................................................................ 525
................................................................................................ 526
.......................................................................................... 527
.................................. 527
............................................................................... 528
................................................................................. 528
............................................................................. 529
..................................................................................... 529
, ................................................... 529
MDB....................................................................................................... 530
@MessageDriven..................................................................................................... 531
@ActivationConfigProperty........................................................................................ 532
....................................................................................... 533

13

MDB......................................................................................................... 533
....................................... 534
MDB .............................................................................................. 535
MDB ....................................................................... 535
............................................................................................................. 536
........................................................................................... 537
.................................................................................................................... 538
OrderDTO................................................................................... 538
OrderProducer............................................................................ 539
OrderConsumer...................................................................................... 540
ExpensiveOrderMDB................................................................... 540
Maven.............................................................. 541
.................................................................. 542
MDB GlassFish............................................................................ 543
............................................................................................. 543
......................................................................................................................... 544
14. - SOAP......................................................................................... 545
- SOAP...................................................................... 546
XML......................................................................................................................... 547
WSDL...................................................................................................................... 547
SOAP...................................................................................................................... 550
UDDI....................................................................................................................... 551
.......................................................................................... 552
- SOAP.......................................................................... 552
- SOAP................................................... 552
, - SOAP................................................... 553
JAX-WS 2.2a............................................................................................................ 554
Web Services1.3...................................................................................................... 554
WS-Metadata 2.3..................................................................................................... 555
- SOAP.......................................................... 555
............................................................................................. 555
- SOAP............................................................................................ 555
- SOAP................................................................................... 557
- SOAP............................................................................ 558
WSDL........................................................................................... 558
@WebService........................................................................................................... 559
@WebMethod.......................................................................................................... 560
@WebResult............................................................................................................ 561
@WebParam............................................................................................................ 562
@OneWay................................................................................................................ 562
@SoapBinding......................................................................................................... 562
....................................................................... 564
........................................................................................... 567
........................................................ 570
WebServiceContext.................................................................................................. 570
.................................................................................... 571
................................................................................................................. 572
- SOAP.................................................................................. 572
- SOAP................................................................................................. 573
SOAP.................................................................................. 574
............................................................................................... 574
.................................................................................. 575
CDI............................................................................................. 576
.................................................................................................................... 577

14

CreditCard.................................................................................. 577
- SOAP CardValidator............................................................. 579
CardValidatorTest....................................................... 579
CardValidatorIT.................................................. 580
, Maven....................................... 581
GlassFish.................................................................................... 583
WebServiceConsumer................................................................. 584
Maven........................... 585
WebServiceConsumer....................................................................... 588
......................................................................................................................... 588
15. - REST............................................................................. 589
- RESTful..................................................................................... 590
................................................................................... 590
URI......................................................................................................... 590
....................................................................................................... 592
......................................................................................................... 592
............................................................................................................... 593
.................................................................................... 594
.......................................................................... 594
HTTP....................................................................................................................... 595
-........................................................................................... 602
WADL...................................................................................................................... 602
- ...................... 603
REST............................................................................................. 603
API Java - ............................... 604
JAX-RS2.0.......................................................................................... 604
.......................................................................................... 605
- ....................................... 605
- ............................... 606
CRUD - REST................................ 606
URI URI ........................................................................ 608
......................................................................................... 609
...................................................... 611
............................................................................................... 613
HTTP-................................................................................ 615
....................................................................................... 617
............................................................................................... 619
........................................................................................... 621
...................................................................... 623
................................................................................................................. 623
- REST...................................................................................... 624
API....................................................................................................... 624
REST.................................................................................. 627
.................................................................................................................... 628
Book...................................................................................... 628
JAXB- Books........................................................................ 629
BookRestService........................................................................ 630
JAX-RS..................................................................................... 634
Maven.............................................................. 635
GlassFish...................................................................................... 637
WADL...................................................................................................................... 637
BookRestServiceIT............................................. 638
......................................................................................................................... 639


Java EE7 . API Java , (CDI)

. Java EE7 , WebSocket, JSON,
Batch Concurrency, . , .
Java EE7.
Java
( Enterprise JavaBeans3.2).
, . Java Community Process (JCP),
.
Java; , JavaEE .
Devoxx France. ,
Java EE5 ,
Java EE6 GlassFish3
(Beginning Java EE 6 Platform with GlassFish 3). .
, . GlassFish,
, Java EE7.
GitHub. ,
, .
,
Java EE GlassFish


. Java-
1990-,
,
Java EE. BEA, ,
WebLogic, JBoss , , GlassFish.

(OSSGTP).
Java, Devoxx France.
Java EE5 2007.
JCP,
Java (Java EE6, JPA 2.0 EJB3.1), Java
EE6 (Beginning JavaEE6) Apress. JCP,
2010 Java EE7 EJB3.2.

Java EE , JavaOne, Devoxx, GeeCon,
The Server Side Symposium, Jazoon, Java.
IT-
(DevX) (Programmez, Linux Magazine). C2009
Java- Les Cast Codeurs.
Java- Java-.
( ), (
- )
- (
).
(@agoncal)
(www.antoniogoncalves.org).



, .
PCIQSA
IT-
IBM ,
IT-, . IBM (FIDTL). IT-:
ITIL (Information Technology Infrastructure Library),
Open Group Master Certified IT Architect Payment
Card Industry (PCI) Qualified Security Assessor (QSA).
, .
19 , IT-,
- , , -,
, .
( ).

, - .
,
, , -,
.. (PKI, SIP,
SAML Proxy areas).
, .


Java EE. ,
,
, (
). .
, Apress
. , , .
, .
,
. ;
-, Java .
,
Java-. ,
. ,
Java, Java, Mac- ,
CDI 1.1 CDI
OSGi. -, -
Red Hat Agorava,
CDI.
.
, 12 XML JSON.
, .
Java EE , .
,
.
, , Visual Paradigm.
Visual Paradigm JetBrains .
.
.
Java: , , , , , , ,
Java EE.
, , ,
, .
, .


, -, ,
,
-. ,
. ,
.
Java Enterprise Edition 1990-
Java .
J2EE, ,
, , , . Java EE .
, - , EJB , , . Enterprise Java Beans , Java
EE7. , , Java EE, ,
. JavaEE, :
,
.

Java EE.
. ,
, JPA, CDI, (Bean Validation),
EJB, JSF, JMS, SOAP - - (RESTful). Java
EE. , Java EE7
(GlassFish, EclipseLink, Weld, Hibernate Validator, Mojarra, OpenMQ, Metro Jersey)
.
,
. Java EE7
30
(CDI 1.1, Bean Validation 1.1, EJB 3.2, JPA 2.1), - (Servlet 3.1, JSF 2.2,
Expression Language 3.0) (JAX-WS 2.3 JAX-RS 2.0).
Java EE7 JDK1.7 ,
GlassFish, Derby, JUnit Maven.
UML-, Java- .

20


Java EE7 .
.

1 Java EE7,
. 2 (Context Dependency
Injection 1.1), 3 (Bean Validation 1.1).
46 JPA 2.1.
4 5 -
( , ), 6 , , , .
- Java EE7 EJB. 79 .
7 - EJB
. 8 EJB,
. 9
, JTA EJB, CDI-.
10 11 ,
JSF 2.2. 10

21

- JSF Facelets.
11 EJB CDI-, .
,
. 12 , XML (
JAXB JAXP) JSON (JSON-P1.0). 13 , JMS2.0 , . 14 - SOAP,
15 - RESTful JAX-RS 2.0.


, ,
Maven3 Java- JDK1.7 . GlassFish 4,
Derby. , , ,
. Mac OS X (
Windows Linux). Source Code Apress (www.apress.com).
GitHub https://github.com/agoncal/agoncal-book-Java EE7.


,
antonio.goncalves@gmail.com.
www.antoniogoncalves.org : @agoncal.


, vinitski@minsk.piter.com ( , ).
!
http://www.piter.com
.

1.
Java EE7
.
, , , ,
.
, ,
, ,
, .
, , - ,
- , .

(EIS),
, .
,
,
. ,
, , . ,
. Java Enterprise Edition (Java EE).
Java EE ( J2EE)
, 1999, .
, -
SOAP RESTful. Java EE ,
. Java EE , , .
Java EE.
, ,
Java EE7.

Java EE
- , -; API -

23
Java EE
( ). ,
- , , , API-,
Java EE. Java Standard Edition (JavaSE)
API , Java EE Java API (JTA),
Java (JMS) JPA. Java EE
, . Java SE
, , .
Java EE7 .
Java EE6, ,
,
. , (CDI)
.
Java EE7 13- . Java 13. Java EE
,
Java Community Process (JCP). Java EE ,
, . Java EE
API,
- . ,
.

Java EE , . Java EE,


, , , ..
Java EE .
( ,
). Java EE Java
SE, , API- Java SE
Java EE.
1.1 .
, . , - ,
EJB RMI-IIOP.

24

1. Java EE7

.1.1. Java EE

Java EE ,
.

(GUI), . Swing API .
, .
,
(GUI) .
.
- ( , -,
JSP JSF) - HTTP
-. -
SOAP RESTful. - EJBLite
( .7).
( Enterprise Java
Beans, Java Message Service, Java API
, , , RMI-IIOP)

25
Java EE
EJB. EJB
-.
, RMI ( HTTP -
SOAP RESTful).

Java EE , (..1.1). ,
API (, , , ,
).
.
, ,
. , -
JSF EJB Lite, a
-. , -
-, ,
-, EJB-.
Java EE .
.
,
. (), , ,
. , , ,
( ).
(ACC) Java-, , Java SE
, , (, Swing, main()).
ACC EJB-, RMI-IIOP,
- HTTP (, -).
- (, EJB Lite, JSP, , , JSF -). , , HTTP HTTPS.
- -.
EJB- EJB
(- EJB , ), - Java EE.
EJB,
, , , ,
, .

26

1. Java EE7

,
. -, , . .1.2 ,
. , - EJB-
,
. Java EE .
Java API
, .
.
Java (ORM).
JPQL , .
.
Java
. (P2P),
- (pub-sub).
Java- (JNDI) , Java SE,
. , () . , JMS, EJB
. JNDI,
1.4 J2EE, .
JavaMail ,
.
JavaBeans (JAF) JAF, JavaSE,
MIME-. JavaMail.
XML Java EE
XML,
XML-. Java
XML (JAXP)
SAX DOM, XSLT.
JSON ( JavaScript) Java
EE7 Java- JSON (JSON-P)

27
Java EE
, ,
JSON.
Java EE
(EIS) Java EE.
,
(ERP).

Java (JAAS)
, . Java (JACC)
Java EE , , ,
Java EE.
Java (JASPIC) ,
.
, .
- Java EE - SOAP RESTful.
Java - XML (JAX-WS), Java XML (JAX-RPC),
-, SOAP/HTTP. Java
- RESTful (JAX-RS) -,
REST.
Java EE5,
. , JMS, ,
EJB .. , Java EE7
(CDI),
Java (DI).
Java EE
API . Java (JMXAPI) .
Java EE Java
EE .


.1.2, , , . , ,
-, HTTP, - EJB, EJB-.
, Java EE.

28

1. Java EE7

.1.2. ,

HTTP -, . JavaSE API java.net. API


HTTP , JSP-,
JSF, - SOAP RESTful.
HTTPS HTTP
SSL.
RMI-IIOP (RMI)
. JavaSE RMI-
Java (JMRP). RMI-IIOP RMI, CORBA. Java- (IDL)
Java EE CORBA IIOP. CORBA
(Ada, C, C++, Cobol ..), Java.


. JavaSE

29
Java EE
Java ( JAR), (Java, , )
( ZIP). .1.3, Java EE
, ,
JAR.

.1.3.

Java-
, JAR. JavaSE
. ,
JAR- META-INF -,
. META-INF/MANIFEST.MF
, .
META-INF/application-client.xml.

30

1. Java EE7

EJB - / ,
(MDB), JAR (
JAR- EJB).
META-INF/ejb-jar.xml EJB.
- , JSP JSF, -,
, ( HTML
XHTML, (CSS), Java-, ,
..). Java EE6 - EJB Lite ( EJBAPI, 7).
JAR WAR (
WAR -). - WEB-INF/web.xml. WAR EJBLite, WEB-INF/ejb-jar.xml
. Java- .class WEB-INF/classes, JAR- WEB-INF/lib.
-,
EJB, . ( JAR .ear) ,
.
META-INF/application.xml. lib
.


: .
( ), , (
). Java EE
, / .
.1.2, , , , .
,
, Java-, , , , .
Java EE5,
. (Java-, ,
, ). 1.1 Java- (POJO),

( EJB,
).
1.1. EJB

@Stateless
@Remote(ItemRemote.class)
@Local(ItemLocal.class)

31
Java EE
@LocalBean
public class ItemEJB implements ItemLocal, ItemRemote {
@PersistenceContext(unitName = "chapter01PU")
private EntityManager em;
public Book findBookById(Long id) {
return em.find(Book.class, id);
}
}

. (DD) XML-
, . 1.2 EJB.
Java EE 7,
http://xmlns.jcp.org/xml/ns/javaee
.
1.2. EJB

<ejb-jar xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/ejb-jar_3_2.xsd"
version="3.2" >
<enterprise-beans>
<session>
<ejb-name>ItemEJB</ejb-name>
<remote>org.agoncal.book.javaee7.ItemRemote</remote>
<local>org.agoncal.book.javaee7.ItemLocal</local>
<local-bean/>
<ejb-class>org.agoncal.book.javaee7.ItemEJB</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
</session>
</enterprise-beans>
</ejb-jar>

, META-INF
WEB-INF. .1.1 Java EE ( ).
1.1. Java EE0

application.xml

Java EE

META-INF

application-client.xml

Java EE

META-INF

beans.xml

CDI

META-INF WEB-INF

32

1. Java EE7

1.1 ()

ra.xml

JCA

META-INF

ejb-jar.xml

EJB

META-INF WEB-INF

faces-config.xml

JSF

WEB-INF

persistence.xml

JPA

META-INF

validation.xml

META-INF WEB-INF

web.xml

WEB-INF

web-fragment.xml

WEB-INF

webservices.xml

- SOAP

META-INF WEB-INF

Java EE5, ,
. .
, ,
. , , . ,
XML-,
.
,
( XML ).

Java- , . (Java + XML) (Java).
, (,
) .

Java EE ( ),
( , ).
, XML .

Java EE . , Java EE
, Java Community Process,
. Java EE
( Java),
. , ,
Java- (Struts, Spring ..).

33
Java EE
,
. , , , , , , , , , , .
Java, , , , . ,
. - , ,
. Java EE ,
(WebLogic, Websphere, MQSeries .)
(GlassFish, Jboss, Hibernate, Open JPA, Jersey ..) , , , ..
.

JCP
Java Communication Process , 1998 Sun Microsystems. JCP Java.
, ( ) Java (JSR) . , ,
, ,
(JSR) :
,
Java (JSR);
(RI), ;
( , TCK), ,
.
(EC) Java- .

Java EE
. , .

34

1. Java EE7

,
. , JNDI. EJB GlassFish, Jboss WebLogic
JNDI, .
. Java EE,
JNDI.
, . API
(), Java EE
, .


Java EE7 . POJO (
XML), . POJO . ,
.
Java EE7 , JSF, EJB, , - SOAP REST XML. 1.3
JSF, Java-
CDI-.
1.3. JSF

@Named
public class BookController {
@Inject
private BookEJB bookEJB;
private Book book = new Book();
private List<Book> bookList = new ArrayList<Book>();
public String doCreateBook() {
book = bookEJB.createBook(book)
bookList = bookEJB.findBooks();
return "listBooks.xhtml";
}
// ,
}

EJB . 1.4,
EJB ,
. EJB WAR JAR.
EJB ,
-.

35
Java Standard Edition7
1.4. EJB

@Stateless
public class BookEJB {
@Inject
private EntityManager em;
public Book findBookById(Long id) {
return em.find(Book.class, id);
}
public Book createBook(Book book) {
em.persist(book);
return book;
}
}

- RESTful .
JAX-RS Java EE7
. 1.5, - RESTful
Java-, HTTP (
15).
1.5. - RESTful ( )

@Path("books")
public class BookResource {
@Inject
private EntityManager em;
@GET
@Produces({"application/xml", "application/json"})
public List<Book> getAllBooks() {
Query query = em.createNamedQuery("findAllBooks");
List<Book> books = query.getResultList();
return books;
}
}

,
-, ( XML). ,
.

Java Standard Edition7


, Java EE JavaSE. ,
Java EE Java, API.
JavaSE7 2011.
JSR336
,
. , JavaSE5 , ,
( ), .. JavaSE6 , , JMX API,

36

1. Java EE7

Java. JavaSE7
JSR334 ( Project
Coin), JSR292 (InvokeDynamic
Java), JSR203 ( API /, NIO.2), (JDBC4.1 (JSR221)).
JavaSE7, ,
, .


JavaSE7
( byte, short, int, long, char) .
- Strcompare.
, if/then/else,
.
, 1.6.
1.6.

Stringaction = "update";
switch (action) {
case "create":
create();
break;
case "read":
read();
break;
case "udpate":
udpate();
break;
case "delete":
delete();
break;
default:
noCrudAction(action);
}


JavaSE5, . JavaSE7 , .
. 1.7 , .
1.7.

//
List<String> list = new ArrayList<String>();
Map<Reference<Object>, Map<Integer, List<String>>> map =

37
Java Standard Edition7
new HashMap<Reference<Object>, Map<Integer, List<String>>>();
// C
List<String> list = new ArrayList<>();
Map<Reference<Object>, Map<Integer, List<String>>> map = new HashMap<>();

try-with-resources
Java API ,
close finally. , , ,
JDBC. 1.8 ,
finally ,
- .
1.8. / Finally

try {
InputStream input = new FileInputStream(in.txt);
try {
OutputStream output = new FileOutputStream(out.txt);
try {
byte[] buf = new byte[1024];
int len;
while ((len = input.read(buf)) >= 0)
output.write(buf, 0, len);
} finally {
output.close();
}
} finally {
input.close();
}
} catch (IOException e) {
e.printStrackTrace();
}

try-with-resources , . try
. , 1.9, , java.lang.AutoCloseable.
(InputStream, OutputStream, JarFile, Reader,
Writer, Socket, ZipFile) (java.sql.ResultSet).
1.9. / .
try-with-resources

try (InputStream input = new FileInputStream(in.txt);


OutputStream output = new FileOutputStream(out.txt)) {
byte[] buf = new byte[1024];
int len;
while ((len = input.read(buf)) >= 0)
output.write(buf, 0, len);

38

1. Java EE7
} catch (IOException e) {
e.printStrackTrace();
}

Multicatch-
JavaSE6
. , . 1.10, .
1.10.

try {
// -
} catch(SAXException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} catch(ParserConfigurationException e) {
e.printStackTrace();
}

, JavaSE7 , , , 1.11.
1.11. Multicatch-

try {
// -
} catch( SAXException | IOException | ParserConfigurationException e) {
e.printStackTrace();
}

NIO.2
, Java-, , JavaSE7: /
java.nio. , , java.io, :
;
( , ..);
FileSystem FileStore (,
);
(/ , /
, , ..).
1.12 java.nio.file.Path (
),

39
Java EE
java.nio.file.Files ( -

). JavaSE7 NIO.2,
java.io . 1.12
source.txt, dest.txt, .
1.12. /

Path path = Paths.get("source.txt");


boolean exists = Files.exists(path);
boolean isDirectory = Files.isDirectory(path);
boolean isExecutable = Files.isExecutable(path);
boolean isHidden = Files.isHidden(path);
boolean isReadable = Files.isReadable(path);
boolean isRegularFile = Files.isRegularFile(path);
boolean isWritable = Files.isWritable(path);
long size = Files.size(path);
//
Files.copy(Paths.get("source.txt"), Paths.get("dest.txt"));
//
List<String> lines = Files.readAllLines(Paths.get("source.txt"), UTF_8);
for (String line : lines) {
System.out.println(line);
}
//
Files.delete(path);

Java EE
Java EE ,
. Java EE7 31,
API.
API, Java EE7
, , POJO,
- .

Java EE
.1.4 14- Java EE. JavaEE J2EE. J2EE 1.2 Sun 1999 ,
JSR. CORBA, J2EE .
Enterprise Java Beans (EJB)
,
(- EJB). , RMI-IIOP (

40

1. Java EE7

ORB ). -
JSP, Java (JMS).

.1.4. J2/Java EE

J2EE 1.3, Java


Community Process (JCP) JSR58. , EJB
XML (
EJB1.0). ,

. . JCA (J2EE
Connector Architecture), Java EE (EIS).

CORBA 1988 , ( : Tuxedo CICS). EJB J2EE, ,
. J2EE CORBA ,

41
Java EE
, -
SOAP REST. CORBA.

2003 J2EE1.4 ( JSR151) 20 -. EJB2.1


- EJB SOAP/HTTP. .
.
J2EE , . , , ,
. J2EE , , .
Struts, Spring Hibernate,
.
, 2006 JavaEE5
( JSR244). ,
POJO.
, XML .
, EJB3 JPA , . JavaServer Faces (JSF), API SOAP- JAX-WS 2.0, JAX-RPC.
2009 JavaEE6 ( JSR 316), . , POJO, , -.
, JAX-RS1.1, 1.0, (CDI 1.0).
API (, EJB3.1) , , ,
(JPA2.0 EJB).
Java EE6 (, JNDI), ( ) .
Java EE7 ( ,
-, JSON), . Java EE7
, (CDI) .
, ,
Java Enterprise Edition.

Java EE 1999, (..1.4). . ,

42

1. Java EE7

, . . ,
Java EE. , , ,
, . Java EE6
, Java EE7
.
- EJB2.xCMP ( JSR 318).
, EJB2., JPA.
JAX-RPC ( JSR101). - SOAP
(RPC). JAX-WS.
JAXR ( JSR93). JAXR , UDDI.
, JAXR Java EE
JSR.
JavaEE ( JSR88). JSR88 ,

. , Java EE7
.

Java EE7
Java EE7 JSR342
31. ,
Java EE7, .
.1.21.6, ,
JSR.
1.2. Java Enterprise Edition

JSR

URL

Java EE

7.0

342

http://jcp.org/en/jsr/detail?id=342

Web Profile (-)

7.0

342

http://jcp.org/en/jsr/detail?id=342

Managed Beans ( 1.0


)

316

http://jcp.org/en/jsr/detail?id=316

- (..1.3) SOAP ,
(. 14).
- REST
-. JAX-RS 2.0

43
Java EE
, , API (. 15).
JavaScript (JSON-P)
Java XML (JAXP), XML
JSON (.12).
1.3. -

JSR

URL

JAX-WS

2.2a

224

http://jcp.org/en/jsr/detail?id=224

JAXB

2.2

222

http://jcp.org/en/jsr/detail?id=222

Web Services (-)

1.3

109

http://jcp.org/en/jsr/detail?id=109

Web Services Metadata (- 2.1


-)

181

http://jcp.org/en/jsr/detail?id=181

JAX-RS

2.0

339

http://jcp.org/en/jsr/detail?id=339

JSON-P

1.0

353

http://jcp.org/en/jsr/detail?id=353

- (..1.4) JSP JSTL, .


JSP- , (JSR341). JSF
(.10 11) . , Java EE7 WebSocket1.0.
1.4. -1

JSR

URL

JSF

2.2

344

http://jcp.org/en/jsr/detail?id=344

JSP

2.3

245

http://jcp.org/en/jsr/detail?id=245

Debugging Support for Other


Languages ( )

1.0

45

http://jcp.org/en/jsr/detail?id=45

JSTL1

1.2

52

http://jcp.org/en/jsr/detail?id=52

Servlet ()

3.1

340

http://jcp.org/en/jsr/detail?id=340

WebSocket (-)

1.0

356

http://jcp.org/en/jsr/detail?id=356

Expression Language (
)

3.0

341

http://jcp.org/en/jsr/detail?id=341

(..1.5)
: JMS 2.0 (.13) JTA1.2 (.9),
. ,
EJB (.7 8), JPA (.46) (.2)
.
1

JSTL (JavaServer Pages Standard Tag Library) JavaServer.

44

1. Java EE7

1.5.

JSR

URL

EJB

3.2

345

http://jcp.org/en/jsr/detail?id=345

Interceptors ()

1.2

318

http://jcp.org/en/jsr/detail?id=318

JavaMail

1.5

919

http://jcp.org/en/jsr/detail?id=919

JCA

1.7

322

http://jcp.org/en/jsr/detail?id=322

JMS

2.0

343

http://jcp.org/en/jsr/detail?id=343

JPA

2.1

338

http://jcp.org/en/jsr/detail?id=338

JTA

1.2

907

http://jcp.org/en/jsr/detail?id=907

Java EE7 (..1.6),


( JSR 352) Java EE ( JSR 236).
1.1 (.3), CDI1.1 (.2) JMS 2.0 (.13).
1.6. ,

JSR

URL

JACC

1.4

115

http://jcp.org/en/jsr/detail?id=115

Bean Validation (
)

1.1

349

http://jcp.org/en/jsr/detail?id=349

Contexts and Dependency


Injection ( )

1.1

346

http://jcp.org/en/jsr/detail?id=346

Dependency Injection for Java


(
Java)

1.0

330

http://jcp.org/en/jsr/detail?id=330

Batch ( )

1.0

352

http://jcp.org/en/jsr/detail?id=352

Concurrency Utilities for Java


EE (
Java EE)

1.0

236

http://jcp.org/en/jsr/detail?id=236

Java EE Management ( Java EE)

1.1

77

http://jcp.org/en/jsr/detail?id=77

Java Authentication Service


Provider Interface for
Containers ( Java )

1.0

196

http://jcp.org/en/jsr/detail?id=196

Java EE7 31 ,
Java SE7. .1.7 ,
Java SE, Java EE.

45
Java EE
1.7. JavaSE 7

JSR

URL

Common Annotations
( )

1.2

250

http://jcp.org/en/jsr/detail?id=250

JDBC

4.1

221

http://jcp.org/en/jsr/detail?id=221

JNDI

1.2

JAXP

1.3

206

http://jcp.org/en/jsr/detail?id=206

StAX

1.0

173

http://jcp.org/en/jsr/detail?id=173

JAAS

1.0

JMX

1.2

http://jcp.org/en/jsr/detail?id=3

JAXB

2.2

222

http://jcp.org/en/jsr/detail?id=222

JAF

1.1

925

http://jcp.org/en/jsr/detail?id=925

SAAJ

1.3

http://java.net/projects/saaj

-7
Java EE6. .
, Java EE7, ,
, API
31. Java EE ,
.
. .1.5,
,
.

.1.5. Java EE

Java EE7 , -.
-

46

1. Java EE7

. - 7.0 JSR
Java EE7.
. .1.8 , -.
1.8. - 7.0

JSR

URL

JSF

2.2

344

http://jcp.org/en/jsr/detail?id=344

JSP

2.3

245

http://jcp.org/en/jsr/detail?id=245

JSTL

1.2

52

http://jcp.org/en/jsr/detail?id=52

Servlet

3.1

340

http://jcp.org/en/jsr/detail?id=340

WebSocket

1.0

356

http://jcp.org/en/jsr/detail?id=356

Expression Language

3.0

341

http://jcp.org/en/jsr/detail?id=341

EJBLite

3.2

345

http://jcp.org/en/jsr/detail?id=345

JPA

2.1

338

http://jcp.org/en/jsr/detail?id=338

JTA

1.2

907

http://jcp.org/en/jsr/detail?id=907

Bean Validation

1.1

349

http://jcp.org/en/jsr/detail?id=349

Managed Beans

1.0

316

http://jcp.org/en/jsr/detail?id=316

Interceptors

1.2

318

http://jcp.org/en/jsr/detail?id=318

Contexts and Dependency


Injection

1.1

346

http://jcp.org/en/jsr/detail?id=346

Dependency Injection
for Java

1.0

330

http://jcp.org/en/jsr/detail?id=330

Debugging Support for Other


Languages

1.0

45

http://jcp.org/en/jsr/detail?id=45

JAX-RS

2.0

339

http://jcp.org/en/jsr/detail?id=339

JSON-P

1.0

353

http://jcp.org/en/jsr/detail?id=353

CD-BookStore
, , , EJB, JSF, JMS,
- SOAP RESTful. CD-BookStore.
, -, .
( ),
, .

. .1.6
.

47

.1.6. CD-BookStore

, , :
, ,
.
;
,
-. - , , ;
, ,
;
, .

Git
https://github.com/agoncal/agoncal-book-javaee7.

Java- , , ,

48

1. Java EE7

,
JavaEE. , ,
,
. Java EE7 ,
-. ( , EJBLite),
( EJB
-). ,

JNDI,
.
Java EE7.
Java EE7. . , ,
: JDK1.7, Maven3, Junit4, Derby 10.8 Glassfishv4.

2.

Java EE ( J2EE)
(IoC), - ( ).
,
. , Java EE, .
XML, API Java EE5 Java EE6.
Java EE6 (Context and
Dependency Injection CDI) , , . CDI EJB .
Java EE , . CDI . , ,
. , . CDI
- .
,
, ,
CDI.


JavaSE JavaBeans, Java EE Enterprise JavaBeans.
JavaEE : , - SOAP
RESTful, , , .
POJO. POJO Java-,
Java (JVM). JavaBeans POJO, (, (/) , )
JVM. JavaEE

50

2.

: , Enterprise JavaBean
, , ..
(, EJB), : , , ,
.. .
,
: ,
. JavaEE6,
,
JavaEE. , JavaEE. , Enterprise JavaBean
.

( EJB) ..
CDI,
.
; ;
, ; ; (EL). ,
Java,
, . JavaBeans Enterprise
JavaBeans CDI.


(DI) ,
. ,
.
.
, JavaEE, JNDI. ,
.
: ( ),
( ).
Java EE 1990-, EJB, JMS.
JNDI , ,
JDBC DataSource, JMS- .
EJB-
(, , ). , .
Java EE5 .
, EJB,

51

, , JMS , (, JSF EJB).
Java EE5 (@Resource, @PersistenceContext,
@PersistenceUnit, @EJB @WebServiceRef).
Java EE5 , Java EE6

(DI): Dependency Injection ( JSR330) Contexts and Dependency Injection
( JSR299). Java EE7 : .


POJO : , Java-,
, new, , (Garbage
Collector) .
CDI ,
new. , . ,
: ,
. , ,
?
.
2.1 (, CDI). , (EJB,
CDI -) ( new). @PostConstruct - .
@PreDestroy ,
.

.2.1.

52

2.

, Java EE , .2.1.


CDI .
, .
CDI , , . ,
HTTP.
. , . , .
, (,
), (), , , . ( , ), ,
. (, ),
, . ( ).
. .

- . - ().
, ( ) -.
, .
(
, ,
..) -. : ,
$10000, ,
, .. AOP .
AOP, -. ,
. .2.2, / .

53

.2.2. , -

2.2 ,
. , EJB-
.
, -. ,
EJB,
( , ,
..).

-.


. .
, . CDI
.
-. ,
, CDI.
. CDI
, , . CDI
(, ,
). XML
, .


Java EE XML. , , (, -) .
CDI beans.xml
. (, , ..),
CDI. , CDI ( ).

54

2.

: ,
CDI POJO CDI. CDI JAR- WAR- ,
beans.xml,
POJO, CDI. beans.xml
( META-INF WEB-INF) CDI
, , .. CDI
. - JAR CDI ,
JAR beans.xml CDI .

CDI
CDI Java EE.
(Bean Validation, JAX-RS),
(EJB), (JSF).
CDI 1.1 , : Dependency Injection for Java 1.0 ( JSR 330), Managed Bean 1.0 (
JSR 342), Common Annotations 1.2 ( JSR 250), Expression Language 3.0
( JSR 341) Interceptors 1.2 ( JSR 318).

CDI
2006 ( Seam),
Seam, Guise Spring, JSR 299,
Web Beans (-).
Java EE6, Context and Dependency Injection 1.0.
JSR 330: Dependency Injection for Java 1.0
( @Inject).
Java EE . Java
(@Inject, @Named, @Qualifier, @Scope @Singleton), . CDI JSR 330
, , , ( JSR 318). , CDI
, . CDI , :
;
- ;
;
.
, Java EE7, CDI 1.1
JSR, .

55
CDI

CDI 1.1
CDI 1.1 .
CDI , , ,
Java EE.
, CDI 1.1:
CDI CDI
;
, (@Prio
rity) ;
@Vetoed CDI
;
@New CDI 1.1 ,
@Dependent;
@WithAnnotations ,
.
.2.1 , CDI.
CDI javax.enterprise.inject javax.decorator.
2.1. , CDI

javax.inject

Java API ( JSR 330)

javax.enterprise.inject

API

javax.enterprise.context

CDI API

javax.enterprise.event

CDI API

javax.enterprise.util

CDI

javax.interceptor

API ( JSR 318)

javax.decorator

API CDI


CDI Weld, JBoss. , Apache OpenWebBeans CanDi ( Caucho).
Apache DeltaSpike, CDI.

CDI
CDI , -.
Java- (EL) JSF. 2.1,

56

2.

POJO, , (@Inject)
, (@PostConstruct). , , ( @Transactional
).
2.1. BookService, ,

public class BookService {


@Inject
private NumberGenerator numberGenerator;
@Inject
private EntityManager em;
private Date instanciationDate;
@PostConstruct
private void initDate() {
instanciationDate = new Date();
}
@Transactional
public Book createBook(String title, Float price, String description) {
Book book = new Book(title, price, description);
book.setIsbn(numberGenerator.generateNumber());
book.setInstanciationDate(instanciationDate);
em.persist(book);
return book;
}
}

CDI
CDI 1.1
CDI , :
;
, @Decorator;
@Inject.
, EL (EL ), .


Java - . , . Book
H2G2, Customer , PurchaseOrder ,
. : , . - .

57
CDI
, (BookService) Book ,
(NumberGenerator ), .
NumberGenerator ISBN 13 ISBN
, ISSN. BookService IsbnGenerator IssnGenerator.
.
2.3 NumberGenerator,
(String generateNumber()) Isbn
Generator IssnGenerator. Bookservice .

.2.3. NumberGenerator

BookService ISBN- NumberGenerator?


new,
2.2.
2.2. POJO- BookService,
new

public class BookService {


private NumberGenerator numberGenerator;
public BookService() {
this.numberGenerator = new IsbnGenerator();
}
public Book createBook(String title, Float price, String description) {
Book book = new Book(title, price, description);
book.setIsbn(numberGenerator.generateNumber());
return book;
}
}

2.2 .
BookService IsbnGenerator,
numberGenerator. numberGenerator.generateNumber() -

13.
, ,
IsbnGenerator?

58

2.

, (2.3).
2.3. POJO BookService,

public class BookService {


private NumberGenerator numberGenerator;
public BookService(NumberGenerator numberGenerator) {
this.numberGenerator = numberGenerator;
}
public Book createBook(String title, Float price, String description) {
Book book = new Book(title, price, description);
book.setIsbn(numberGenerator.generateNumber());
return book;
}
}

, BookService
.
BookService bookService = new BookService(new IsbnGenerator())
BookService bookService = new BookService(new IssnGenerator())

:
( ) BookService NumberGenerator,
. , .
(
),
( ).
(, CDI).

@Inject
Java EE ,
. . , CDI
, XML
.
Java EE5 , @Resource,
@PersistentUnit EJB. ( , EJB) (, EJB,
JSF ..). CDI
@Inject. , Java
EE7 (@Resource),
@Inject , (. CDI ).
2.4 , BookService NumberGenerator
CDI.

59
CDI
2.4. BookService, @Inject
NumberGenerator

public class BookService {


@Inject
private NumberGenerator numberGenerator;
public Book createBook(String title, Float price, String description) {
Book book = new Book(title, price, description);
book.setIsbn(numberGenerator.generateNumber());
return book;
}
}

2.4, @Inject
, NumberGenerator,
NumberGenerator. (, @Inject ). 2.5
IsbnGenerator. , ,
NumberGenerator.
2.5. IsbnGenerator

public class IsbnGenerator implements NumberGenerator {


public String generateNumber() {
return "13-84356-" + Math.abs(new Random().nextInt());
}
}


,
@Inject. : , .
@Inject
():
@Inject
private NumberGenerator numberGenerator;

,
, . CDI
( ), .
@Inject , :
@Inject
public BookService (NumberGenerator numberGenerator) {
this.numberGenerator = numberGenerator;
}

, . ( ) ,
. ,

60

2.

, .
,
. @Inject:
@Inject
public void setNumberGenerator(NumberGenerator numberGenerator) {
this.numberGenerator = numberGenerator;
}

,
. ,
. ,
.


, NumberGenerator (IsbnGenearator).
CDI ,
@Inject:
@Inject
private NumberGenerator numberGenerator;

. ,
,
@javax.enterprise.inject.Default.
:
@Inject @Default
private NumberGenerator numberGenerator;
@Default , CDI, .
, @Default. , 2.6 2.5.
2.6. IsbnGenerator @Default

@Default
public class IsbnGenerator implements NumberGenerator {
public String generateNumber() {
return "13-84356-" + Math.abs(new Random().nextInt());
}
}

, , @Inject. .2.4 @Default


(IsbnGenerator), (@Inject @Default). . , .

61
CDI

.2.4. @Default

,
. , NumberGenerator .
,
@Default (..2.4). ,
. , , .
, , (IsbnGenrator IssnGenerator)
? XML-. CDI :
Java,
.
, BookService,
ISBN, LegacyBookService, ISSN. .2.5,
NumberGenerator. .

.2.5. ,

62

2.

, . ,
, , @javax.in
ject.Qualifer. ,
- . 2.7 2.8.
2.7.

@Qualifier
@Retention(RUNTIME)
@Target({FIELD, TYPE, METHOD})
public @interface ThirteenDigits { }
2.8.

@Qualifier
@Retention(RUNTIME)
@Target({FIELD, TYPE, METHOD})
public @interface EightDigits { }

,
. 2.9 2.10, @ThirteenDigits IsbnGenerator, a @EightDigits
IssnGenerator.
2.9. IsbnGenerator @ThirteenDigits

@ThirteenDigits
public class IsbnGenerator implements NumberGenerator {
public String generateNumber() {
return "13-84356-" + Math.abs(new Random().nextInt());
}
}
2.10. IssnGenerator @EightDigits

@EightDigits
public class IssnGenerator implements NumberGenerator {
public String generateNumber() {
return "8-" + Math.abs(new Random().nextInt());
}
}

, ,
. 2.11 BookService

@ThirteenDigits, 2.12 LegacyBookService .
2.11. BookService, @ThirteenDigits NumberGenerator

public class BookService {


@Inject @ThirteenDigits
private NumberGenerator numberGenerator;

63
CDI
public Book createBook(String title, Float price, String description) {
Book book = new Book(title, price, description);
book.setIsbn(numberGenerator.generateNumber());
return book;
}
}
2.12. LegacyBookService, @EightDigits
NumberGenerator

public class LegacyBookService {


@Inject @EightDigits
private NumberGenerator numberGenerator;
public Book createBook(String title, Float price, String description) {
Book book = new Book(title, price, description);
book.setIsbn(numberGenerator.generateNumber());
return book;
}
}

, .
, CDI . (
). , CDI .
, - ,
. , .
, . ,
, ( ).
,
, (, @TwoDigits, @EightDigits,
@TenDigits, @ThirteenDigits). ,
, . :
@TwoOddDigits, @TwoEvenDigits, @EightOddDigits .. .

@NumberOfDigits
(2.13).
2.13. @NumberOfDigits DigitsEnum

@Qualifier
@Retention(RUNTIME)
@Target({FIELD, TYPE, METHOD})
public @interface NumberOfDigits {
Digits value();
boolean odd();
}
public enum Digits {
TWO,

64

2.
EIGHT,
TEN,
THIRTEEN
}

,
. , :
@Inject @NumberOfDigits(value = Digits.THIRTEEN, odd = false)
private NumberGenerator numberGenerator;

:
@NumberOfDigits(value = Digits.THIRTEEN, odd = false)
public class IsbnEvenGenerator implements NumberGenerator {...}

.
. , (@TwoOddDigits, @TwoEvenDigits) , (@NumberOfDigits),
: (@Odd @Even), . , 13 :
@ThirteenDigits @Even
public class IsbnEvenGenerator implements NumberGenerator {...}

:
@Inject @ThirteenDigits @Even
private NumberGenerator numberGenerator;

,
. . , .

. , . , .
, javax.enterprise.inject.Alternative. ,
,
beans.xml. 2.14
.
2.14.

@Alternative
public class MockGenerator implements NumberGenerator {

65
CDI
public String generateNumber() {
return "MOCK";
}
}

2.14, MockGenerator, ,
NumberGenerator. @Alternative, ,
CDI NumberGenerator . 2.6,
@Default :
@Alternative @Default
public class MockGenerator implements NumberGenerator {...}

. , CDI, :
@Alternative @ThirteenDigits
public class MockGenerator implements NumberGenerator {...}

@Alternative , beans.xml, 2.15.


2.15. beans.xml

<beans xmlns=" http://xmlns.jcp.org/xml/ns/javaee"


xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
version="1.1" bean-discovery-mode="all">
<alternatives>
<class>org.agoncal.book.javaee7.chapter02.MockGenerator</class>
</alternatives>
</beans>

, . , .
. ,
MockGenerator, 2.14, .
@Inject
private NumberGenerator numberGenerator;

beans.xml, , (, ,
..).


, CDI . ( int, long, float ..),
POJO, CDI. CDI
, , beans.xml.

66

2.

, java.util.Date ja
va.lang.String. , rt.jar
( Java), beans.xml. META-INF beans.xml, CDI POJO , , . POJO
, 2.16.
2.16.

public class NumberProducer {


@Produces @ThirteenDigits
private String prefix13digits = "13-";
@Produces @ThirteenDigits
private int editorNumber = 84356;
@Produces @Random
public double random() {
return Math.abs(new Random().nextInt());
}
}

NumberProducer 2.16 (
javax.enterprise.inject.Produces). ,
@Inject (@ThirteenDigits, @EightDigits @Random).
(random() 2.16) ,
. . (, @Random),
EL-, .
(prefix13digits editorNumber)
, -. , .
2.9 IsbnGenerator ISBN "13-84356-" +
Math.abs(newRandom().nextInt()). NumberProducer (. 2.16)
. 2.17 IsbnGenerator ,
@Inject @ThirteenDigits, ("13-") (84356) ISBN.
@Inject @Random .
2.17. IsbnGenerator,

@ThirteenDigits
public class IsbnGenerator implements NumberGenerator {
@Inject @ThirteenDigits
private String prefix;
@Inject @ThirteenDigits
private int editorNumber;
@Inject @Random

67
CDI
private double postfix;
public String generateNumber() {
returnprefix + editorNumber + postfix;
}
}

2.17 .
(@Inject @ThirteenDigits) CDI ,
, NumberGenerator.
(.2.17) (.2.9) ,
CDI, ( ISBN).
InjectionPoint API. 2.16 , @Produces, ,
.
. .
, . JDK java.util.logging.Logger ,
. , BookService ,
:
Logger log = Logger.getLogger(BookService.class.getName());

Logger, ? CDI InjectionPoint API, ,


(.2.2). ,
, InjectionPoint API
. 2.18 ,
createLogger .
2.2. InjectionPoint API

Type getType()

Set<Annotation>
getQualifiers()

Bean<?> getBean()

Bean, ,

Member getMember()

Field

Annotated
getAnnotated()

Annotated Field AnnotatedParameter ,


/

boolean isDelegate()

boolean isTransient()

68

2.

2.18.

public class LoggingProducer {


@Produces
private Logger createLogger(InjectionPoint injectionPoint) {
return Logger.getLogger(injectionPoint.getMember().getDeclaringClass().
getName());
}
}

, . :
@Inject Logger log;

(.2.17 2.18) POJO ,


. , , ,
. , , Java Database Connectivity (JDBC), JMS
. CDI , .
, .
2.19 , JDBC. createConnection Derby JDBC,
URL, JDBC. @Disposes.
2.19. JDBC

public class JDBCConnectionProducer {


@Produces
private Connection createConnection() {
Connection conn = null;
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
conn = DriverManager.getConnection("jdbc:derby:memory:chapter02DB",
"APP", "APP");
} catch (InstantiationException | IllegalAccessException |
ClassNotFoundException) {
e.printStackTrace();
}
return conn;
}
private void closeConnection(@Disposes Connection conn) throws SQLException
{

69
CDI
conn.close();
}
}

, , .
, @Disposes,
( java.sql.Connection) (@Default),
(
@Produces). (closeConnection())
(2.20 @ApplicationScoped),
, .
2.20. JDBS

@ApplicationScoped
public class DerbyPingService {
@Inject
private Connection conn;
public void ping() throws SQLException {
conn.createStatement().executeQuery("SELECT 1 FROM SYSIBM.SYSDUMMY1");
}
}

2.20 , JDBC
@Inject
Derby. ,
JDBC .

.


CDI , ( CDI ). , CDI,
, . Java POJO :
, new, , .
CDI
, . .
- (, , ), (. 7
- EJB ). ,
- POJO -, . CDI - .
,
.

70

2.

(@ApplicationScoped)
.
, . ,
, .
,
.
(@SessionScoped) HTTP . HTTP , .
, , .
(@RequestScoped)
HTTP- .
. JSF, HTTP-.
(@ConverationScoped) ,
.
.
(@Dependent) .
,
. CDI.
, , CDI (
javax.enterprise.context). . , ,
, , (, ),
.
@SessionScoped
public class ShoppingCart implements Serializable {...}

ShoppingCart , .
, ,
,
, . ,
@SessionScoped @ConversationScoped
, .

71
CDI
, (@Dependent).

.
, . ,
, , , .
ISBN- :
@Dependent @ThirteenDigits
public class IsbnGenerator implements NumberGenerator {...}

, @Dependent :
@ThirteenDigits
public class IsbnGenerator implements NumberGenerator {...}

. @Session
Scoped @RequestScoped @ApplicationScoped .
. , . ,
, . @ConversationScoped ,
,
.
, (HTTP ), ,
. ,
. , . CDI
(@ConversationScoped).
,
, , ,
API javax.enterprise.con
text.Conversation.
-: . .
, .
, , , .
. 2.21 ,
.

72

2.

2.21.

@ConversationScoped
public class CustomerCreatorWizard implements Serializable {
private Login login;
private Account account;
@Inject
private CustomerService customerService;
@Inject
private Conversation conversation;
public void saveLogin() {
conversation.begin();
login = newLogin();
//
}
public void saveAccount() {
account = new Account();
//
}
public void createCustomer() {
Customer customer = new Customer();
customer.setLogin(login);
customer.setAccount(account);
customerService.createCustomer(customer);
conversation.end();
}
}

2.21 CustomerCreationWizard
@ConversationScoped. CustomerService Customer,
, Conversation. . ,
saveLogin (conversation.begin()). .
, createCustomer
(conversation.end()). 2.3 API Conversation.
2.3. API Conversation

void begin()

void begin(String id)

void end()

String getId()

long getTimeout()

void setTimeout(long millis)


boolean isTransient()

73


CDI ,
-. , ,
CDI , (DI)
. Java- , Java. , EL- JSF.
CDI
EL-. ,
@javax.inject.Named,
2.22.
2.22. BookService

@Named
public class BookService {
private String title, description;
private Float price;
private Book book;
@Inject @ThirteenDigits
private NumberGenerator numberGenerator;
public String createBook() {
book = new Book(title, price, description);
book.setIsbn(numberGenerator.generateNumber());
return "customer.xhtml";
}
}

@Named BookService
( (CamelCase)
). JSF, createBook:
<h:commandButton value="Sendemail" action="#{bookService.createBook}"/>

, .
@Named("myService")
public class BookService {...}

JSF.
<h:commandButton value="Send email" action="#{myService.createBook}"/>

. .2.2,
(, CDI, EJB - RESTful ..),

74

2.

- ,
. :
, , ,
(@AroundConstruct);
, , ,
- (@AroundInvoke);
, @Around
Timeout, (
EJB, .8);
,

(@PostConstruct @PreDestroy).

Java EE6, (
EJB). , , EJB -
SOAP RESTful.


.
( , - ) , 2.23. CustomerService logMethod() @AroundInvoke.
. , createCustomer() findCustomerById()
logMethod(). ,
( ).
2.23. CustomerService, ,

@Transactional
public class CustomerService {
@Inject
private EntityManager em;
@Inject
private Logger logger;
public void createCustomer(Customer customer) {
em.persist(customer);
}
public Customer findCustomerById(Long id) {
return em.find(Customer.class, id);
}
@AroundInvoke
private Object logMethod(InvocationContext ic) throws Exception {
logger.entering(ic.getTarget().toString(), ic.getMethod().getName());
try {

75

return ic.proceed();
} finally {
logger.exiting(ic.getTarget().toString(), ic.getMethod().getName());
}
}
}

@AroundInvoke, logMethod()
:
@AroundInvoke
Object <METHOD>(InvocationContext ic) throws Exception;

, (
, ):
public, private, protected , static final;
javax.interceptor.InvocationContext
, ;
.
InvocationContext
. ,
InvocationContext ,
.
2.4 API InvocationContext.
2.4. InvocationContext

getContextData


InvocationContext Map

getConstructor

getMethod

getParameters

,
-

getTarget

getTimer

, @Timeout

proceed

.
.
void, proceed null

setParameters

,
.
,
IllegalArgumentException

76

2.

, 2.23, .2.6. , ,
createCustomer().
createCustomer() logMethod(). InvocationContext (ic.getTarget()), (ic.getMethod()) (logger.entering()). proceed().
InvocationContext.proceed() , ,
-
. proceed() , - . createCustomer(),
, ,
(logger.exiting()). findCustomerById()
.

.2.6. -


2.23 @javax.transaction.Transactional. CDI, JAX-RS JAX-WS.
EJB CDI. @Transactional
. 9.


2.23 , CustomerService .

, . () ,
,
.

77

.
,
logMethod() 2.23 ,
2.24. init(), @AroundConstruct .
2.24. Around-Invoke Around-Construct

public class LoggingInterceptor {


@Inject
private Logger logger;
@AroundConstruct
private void init(InvocationContext ic) throws Exception {
logger.fine("Entering constructor");
try {
ic.proceed();
} finally {
logger.fine("Exiting constructor");
}
}
@AroundInvoke
public Object logMethod(InvocationContext ic) throws Exception {
logger.entering(ic.getTarget().toString(), ic.getMethod().getName());
try {
return ic.proceed();
} finally {
logger.exiting(ic.getTarget().toString(), ic.getMethod().getName());
}
}
}

LoggingInterceptor ,
. @javax.interceptor.Interceptors. 2.25 createCustomer(). ,
, LoggingInterceptor
( ).
2.25. CustomerService

@Transactional
public class CustomerService {
@Inject
private EntityManager em;
@Interceptors(LoggingInterceptor.class)
public void createCustomer(Customer customer) {
em.persist(customer);
}
public Customer findCustomerById(Long id) {

78

2.
return em.find(Customer.class, id);
}
}

2.25 @Interceptors
createCustomer(). , , findCustomerById(), . ,
, @Interceptors , . , .
@AroundConstruct, .
@Transactional
@Interceptors(LoggingInterceptor.class)
public class CustomerService {
public void createCustomer(Customer customer) {...}
public Customer findCustomerById(Long id) {...}
}

, javax.interceptor.ExcludeClassInterceptors
. updateCustomer()
, :
@Transactional
@Interceptors(LoggingInterceptor.class)
public class CustomerService {
public void createCustomer(Customer customer) {...}
public Customer findCustomerById(Long id) {...}
@ExcludeClassInterceptors
public Customer updateCustomer(Customer customer) { ... }
}


(..2.2) .

( @PostConstruct @PreDestroy ). ,
, ,
@PostConstruct . ,
?
,
.
2.26 ProfileInterceptor :
logMethod(), , profile(),
(@AroundInvoke).

79

2.26. Around-Invoke

public class ProfileInterceptor {


@Inject
private Logger logger;
@PostConstruct
public void logMethod(InvocationContext ic) throws Exception {
logger.fine(ic.getTarget().toString());
try {
ic.proceed();
} finally {
logger.fine(ic.getTarget().toString());
}
}
@AroundInvoke
public Object profile(InvocationContext ic) throws Exception {
long initTime = System.currentTimeMillis();
try {
return ic.proceed();
} finally {
long diffTime = System.currentTimeMillis() - initTime;
logger.fine(ic.getMethod() + " took " + diffTime + " millis");
}
}
}

2.26,
InvocationContext Object void. ,
2.26, CustomerService (2.27)
@Interceptors ProfileInterceptor. , logMethod() init(). , createCustomer() findCustomerById(),
profile().
2.27. CustomerService,

@Transactional
@Interceptors(ProfileInterceptor.class)
public class CustomerService {
@Inject
private EntityManager em;
@PostConstruct
public void init() {
// ...
}
public void createCustomer(Customer customer) {
em.persist(customer);
}
public Customer findCustomerById(Long id) {
return em.find(Customer.class, id);
}
}

80

2.


, ( @Around Invoke), ( @Interceptors). Interceptors1.2
.
@Interceptors , ,
. ,
, @Interceptors.
, 2.28 @Interceptors
.
2.28. CustomerService,

@Stateless
@Interceptors({I1.class, I2.class})
public class CustomerService {
public void createCustomer(Customer customer) {...}
@Interceptors({I3.class, I4.class})
public Customer findCustomerById(Long id) {...}
public void removeCustomer(Customer customer) {...}
@ExcludeClassInterceptors
public Customer updateCustomer(Customer customer) {...}
}

updateCustomer(), ,
@ExcludeClassInterceptors. createCustomer()
I1, I2.
findCustomerById() I1, I2, I3 I4 .


( JSR 318)
(EJB, , RESTful ..). CDI ,
. ,
, CDI.
2.25, , .

(, @Interceptors(LoggingInterceptror.class)). , . CDI ,
. ,
@InterceptorBinding, .
2.29 Loggable.
, . -

81

, @InterceptorBinding,
(, 2.13).
2.29. Loggable

@InterceptorBinding
@Target({METHOD, TYPE})
@Retention(RUNTIME)
public @interface Loggable { }

. @Interceptor
(Loggable 2.30).
2.30. Loggable

@Interceptor
@Loggable
public class LoggingInterceptor {
@Inject
private Logger logger;
@AroundInvoke
public Object logMethod(InvocationContext ic) throws Exception {
logger.entering(ic .getTarget().toString(), ic .getMethod().getName());
try {
return ic.proceed() ;
} finally {
logger.exiting(ic .getTarget().toString(), ic .getMethod().getName());
}
}
}

,
, 2.31.
( ) .
2.31. CustomerService,

@Transactional
@Loggable
public class CustomerService {
@Inject
private EntityManager em;
public void createCustomer(Customer customer) {
em.persist(customer);
}
public Customer findCustomerById(Long id) {
return em.find(Customer.class, id);
}
}

2.31 . , . ,

82

2.

, ,
.
@Transactional
public class CustomerService {
@Loggable
public void createCustomer(Customer customer) {...}
public Customer findCustomerById(Long id) {...}
}

.
, , beans.xml JAR- Java EE,
2.32.
2.32. beans.xml

<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
version="1.1" bean-discovery-mode="all">
<interceptors>
<class>org.agoncal.book.javaee7.chapter02.LoggingInterceptor</class>
</interceptors>
</beans>


, , 2.28
(@Interceptors({I1.class, I2.class})). CDI1.1
, @javax.annotation.Priority ( XML- beans.xml) , 2.33.
2.33. Loggable

@Interceptor
@Loggable
@Priority(200)
public class LoggingInterceptor {
@Inject
private Logger logger;
@AroundInvoke
public Object logMethod(InvocationContext ic) throws Exception {
logger.entering(ic.getTarget().toString(), ic.getMethod().getName());
try {
return ic.proceed() ;
} finally {
logger.exiting(ic.getTarget().toString(), ic.getMethod().getName());
}
}
}

83

@Priority , . , . Java EE7 ,


. javax.interceptor.Interceptor :
PLATFORM_BEFORE = 0 , Java EE;
LIBRARY_BEFORE = 1000 , ;
APPLICATION = 2000 ,
;
LIBRARY_AFTER = 3000 , ;
PLATFORM_AFTER = 4000 , Java EE.
, , , ,
:
@Interceptor
@Loggable
@Priority(Interceptor.Priority.LIBRARY_BEFORE + 10)
public class LoggingInterceptor {...}


, ,
.
,
. .
, Gang
of Four. ,
( ). ,
, . -
. , .
, .
ISSN. ISSN ,
ISBN ( ).
(, 2.9 2.10),
ISSN, ,
. 2.34 . FromEightToThirteenDigitsDecorator

84

2.

javax.decorator.Decorator, - (Number
Generator .2.3) generateNumber.
, - , . generateNumber()
ISSN, -
ISBN.
2.34. ,

@Decorator
public class FromEightToThirteenDigitsDecorator implements NumberGenerator {
@Inject @Delegate
private NumberGenerator numberGenerator;
public String generateNumber() {
String issn = numberGenerator.generateNumber();
String isbn = "13-84356" + issn.substring(1);
returnisbn;
}
}

( @Delegate)
, , (
NumberGenerator). - (,
IssnNumberGenerator), , ,
- (, numberGenerator.generateNumber() 2.34).
, . beans.xml, 2.35.
2.35. beans.xml

<beansxmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
version="1.1" bean-discovery-mode="all">
<decorators>
<class>org.agoncal.book.javaee7.chapter02.FromEightToThirteenDigitsDeco
rator</class>
</decorators>
</beans>

, , .

, ,
, . , ,

85

.
, ,
.
(Observer), Gang of Four.
, javax.enter
prise.event. fire(),
. 2.36 BookService
(bookAddedEvent) . bookAddedEvent.fi
re(book) ,
. Book, .
2.36. BookService ,

public class BookService {


@Inject
private NumberGenerator numberGenerator;
@Inject
private Event<Book> bookAddedEvent;
public Book createBook(String title, Float price, String description) {
Book book = new Book(title, price, description);
book.setIsbn(numberGenerator.generateNumber());
bookAddedEvent.fire(book);
return book;
}
}

.
.
, @Observers . ,
. 2.37
, , . addBook,
Book.
. , BookService, CDI
. 2.37
addBook, , , BookService.
, CDI .
2.37. InventoryService Book

public class InventoryService {


@Inject
private Logger logger;
List<Book> inventory = new ArrayList<>();
public void addBook(@Observes Book book) {

86

2.
logger.info("Adding book " + book.getTitle() + "to inventory");
inventory.add(book);
}
}

CDI, ,
. ( ),
. 2.38
BookService, .
bookAddedEvent, bookRemovedEvent, Book. , @Added @Removed.
2.7: @Qualifier.
2.38. BookService

public class BookService {


@Inject
private NumberGenerator numberGenerator;
@Inject @Added
private Event<Book> bookAddedEvent;
@Inject @Removed
private Event<Book> bookRemovedEvent;
public Book createBook(String title, Float price, String description) {
Book book = new Book(title, price, description);
book.setIsbn(numberGenerator.generateNumber());
bookAddedEvent.fire(book);
return book;
}
public void deleteBook(Book book) {
bookRemovedEvent.fire(book);
}
}
InventoryService 2.39 , , (@Observes
@Added Book), (@Observes @Removed Book).
2.39. InventoryService

public class InventoryService {


@Inject
private Logger logger;
List<Book> inventory = new ArrayList<>();
public void addBook(@Observes @Added Book book) {
logger.warning(" " + book.getTitle() + " ");
inventory.add(book);
}
public void removeBook(@Observes @Removed Book book) {

87

logger.warning(" " + book.getTitle() + " ");
inventory.remove(book);
}
}

,
. , 100:
void addBook(@Observes @Added @Price(greaterThan=100) Book book)


, ,
, , ,
. Weld
Main JavaSE, .
2.7 ,
, .

.2.7.

BookService Java- Book.


NumberGenerator ISBN
ISSN (IsbnGenerator IssnGenerator) ,
(MockGenerator).
NumberGenerator ,
: @ThirteenDigits @EightDigits.
LoggingProducer Logger . LoggingInterceptor Loggable
CDI .

88

2.

Main BookService, Book


IsbnGenerator. BookServiceIT MockGenerator .
, . 2.7,
Maven:
src/main/java , ,
Main;
src/main/resources beans.xml,
CDI ;
src/test/java BookServiceIT
MockGenerator;
src/test/resources beans.xml ,
MockGenerator LoggingInterceptor;
pom.xml Maven (POM),
.

Book BookService
CD-Bookstore BookService (2.40). Java- Book (2.41) , .
(ISBN ISSN) .
2.40. BookService,

@Loggable
public class BookService {
@Inject @ThirteenDigits
private NumberGenerator numberGenerator;
public Book createBook(String title, Float price, String description) {
Book book = new Book(title, price, description);
book.setNumber(numberGenerator.generateNumber());
return book;
}
}
BookService , , POJO Book. ISBN- , (@Inject) (@ThirteenDigits)
generateNumber, IsbnGenerator.
2.41. POJO- Book

public class Book {


private String title;
private Float price;
private String description;
private String number;
//, ,
}

89

2.40 BookService @Loggable
(2.50). ,
.

NumberGenerator
BookService 2.40 NumberGenerator (2.42). ,
. IsbnGenerator , IssnGenerator
MockGenerator.
2.42. NumberGenerator

public interface NumberGenerator {


String generateNumber();
}

IsbnGenerator (2.43) @Thirteen


Digits. CDI , 13.
, IsbnGenerator ja
va.util.logging.Logger ( 2.48)
@Loggable .
2.43. IsbnGenerator

@ThirteenDigits
public class IsbnGenerator implements NumberGenerator {
@Inject
private Logger logger;
@Loggable
public String generateNumber() {
String isbn = "13-84356-" + Math.abs(new Random().nextInt());
logger.info(" ISBN : " + isbn);
return isbn;
}
}

IssnGenerator 2.44 Number


Generator.
2.44. IssnGenerator

@EightDigits
public class IssnGenerator implements NumberGenerator{
@Inject
private Logger logger;
@Loggable
public String generateNumber() {
String issn = "8-" + Math.abs(new Random().nextInt());
logger.info(" ISBN : " + issn);
return issn;
}
}

90

2.

MockGenerator 2.45 IsbnGenerator ( @ThirteenDigits). MockGenerator


,
beans.xml (.2.55).
2.45. ,

@Alternative
@ThirteenDigits
public class MockGenerator implements NumberGenerator {
@Inject
private Logger logger;
@Loggable
public String generateNumber() {
String mock = "MOCK-" + Math.abs(new Random().nextInt());
logger.info(" Mock : " + mock);
return mock;
}
}


NumberGenerator, CDI

. : Thirteen
Digits (2.46) EightDigits (2.47),
javax.inject.Qualifier ( ).
@ThirteenDigits IsbnGenerator (.2.43),
BookService (.2.40).
2.46.

@Qualifier
@Retention(RUNTIME)
@Target({FIELD, TYPE, METHOD})
public @interface ThirteenDigits { }
2.47.

@Qualifier
@Retention(RUNTIME)
@Target({FIELD, TYPE, METHOD})
public @interface EightDigits { }


. 2.432.45, NumberGenerator
java.util.logging.Logger .
Logger JDK,
( rt.jar beans.xml) .
LoggingProducer 2.48 (produceLogger), -

91

@Produces. Logger, .
2.48.

public class LoggingProducer {


@Produces
public Logger produceLogger(InjectionPoint injectionPoint) {
return Logger.getLogger(injectionPoint.getMember().getDeclaringClass().
getName());
}
}

LoggingInterceptor 2.49 Logger


.
,
(@AroundInvoke logMethod). LoggingInterceptor
@Loggable (2.50) (, BookService 2.40).
2.49.

@Interceptor
@Loggable
public class LoggingInterceptor {
@Inject
private Logger logger;
@AroundInvoke
public Object logMethod(InvocationContext ic) throws Exception {
logger.entering(ic.getTarget().getClass().getName(),
ic.getMethod().getName());
try {
return ic.proceed();
} finally {
logger.exiting(ic.getTarget().getClass().getName(),
ic.getMethod().getName());
}
}
}
2.50. Loggable

@InterceptorBinding
@Target({METHOD, TYPE})
@Retention(RUNTIME)
public @interface Loggable { }

Main
( Main), CDI
BookService.createBook. CDI1.1 API
, 2.51 Weld.

92

2.

WeldContainer
BookService.class. createBook
: IsbnGenerator Logger
BookService Book ISBN.
2.51. Main CDI BookService

public class Main {


public static void main(String[] args) {
Weld weld = new Weld();
WeldContainer container = weld.initialize();
BookService bookService =
container.instance().select(BookService.class).get();
Book book = bookService.createBook("H2G2", 12.5f, "
");
System.out.println(book);
weld.shutdown();
}
}

2.51 Weld, .
CDI, OpenWebBeans
(Apache) CanDI (Caucho). CDI API .

CDI beans.xml
CDI
, beans.xml .
2.52, beans.xml ,
CDI, .
2.52. beans.xml CDI

<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
version="1.1" bean-discovery-mode="all">
</beans>

Maven
Main BookServiceIT. pom.xml 2.53
(org.jboss.weld.se:weld-se APICDI
Weld) (junit:junit). 1.7 maven-compilerplugin , JavaSE7 (<source>1.7</source>). ,
exec-maven-plugin ,
Main Maven.

93

2.53. pom.xml ,

<?xml version="1.0" encoding="UTF-8"?>


<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.agoncal.book.javaee7</groupId>
<artifactId>chapter02</artifactId>
<version>1.0</version>
</parent>
<groupId>org.agoncal.book.javaee7.chapter02</groupId>
<artifactId>chapter02-putting-together</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<goals>
<goal>java</goal>

94

2.
</goals>
<configuration>
<mainClass>org.agoncal.book.javaee7.chapter02.Main</mainClass>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.12.4</version>
<executions>
<execution>
<id>integration-test</id>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

, pom.xml, Maven:
$ mvn compile

Main
exec-maven-plugin, pom.xml 2.53,
Main, 2.51.
, pom.xml, Maven:
$ mvn exec:java

Main, BookService
Book. Logger :
Info: ISBN : 13-84356-1864341788
Book{title='H2G2', price=12.5, description='
', isbn='13-84356-1864341788'}

BookServiceIT
2.54 , BookServiceIT BookService.
API, Weld, CDI

95

Main , 2.51.
BookService.createBook, ,
"MOCK". , MockGenerator ( IsbnGenerator).
2.54. BookServiceIT

public class BookServiceIT {


@Test
public void shouldCheckNumberIsMOCK () {
Weld weld = new Weld();
WeldContainer container = weld.initialize();
BookService bookService =
container.instance().select(BookService.class).get();
Book book = bookService.createBook("H2G2", 12.5f, "
");
assertTrue(book.getNumber().startsWith("MOCK"));
weld.shutdown();
}
}


beans.xml

BookServiceIT 2.54 , MockGenerator. beans.xml


(2.55) ( <alternatives>).
, LoggingInterceptor beans.xml.
2.55. beans.xml

<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
version="1.1" bean-discovery-mode="all">
<alternatives>
<class>org.agoncal.book.javaee7.chapter02.MockGenerator</class>
</alternatives>
<interceptors>
<class>org.agoncal.book.javaee7.chapter02.LoggingInterceptor</class>
</interceptors>
</beans>


Maven Failsafe ( pom.xml 2.53) Maven:
$ mvn integration-test

96

2.

BookServiceIT .

.

POJO, CDI, ,
. Managed Bean ( JSR 330) CDI Bean ( JSR299) Java EE ,
. CDI , ,
, .
CDI ,
(), (), ,
(), , , .
Java EE, ,
. ,
, .
, CDI Java EE.
CDI.

3.

CDI, ,
, Java EE.
, , , , .

. ,
( ), .
, .
, , -.
, , ,
.
, . ,
, .
.
, . Java,
().
, , ,
. API, , -.
,
. :
. ,
-.
( Java EE, ).


,
() ,

98

3.

. ,
, ,
. ,
(, , -),
, -, - ( ),
(.3.1). , .

. 3.1.

. ,

, - Java, JavaScript,
XML-.

, ,
,
. , , . Java , (if order.get
DeliveryAddress() == null).
.
, . (
?
?)
,
, .

99

. ,
(; , cURL, HTTP; ). .
-. , , , .
-.
, .

, -
.


, , .
,
. (DDL, )
, . , (NOT NULL), (INTEGER)
(VARCHAR(20)).
20 .

: ,
. ,
, . , , ,
, .
.
.

: , . , ,
. ,
.
, -
JavaScript. ,

100 3.
-. , Java (Swing, Android),
.

/. ,
, , , . ()
.
XML. DDL .
XML XSD ( XML-)
XML-. XSD ,
XML-, .
XML ,
Java.

, (
) (JavaScript, Java, DDL, XSD).
,
.
, , . ,
, ( , , ). .
.
(Bean Validation) ,
Java, ,
DDL XSD. . , ,
-.
, , Java (Swing, Android). JavaBeans ,,
( ).
, ,
, , ,

101

. API , (
XML).



, Java. ,
,
. , 2000 Struts MVC- . , , Java (
-). , , Commons Validator Apache Commons Hibernate Validator. iScreen, OVal, Spring,
.

Bean Validation1.1
1.1 Java EE7.
() ,
. .
. ( ) .
.
API ,
.
,
( ).
.3.1 ,
Bean Validation 1.1.
3.1.

javax.validation

API

javax.validation.bo
otstrap

, ,

javax.validation.con
straints

javax.validation.gro
ups

102 3.
3.1 ()

javax.validation.me
tadata


API

javax.validation.spi

API,


Hibernate Validator . 2005 JBoss Hibernate
Annotations, 2007, 2009 ( Hibernate Validator4). Hibernate
Validator5 (1.1) -
, . .
API , .
Hibernate Validator5 , Bean Validation1.1. Apache BVal Bean Validation1.0, 1.1. Oval Bean Validation,
.


,
.
, .
. ,
Java, ? 3.1 , -.
3.1. Book.

public class Book {


@NotNull
private String title;
@NotNull @Min(2)
private Float price;
@Size(max = 2000)
private String description;
private String isbn;
private Integer nbOfPage;
// , ,
}

103

3.1 Book , , ,
. , @NotNull, @Min @Size.
, title
description 2000. ,
(, price
2).



.
, , ( ). Java EE (, @Entity, @Stateless
@Path). CDI ( )
. , :
, ;
, .
,
. , , .


, JavaBean,
. , RUNTIME javax.validation.Constraint
( ). 3.2
NotNull. , @Constraint(validatedBy = {}) NotNullValidator.
3.2. NotNull

@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})


@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = NotNullValidator.class)
public @interface NotNull {
String message() default "{javax.validation.constraints.NotNull.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}

,
:

104 3.
@Target({METHOD, FIELD, ...}) , ( );
@Retention(RUNTIME) , . RUNTIME,
;
@Constraint(validatedBy = NotNullValidator.class) (
),
;
@Documented , Javadoc .
.
Bean Validation :
message , , . ;
groups ,
, ;
payload .
, . ,
, , length
.


. validatedBy @Constraint
( 3.2). 3.3
@NotNull. , ConstraintValidator (NotNull) ,
( Object).
3.3. NotNull

public class NotNullValidator implements ConstraintValidator<NotNull, Object>


{
public void initialize(NotNull parameters) {
}
public boolean isValid(Object object, ConstraintValidatorContext context) {
return object != null;
}
}

ConstraintValidator ,
.

105

initialize - .
, .
isValid . , . false, , true . ConstraintValidatorContext
, ,
.

. 3.3 @NotNull Object (
, ). , ,
. ,
String, BigDecimal
Collection. :

( @Size ), ( String , BigDecimal
Collection<?>):
public class SizeValidatorForString
implements<Size, String>
{...}
public class SizeValidatorForBigDecimal implements<Size, BigDecimal> {...}
public class SizeValidatorForCollection implements<Size, Collection<?>> {...}


,
(, , , ,
, ). , @Target(Element
Type.*) (.3.2). :
FIELD ;
METHOD
;
CONSTRUCTOR ;
PARAMETER ;
TYPE , ;
ANNOTATION_TYPE , .
,
, Java.
. 3.4
Order, , , -.

106 3.
3.4. ,

@ChronologicalDates
public class Order {
@NotNull @Pattern(regexp = "[C,D,M][A-Z][0-9]*")
private String orderId;
private Date creationDate;
@Min(1)
private Double totalAmount;
private Date paymentDate;
private Date deliveryDate;
private List<OrderLine> orderLines;
public Order() {
}
public Order(@Past Date creationDate) {
this.creationDate = creationDate;
}
public @NotNull Double calculateTotalAmount(@GreaterThanZero Double
changeRate) {
// ...
}
//
}

3.4 @ChronologicalDates , Order (


, creationDate, paymentDate deliveryDate
). orderId :
(@NotNull) (@Pattern). Order , creationDate
. calculateTotalAmount (
) , changeRate
@GreaterThanZero, ,
.

,
. ,
, .
, .


Bean Validation
. .
, .3.2
(,

). javax.va
lidation.constraints.

107

3.2.

AssertFalse
AssertTrue

Boolean

true false

DecimalMax
DecimalMin

BigDecimal, BigInteger,
CharSequence, byte, short,
int, long

Future
Past

Calendar, Date

Max
Min

BigDecimal, BigInteger,
byte, short, int, long

Null
NotNull

Object

Pattern

CharSequence

Digits

BigDecimal, BigInteger,
CharSequence, byte, short,
int, long

Size

Object[], CharSequence,
Collection<?>, Map<?, ?>


, API , . (
).
(, , ).


()
. .
, @Target(ElementType.AN
NOTATION_TYPE),
.
.
3.5 , Email, API . , (@NotNull),
(@Size(min = 7)) (@Pattern).

108 3.
message, groups payload. : (validatedBy = {}).
3.5. ,

@NotNull
@Size(min = 7)
@Pattern(regexp = "[a-z0-9!#$%&'*+/=?^_`{|}~-]+
(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*"
+ "@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*
[a-z0-9])?")
@Constraint(validatedBy = {})
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface Email {
String message() default " ";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}

(@NotNull, @Size @Pattern)


( message()). ,
, , 3.5, @NotNull, ,
( ). ,
Email , . @ReportAsSingleViolation (
, 3.24). ,

,
, .
, . ,
.

, .
, .


, , ,
. :
,
.. .

109

3.6 POJO,
, CD-BookStore. POJO
String, URL. ,
URL , (,
http, ftp), / . @URL , ItemServerConnection URL. , resourceURL
URL (, file://www.cdbookstore.com/item/123). , itemURL ,
http- , www.cdbookstore.com
(, http://www.cdbookstore.com/book/h2g2).
3.6. URL,

public class ItemServerConnection {


@URL
private String resourceURL;
@NotNull @URL(protocol = "http", host = "www.cdbookstore.com")
private String itemURL;
@URL(protocol = "ftp", port = 21)
private String ftpServerURL;
private Date lastConnectionDate;
// , ,
}


URL, . 3.7 ,
( @Constraint, message, groups payload). ,
: protocol, host port, (, @URL(protocol = "http")). .
, , , , 1
.
3.7. URL

@Constraint(validatedBy = {URLValidator.class})
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
public @interface URL {
String message() default "Malformed URL";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String protocol() default "";
String host() default "";
int port() default -1;
}

110 3.
3.7 ,
@NotNull.

, validatedBy ( URLValidator.class).
3.8 URLValidator. ,
ConstraintValidator , , initialize isValid.
, URLValidator , (protocol, host port), initialize(URL url).
.
( URL), . itemURL
protocol, 3.6 "http".
3.8. URL

public class URLValidator implements ConstraintValidator<URL, String> {


private String protocol;
private String host;
private int port;
public void initialize(URL url) {
this.protocol = url.protocol();
this.host = url.host();
this.port = url.port();
}
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value == null || value.length() == 0) {
return true;
}
java.net.URL url;
try {
// URL java.net.URL ,
// URL
url = new java.net.URL(value);
} catch (MalformedURLException e) {
return false;
}
// ,
if (protocol != null && protocol.length() > 0 &&
!url.getProtocol().equals(protocol)) {
return false;
}
if (host != null && host.length() > 0 && !url.getHost().startsWith(host)) {
return false;
}
if (port != -1 && url.getPort() != port) {
return false;
}
return true;
}
}

111

isValid URL, 3.8.
value , (, file://www.cdbookstore.com/item/123). context
, (
). , .
3.8 java.net.URL , URL.
protocol, host port.
, false. ,
ConstraintViolation.
: isValid (if
(value == null ... return true)). Bean Validation
. @NotNull.
@URL @NotNull, , URL (
itemURL 3.6).
, . 3.8 URLValidator String ( Constraint
Validator<URL, String>). , @URL
(, lastConnectionDate ),
javax.validation.UnexpectedTypeException,
java.util.Date .
, ,
, (, URLValidator CharSequence, ,
: ConstraintValidator<URL, CharS equence> ),
( String, CharBuffer, StringBuffer, StringBuilder)
.

. ,
, , , EJB EntityManager
( ). initialize isValid
(@PostConstruct @PreDestroy).

,
( ).
@Pattern, . 3.9 , .

112 3.
AND. ,
orderId , .
3.9. POJO,

public class Order {


@Pattern.List({
@Pattern(regexp = "[C,D,M][A-Z][0-9]*"),
@Pattern(regexp = ".[A-Z].*?")
})
private String orderId;
private Date creationDate;
private Double totalAmount;
private Date paymentDate;
private Date deliveryDate;
private List<OrderLine> orderLines;
// , ,
}


,
. -: . 3.10 @Pattern,
( List) Pattern[].
RUNTIME
(
METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER).
3.10. ,

@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})


@Retention(RUNTIME)
@Constraint(validatedBy = PatternValidator.class)
public @interface Pattern {
String regexp();
String message() default "{javax.validation.constraints.Pattern.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
// @Pattern,
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
@interface List {
Pattern[] value();
}
}

. Bean Validation
, List.

113


, ( ).
. , , .
3.11 . -: , , . ,
: creationDate, paymentDate deliveryDate. @ChronologicalDates ,
.
3.11. ,

@ChronologicalDates
public class Order {
private String orderId;
private Double totalAmount;
private Date creationDate;
private Date paymentDate;
private Date deliveryDate;
private List<OrderLine> orderLines;
// , ,
}

3.12 @ChronologicalDates.
, , Constraint
Validator, Order. isValid ,
, true.
3.12. ChronologicalDates,

public class ChronologicalDatesValidator implements


ConstraintValidator<ChronologicalDates, Order> {
@Override
public void initialize(ChronologicalDates constraintAnnotation) {
}
@Override
public boolean isValid(Order order, ConstraintValidatorContext context) {
return order.getCreationDate().getTime() <
order.getPaymentDate().getTime() &&
order.getPaymentDate().getTime() <
order.getDeliveryDate().getTime();
}
}


, , Bean
Validation1.1. , ,

114 3.
( ).
( )
( ). ,
Bean Validation
, .
:
;

, .
3.13
. CardValidator
. @NotNull ValidationAlgorithm. validate Boolean ( ?) @AssertTrue
@NotNull @Future .
3.13.

public class CardValidator {


private ValidationAlgorithm validationAlgorithm;
public CardValidator(@NotNull ValidationAlgorithm validationAlgorithm) {
this.validationAlgorithm = validationAlgorithm;
}
@AssertTrue
public Boolean validate(@NotNull CreditCard creditCard) {
return validationAlgorithm.validate(creditCard.getNumber(),
creditCard.getCtrlNumber());
}
@AssertTrue
public Boolean validate(@NotNull String number, @Future Date expiryDate,
Integer controlNumber, String type) {
return validationAlgorithm.validate(number, controlNumber);
}
}


- .
, -.
, Java: . , ,
.
3.15 CD, Item (3.14). . CD, , ,
.

115

3.14. Item,

Public class Item {


@NotNull
protected Long id;
@NotNull @Size(min = 4, max = 50)
protected String title;
protected Float price;
protected String description;
@NotNull
public Float calculateVAT() {
return price * 0.196f;
}
@NotNull
public Float calculatePrice(@DecimalMin("1.2") Float rate) {
return price * rate;
}
}
3.15. CD, Item

public class CD extends Item {


@Pattern(regexp = "[A-Z][a-z]{1,}")
private String musicCompany;
@Max(value = 5)
private Integer numberOfCDs;
private Float totalDuration;
@MusicGenre
private String genre;
// ConstraintDeclarationException :
public Float calculatePrice(@DecimalMin("1.4") Float rate) {
return price * rate;
}
}

,
. calculateVAT, Item, CD.
.
.
, . , ( ).
, calculatePrice CD (.3.15),
javax.validati
on.ConstraintDeclarationException. , .

(.3.2), : message, groups payload.

116 3.
String, ,
.
,
.

, .message.
//
String message() default " ";
//
String message() default "{org.agoncal.book.javaee7.Email.message}";

ValidationMessages.properties
.
, .
org.agoncal.book.javaee7.Email.message=

, ,
.
@Email(message = " ")
private String recoveryEmail;

( javax.validation.Message
Interpolator) .
, , .
, {min} {max} :
javax.validation.constraints.Size.message = size must be between {min} and {max}

3.16 Customer,
. userId @Email, ,
,
.
: firstName age , .
3.16. Customer,

public class Customer {


@Email
private String userId;
@NotNull @Size(min = 4, max = 50, message = "
{min} {max} ")

117

private String firstName;
private String lastName;
@Email(message = " ")
private String recoveryEmail;
private String phoneNumber;
@Min(value = 18, message = " .
{value} ")
Private Integer age;
// , ,
}

ConstraintValidator
, ,
ConstraintValidator , , isValid. isValid , ,
ConstraintValidationContext. , , . .3.3 , javax.vali
dation.ConstraintValidatorContext.
3.3. ConstraintValidationContext

disableDefaultConstraintViolation

ConstraintViolation

getDefaultConstraintMessageTemplate

, ,

buildConstraintViolationWithTemplate

ConstraintViolationBuilder,

ConstraintValidatorContext , . build
ConstraintViolationWithTemplate ConstraintViolationBuilder,
API, .
:
context.buildConstraintViolationWithTemplate("Invalid protocol")
.addConstraintViolation();

-. @URL
3.7, ,
(Malformed URL). (protocol, host port),
, : Invalid protocol ( ) Invalid host ( ).

118 3.

ConstraintViolation .
, , , . .

3.17 URL ConstraintValidatorContext, .



(disableDefaultConstraintViolation)
.
3.17. URL, ConstraintValidatorContext

public class URLValidator implements ConstraintValidator<URL, String> {


private String protocol;
private String host;
private int port;
public void initialize(URL url) {
this.protocol = url.protocol();
this.host = url.host();
this.port = url.port();
}
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value == null || value.length() == 0) {
return true;
}
java.net.URL url;
try {
url = new java.net.URL(value);
} catch (MalformedURLException e) {
return false;
}
if (protocol != null && protocol.length() > 0 &&
!url.getProtocol().equals(protocol)) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate("
").addConstraintViolation();
return false;
}
if (host != null && host.length() > 0 && !url.getHost().startsWith(host)) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate("
").addConstraintViolation();
return false;
}
if (port != -1 && url.getPort() != port) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate("
").addConstraintViolation();
return false;

119

}
return true;
}
}

,
. ,
( )
? .
, .
.
public interface Payment {}

- . , Payment () , , , . ,
groups :
@Past(groups = Payment.class)
private Date paymentDate;

, -,
,
groups :
@Past(groups = {Payment.class, Delivery.class})
private Date deliveryDate;

groups.
, javax.validation.groups.Default. , Default:
@NotNull
private Long id;
@Past(groups = Default.class)
private Date creationDate;

,
@ChronologicalDates, . Order 3.18 ,
: creationDate, paymentDate deliveryDate.
, creationDate, paymentDate
deliveryDate. ,
, creationDate. ,
creationDate ,
( ,
javax.validation.groups.Default). paymentDate

120 3.
Payment, deliveryDate @ChronologicalDates
Delivery.
3.18. ,

@ChronologicalDates(groups = Delivery.class)
public class Order {
@NotNull
private Long id;
@NotNull @Past
private Date creationDate;
private Double totalAmount;
@NotNull(groups = Payment.class) @Past(groups = Payment.class)
private Date paymentDate;
@NotNull(groups = Delivery.class) @Past(groups = Delivery.class)
private Date deliveryDate;
private List<OrderLine> orderLines;
// , ,
}

, , , Bean Validation .


, Java EE7,
(
) XML. Bean Validation
, META-INF. ,
validation.xml, (,
, , ). , ,
. Java EE7, XML .
3.19 validation.xml, XML- validation-config. ,
: constraints.xml ( 3.20).
3.19. validation.xml,

<?xml version="1.0" encoding="UTF-8"?>


<validation-config
xmlns="http://jboss.org/xml/ns/javax/validation/configuration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/configuration
validation-configuration-1.1.xsd"
version="1.1">
<constraint-mapping>META-INF/constraints.xml</constraint-mapping>
</validation-config>

121

3.20. ,

<?xml version="1.0" encoding="UTF-8"?>


<constraint-mappings
xmlns="http://jboss.org/xml/ns/javax/validation/mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/mapping
validation-mapping-1.1.xsd"
version="1.1">
<bean class="org.agoncal.book.javaee7.chapter03.Book" ignore-annotations="false">
<field name="title">
<constraint annotation="javax.validation.constraints.NotNull">
<message>Title should not be null</message>
</constraint>
</field>
<field name="price">
<constraint annotation="javax.validation.constraints.NotNull"/>
<constraint annotation="javax.validation.constraints.Min">
<element name="value">2</element>
</constraint>
</field>
<field name="description">
<constraint annotation="javax.validation.constraints.Size">
<element name="max">2000</element>
</constraint>
</field>
</bean>
</constraint-mappings>

constraints.xml 3.20
, Book.
@NotNull title
( ). price
, 2.
3.1, .


, ,
, ,
. . Java EE7,
.
, , , , . ,
. ,
, , ,
. ,
API.

122 3.

API
API, . API javax.validation.Va
lidator. , ( ,
- -).
javax.validation.ConstraintViolation.
, , .

Validator. API
,
, .3.4.
.
1. ConstraintValidator,
(, ConstraintValidator @Size, ).
2. isValid.
3. isValid true, .
4. isValid false,
ConstraintViolation .
3.4. Validator

<T> Set<ConstraintViolation<T>>vali
date(Tobject, Class<?>... groups)

<T> Set<ConstraintViolation<T>>vali
dateProperty(Tobject, String propName,
Class<?>... groups)

<T> Set<ConstraintViolation<T>>vali
dateValue(Class<T> beanType, String
propName, Object value,Class<?>... groups)

BeanDescriptor getConstraints
ForClass(Class<?> clazz)

ExecutableValidator forExecutables()

-
, ValidationException.
(
, , ).

123

validate, validateProperty validateValue
, .
varargs,
. forExecutables ExecutableValidator
, . .3.5 API ExecutableValidator.
3.5. ExecutableValidator

<T> Set<ConstraintViolation<T>>vali
,
dateParameters(Tobject, Method

method, Object[] params, Class<?>... groups)
<T> Set<ConstraintViolation<T>>vali
dateReturnValue(Tobject, Method method,
Object returnValue, Class<?>... groups)

<T> Set<ConstraintViolation<T>>vali
dateConstructorParameters
(Constructor<T> constructor, Object[]
params, Class<?>... groups)

<T> Set<ConstraintViolation<T>>vali
dateConstructorReturnValue
(Constructor<T> constructor,
TcreatedObject, Class<?>... groups)

ConstraintViolation
, .3.4 3.5,
ConstraintViolation, ,
. ,
.
ConstraintViolation . ConstraintViolation
, , API
. .3.6 API.
3.6. ConstraintViolation

String getMessage()

String getMessageTemplate()

T getRootBean()

Class<T> getRootBeanClass()

124 3.
3.6 ()

Object getLeafBean()

Path getPropertyPath()

Object getInvalidValue()

ConstraintDescriptor<?>
getConstraintDescriptor()


Validator.
Java EE, Validator
( ), (
EJB- -).
, Validation,
.
buildDefaultValidatorFactory ValidatorFactory,
, , Validator.
:
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();

ValidatorFactory :
factory.close();

Java EE,
JNDI :
ValidatorFactory java:comp/ValidatorFactory;
Validator java:comp/Validator.
JNDI- Validator.
JNDI ,
@Resource:
@Resource ValidatorFactory validatorFactory;
@Resource Validator validator;

CDI ( Java EE7 ), @Inject:


@Inject ValidatorFactory;
@Inject Validator;

125

( @Resource, @Inject)
.
ValidatorFactory.


Validator , ,
. 3.21 CD, , , .
3.21. ,

public class CD {
@NotNull @Size(min = 4, max = 50)
private String title;
@NotNull
private Float price;
@NotNull(groups = PrintingCatalog.class)
@Size(min = 100, max = 5000, groups = PrintingCatalog.class)
private String description;
@Pattern(regexp = "[A-Z][a-z]{1,}")
private String musicCompany;
@Max(value = 5)
private Integer numberOfCDs;
private Float totalDuration;
@NotNull @DecimalMin("5.8")
public Float calculatePrice(@DecimalMin("1.4") Float rate) {
return price * rate;
}
@DecimalMin("9.99")
public Float calculateVAT() {
return price * 0.196f;
}
}

,
CD Validator.validate(). , ConstraintViolation. CD ( ), .
, .
CD cd = new CD("Kind of Blue", 12.5f);
Set<ConstraintViolation<CD>> violations = validator.validate(cd);
assertEquals(0, violations.size());

, ConstraintViolation
, ( @NotNull):
CD cd = new CD();
Set<ConstraintViolation<CD>> violations = validator.validate(cd);
assertEquals(2, violations.size());

126 3.


. Validator.validateProperty(), .
CD ,
; , . ,
numberOfCDs, :
CD cd = new CD();
cd.setNumberOfCDs(2);
Set<ConstraintViolation<CD>> violations = validator.validateProperty(cd,
"numberOfCDs");
assertEquals(0, violations.size());

, ,
CD , . : API ConstraintViolation
, , , :
CD cd = new CD();
cd.setNumberOfCDs(7);
Set<ConstraintViolation<CD>> violations = validator.validateProperty(cd,
"numberOfCDs");
assertEquals(1, violations.size());
assertEquals("must be less than or equal to 5", violations.iterator().next().
getMessage());
assertEquals(7, violations.iterator().next().getInvalidValue());
assertEquals("{javax.validation.constraints.Max.message}",
violations.iterator().next().getMessageTemplate());


Validator.validateValue(), ,
. ,
,
.
CD, numberOfCDs
CD. , ( CD ):
Set<ConstraintViolation<CD>> constr = validator.validateValue(CD.class,
"numberOfCDs", 2);
assertEquals(0, constr.size());
Set<ConstraintViolation<CD>> constr = validator.validateValue(CD.class,
"numberOfCDs", 7);
assertEquals(1, constr.size());

127


javax.validation.ExecutableValidator .
Validator.forExecutables() ExecutableValidator, validateParameters, validateReturnValue, validateConstructorParameters
validateConstructorReturnValue.
calculatePrice, 1.2.
, :
@DecimalMin("1.4").
java.lang.reflect.Method, calculatePrice
Float . ExecutableValidator
validateParameters, ,
( 1.2). , .
CD cd = new CD("Kind of Blue", 12.5f);
Method method = CD.class.getMethod("calculatePrice", Float.class);
ExecutableValidator methodValidator = validator. forExecutables();
Set<ConstraintViolation<CD>> violations = methodValidator.
validateParameters(cd, method,
new Object[]{new Float(1.2)});
assertEquals(1, violations.size());


. .
,
. , Default. ,
, ,
. ,
(javax.va
lidation.groups.Default). Default , Default
.
3.21 ,
description, Default. (@NotNull @Size(min = 100, max =
5000)) ,
( PrintingCatalog). , CD , ,
Default,
@NotNull, title price.
CD cd = new CD();
cd.setDescription("Best Jazz CD ever");
Set<ConstraintViolation<CD>> violations = validator.validate(cd, Default.
class);
assertEquals(2, violations.size());

128 3.
:
Default, . ,
:
Set<ConstraintViolation<CD>> violations = validator. validate(cd);

, CD
PrintingCatalog, ,
description, :
CD cd = new CD();
cd.setDescription("Too short");
Set<ConstraintViolation<CD>> violations = validator.validate(cd,
PrintingCatalog.class);
assertEquals(1, violations.size());


Default PrintingCatalog, (@NotNull
title price, ):
CD cd = new CD();
cd.setDescription("Too short");
Set<ConstraintViolation<CD>> violations = validator.validate(cd, Default.
class, PrintingCatalog.class);
assertEquals(3, violations.size());


Java-,
,
. CDI JavaSE ( - GlassFish).
, ,
.
.3.2 Customer, (Address). (@NotNull, @Size @Past),
.
:
@Email ,
;
@ZipCode , ZIP- (
). ,
(ZipCodeValidator). : ZipCodeValidator ZipCodeChecker @Inject (CDI- @USA).
, .3.2, Maven :
src/main/java Customer, Address ZipCode
Email;

. 3.2.

129

130 3.
src/main/resources beans.xml,
CDI, ValidationMessages.properties ,
;
src/test/java AddressIT CustomerIT;
pom.xml Maven (POM),
.

Customer
CD-Book Store , ,
. ,
. ,
. 3.22
Customer, , (firstname , dateOfBirth ). @Email,
. , String .
3.22. Customer

public class Customer {


@NotNull @Size(min = 2)
private String firstName;
private String lastName;
@Email
private String email;
private String phoneNumber;
@Past
private Date dateOfBirth;
private Address deliveryAddress;
// , ,
}

Address
Customer . Address ,
,
: , , , ZIP- . 3.23
Address @NotNull, (street1, city
zipcode), @ZipCode, ZIP-
( ).
3.23. Address .
@ZipCode

public class Address {


@NotNull
private String street1;

131

private String street2;
@NotNull
private String city;
private String state;
@NotNull @ZipCode
private String zipcode;
private String country;
// , ,
}

@Email
@Email ,
. (@Const
raint(validatedBy = {})), (@Pattern) .
3.24 @Email.
3.24.

@Size(min = 7)
@Pattern(regexp = "[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\."
+ "[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*"
+ "@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")
@ReportAsSingleViolation
@Constraint(validatedBy = {})
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
public @interface Email {
String message() default " {org.agoncal.book.javaee7.chapter03.Email.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
@interface List {
Email[] value();
}
}

: 3.24
, META-INF/ValidationMessages.properties.
org.agoncal.book.javaee7.chapter03.Email.message=invalid email address

@ZipCode
@ZipCode , @Email. ZIP-
(, ), . ,
ZIP- , ,
, , ZIP-

132 3.
. ZipCode 3.25
(ZipCodeValidator).
3.25. @ZipCode

@Constraint(validatedBy = ZipCodeValidator.class)
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
public @interface ZipCode {
String message() default "{org.agoncal.book.javaee7.chapter03.ZipCode.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
@interface List {
ZipCode[] value();
}
}

3.26 : ZipCode
Validator javax.validation.ConstraintValidator
String. isValid ,
: ZipCodeChecker. ZipCodeChecker ,
. , (@Inject)
CDI (@USA, 3.27). ,
CDI Bean Validation.
3.26. ZipCodeValidator

public class ZipCodeValidator implements ConstraintValidator<ZipCode, String> {


@Inject @USA
private ZipCodeChecker checker;
private Pattern zipPattern = Pattern.compile("\\d{5}(-\\d{5})?");
public void initialize(ZipCode zipCode) {
}
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value == null)
return true;
Matcher m= zipPattern.matcher(value);
if (!m.matches())
return false;
return checker.isZipCodeValid(value);
}
}
3.27. USACDI

@Qualifier
@Retention(RUNTIME)
@Target({FIELD, TYPE, METHOD})
public @interface USA {
}

133


, , JPA ( ) JSF ( ).


CustomerIT AddressIT
, ? @Email, , , @ZipCode,
( ).
, ValidatorFactory
Validator, .
3.28 CustomerIT, Customer. Validator (
ValidatorFactory), close() .
: Customer,
, .
3.28. CustomerIT

public class CustomerIT {


private static ValidatorFactory vf;
private static Validator validator;
@BeforeClass
public static void init() {
vf = Validation.buildDefaultValidatorFactory();
validator = vf.getValidator();
}
@AfterClass
public static void close() {
vf.close();
}
@Test
public void shouldRaiseNoConstraintViolation() {
Customer customer = new Customer("John", "Smith", "jsmith@gmail.com");
Set<ConstraintViolation<Customer>> violations = validator.validate(customer);
assertEquals(0, violations.size());
}
@Test
public void shouldRaiseConstraintViolationCauseInvalidEmail() {
Customer customer = new Customer("", "", "DummyEmail");
Set<ConstraintViolation<Customer>> violations = validator.validate(customer);
assertEquals(1, violations.size());
assertEquals("invalid email address", violations.iterator().next().
getMessage());
assertEquals("dummy", violations.iterator().next().getInvalidValue());

134 3.
assertEquals("{org.agoncal.book.javaee7.chapter03.Email.message}",
violations.iterator().next().getMessageTemplate());
}
}

3.29 (Validator
, , ),
Address.
3.29. AddressIT

public class AddressIT {


@Test
public void shouldRaiseConstraintViolationCauseInvalidZipCode() {
ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
Validator validator = vf.getValidator();
Address address = new Address("233 ", "-", "NY",
"DummyZip", "");
Set<ConstraintViolation<Address>> violations =
validator.validate(address);
assertEquals(1, violations.size());
vf.close();
}
}

Maven
, .
pom.xml 3.20 ,
: Hibernate Validator ( Bean Validation) Weld (
CDI). : pom.xml Failsafe, (
CustomerIT AddressIT).
3.30. pom.xml

<?xml version="1.0" encoding="UTF-8"?>


<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>chapter03</artifactId>
<groupId>org.agoncal.book.javaee7</groupId>
<version>1.0</version>
</parent>
<groupId>org.agoncal.book.javaee7.chapter03</groupId>
<artifactId>chapter03-putting-together</artifactId>
<version>1.0</version>
<dependencies>
<dependency>

135

<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se</artifactId>
<version>2.0.0.Final</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.12.4</version>
<executions>
<execution>
<id>integration-test</id>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

, , pom.xml, Maven:
$ mvn compile

Maven Failsafe,
:
$ mvn integration-test

136 3.

,
, .
, - , API
, .
, , .

. Bean Validation
, , ,
(@Email, @URL, @CreditCard).
Bean Validation
. ,
POJO, . Bean Validation1.1 ,
. , .
,
Java EE, JPA JSF .

4.
Java Persistence API
-, , . ,
, . ,
. :
-,
. ,
(
).
, .
,
. .
- , Java,
. Java ,
. ,
,
. , ,
, , , , ..
,
Java (Java Virtual Machine JVM): Java
, . , .
,
, - .. , , .
- (Object-Relational Mapping
ORM) .

, , , -
, . . , Hibernate, TopLink Java Data
Objects (JDO), Java Persistence API (JPA)
Java EE7.

138 4. Java Persistence API


JPA,
- ,
.


,

. ,
. , , .
. ;
, , ..
, JPA.
, ,
Java Persistence Query Language,
JPQL. - . , ,
. JPA
.
,
. JPA Java-
(Plain Old Java Object POJO). , ,
, Java-. ( ),
.
4.1.
4.1. Book

@Entity
public class Book {
@Id @GeneratedValue
private Long id;
private String title;
private Float price;
private String description;
private String isbn;
private Integer nbOfPage;
private Boolean illustrations;
public Book() {
}
// ,
}

4.1 Book,
. , -

139

, , Java-:
(id, title, price ..) (Long, String, Float, Integer Boolean),
,
. ?
.


, @javax.persisten
ce.Entity,
, POJO. , @javax.persistence.Id
. JPA ,
, . 4.1 (title, price, description ..) , .
, , ,
-. ,
Book Java-, - . , ,
.
- @javax.persistence.Entity
( XML- ).
@javax.persistence.Id.
- ,
public protected. -
.
- .
.
- final.
- final.

(, ), Serializable.

Java EE Entity Bean
(- EJB) Entity Bean CMP (Container-Managed Persistence) ( - EJB, )
Enterprise JavaBeans. , J2EE1.3
1.4,
JPA Java EE5. JPA -
EJB .

140 4. Java Persistence API

-
-
( JPA) . ,
,
, . ,
. JPA
? : .
, . . .
, javax.persistence.
XML- ( )
XML-. XML, .
, , , .
Book ( 4.1)
JPA, Book BOOK. , isbn
, ISBN
( , ..).
.4.1, Book BOOK,
(,
isbn, String, , ISBN
VARCHAR).
, .
Java EE5 ( ), -
Java EE7. , , , . , . ,
, ,
. , , .
,
.
Book 4.1
POJO, . :

141

.4.1.

, , , Book
. , , @Entity.
. ,
id ,
@Id,
@GeneratedValue. , ,
, . ,

.
(,
Book BOOK). , @Table,
.

142 4. Java Persistence API


(, id
getId() ID). , @Column.
JDBC Java- . String VARCHAR, Long BIGINT, Boolean SMALLINT
.. , String, 255
(String VARCHAR(255)). , . , String
VARCHAR Derby VARCHAR2,
Oracle. Integer INTEGER
Derby NUMBER Oracle. ,
, persistence.xml,
.
, Book Derby-
, 4.2.
4.2. BOOK

CREATE TABLE BOOK (


ID BIGINT NOT NULL,
TITLE VARCHAR(255),
PRICE FLOAT,
DESCRIPTION VARCHAR(255),
ISBN VARCHAR(255),
NBOFPAGE INTEGER,
ILLUSTRATIONS SMALLINT DEFAULT 0,
PRIMARY KEY (ID)
)

JPA2.1 API-
, 4.2. ,
. , .
4.1 . , ,
, .
- ( ).
, -
. JPA . .
,
( ).
, JPA
.

143


JPA . (
XML) , .
NoSQL (Not Only SQL SQL) ( ):
/, , . JPA . Hibernate OGM
, . EclipseLink NoSQL-. Hibernate OGM EclipseLink , ,
NoSQL.


JPA ,
. JPA ,
-
,
. API-,
, javax.persistence.EntityManager.
,
CRUD (create, read,
update, delete , , , ), JPQL. EntityManager , (, EclipseLink).
, EntityManager Book:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("chapter04PU");
EntityManager em = emf.createEntityManager();
em.persist(book);

.4.2 ,
( Main)
( Book). , persist() find(),
EntityManager JDBC- SQL (Structured Query
Language ) INSERT SELECT.
. ,
SQL JPA JPQL. (.)
. , H2G2, :
SELECT bFROM Book bWHERE b.title = 'H2G2'

, title Book,
. JPQL- ,
. JPQL-

144 4. Java Persistence API

.4.2.

( ) (
) .
SQL- . ,
, (@NamedQuery),
XML-. JPQL- , ,
Book. 4.3 Book findBookH2G2
@NamedQuery ( 6).
4.3. Book findBookH2G2

@Entity
@NamedQuery(name = "findBookH2G2",
query = "SELECT bFROM Book bWHERE b.title ='H2G2'")
public class Book {
@Id @GeneratedValue
private Long id;
private String title;
private Float price;
private String description;
private String isbn;
private Integer nbOfPage;
private Boolean illustrations;
// , ,
}
EntityManager Java-
. 4.4 , Book, . 1 5.

1. Book .
POJO, . Java
, POJO,

145

new. ,
Book.

2. EntityManager . ,
EntityManager .
EntityManagerFactory chapter04PU.
EntityManagerFactory EntityManager ( em), ( tx) Book.
3. Book . (tx.begin())
EntityManager.persist() Book.
(tx.commit()) .
4. . - EntityManager
Book findBookH2G2.
5. EntityManager EntityManagerFactory.
4.4. Main,
Book

public class Main {


public static void main(String[] args) {
// 1. Book
Book book = new Book("H2G2", " ", 12.5F,
"1-84023-742-2", 354, false);
// 2. EntityManager
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("chapter04PU");
EntityManager em = emf.createEntityManager();
// 3. Book
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(book);
tx.commit();
// 4.
book = em.createNamedQuery("findBookH2G2", Book.class).getSingleResult();
// 5. EntityManager EntityManagerFactory
em.close();
emf.close();
}
}

SQL- JDBC- 4.4. .4.2, Main


EntityManager ,
,
Book . EntityManager
. EntityManager
SQL-
JDBC-.

146 4. Java Persistence API


JDBC- ?
? ? . Main (. 4.4) EntityManagerFactory,
;
chapter04PU. EntityManager
,
persistence.xml, 4.5
.
4.5. persistence.xml,

<?xml version="1.0" encoding="UTF-8"?>


<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="chapter04PU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>org.agoncal.book.javaee7.chapter04.Book</class>
<properties>
<property name="javax.persistence.schema-generation-action"
value="drop-and-create"/>
<property name="javax.persistence.schema-generation-target"
value="database"/>
<property name="javax.persistence.jdbc.driver"
value="org.apache.derby.jdbc.ClientDriver"/>
<property name="javax.persistence.jdbc.url"
value="jdbc:derby://localhost:1527/chapter04DB;create=true"/>
<property name="javax.persistence.jdbc.user" value="APP"/>
<property name="javax.persistence.jdbc.password" value="APP"/>
</properties>
</persistence-unit>
</persistence>

chapter04PU JDBC-
Derby chapter04DB,
1527. (APP) (APP)
URL-. <class>
Book ( , <mapping-file>, <jar-file> <excludeunlisted-classes>).
POJO, .


POJO. EntityManager
POJO, (, ),

147

. (
EntityManager), Java. , (.4.3).
Book new, , JPA (
)
EntityManager, BOOK . EntityManager.remove()
, Java- ,
.

.4.3.

: , ,
, , , . pre
post ( , post). EntityManager
-. 6,
@PrePersist, @PostPersist .. JPA -
, .
( ) ( ).
.

148 4. Java Persistence API

Bean Validation
Bean Validation, , Java EE .
JPA .
Bean Validation . , JPA
Bean Validation pre-persist, pre-update pre-remove. , - validate
Validator .
4.6 Book Bean Validation
(@NotNull @Size). title null, ( EntityManager.persist()),
JPA ConstraintViolation , .
4.6. Bean Validation

@Entity
public class Book {
@Id @GeneratedValue
private Long id;
@NotNull
private String title;
private Float price;
@Size(min = 10, max = 2000)
private String description;
private String isbn;
private Integer nbOfPage;
private Boolean illustrations;
// , ,
}

JPA
JPA 1.0 Java EE5 . - . Java EE7 JPA2.1 , .
API- Enterprise JavaBeans,
- JavaSE .
JPA JDBC,
SQL. API-
javax.persistence. JPA.
- ,
, .

149
JPA
API ,
, CRUD-.
JPQL, -
.
, Java Transaction
API (JTA) . JPA
(-JTA) .
-
.

JPA
, - , , Java.
TopLink Smalltalk 1994, Java. - ,
TopLink, Java.
, Java.
-
JDO, .
1998 EJB1.0, J2EE1.2.
, , -. Entity Bean CMP,
EJB1.0 , EJB1.1
EJB2.1 (J2EE1.4).

, .
-
, .
J2EE
,
: Hibernate, ,
- .
Entity CMP 2.x
Hibernate Enterprise Edition Java EE5.
JPA1.0 , Hibernate.
JPA1.0 EJB3.0 (JSR 220). 2009 JPA2.0 (JSR317)
Java EE6 API-, JPQL
, , , ,
Criteria API.
, Java EE7, JPA2.1 . JSR 338.

150 4. Java Persistence API

JPA2.1
JPA 1.0 Entity
CMP 2.x , JPA 2.0 JPA 1.0, JPA2.1 .
JPA2.1 , API-
( persistence.xml).
,
.
CDI .
JPA 2.1
.

Criteria API ;
.
TREAT
.
.4.1 , JPA2.1 .
4.1. JPA-

javax.persistence

API-
-

javax.persistence.criteria

Java Persistence Criteria API

javax.persistence.metamode

Java Persistence Metamodel API

javax.persistence.spi

SPI Java Persistence


EclipseLink 2.5 JPA2.1, . Java- . EclipseLink JPA, XML- Java XML
Binding (JAXB) Service Data Objects (SDO). EclipseLink
- ,
Object XML Mapping (OXM), (Enterprise Information System EIS) c Java EE Connector Architecture (JCA) - .
EclipseLink TopLink Oracle,
Eclipse Foundation 2006. EclipseLink

151

JPA ,
. , .
EclipseLink JPA 2.1.
Hibernate OpenJPA
.


, JPA, EclipseLink, ,
JPQL, ,
. , Book Bean Validation
Main, . Maven
EclipseLink Derby. , , ,
(BookIT) JUnit4 Derby
.
Maven,
, .4.4, :
src/main/java Book Main;
src/main/resources persistence.xml,
Main BookIT, insert.sql;
src/test/java BookIT, ;
pom.xml POM- Maven,
.

.4.4.

152 4. Java Persistence API

Book
Book, 4.7, src/main/java. (title, price ..) (String, Float, Integer Boolean), Bean Validation
(@NotNull @Size), JPA.
@Entity , .
@NamedQueries @NamedQuery , JPQL
.
@Id id .
@GeneratedValue
id .
4.7. Book

package org.agoncal.book.javaee7.chapter04;
@Entity
@NamedQueries({
@NamedQuery(name = "findAllBooks", query = "SELECT bFROM Book b"),
@NamedQuery(name = "findBookH2G2", query = "SELECT bFROM Book b
WHERE b.title ='H2G2'")
})
public class Book {
@Id @GeneratedValue
private Long id;
@NotNull
private String title;
private Float price;
@Size(min = 10, max = 2000)
private String description;
private String isbn;
private Integer nbOfPage;
private Boolean illustrations;
// , ,
}

, ,
. ,
, Book POJO. Main,
Book .

Main
Main, 4.8, ,
Book. , Book ( Java new) .

153

, Java-.
Persistence EntityManagerFactory, chapter04PU, , . EntityManagerFactory
EntityManager ( em). , EntityManager
JPA , , Book EntityManager.persist(),
. main() EntityManager,
EntityManagerFactory , .
4.8. Main, Book

package org.agoncal.book.javaee7.chapter04;
public class Main {
public static void main(String[] args) {
// Book
Book book = new Book("H2G2", " ",
12.5F, "1-84023-742-2", 354, false);
// EntityManager
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("chapter04PU");
EntityManager em = emf.createEntityManager();
// Book
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(book);
tx.commit();
// EntityManager EntityManagerFactory
em.close();
emf.close();
}
}

- .
, , EntityManager .

BookIT
Entity CMP 2.x
. JPA ,

. ?
.
. ,
, ,
, (
).
.

154 4. Java Persistence API


? ,
findBookH2G2 ? , ?
, ,
. JPA-. CRUD- JPQL-
, (
.jar, ). ,
BookIT Derby.
Maven , , . BookIT,
4.9, src/test/java
, Book , ,
Bean Validation.
4.9. , Book

public class BookIT {


private static EntityManagerFactory emf =
Persistence.createEntityManagerFactory("chapter04TestPU");
private EntityManager em;
private EntityTransaction tx;
@Before
public void initEntityManager() throws Exception {
em = emf.createEntityManager();
tx = em.getTransaction();
}
@After
public void closeEntityManager() throws Exception {
if (em != null) em.close();
}
@Test
public void shouldFindjavaee7Book() throws Exception {
Book book = em.find(Book.class, 1001L);
assertEquals(" Java EE7", book.getTitle());
}
@Test
public void shouldCreateH2G2Book() throws Exception {
// Book
Book book = new Book("H2G2", " ",
12.5F, "1-84023-742-2", 354, false);
// Book
tx.begin();
em.persist(book);
tx.commit();
assertNotNull("ID ", book.getId());

155

//
book = em.createNamedQuery("findBookH2G2", Book.class).getSingleResult();
assertEquals(" ", book.getDescription());
}
@Test(expected = ConstraintViolationException.class)
public void shouldRaiseConstraintViolationCauseNullTitle() {
Book book = new Book(null, " , ", 12.5F,
"1-84023-742-2", 354, false);
em.persist(book);
}
}

Main, BookIT 4.9 EntityManager


EntityManagerFactory. JUnit4. @Before @After
. EntityManager .
shouldFindJavaEE7Book() ,
( inset.sql ), Book 1001 ,
" Java EE7". shouldCreateH2G2Book()
Book ( EntityManager.persist()) ,
EclipseLink ( assertNotNull). ,
, " " Book.
Book Nulltitle, Book , ConstraintViolationException.


Main (. 4.8), EntityManagerFactory
chapter04PU. BookIT
(. 4.9) (chapter04TestPU).
persistence.xml, src/main/resources/META-INF (4.10). , JPA, , JPA
( EclipseLink) (Derby). , (URL-,
JDBC-, , ),
(drop-and-create ,
, ). <provider> , EclipseLink. , . <class> Book.
, chapter04PU Derby, chapter04TestPU ,
. ,
inset.sql .

156 4. Java Persistence API


4.10. persistence.xml

<?xml version="1.0" encoding="UTF-8"?>


<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="chapter04PU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>org.agoncal.book.javaee7.chapter04.Book</class>
<properties>
<property name="javax.persistence.schema-generation-action"
value="drop-and-create"/>
<property name="javax.persistence.schema-generation-target"
value="database-and-scripts"/>
<property name="javax.persistence.jdbc.driver"
value="org.apache.derby.jdbc.ClientDriver"/>
<property name="javax.persistence.jdbc.url"
value="jdbc:derby://localhost:1527/chapter04DB;create=true"/>
<property name="javax.persistence.jdbc.user" value="APP"/>
<property name="javax.persistence.jdbc.password" value="APP"/>
<property name="javax.persistence.sql-load-script-source"
value="insert.sql"/>
</properties>
</persistence-unit>
<persistence-unit name="chapter04TestPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>org.agoncal.book.javaee7.chapter04.Book</class>
<properties>
<property name="javax.persistence.schema-generation-action"
value="drop-and-create"/>
<property name="javax.persistence.schema-generation-target"
value="database"/>
<property name="javax.persistence.jdbc.driver"
value="org.apache.derby.jdbc.EmbeddedDriver"/>
<property name="javax.persistence.jdbc.url"
value="jdbc:derby:memory:chapter04DB;create=true"/>
<property name="javax.persistence.sql-load-script-source"
value="insert.sql"/>
</properties>
</persistence-unit>
</persistence>

SQL-
, 4.10,
insert.sql ( javax.persistence.sql-loadscript-source).
, , 4.11, .

157

4.11. insert.sql

INSERT INTO BOOK(ID, TITLE, DESCRIPTION, ILLUSTRATIONS, ISBN, NBOFPAGE,


PRICE) values (1000, Java EE 6',
' Java EE', 1, '1234-5678', 450, 49)
INSERT INTO BOOK(ID, TITLE, DESCRIPTION, ILLUSTRATIONS, ISBN, NBOFPAGE,
PRICE) values (1001, ' Java EE 7', ', ',
1, '5678-9012', 550, 53)
INSERT INTO BOOK(ID, TITLE, DESCRIPTION, ILLUSTRATIONS, ISBN, NBOFPAGE,
PRICE) values (1010, ' ', '
', 0, '9012-3456', 222, 23)

BookIT (
shouldFindJavaEE7Book), , ,
Book 1001. .


Maven

Main : Book , BookIT
,
Derby. Maven ,
javac. pom.xml, JPA
Bean Validation API. Maven ,
Java SE7, maven-compiler-plugin,
4.12.
4.12. Maven- pom.xml ,

<?xml version="1.0" encoding="UTF-8"?>


<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>parent</artifactId>
<groupId>org.agoncal.book.javaee7</groupId>
<version>1.0</version>
</parent>
<groupId>org.agoncal.book.javaee7</groupId>
<artifactId>chapter04</artifactId>
<version>1.0</version>
<dependencies>
<dependency>

158 4. Java Persistence API


<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derbyclient</artifactId>
<version>10.9.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<version>10.9.1.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.12.4</version>
<executions>
<execution>
<id>integration-test</id>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>

159

</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>org.agoncal.book.javaee7.chapter04.Main</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>

, , JPA API, ,
javax.persistence. , EclipseLink ( )
org.eclipse.persistence.jpa. , Bean
Validation API hibernate-validator. , JDBC- Derby.
derbyclient .jar, JDBC-
Derby, ( ), derby Derby
. , (<scope>test</scope>),
JUnit4.

, pom.xml, Maven-:
$ mvn compile

BUILD SUCCESS,
, . Maven target
persistence.xml.
Maven, :
$ mvn integration-test

Derby
. BookIT,
Maven ,
:

160 4. Java Persistence API


Results :
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO] --------------------------------------------------------------------[INFO] BUILD SUCCESS
[INFO] --------------------------------------------------------------------[INFO] Total time: 5.192s
[INFO] Finished
[INFO] Final Memory: 18M/221M
[INFO] ---------------------------------------------------------------------

Main
Maven
Main, Derby.
$DERBY_HOME/bin
startNetworkServer. Derby :
Security manager installed using the Basic server security policy.
Apache Derby Network Server - 10.9.1.0 - (802917) started and ready to accept
connections on port 1527

Derby 1527 , JDBC-


- SQL-. Main java exec-maven-plugin,
:
$ mvn exec:java

Main .
Derby chapter04DB, Book. , persistence.xml
create=true URL- JDBC:
<property name="javax.persistence.jdbc.url"
value="jdbc:derby://localhost:1527/chapter04DB;create=true"/>

, , SQL- .
javax.persistence.schema-generation-action EclipseLink
BOOK. ,
Book ( ).
Derby- : ij ( $DERBY_HOME/bin
PATH). Derby, ,
chapter04DB (show tables), BOOK (describebook)
, SQL-, SELECT * FROM BOOK.
$ ij
version 10.9.1.0

161

ij> connect 'jdbc:derby://localhost:1527/chapter04DB';
ij> show tables;
TABLE_SCHEM
|TABLE_NAME
|REMARKS
-----------------------------------------------------------------------APP
|BOOK
|
APP
|SEQUENCE
|
ij> describe book;
COLUMN_NAME
|TYPE_NAME|DEC&|NUM&|COLUM&|COLUMN_DEF|CHAR_OCTE&|IS_NULL&
-----------------------------------------------------------------------ID
|BIGINT
|0
|10 |19
|NULL
|NULL
|NO
TITLE
|VARCHAR |NULL|NULL|255
|NULL
|510
|YES
PRICE
|DOUBLE
|NULL|2
|52
|NULL
|NULL
|YES
ILLUSTRATIONS |SMALLINT |0
|10 |5
|0
|NULL
|YES
DESCRIPTION
|VARCHAR |NULL|NULL|255
|NULL
|510
|YES
ISBN
|VARCHAR |NULL|NULL|255
|NULL
|510
|YES
NBOFPAGE
|INTEGER |0
|10 |10
|NULL
|NULL
|YES

Book (.4.7), , ,
@GeneratedValue (
), EclipseLink
( SEQUENCE). BOOK JPA ,
(, String VARCHAR(255)).


persistence.xml , 4.10,
EclipseLink
:
<property name="javax.persistence.schema-generation.database.action"
value="drop-and-create"/>
<property name="javax.persistence.schema-generation.scripts.action"
value="drop-and-create"/>

SQL-: crea
teDDL.jdbc (4.13) SQL-
dropDDL.jdbc (4.14) .
,
.
4.13. createDDL.jdbc

CREATE TABLE BOOK (ID BIGINT NOT NULL, DESCRIPTION VARCHAR(255),


ILLUSTRATIONS SMALLINT DEFAULT 0, ISBN VARCHAR(255),
NBOFPAGE INTEGER, PRICE FLOAT, TITLE VARCHAR(255), PRIMARY KEY (ID))
CREATE TABLE SEQUENCE (SEQ_NAME VARCHAR(50) NOT NULL, SEQ_COUNT DECIMAL(15),
PRIMARY KEY (SEQ_NAME))
INSERT INTO SEQUENCE (SEQ_NAME, SEQ_COUNT) values ('SEQ_GEN', 0)

162 4. Java Persistence API


4.14. dropDDL.jdbc

DROP TABLE BOOK


DELETE FROM SEQUENCE WHERE SEQ_NAME = 'SEQ_GEN'

JPA2.1. Java EE7, JPA , ( EJB


CMP2.x). ,
, XML.
, JPA EclipseLink Derby.
, JPA
Derby .
JPA. 5 , , .
6 API , JPQL. , ,
, , .

5.
-

-
(Object-Relational Mapping ORM), .
, JPA . ,
. JPA ,
.
, , ,
. , .
( ).
,
, , , . ,
, ,
.


, Java , , ,
. Java
, .
, , , new.
( ), ,
,
, . Java-
, .

164 5. -

. , (
null , ..).

( Book
BOOK, AncientBook ANCIENTBOOK
..). , , ,

.

@Table
@javax.persistence.Table
, . ,
, , .

@UniqueConstraint @Table.
@Table, . BOOK T_BOOK, , 5.1.
5.1. Book, T_BOOK

@Entity
@Table(name = "t_book")
public class Book {
@Id
private
private
private
private
private
private
private

Long id;
String title;
Float price;
String description;
String isbn;
Integer nbOfPage;
Boolean illustrations;

// , ,
}

@Table (t_book).
( Derby), .

165

@SecondaryTable
, ,
.
, , . @SecondaryTable,
, @SecondaryTables ( s ) . ,
, , ,
( @Column, @Column). 5.2
Address .
5.2. Address,

@Entity
@SecondaryTables({
@SecondaryTable(name = "city"),
@SecondaryTable(name = "country")
})
public class Address {
@Id
private Long id;
private String street1;
private String street2;
@Column(table = "city")
private String city;
@Column(table = "city")
private String state;
@Column(table = "city")
private String zipcode;
@Column(table = "country")
private String country;
// , ,
}

Address ( , ADDRESS).
@SecondaryTables ,
: CITY COUNTRY. ,
( @Column(table="ci
ty") @Column(table="country")). .5.1 ,
Address. ,
( ).
- , Derby
(city) (CITY).

166 5. -

.5.1. Address

, , , . , @Table, 5.3.
5.3. T_ADDRESS

@Entity
@Table(name = "t_address")
@SecondaryTables({
@SecondaryTable(name = "t_city"),
@SecondaryTable(name = "t_country")
})
public class Address {
// , , ,
}

. , ,
, . , ,
(Binary Large Object BLOB),
.



. , . ,
( null ).
, , , ISBN. JPA , , -

167

, :
, ( ). , .

@Id @GeneratedValue
( ) -. @Id, ,
. @javax.persistence.Id
. , :
Java-: byte, int, short, long, char;
- Java-: Byte, Integer, Short, Long, Character;
-: int[], Integer[] ..;
, : java.lang.String, java.math.BigInteger , java.util.Date,
java.sql.Date.
,
@GeneratedValue.
:
SEQUENCE IDENTITY SQL-
;
TABLE
, ,
. ,
EclipseLink SEQUENCE : (),
( , Derby);
(AUTO)
,
(EclipseLink TABLE). AUTO @GeneratedValue.
@GeneratedValue ,
, , . , 5.4, , . , GenerationType.AUTO
strategy. , id : @Id @GeneratedValue.
5.4. Book

@Entity
public class Book {

168 5. -
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
private Float price;
private String description;
private String isbn;
private Integer nbOfPage;
private Boolean illustrations;
// , ,
}


. ,
(,
- ,
). , . ,
,
: @EmbeddedId @IdClass. ,
,
.
, CD-BookStore , ,
. , , , (EN ,
PT ..).
,
, . , NewsId , String: title language.
equals()
hashCode() (
, ,
), ,
. , Serializable,
(, ,
),
.
@EmbeddedId. , JPA . , ,
- ( ),
.

169

5.5 NewsId .
( @Embeddable),
(title language).
, , , equals()
hashCode(). , JavaBeans.
( @Id). .
5.5. @Embeddable

@Embeddable
public class NewsId {
private String title;
private String language;
// , ,
}

News, 5.6,
NewsId @EmbeddedId.
@Id. @EmbeddedId
, @Embeddable.
5.6. @EmbeddedId

@Entity
public class News {
@EmbeddedId
private NewsId id;
private String content;
// , ,
}

, . , , : .
, , ( em), :
NewsId pk = new NewsId("Richard Wright has died on September 2008", "EN")
News news = em.find(News.class, pk);

@IdClass. @IdClass. , - @Id.


NewsId, 5.7, POJO, - (

170 5. -
5.6 @EmbeddedId).
5.7.

public class NewsId {


private String title;
private String language;
// , ,
}

News, 5.8, @IdClass,


@Id. News title language.
5.8. @IdClass

@Entity
@IdClass(NewsId.class)
public class News {
@Id private String title;
@Id private String language;
private String content;
// , ,
}

@EmbeddedId @IdClass . 5.9 (Data Definition Language DDL).


, (title language).
5.9. DDL- NEWS

create table NEWS (


CONTENT VARCHAR(255),
TITLE VARCHAR(255) not null,
LANGUAGE VARCHAR(255) not null,
primary key (TITLE, LANGUAGE)
);

@IdClass , @IdClass,
, Java-.
, ( ). , ,

171

,
.
,
JPQL. @IdClass - :
select n.title from News n

@EmbeddedId - :
select n.newsId.title from News n

( ),
. , . Java-,
:
Java- - (int, double, float ..) (Integer,
Double, Float ..);
(byte[], Byte[], char[], Character[]);
, , (java.lang.String,
java.math.BigInteger, java.math.BigDecimal, java.util.Date, java.util.Calendar, ja
va.sql.Date, java.sql.Time, java.sql.Timestamp);
, , Serializable;
.
, ,
. ( ).
,
. .
JPA ( XML-).

@Basic
@javax.persistence.Basic (5.10) , , .
5.10. @Basic

@Target({METHOD, FIELD}) @Retention(RUNTIME)


public @interface Basic {
FetchType fetch() default EAGER;
boolean optional() default true;
}

172 5. -
: optional fetch. optional , null .
. fetch : LAZY EAGER.
,
(
) ( ).
, , Track, 5.11. CD-
, , WAV-
, . WAV-
BLOB-, . ,
Track WAV- ;
@Basic(fetch = FetchType.LAZY),
(,
wav ).
5.11. Entity wav

@Entity
public class Track {
@Id @GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
private Float duration;
@Basic(fetch = FetchType.LAZY)
@Lob
private byte[] wav;
private String description;
}

// , ,

, wav byte[]
@Lob (Large Object LOB). , , JDBC- Java-.
@Lob.

@Column
@javax.persistence.Column, 5.12,
. (
), ( ) null,
. 5.12 API-
@Column .
5.12. @Column

@Target({METHOD, FIELD}) @Retention(RUNTIME)


public @interface Column {

173

String name() default "";


boolean unique() default false;
boolean nullable() default true;
boolean insertable() default true;
boolean updatable() default true;
String columnDefinition() default "";
String table() default "";
int length() default 255;
int precision() default 0; //
int scale() default 0;
//

Book
(.5.1) @Column
(5.13). , title nbOfPage
description null. ,
(, length , scale precision
).
5.13. Book

@Entity
public class Book {
@Id @GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "book_title", nullable = false, updatable = false)
private String title;
private Float price;
@Column(length = 2000)
private String description;
private String isbn;
@Column(name = "nb_of_page", nullable = false)
private Integer nbOfPage;
private Boolean illustrations;
// , ,
}

Book 5.13 , 5.14.


5.14. BOOK

create table BOOK (


ID BIGINT not null,
BOOK_TITLE VARCHAR(255) not null,
PRICE DOUBLE(52, 0),
DESCRIPTION VARCHAR(2000),
ISBN VARCHAR(255),
NB_OF_PAGE INTEGER not null,
ILLUSTRATIONS SMALLINT,
primary key (ID)
);

174 5. -
@Column .
description 2000,
2000. updatable insertable
true, , , .
false, ,
, . , ,
. -
, .
, SQL- (INSERT
UPDATE) . ,
, .

3, Bean Validation Java. @NotNull Java-,
, null. ,
JPA @Column(nullable = false)
. JPA Bean Validation .

@Temporal
Java java.util.Date java.util.Calendar,
, ,
, , , .
- ,
@javax.persistence.Temporal. : DATE, TIME
TIMESTAMP (, , ). 5.15
Customer, dateOfBirth, , ( TIMESTAMP).
5.15. Customer @Temporal

@Entity
public class Customer {
@Id @GeneratedValue
private Long id;
private String firstName;
private String lastName;
private String email;
private String phoneNumber;
@Temporal(TemporalType.DATE)
private Date dateOfBirth;
@Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
// , ,
}

175

Customer 5.15 ,
5.16. dateOfBirth DATE ,
creationDate TIMESTAMP.
5.16. CUSTOMER

create table CUSTOMER (


ID BIGINT not null,
FIRSTNAME VARCHAR(255),
LASTNAME VARCHAR(255),
EMAIL VARCHAR(255),
PHONENUMBER VARCHAR(255),
DATEOFBIRTH DATE,
CREATIONDATE TIMESTAMP,
primary key (ID)
);

@Transient
JPA, @Entity,
. ,
, @javax.per
sistence.Transient Java- transient. , Customer age (5.17). ,
age , , .
5.17. Customer age

@Entity
public class Customer {
@Id @GeneratedValue
private Long id;
private String firstName;
private String lastName;
private String email;
private String phoneNumber;
@Temporal(TemporalType.DATE)
private Date dateOfBirth;
@Transient
private Integer age;
@Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
// , ,
}

age - AGE.

@Enumerated
Java SE5 ,
, .
, , .

176 5. -
,
. 5.18 CreditCardType.
5.18. CreditCardType

public enum CreditCardType {


VISA,
MASTER_CARD,
AMERICAN_EXPRESS
}

,
, 0 VISA, 1 MASTER_CARD 2 AMERICAN_EXPRESS.

, , Integer. , 5.19, CreditCard,
.
5.19.

@Entity
@Table(name = "credit_card")
public class CreditCard {
@Id
private String number;
private String expiryDate;
private Integer controlNumber;
private CreditCardType creditCardType;
// , ,
}

,
, . ,
.
, , , , .
. , @Enumerated STRING (
ORDINAL), 5.20.
5.20. STRING

@Entity
@Table(name = "credit_card")
public class CreditCard {
@Id
private String number;
private String expiryDate;
private Integer controlNumber;
@Enumerated(EnumType.STRING)
private CreditCardType creditCardType;

177

// , ,
}

CreditCardType VARCHAR, Visa "VISA".


(@Entity @Table) (@Basic, @Column, @Temporal ..), ,
( ), ( ). , @Id id getId().
, ( ),
, , .
, .
, . (, )
, .

Java . ( ) , JavaBean
( getXXX, setXXX isXXX Boolean).

()
() . : , ,
(,
, -). ,
, . (5.21) .
5.21. Customer

@Entity
public class Customer {
@Id @GeneratedValue
private Long id;
@Column(name = "first_name", nullable = false, length = 50)
private String firstName;
@Column(name = "last_name", nullable = false, length = 50)
private String lastName;
private String email;
@Column(name = "phone_number", length = 15)
private String phoneNumber;
// , ,
}

178 5. -
, 5.22, , . , @Transient, .
5.22. Customer

@Entity
public class Customer {
private Long id;
private String firstName;
private String lastName;
private String email;
private String phoneNumber;
//
@Id @GeneratedValue
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "first_name", nullable = false, length = 50)
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Column(name = "last_name", nullable = false, length = 50)
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Column(name = "phone_number", length = 15)
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}

5.21 5.22 , .

179

@javax.persistence.Access.
FIELD PROPERTY, /
. , @Access(AccessType.FIELD)
, . @Access(AccessTy
pe.PROPERTY).
(,
), . 5.23 ,
.
5.23. Customer,

@Entity
@Access(AccessType.FIELD)
public class Customer {
@Id @GeneratedValue
private Long id;
@Column(name = "first_name", nullable = false, length = 50)
private String firstName;
@Column(name = "last_name", nullable = false, length = 50)
private String lastName;
private String email;
@Column(name = "phone_number", length = 15)
private String phoneNumber;
// , ,
@Access(AccessType.PROPERTY)
@Column(name = "phone_number", length = 555)
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}

, 5.23, FIELD . PersistenceManager


, , . phoneNumber @Column,
length 15. , ,
VARCHAR(15), . - ,
getPhoneNumber() ,
length phoneNumber ( 555).
AccessType.FIELD AccessType.PROPERTY.
VARCHAR(555).

180 5. -


Java.
( ). , ,
. , ,
. , Java- . ,
Java-, String Integer?
JPA2.0,
.
@ElementCollection @CollectionTable.
@ElementCollection ,
java.util.Collection (
, ) (
).
:
java.util.Collection ;
java.util.Set , -;
java.util.List , ,
, .
, @CollectionTable ( ,
), .
, .
-, - Book, ,
. . ,
, Book
. ,
Book ,
5.24.
5.24. Book

@Entity
public class Book {
@Id @GeneratedValue
private Long id;
private String title;
private Float price;
private String description;
private String isbn;
private Integer nbOfPage;
private Boolean illustrations;

181

@ElementCollection(fetch = FetchType.LAZY)
@CollectionTable(name = "Tag")
@Column(name = "Value")
private List<String> tags = new ArrayList<>();
// , ,
}

@ElementCollection, 5.24, , tags


, . @CollectionTable
BOOK_TAGS (
, ),
TAG, name (name = "Tag"). ,
@Column, VALUE ( , , TAGS).
.5.2.

.5.2. BOOK TAG


JPA 1.0 . , BLOB, . ? , java.util.ArrayList
Serializable, JPA
BLOB-. , java.util.List,
, Serializable. @ElementCollection
.

(
, Java
Ruby, PHP).


, . JPA1.0
,
.
, ,
. .

182 5. -
, @ElementCollection
@CollectionTable ,
.
.
CD-, (5.25).
( , ..).
,
( ), ( ).
5.25. CD-

@Entity
public class CD {
@Id @GeneratedValue
private Long id;
private String title;
private Float price;
private String description;
@Lob
private byte[] cover;
@ElementCollection
@CollectionTable(name="track")
@MapKeyColumn (name = "position")
@Column(name = "title")
private Map<Integer, String> tracks = new HashMap<>();
// , ,
}

, @ElementCollection
, . @Col
lectionTable TRACK.
: @Map
KeyColumn. .
,
_KEY. 5.25 ,
POSITION, , (TRACK_KEY).
@Column , , , TITLE. .5.3.

.5.3. CD TRACK

183
XML

XML
, , XML-.
- Hibernate,
, XML . XML-, . JPA XML .
XML-, (
,
XML-). , ,
, XML-, , .
12 XML- - JPA2.1, XML.
XML- .
, XML-
, , XML .

XML-
, XML.
: XML
? , , . (,
), , . ,
, (,
, ). , JPA
. , ..
.
XML- ( ),
.
Book. ,
Book BOOK
BOOK_XML_MAPPING . @Entity (5.26) , ( @Table
). @Id , @Column
500.

184 5. -
5.26. Book

@Entity
public class Book {
@Id @GeneratedValue
private Long id;
private String title;
private Float price;
@Column(length = 500)
private String description;
private String isbn;
private Integer nbOfPage;
private Boolean illustrations;
// , ,
}

book_mapping.xml (5.27),
XML-, .
<table> , (BOOK_XML_MAPPING BOOK ). <attributes>
, ,
. , title (nbOfPage).
5.27. META-INF/book_mapping.xml

<?xml version="1.0" encoding="UTF-8"?>


<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm
http://java.sun.com/xml/ns/persistence/orm_2_1.xsd"
version="2.1">
<entity class="org.agoncal.book.javaee7.chapter05.Book">
<table name="book_xml_mapping"/>
<attributes>
<basic name="title">
<column name="book_title" nullable="false" updatable="false"/>
</basic>
<basic name="description">
<column length="2000"/>
</basic>
<basic name="nbOfPage">
<column name="nb_of_page" nullable="false"/>
</basic>
</attributes>
</entity>
</entity-mappings>

, XML
. description @Column(length
= 500), , book_mapping.xml

185
XML
(.5.27). 2000. ,
500,
DDL- 2000. XML-
.
XML- ,
Book BOOK_XML_MAPPING,
5.28.
XML, <xml-mappingmetadata-complete> book_mapping.xml (
, XML ).
5.28. BOOK_XML_MAPPING

create table BOOK_XML_MAPPING (


ID BIGINT not null,
BOOK_TITLE VARCHAR(255) not null,
DESCRIPTION VARCHAR(2000),
NB_OF_PAGE INTEGER not null,
PRICE DOUBLE(52, 0),
ISBN VARCHAR(255),
ILLUSTRATIONS SMALLINT,
primary key (ID)
);

, .
book_mapping.xml persistence.xml,
<mapping-file>. , . ,
XML- . Book XML- META-INF,
(5.29).
5.29. persistence.xml

<?xml version="1.0" encoding="UTF-8"?>


<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="chapter05PU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>org.agoncal.book.javaee7.chapter05.Book</class>
<mapping-file>META-INF/book_mapping.xml</mapping-file>
<properties>
<!-- -->
</properties>
</persistence-unit>
</persistence>

186 5. -



,
@EmbeddedId. ,
;
.
, .

. ,
. ( ),
, .
. @Embeddable, , , @Embedded.
, , , , .
Customer (5.31), : Customer Address. Address
, Customer,
, (5.30).
5.30. Address

@Embeddable
public class Address {
private String street1;
private String street2;
private String city;
private String state;
private String zipcode;
private String country;
// , ,
}

5.30, Address , . @Embeddable , Address


- ( ).
, Customer
@Embedded, , Address ,
(. 5.31).
5.31. Customer Address

@Entity
public class Customer {
@Id @GeneratedValue
private Long id;

187

private String firstName;
private String lastName;
private String email;
private String phoneNumber;
@Embedded
private Address address;
// , ,
}

Address
Customer. , 5.32.
,
( @AttributeOverrides).
5.32. CUSTOMER Address

create table CUSTOMER (


ID BIGINT not null,
LASTNAME VARCHAR(255),
PHONENUMBER VARCHAR(255),
EMAIL VARCHAR(255),
FIRSTNAME VARCHAR(255),
STREET2 VARCHAR(255),
STREET1 VARCHAR(255),
ZIPCODE VARCHAR(255),
STATE VARCHAR(255),
COUNTRY VARCHAR(255),
CITY VARCHAR(255),
primary key (ID)
);

,
. JPA 2.1 .
, ( , ).

. -, .
, ,
. @Access.
Customer (5.33) Address (5.34)
.
5.33. Customer ,

@Entity
@Access(AccessType.FIELD)
public class Customer {
@Id @GeneratedValue

188 5. -

private Long id;


@Column(name = "first_name", nullable = false, length = 50)
private String firstName;
@Column(name = "last_name", nullable = false, length = 50)
private String lastName;
private String email;
@Column(name = "phone_number", length = 15)
private String phoneNumber;
@Embedded
private Address address;
// , ,

5.34. ,

@Embeddable
@Access(AccessType.PROPERTY)
public class Address {
private String street1;
private String street2;
private String city;
private String state;
private String zipcode;
private String country;
//
@Column(nullable = false)
public String getStreet1() {
return street1;
}
public void setStreet1(String street1) {
this.street1 = street1;
}
public String getStreet2() {
return street2;
}
public void setStreet2(String street2) {
this.street2 = street2;
}
@Column(nullable = false, length = 50)
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Column(length = 3)
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}

189

@Column(name = "zip_code", length = 10)
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}

, ,
. ,
, Order, .5.4. Address
Customer Order.

.5.4. Address Customer Order

: Customer , Order .
-,
, Address ,
. , Address
.

, . . - . @Access ,
.


- . ,
,

190 5. -
.
.
, . ( ) ( ). Java
(.) . , customer.getAddress().getCountry(),
Customer Address,
Country.
(Unified Modeling Language UML)
, . .5.5 Class1 ()
Class2 (), .

.5.5.

.
.5.6, Class1 Class2
. Java Class1 Class2
Class2 Class1.

.5.6.

( ).
,
. UML-, .5.7, , Class1
Class2.

.5.7.

UML
. , 0..1 ,
; 1 , ;
1..* , , 3..6 -

191

, . Java , , java.util.Col
lection, java.util.Set, java.util.List java.util.Map.
( ). : , .5.5 Class1 , ,
.5.6, . ,
( ).
, JPA.


-, , , ( ),
, , .
, . JPA

. :
( ) .
, , .
, .
5.33 5.34 , . Java
Customer Address.
CUSTOMER, ADDRESS ( ), .5.8.

.5.8.

.
CUSTOMER, .5.9, ADDRESS.

.

,
( ).

192 5. -

.5.9.


. , JPA
.


JPA. .
, -. JPA ,
. , , JPA
, . JPA , ,
, .
,
, .
: @OneToOne,
@OneToMany, @ManyToOne @ManyToMany.
. .5.1 .
5.1.

193

, ,
. ,
, .
, . .
, , .


.
; .
,
, ,
, .
Customer Address
(.5.10).
. Customer .
, CUSTOMER
( ), ADDRESS, , . ,
,
Customer ( ).

.5.10. Customer Address

, .
Address Customer,
,

194 5. -
Customer Address (.5.11). , UML-

, .

.5.11. Customer Address

Java-
, . ,
(.5.12).

.5.12. ,

?
?
?
, , , mappedBy @OneToOne, @OneToMany @ManyToMany. mappedBy , .
Java- ( )
( ). .5.13,
: Customer , @OneToOne, Address Customer,
.
, CUSTOMER ADDRESS. CUSTOMER
, ADDRESS.

195

.5.13. Customer Address .


.5.13 @OneToOne Address


mappedBy. Address ,
mappedBy. mappedBy , (address) . ,
Customer @JoinColumn address_fk.
Customer , ,
. Address ,
( CUSTOMER ADDRESS_FK).
mappedBy @OneToOne, @OneToMany
@ManyToMany, @ManyToOne. mappedBy
. ,
,
. ,
.

Hibernate,
JPA- mappedBy Hibernate- inverse.

196 5. -

@OneToOne
1, . , ,
( 1). Customer () Address (), , .
, .5.14, (,
, ).

.5.14.

Java , Customer
Address (5.35), Address Customer (5.36).
5.35. Customer Address

@Entity
public class Customer {
@Id @GeneratedValue
private Long id;
private String firstName;
private String lastName;
private String email;
private String phoneNumber;
private Address address;
// , ,
}
5.36. Address

@Entity
public class Address {
@Id @GeneratedValue
private Long id;
private String street1;
private String street2;
private String city;
private String state;
private String zipcode;

197

private String country;
// , ,
}

5.35 5.36, : @Entity @Id @GeneratedValue


.
,
( customer, address). , Address
Customer . ,
, @OneToOne, (5.37 5.38).
5.37. CUSTOMER ADDRESS

create table CUSTOMER (


ID BIGINT not null,
FIRSTNAME VARCHAR(255),
LASTNAME VARCHAR(255),
EMAIL VARCHAR(255),
PHONENUMBER VARCHAR(255),
ADDRESS_ID BIGINT,
primary key (ID),
foreign key (ADDRESS_ID) references ADDRESS(ID)
);
5.38. ADDRESS

create table ADDRESS (


ID BIGINT not null,
STREET1 VARCHAR(255),
STREET2 VARCHAR(255),
CITY VARCHAR(255),
STATE VARCHAR(255),
ZIPCODE VARCHAR(255),
COUNTRY VARCHAR(255),
primary key (ID)
);

, JPA, ,
. , ADDRESS_ID (5.37),
( address), _
( ADDRESS). , DDL- ADDRESS_ID
nullable, ,
( null) .
.
@OneToOne ( ).
, , ,

198 5. -
. 5.39 API- @OneToOne.
5.39. API- @OneToOne

@Target({METHOD, FIELD}) @Retention(RUNTIME)


public @interface OneToOne {
Class targetEntity() default void.class;
CascadeType[] cascade() default {};
FetchType fetch() default EAGER;
boolean optional() default true;
String mappedBy() default "";
boolean orphanRemoval() default false;
}

@JoinColumn ( API-
API- @Column 5.12).
, .
5.40 , .
5.40. Customer

@Entity
public class Customer {
@Id @GeneratedValue
private Long id;
private String firstName;
private String lastName;
private String email;
private String phoneNumber;
@OneToOne (fetch = FetchType.LAZY)
@JoinColumn(name = "add_fk", nullable = false)
private Address address;
// , ,
}

JPA . @JoinColumn
. 5.40 ADD_FK, ,
, null (nullable=false). @OneToOne ,
( ).

@OneToMany
, -
-. ,
(.5.15). @ManyToOne, , . Order , OrderLine
.

199

.5.15.

,
Order OrderLine. Java
Collection, List Set java.util. 5.41
Order
OrderLine (5.42).
5.41. Order orderLines

@Entity
public class Order {
@Id @GeneratedValue
private Long id;
@Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
private List<OrderLine> orderLines;
// , ,
}
5.42. OrderLine

@Entity
@Table(name = "order_line")
public class OrderLine {
@Id @GeneratedValue
private Long id;
private String item;
private Double unitPrice;
private Integer quantity;
// , ,
}
Order 5.41 - . ,
, .

.
ORDER ,
, ORDER_LINE. , _.
ORDER_ORDER_LINE,
, .5.16.

200 5. -

.5.16. ORDER ORDER_LINE


, JPA
.
, _ , .
@JoinColumn
, @JoinTable (5.43)
, .
@OneToMany (5.44), , @OneToOne,
( fetch ..).
5.43. API- @JoinTable

@Target({METHOD, FIELD}) @Retention(RUNTIME)


public @interface JoinTable {
String name() default "";
String catalog() default "";
String schema() default "";
JoinColumn[] joinColumns() default {};
JoinColumn[] inverseJoinColumns() default {};
UniqueConstraint[] uniqueConstraints() default {};
Index[] indexes() default {};
}
5.44. Order

@Entity
public class Order {
@Id @GeneratedValue
private Long id;
@Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
@OneToMany
@JoinTable(name = "jnd_ord_line",
joinColumns = @JoinColumn(name = "order_fk"),
inverseJoinColumns = @JoinColumn(name = "order_line_fk") )
private List<OrderLine> orderLines;
// , ,
}

201

API- @JoinTable 5.42
@JoinColumn: joinColumns inverseJoinColumns. . joinColumns ( )
ORDER. inverseJoinColumns ,
, ORDER_LINE.
Order (5.44)
@OneToMany @JoinTable orderLines,
JND_ORD_LINE ( ORDER_ORDER_LINE), .
Order 5.44 , 5.45.
5.45. ORDER ORDER_LINE

create table JND_ORD_LINE (


ORDER_FK BIGINT not null,
ORDER_LINE_FK BIGINT not null,
primary key (ORDER_FK, ORDER_LINE_FK),
foreign key (ORDER_LINE_FK) references ORDER_LINE(ID),
foreign key (ORDER_FK) references ORDER(ID)
);

, (,
) , . Order @JoinColumn @JoinTable, , 5.46.
5.46. Order

@Entity
public class Order {
@Id @GeneratedValue
private Long id;
@Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
@OneToMany(fetch = FetchType.EAGER)
@JoinColumn(name = "order_fk")
private List<OrderLine> orderLines;
// , ,
}

OrderLine ( 5.46) .
, 5.46 @OneToMany fetch ( LAZY EAGER). @JoinColumn
. ORDER_FK
(ORDER_LINE). ,
.5.17. ,
ORDER_FK.

202 5. -

.5.17. ORDER ORDER_LINE

@ManyToMany
, .
, CD- , CD-. Java
.
( ). , , (
mappedBy).
, Artist ,
, (5.47) CD, , mappedBy
@ManyToMany. mappedBy ,
appearsOnCDs .
5.47. CD-

@Entity
public class CD {
@Id @GeneratedValue
private Long id;
private String title;
private Float price;
private String description;
@ManyToMany(mappedBy = "appearsOnCDs")
private List<Artist> createdByArtists;
// , ,
}

, Artist ,
5.48,
@JoinTable @JoinColumn.
5.48. CD-

@Entity
public class Artist {
@Id @GeneratedValue
private Long id;
private String firstName;

203

private String lastName;
@ManyToMany
@JoinTable(name = "jnd_art_cd",
joinColumns = @JoinColumn(name = "artist_fk"),
inverseJoinColumns = @JoinColumn(name = "cd_fk"))
private List<CD>appearsOnCDs;
// , ,
}

5.48, Artist CD
JND_ART_CD, (
@JoinTable ). joinColumns
(Artist), inverseJoinColumns (CD). .5.18.

.5.18. ARTIST, CD

,
.
, ,
mappedBy. ,
, . : ARTIST CD ARTIST_CD CD_
ARTIST. mappedBy .


, (@OneToOne, @OneToMany, @ManyToOne @ManyToMany),
, ,

.
, .
, , ( )
( ). .

204 5. -
,
( , ).
(.5.19) EAGER. , , Class1 ( ),
. .

.5.19. EAGER

,
fetch, (.5.20).
Class1 ( , , Class1).
Class2 (, -),
..
,
.

.5.20. LAZY

, EAGER , LAZY . EAGER



( , , ). LAZY , ,
.
.
fetch , , ,
.
fetch , , ,
, (.5.2).
5.2.

@OneToOne

EAGER

@ManyToOne

EAGER

@OneToMany

LAZY

@ManyToMany

LAZY

205


, , , fetch
@OneToMany EAGER (5.49).
5.49. Order EAGER OrderLine

@Entity
public class Order {
@Id @GeneratedValue
private Long id;
@Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
@OneToMany(fetch = FetchType.EAGER)
private List<OrderLine> orderLines;
// , ,
}



. Java .
- . , ,
, JPQL- ORDER BY. JPA , , .

@OrderBy
@OrderBy.
, .
CD-BookStore . ,
(5.50).
, .
5.50. Comment postedDate

@Entity
public class Comment {
@Id @GeneratedValue
private Long id;
private String nickname;
private String content;
private Integer note;
@Column(name = "posted_date")
@Temporal(TemporalType.TIMESTAMP)
private Date postedDate;
// , ,
}

206 5. -
Comment,
5.50. content, ( nickname), , ,
postedDate TIMESTAMP, . News, 5.51,

. @OrderBy
@OneToMany.
5.51. , News,

@Entity
public class News {
@Id @GeneratedValue
private Long id;
@Column(nullable = false)
private String content;
@OneToMany(fetch = FetchType.EAGER)
@OrderBy("postedDate DESC")
private List<Comment> comments;
// , ,
}

@OrderBy ,
( postedDate), (
). ASC DESC , . @OrderBy . ,
OrderBy("postedDate DESC, note ASC").
@OrderBy .

ORDER BY .

@OrderColumn
JPA1.0 @OrderBy,
. JPA 2.0 @OrderColumn ( API- API-
@Column 5.12). ,
, . @OrderColumn
.
News Comment .
Comment, 5.52,
postedDate , ,
.

207

5.52. Comment postedDate

@Entity
public class Comment {
@Id @GeneratedValue
private Long id;
private String nickname;
private String content;
private Integer note;
// , ,
}

News
( 5.53) @OrderColumn.
News
.
5.53.

@Entity
public class News {
@Id @GeneratedValue
private Long id;
@Column(nullable = false)
private String content;
@OneToMany(fetch = FetchType.EAGER)
@OrderColumn(name = "posted_index")
private List<Comment> comments;
// , ,
}

5.53 @OrderColumn POSTED_


INDEX. , _ORDER (COMMENTS_
ORDER ). .
, :
create table NEWS_COMMENT (
NEWS_ID BIGINT not null,
COMMENTS_ID BIGINT not null,
POSTED_INDEX INTEGER
);

, ,
; @OrderColumn,
. ,
.
,
.
,
, ,

208 5. -
, . @OrderColumn
@OrderBy. ,
.


- . C++ , Java . -
, , .
, . . ,
. .
? JPA
.

( ).

, , .

.

JPA 2.1
. ,
.

, JPA 2.1
, , , . @Inheritance . JPA
, .
,
.


, , JPA
. -

209

. , strategy @Inheritance, , javax.persistence.InheritanceType .

. ,
, CD Book, Item
(.5.21).

.5.21. CD, Book Item

Item id, title, description


price. CD Book Item.
, isbn
Book totalDuration, CD.



. . , @Inheritance (
), Item (5.54).
5.54. Item

@Entity
public class Item {
@Id @GeneratedValue
protected Long id;
protected String title;
protected Float price;
protected String description;
// , ,
}

210 5. -
Item (.5.54) Book
(5.55) CD (5.56). Item,
,
@Inheritance.
5.55. Book Item

@Entity
public class Book extends Item {
private String isbn;
private String publisher;
private Integer nbOfPage;
private Boolean illustrations;
// , ,
}
5.56. CD Item

@Entity
public class CD extends Item {
private String musicCompany;
private Integer numberOfCDs;
private Float totalDuration;
private String genre;
// , ,
}

, ,
, -.
,
ITEM. .5.22.

.5.22. ITEM

211

.5.22, ITEM Item, Book CD. ,
- DTYPE.
ITEM , , CD. ,
. ,
(Item, Book CD) ITEM.
,
.
.5.23 ITEM . ,
;
. ,
Item ( DTYPE).
Item , (.5.53),
, ISBN- .. .

.5.23. ITEM,

DTYPE, String ( VARCHAR) .


, @DiscriminatorColumn
.
, ,
@DiscriminatorValue.
5.57 DISC (
DTYPE), String Char. Item I, Book
B(5.58) CD C(5.59).
5.57. Item

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn (name="disc",
discriminatorType = DiscriminatorType.CHAR)

212 5. -
@DiscriminatorValue("I")
public class Item {
@Id @GeneratedValue
protected Long id;
protected String title;
protected Float price;
protected String description;
// , ,
}
5.58. Book B@Entity

@DiscriminatorValue("B")
public class Book extends Item {
private String isbn;
private String publisher;
private Integer nbOfPage;
private Boolean illustrations;
// , ,
}
5.59. CD C@Entity

@DiscriminatorValue("C")
public class CD extends Item {
private String musicCompany;
private Integer numberOfCDs;
private Float totalDuration;
private String genre;
// , ,
}

Item
@DiscriminatorColumn.
I @DiscriminatorValue. .
.5.24. , .5.23.

.5.24. ITEM,

213

, .
- :
, . ,
null. Book, ISBN-, , , CD-, CD .


. ,
, , . , (
) ,
. , , .
,
@Inheritance, 5.60 ( CD Book
, ).
5.60. Item

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Item {
@Id @GeneratedValue
protected Long id;
protected String title;
protected Float price;
protected String description;
// , ,
}

, ,
, , . .5.25 , Item, Book CD.
- @DiscriminatorColumn @Disc
riminatorValue ( DTYPE ITEM).
,
, .
. , .

214 5. -
,
. , ,
. .
, , , .


(
),
, . , . ,
, .
, . ,
.

TABLE_PER_CLASS @Inheritance (5.61)
(Item).
5.61. Item

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Item {
@Id @GeneratedValue
protected Long id;
protected String title;
protected Float price;
protected String description;
// , ,
}

.5.26 ITEM, BOOK CD. , BOOK CD


ID, TITLE, PRICE DESCRIPTION ITEM.
, .
, , ,
@Table.

, :

.5.26. ITEM BOOK CD

.5.25.

215

216 5. -
. , , (,
, CD- ). UNION, ,
. JPA2.1 .



.
. , , ? JPA @AttributeOverride @AttributeOverrides,
.
ID, TITLE DESCRIPTION BOOK CD,
Item ,
@AttributeOverride Book (5.62) CD (5.63).
5.62. Book , Item

@Entity
@AttributeOverrides({
@AttributeOverride(name = "id",
column = @Column(name = "book_id")),
@AttributeOverride(name = "title",
column = @Column(name = "book_title")),
@AttributeOverride(name = "description",
column = @Column(name = "book_description"))
})
public class Book extends Item {
private String isbn;
private String publisher;
private Integer nbOfPage;
private Boolean illustrations;
// , ,
}
5.63. CD , Item

@Entity
@AttributeOverrides({
@AttributeOverride(name = "id",
column = @Column(name = "cd_id")),
@AttributeOverride(name = "title",
column = @Column(name = "cd_title")),
@AttributeOverride(name = "description",
column = @Column(name = "cd_description"))
})
public class CD extends Item {
private String musicCompany;

217

private Integer numberOfCDs;
private Float totalDuration;
private String genre;
// , ,
}

,
@AttributeOverrides,
@AttributeOverride.
Item @Column.
, name = "title" title Item, @Column(name =
"cd_title") , title CD_TITLE. .5.27.

, (Address
Customer Order). , ,
. , @AttributeOverrides ,
.


, ,
. Item, Book CD, .
.
: , ,
( ),
.
.


Item
. @Entity abstract,
.
,
new.
(Book CD) . .
Java, .

,
, , ,
, POJO. , ,

.5.27. BOOK CD ITEM

218 5. -

219

. ,
? , .
, ,
. ,
, ,
(, , , @Entity).
, Book (5.65)
Item , ( Item ),
5.64.
5.64. Item POJO @Entity

public class Item {


protected String title;
protected Float price;
protected String description;
// , ,
}

Book (. 5.65) Item, Java-


title, price description,
, , -, . Item
.
5.65. Book POJO

@Entity
public class Book extends Item {
@Id @GeneratedValue
private Long id;
private String isbn;
private String publisher;
private Integer nbOfPage;
private Boolean illustrations;
// , ,
}

Book Item.
Book. Item , 5.66, . Book, Book,
(title, price, isbn, publisher ..),
Book (id, isbn ..).
5.66. BOOK Item

create table BOOK (


ID BIGINT not null,
ILLUSTRATIONS SMALLINT,

220 5. -
ISBN VARCHAR(255),
NBOFPAGE INTEGER,
PUBLISHER VARCHAR(255),
primary key (ID)
);


JPA , ,
,
, . . ,
- ,
,
, . ,
. , ,
@MappedSuperclass.
Item @Mapped
Superclass, @Entity, 5.67. (JOINED), @Column. ,
, @Table.
5.67. Item

@MappedSuperclass
@Inheritance(strategy = InheritanceType.JOINED)
public class Item {
@Id @GeneratedValue
protected Long id;
@Column(length = 50, nullable = false)
protected String title;
protected Float price;
@Column(length = 2000)
protected String description;
// , ,
}

5.67, title description


@Column. 5.68 Book, Item.
5.68. Book Item

@Entity
public class Book extends Item {
private String isbn;
private String publisher;
private Integer nbOfPage;
private Boolean illustrations;
// , ,
}

221

. Item . Item Book


BOOK, ,
. @Column Item . ,
, , , ,
. 5.69 BOOK TITLE DESCRIPTION.
5.69. BOOK Item

create table BOOK (


ID BIGINT not null,
TITLE VARCHAR(50) not null,
PRICE DOUBLE(52, 0),
DESCRIPTION VARCHAR(2000),
ILLUSTRATIONS SMALLINT,
ISBN VARCHAR(255),
NBOFPAGE INTEGER,
PUBLISHER VARCHAR(255),
primary key (ID)
);

,
.
, ( @Entity), ( @Id), JPA .
,
, . JPA -
( XML-).

(@Basic, @Temporal ..) .
@Transient. JPA,
.
- (@OneToOne, @ManyToMany ..) .
(@Inheritance, @MappedSuperclass ..),
, ,
.
JPA,
, . :
.

6.

Java Persistence API .


.
, JPA
XML-. JPA , ( ) ().
.
JPA
. JPA
. API- , , . JPQL-, ,
.
.
.
(, , ), . , , , SQL-
.. , ,
. Java, , ,
(SQL), , , (Java).
Java Persistence Query Language.
JPQL , JPA ,
. JPQL
SQL, -, . JPQL
,
. (.) ,
Java-.
, . , , ,

223

(CRUD) , JPQL. , JPA
.
, JPA -,
.


JPA. ,
. .
,
, JPQL- .
, , . POJO-
( ). JPA , , . ,
, ,
. ( ),
Java-,
(, JavaServer Faces JSF ) .
, . , , SQL-.
javax.persistence.EntityManager API- ( 6.1).
6.1. API- EntityManager

public interface EntityManager {


// EntityManagerFactory EntityManager,
// ,
EntityManagerFactory getEntityManagerFactory();
void close();
boolean isOpen();
// EntityTransaction
EntityTransaction getTransaction();
// , ,

224 6.
//
void persist(Object entity);
<T> Tmerge(Tentity);
void remove(Object entity);
//
// ( )
<T> Tfind(Class<T> entityClass, Object primaryKey);
<T> Tfind(Class<T> entityClass, Object primaryKey, LockModeType lockMode);
<T> TgetReference(Class<T> entityClass, Object primaryKey);
// ,
// (, ...)
void lock(Object entity, LockModeType lockMode);
//
void flush();
void setFlushMode(FlushModeType flushMode);
FlushModeType getFlushMode();
// ,
//
void refresh(Object entity);
void refresh(Object entity, LockModeType lockMode);
// , ,
void clear();
void detach(Object entity);
boolean contains(Object entity);
// EntityManager
void setProperty(String propertyName, Object value);
Map<String, Object> getProperties();
// Query TypedQuery JPQL-
Query createQuery(String qlString);
<T> TypedQuery<T> createQuery(CriteriaQuery<T> criteriaQuery);
<T> TypedQuery<T> createQuery(String qlString, Class<T> resultClass);
// Query TypedQuery
Query createNamedQuery(String name);
<T> TypedQuery<T> createNamedQuery(String name, Class<T> resultClass);
// TypedQuery SQL-
Query createNativeQuery(String sqlString);
Query createNativeQuery(String sqlString, Class resultClass);
Query createNativeQuery(String sqlString, String resultSetMapping);
// StoredProcedureQuery
StoredProcedureQuery createStoredProcedureQuery(String procedureName);

225

StoredProcedureQuery createNamedStoredProcedureQuery(String name);
// Metamodel CriteriaBuilder
// (, )
CriteriaBuilder getCriteriaBuilder();
Metamodel getMetamodel();
Query createQuery(CriteriaUpdate updateQuery);
Query createQuery(CriteriaDelete deleteQuery);
// , JTA- ,
//
void joinTransaction();
boolean isJoinedToTransaction();
// EntityManager
<T> Tunwrap(Class<T> cls);
Object getDelegate();
// EntityGraph
<T> EntityGraph<T> createEntityGraph(Class<T> rootType);
EntityGraph<?> createEntityGraph(String graphName);
<T> EntityGraph<T> getEntityGraph(String graphName);
<T> List<EntityGraph<? super T>> getEntityGraphs(Class<T> entityClass);
}

API- 6.1, . , EntityManager.


, , . , ( 7 EJB-) ,
. , , , . ,
commit rollback, ,
.
, EntityManager
(, ).
, 6.2, , , JavaSE, .
Persistence EntityManagerFactory, (chapter06PU ),
EntityManager. , , ,
(
) .

226 6.
6.2. Main,
EntityManagerFactory

public class Main {


public static void main(String[] args) {
// Book
Book book = new Book ("H2G2", " ",
12.5F, "1-84023-742-2", 354, false);
//
EntityManagerFactory emf = Persistence.createEntityManagerFactory("chap
ter06PU");
EntityManager em = emf.createEntityManager();
// Book
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(book);
tx.commit();
//
em.close();
emf.close();
}
}

, ,
EntityManagerFactory. , , ,
EJB-. Java EE @PersistenceContext JNDI-. , ( , EJB-, - ..),
EntityManager, . 6.3 EJB- , chapter06PU.
6.3. EJB-

@Stateless
public class BookEJB {
@PersistenceContext(unitName = "chapter06PU")
private EntityManager em;
public void createBook() {
// Book
Book book = new Book("H2G2", " ",
12.5F, "1-84023-742-2", 354, false);
// Book
em.persist(book);

227

}
}

6.2 , 6.3, . -, Persistence EntityManagerFactory,


EntityManager. ( ). -,
EJB- ,
commit rollback.
EntityManager 7.

2, ,
@Inject EntityManager,
( @Produces).


API- ,
: .
, . :

. , Book 12 , Book
. , , ,
.

javax.persistence.EntityManager. ,
persist(), , , , . ,
. .
, ,
. , .
, .6.1, , , .
,
, . 1
12 56,
. 2 12 34.
, 12 . ,

228 6.
, ,
. , .

.6.1. ,

Entity
ManagerFactory, . , , ,
. , . persistence.xml (6.4), META-INF, , (chapter06PU)
.
6.4. ,

<?xml version="1.0" encoding="UTF-8"?>


<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="chapter06PU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>org.agoncal.book.javaee7.chapter06.Book</class>
<class>org.agoncal.book.javaee7.chapter06.Customer</class>
<class>org.agoncal.book.javaee7.chapter06.Address</class>

229

<properties>
<property name="javax.persistence.schema-generation.database.action"
value="drop-and-create"/>
<property name="javax.persistence.jdbc.driver"
value="org.apache.derby.jdbc.EmbeddedDriver"/>
<property name="javax.persistence.jdbc.url"
value="jdbc:derby:memory:chapter06DB;create=true"/>
<property name="eclipselink.logging.level" value="INFO"/>
</properties>
</persistence-unit>
</persistence>


. , <class> ,
, , , ,
( ). ,
, (transaction-type="RESOURCE_LOCAL").
7, , , persistence.xml

JTA (transaction-type="JTA").
JPA2.1 persistence.xml
(.6.1). javax.persistence, javax.persisten
ce.jdbc.url. , JPA
, eclipselink
(, eclipselink.logging.level).
6.1. JPA

javax.persistence.jdbc.driver

javax.persistence.jdbc.url

URL-

javax.persistence.jdbc.user

javax.persistence.jdbc.password

javax.persistence.database-product-name

(,
Derby)

javax.persistence.database-major-version

javax.persistence.database-minor-version

javax.persistence.ddl-create-script-source

javax.persistence.ddl-drop-script-source

javax.persistence.sql-load-script-source

230 6.
6.1 ()

javax.persistence.schema-generation.data
base.action

,
(none, create, drop-and-create, drop)

javax.persistence.schema-generation.scripts.
action

, DDL-
(none, create, drop-and-create, drop)

javax.persistence.lock.timeout

javax.persistence.query.timeout

javax.persistence.validation.group.pre-persist

,
pre-persist

javax.persistence.validation.group.pre-update ,
pre-update
javax.persistence.validation.group.pre-remove ,
pre-remove


, JPQL-.
(Data Access Object DAO), CRUD- (.6.2).
6.2.

void persist(Object entity)

,
,

<T> Tfind(Class<T> entityClass, Object


primaryKey)

<T> TgetReference(Class<T> entityClass,


Object primaryKey)

void remove(Object entity)

<T> Tmerge(Tentity)

void refresh(Object entity)


, , ,

231

void flush()

void clear()

, , ,
,

void detach(Object entity)

, ,
, ,

boolean contains(Object entity)

, , ,

,
Customer Address.
(
@GeneratedValue), Customer (6.5) Address (6.6).
6.5. Customer Address

@Entity
public class Customer {
@Id @GeneratedValue
private Long id;
private String firstName;
private String lastName;
private String email;
@OneToOne (fetch = FetchType.LAZY)
@JoinColumn(name = "address_fk")
private Address address;
// , ,
}
6.6. Address

@Entity
public class Address {
@Id @GeneratedValue
private Long id;
private String street1;
private String city;
private String zipcode;
private String country;
// , ,
}

232 6.
, .6.2. , ADDRESS_FK , ADDRESS.

.6.2. CUSTOMER ADDRESS

,
, , em EntityManager, tx
EntityTransaction.


, (
EntityExistsException).
new, ,
, , , , EntityMana
ger.persist(), JUnit 6.7.
6.7. Customer Address

Customer customer = new Customer("", "", "tballa@mail.com");


Address address = new Address(" ", "", "8QE", "");
customer.setAddress(address);
tx.begin();
em.persist(customer);
em.persist(address);
tx.commit();
assertNotNull(customer.getId());
assertNotNull(address.getId());

6.7 customer address , Java. ,


, ( em)
, (em.persist(customer) ).
.
(tx.commit() ),
, , , ADDRESS,
, , CUSTOMER. Customer
, ,

233

ADDRESS. assertNotNull ,
( ,
@Id @GeneratedValue).
persist(): Customer, Address. ,
. . ,
, . , , ,
( ). CUSTOMER,
insert ADDRESS, CUSTOMER.

Serializable.
, , .
, , ,
EntityManager.persist().
( , EJB- ..),
( ) java.io.Serializable. , , , , .

(Remote Method Invocation RMI).


.
EntityManager.find(), : - (6.8). ,
; , null.
6.8. Customer

Customer customer = em.find(Customer.class, 1234L)


if (customer!= null) {
//
}

getReference() (6.9). find,


, ( ), .
, . , , , , , ,
. getReference()
, , , , ,

234 6.
. ,
EntityNotFoundException.
6.9. Customer

try {
Customer customer = em.getReference(Customer.class, 1234L)
//
} catch(EntityNotFoundException ex) {
//
}


EntityManager.remove().
, ,
.
Java- - ,
. , 6.10, , , .
6.10. Customer Address

Customer customer = new Customer("", "", "tballa@mail.com");


Address address = new Address(" ", "", "8QE", "");
customer.setAddress(address);
tx.begin();
em.persist(customer);
em.persist(address);
tx.commit();
tx.begin();
em.remove(customer);
tx.commit();
// , -
assertNotNull(customer);

6.10 Customer Address, (custo


mer.setAddress(address)) . ,
, , ,
; Customer. ,
( ),
Address - , ,
, , .

-
, ,
, - ,
. JPA -

235

. ( Address)
(Customer), , ,
, .
, ,
orphanRemoval. , , orphanRemoval=true @OneToOne (6.11).
6.11. Customer Address

@Entity
public class Customer {
@Id @GeneratedValue
private Long id;
private String firstName;
private String lastName;
private String email;
@OneToOne (fetch = FetchType.LAZY, orphanRemoval=true)
private Address address;
// , ,
}

, 6.10,
Address, Customer
( address null
). ( ).



. ,
, . ,
Customer Address?
tx.begin();
em.persist(customer);
em.persist(address);
tx.commit();

SQL-.
insert , .
. ,
, , , .
, (flush)

236 6.
(refresh). ,
rollback(),
.
. EntityManager.flush() ,
.
,
.
tx.begin();
em.persist(customer);
em.flush();
em.persist(address);
tx.commit();

. , em.flush()
. insert
. ,
- .
,
. insert
CUSTOMER, ADDRESS
( ADDRESS_FK CUSTOMER). . . .
. refresh() , ,
, ,
, .
EntityManager.refresh() ,
. ,
6.12, Customer , firstName refresh().
6.12. Customer

Customer customer = em.find(Customer.class, 1234L)


assertEquals(customer.getFirstName(), "");
customer.setFirstName("");
em.refresh(customer);
assertEquals(customer.getFirstName(), "");");


, . EntityManager, ,
,
.

237

Contains. , .
EntityManager.contains() -

,
. , 6.13, , Customer,
,
(em.contains(customer)). .
remove() ,
(em.contains(customer) false).
6.13. ,
Customer

Customer customer = new Customer("", "", "tballa@mail.com");


tx.begin();
em.persist(customer);
tx.commit();
assertTrue(em.contains(customer));
tx.begin();
em.remove(customer);
tx.commit();
assertFalse(em.contains(customer));

. clear() : ,
, , , . detach(Object entity)
. , ,
, . , 6.14, , , , , , .
6.14. , Customer

Customer customer = new Customer("", "", "tballa@mail.com");


tx.begin();
em.persist(customer);
tx.commit();
assertTrue(em.contains(customer));
em.detach(customer);
assertFalse(em.contains(customer));


.
,
( ). , JSF-. ,
( ),
EJB- ( ,

238 6.
), (
), .
, ,
.
6.15 (em.clear()), .
6.15.

Customer customer = new Customer("", "", "tballa@mail.com");


tx.begin();
em.persist(customer);
tx.commit();
em.clear();
//
customer.setFirstName("");
tx.begin();
em.merge(customer);
tx.commit();

, 6.15,
Customer. em.clear() Customer,

,
, , .
customer.setFirstName("William").
, .
( ) em.merge(customer) .


,
. , EntityManager.mer
ge()
.
,
.
merge().
6.16 Customer setFirstName,
Antony. em.persist(), , ,
, .
setFirstName(), .
, tx.begin(), .

239

6.16. setFirstName Customer

Customer customer = new Customer("", "", "tballa@mail.com");


tx.begin();
em.persist(customer);
customer.setFirstName("");
tx.commit();


, .
, , . .
, . 6.17 , Customer
Customer Address, (customer.setAddress(address)), .
6.17. Customer Address

Customer customer = new Customer("", "", "tballa@mail.com");


Address address = new Address(" ", "", "8QE", "");
customer.setAddress(address);
tx.begin();
em.persist(customer);
em.persist(address);
tx.commit();

Customer Address ,
persist Customer Address. , em.persist(customer)
PERSIST Address, .
em.persist(address), 6.18.
6.18. PERSIST Address

Customer customer = new Customer("", "", "tballa@mail.com");


Address address = new Address(" ", "", "8QE", "");
customer.setAddress(address);
tx.begin();
em.persist(customer);
tx.commit();

Customer, Address.
. @OneToOne, @OneToMany, @ManyToOne @ManyToMany cascade,
, PERSIST,
, REMOVE (

240 6.
).
Customer (6.19) cascade @OneToOne
Address.
6.19. Customer PERSIST REMOVE

@Entity
public class Customer {
@Id @GeneratedValue
private Long id;
private String firstName;
private String lastName;
private String email;
@OneToOne (fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST,
CascadeType.REMOVE})
@JoinColumn(name = "address_fk")
private Address address;
// , ,
}

( .6.3) , CascadeType.ALL.
6.3.

CascadeType

PERSIST

REMOVE

MERGE

REFRESH

DETACH

ALL

JPQL
, ,
API- EntityManager. , , , .. ,
, .
, (, ISBN-
..), (,
, , ).
, JPA ,
, JPQL.

241
JPQL
JPQL ,
. JPQL ,
SQL.
. ,
SQL (), JPQL . JPQL
- , , , -
. ,
, (, myClass.myAttri
bute).
JPQL
JPQL- , SQL. SQL- JDBC,
.
JPQL-
:
SELECT b
FROM Book b

SQL, . JPQL , ,
Book. , FROM
: b Book. SELECT
, b(Book).
,
Book.
, . WHERE, :
SELECT b
FROM Book b
WHERE b.title = 'H2G2'

-. Book ,
title String, b.title title Book.
, Book title H2G2.
SELECT FROM. SELECT . FROM
, ,
WHERE, ORDER BY, GROUP BY HAVING . 6.20 JPQL-.

242 6.
6.20. JPQL-

SELECT < SELECT>


FROM < FROM>
[WHERE < WHERE>]
[ORDER BY < ORDER BY>]
[GROUP BY < GROUP BY>]
[HAVING < HAVING>]

6.20 SELECT, DELETE UPDATE


-.

SELECT
SELECT : , , , .

( ) (.) :
SELECT [DISTINCT] <> [[AS] < >]
expression ::= { NEW | TREAT | AVG | MAX | MIN | SUM | COUNT }

SELECT . ,
Customer c, SELECT :
SELECT c
FROM Customer c

SELECT . Customer
firstName, SELECT c.firstName
firstName.
firstName lastName Customer, , :
SELECT c.firstName, c.lastName
FROM Customer c

JPA 2.0 ( CASE WHEN ... THEN ... ELSE ... END).
, , ,
(, 50%-)
(, 50%- Apress 20%-
).
SELECT CASE b.editor WHEN 'Apress'
THEN b.price * 0.5
ELSE b.price * 0.8
END
FROM Book b

243
JPQL
Customer Address,
c.address , , :
SELECT c.address
FROM Customer c

EntityGraph.
, c.address.country.code,
:
SELECT c.address.country.code
FROM Customer c

SELECT
Java-, .
,
.
SELECT NEW org.agoncal.javaee7.CustomerDTO(c.firstName, c.lastName, c.address.
street1)
FROM Customer c

CustomerDTO, new , .

, ( ),
. DISTINCT.
SELECT DISTINCT c
FROM Customer c
SELECT DISTINCT c.firstName
FROM Customer c


, . SELECT : AVG, COUNT, MAX, MIN, SUM.
GROUP BY
HAVING.
SELECT COUNT(c)
FROM Customer c

SELECT , WHERE HAVING. (ABS, SQRT, MOD, SIZE, INDEX) (CONCAT, SUBSTRING,
TRIM, LOWER, UPPER, LENGTH, LOCATE), / (CURRENT_DATE,
CURRENT_TIME, CURRENT_TIMESTAMP).

244 6.

FROM
FROM . , , ,
(SELECT, WHERE ..). FROM . Customer , c :
SELECT c
FROM Customer c

WHERE
WHERE ,
SELECT, UPDATE DELETE. WHERE
,
.

. , , firstName :
SELECT c
FROM Customer c
WHERE c.firstName = ''

,
AND OR. AND
, firstName , country
:
SELECT c
FROM Customer c
WHERE c.firstName = '' AND c.address.country = ''

WHERE : =, >, >=, <, <=, <>,


[NOT] BETWEEN, [NOT] LIKE, [NOT] IN, IS [NOT] NULL, IS [NOT] EMPTY, [NOT] MEMBER [OF].
:
SELECT c
FROM Customer c
WHERE c.age > 18
SELECT c
FROM Customer c
WHERE c.age NOT BETWEEN 40 AND 50
SELECT c
FROM Customer c
WHERE c.address.country IN ('', '')

LIKE ,
: (_) -

245
JPQL
, , (%), , .
SELECT c
FROM Customer c
WHERE c.email LIKE '%mail.com'


WHERE, , .
. JPQL ,

. .
(?),
(, ?1).
, .
SELECT c
FROM Customer c
WHERE c.firstName = ?1 AND c.address.country = ?2

(:).
, .
SELECT c
FROM Customer c
WHERE c.firstName = :fname AND c.address.country = :country

, , , .

SELECT, WHERE
HAVING. . MIN(age),
.
SELECT c
FROM Customer c
WHERE c.age = (SELECT MIN(cust. age) FROM Customer cust ))

ORDER BY
ORDER BY ,
SELECT.
, ASC DESC. ASC ,
; DESC, ,

246 6.
, .
, .
SELECT c
FROM Customer c
WHERE c.age > 18
ORDER BY c.age DESC


:
SELECT c
FROM Customer c
WHERE c.age > 18
ORDER BY c.age DESC, c.address.country ASC

GROUP BY HAVING
GROUP BY
.
, GROUP BY. , :
SELECT c.address.country, count(c)
FROM Customer c
GROUP BY c.address.country
GROUP BY (c.address.country), (count(c)).
, , GROUP BY,
SELECT.
HAVING ,
, ,
WHERE, GROUP BY. , HAVING, , country , .
SELECT c.address.country, count(c)
FROM Customer c
GROUP BY c.address.country
HAVING c.address.country <> ''
GROUP BY HAVING SELECT ( DELETE
UPDATE).


, EntityManager.remove() , . ,
, -

247

. , ( ).
.
JPQL -.
. DELETE
SELECT, WHERE . , . DELETE :
DELETE FROM < > [[AS] < >]
[WHERE < WHERE>]

18,
DELETE.
DELETE FROM Customer c
WHERE c.age < 18


UPDATE,

WHERE. UPDATE
:
UPDATE < > [[AS] < >]
SET < UPDATE> {, < UPDATE>}*
[WHERE < WHERE>]

,
firstName TOO YOUNG :
UPDATE Customer c
SET c.firstName = 'TOO YOUNG'
WHERE c.age < 18

JPQL ,
(SELECT, FROM, WHERE ..). JPQL-
? : . JPA2.1
, ,
.
,
JPQL-, .
.
Criteria API JPA2.0 -
Query API.

248 6.

SQL- JPQL-.
JPA 2.1 API
.
, ,
, , .6.4, Query,
TypedQuery, StoredProcedureQuery (TypedQuery StoredProcedureQuery Query). Query , Object, TypedQuery , . StoredProcedureQuery
.
6.4.

Query createQuery(String jpqlString)

Query
JPQL-

Query createNamedQuery(String name)

Query
(
JPQL SQL)

Query createNativeQuery(String sqlString)

Query
SQL-

Query createNativeQuery(String sqlString,


Class resultClass)

Query createNativeQuery(String sqlString,


String resultSetMapping)

<T> TypedQuery<T>
createQuery(CriteriaQuery<T>
criteriaQuery)

TypedQuery

<T> TypedQuery<T> createQuery(String


jpqlString, Class<T> resultClass)

<T> TypedQuery<T>
createNamedQuery(String name, Class<T>
resultClass)

StoredProcedureQuery createStored
ProcedureQuery(String procedureName)

StoredProcedureQuery

StoredProcedureQuery createStored
ProcedureQuery(String procedureName,
Class... resultClasses)

,
,

StoredProcedureQuery createStored
ProcedureQuery(String procedureName,
String... resultSetMappings)

StoredProcedureQuery createNamedStored
ProcedureQuery(String name)

249

Query, TypedQuery StoredProcedureQuery



API. API Query, 6.21, ( )
JPQL, SQL.
, API Query .
6.21. Query API

public interface Query {


//
List getResultList();
Object getSingleResult();
int executeUpdate();
//
Query setParameter(String name, Object value);
Query setParameter(String name, Date value, TemporalType temporalType);
Query setParameter(String name, Calendar value, TemporalType temporalType);
Query setParameter(int position, Object value);
Query setParameter(int position, Date value, TemporalType temporalType);
Query setParameter(int position, Calendar value, TemporalType temporalType);
<T> Query setParameter(Parameter<T> param, Tvalue);
Query setParameter(Parameter<Date> param, Date value, TemporalType
temporalType);
Query setParameter(Parameter<Calendar> param, Calendar value, TemporalType
temporalType);
//
Set<Parameter<?>> getParameters();
Parameter<?> getParameter(String name);
Parameter<?> getParameter(int position);
<T> Parameter<T> getParameter(String name, Class<T> type);
<T> Parameter<T> getParameter(int position, Class<T> type);
boolean isBound(Parameter<?> param);
<T> TgetParameterValue(Parameter<T> param);
Object getParameterValue(String name);
Object getParameterValue(int position);
// ,
Query setMaxResults(int maxResult);
int getMaxResults();
Query setFirstResult(int startPosition);
int getFirstResult();
//
Query setHint(String hintName, Object value);
Map<String, Object> getHints();
//

250 6.
Query setFlushMode(FlushModeType flushMode);
FlushModeType getFlushMode();
//
Query setLockMode(LockModeType lockMode);
LockModeType getLockMode();
// API,
<T> Tunwrap(Class<T> cls);
}

, API,
. SELECT,
.
getResultList() (, , ..).
getSingleResult()
( NonUniqueResultException
).
executeUpdate()
,
.
JPQL ,
, (, :myParam), (, ?1). API Query setParameter
.
, .
(, - ).
Query
setFirstResult() setMaxResults(),
(, )
.
,
.
: AUTO COMMIT. AUTO ( ) , ,
. COMMIT ,
.
setLockMode(LockModeType).
.


, . EntityMana

251

ger.createQuery(), , -

JPQL-.
JPQL-
. , , getResultList(), Customer
(List<Customer>). ,
, getSingleResult().
.
Query query = em.createQuery("SELECT cFROM Customer c");
List<Customer> customers = query.getResultList();

JPQL- Query. query.get


ResultList(), . ,
Customer,
TypedQuery :
TypedQuery<Customer> query =
em.createQuery("SELECT cFROM Customer c", Customer.class);
List<Customer> customers = query.getResultList();

,
. .
String jpqlQuery = "SELECT cFROM Customer c";
if (someCriteria)
jpqlQuery += "WHERE c.firstName = ''";
query = em.createQuery(jpqlQuery);
List<Customer> customers = query.getResultList();

, firstName
, firstName. : .
:fname (
:) setParameter:
query = em.createQuery("SELECT cFROM Customer cwhere c.firstName = :fname");
query.setParameter("fname", "");
List<Customer> customers = query.getResultList();

, fname , . , ,
:
query = em.createQuery("SELECT cFROM Customer cwhere c.firstName = ?1");
query.setParameter(1, "");
List<Customer> customers = query.getResultList();


, setMax
Results, :

252 6.
query = em.createQuery("SELECT cFROM Customer c", Customer.class);
query.setMaxResults(10);
List<Customer> customers = query.getResultList();

,
JPQL- SQL- .
,
JPQL-, SQL-.
. , , ,
.


, . , ,
, JPQL- SQL-,
, .
,
@NamedQuery, XML-.
, , @NamedQuery, : .
, Customer (6.22).
6.22. Customer

@Entity
@NamedQueries({
@NamedQuery(name = "findAll", query="select cfrom Customer c"),
@NamedQuery(name = "findVincent",
query="select cfrom Customer cwhere c.firstName = ''"),
@NamedQuery(name = "findWithParam",
query="select cfrom Customer cwhere c.firstName = :fname")
})
public class Customer {
@Id @GeneratedValue
private Long id;
private String firstName;
private String lastName;
private Integer age;
private String email;
@OneToOne
@JoinColumn(name = "address_fk")
private Address address;
// , ,
}

253

Customer , @NamedQueries,
@NamedQuery. findAll
- ( WHERE ). findWithParam
:fname
firstName. 6.22 @NamedQuery,
Customer , :
@Entity
@NamedQuery(name = "findAll ", query="select cfrom Customer c")
public class Customer {...}

,
. EntityManager.create
NamedQuery(), , .
Query TypedQuery, , , ..
findAll, :
Query query = em.createNamedQuery("findAll");

-
Customer, TypedQuery,
:
TypedQuery<Customer> query = em.createNamedQuery("findAll", Customer.class);

findWithParam :fname setMaxResults 3:


Query query = em.createNamedQuery("findWithParam");
query.setParameter("fname", "");
query.setMaxResults(3);
List<Customer> customers = query.getResultList();

Query API Query, . (setParameter().setMaxResults() ..):


Query query = em.createNamedQuery("findWithParam").setParameter("fname",
"")
.setMaxResults(3);

.
, -, ( findAll
, Customer).
: , .
, findAll.

254 6.
findAll, , findAll, ,
-.
. , findAll
Customer Customer.findAll.
, , ,
, , , , ,
. , . 6.23 , Customer.
6.23. Customer

@Entity
@NamedQuery(name = Customer.FIND_ALL, query="select cfrom Customer c"),
public class Customer {
public static final String FIND_ALL = "Customer.findAll";
// , , ,
}

FIND_ALL findAll
.
@NamedQuery, ,
:
TypedQuery<Customer> query = em.createNamedQuery(Customer.FIND_ALL,
Customer.class);

Criteria API ( -
)
JPQL- (
) . , . , . ,
, - .
, JPQL (SLECT
SELECT), (Custmer Customer) (firstname
firstName ).
(SELECT cWHERE c.firstName = 'John' FROM Customer).
, ,
.
JPA 2.0 API- Criteria API,
javax.persistence.criteria.
- . , ,
, .

255

, JPQL (SELECT, UPDATE, DELETE, WHERE, LIKE, GROUP BY...)


API-. , Criteria API
, JPQL, . , ,
firstName Vincent. JPQL :
SELECT cFROM Customer cWHERE c.firstName = ''

JPQL- 6.24 -
Criteria API.
6.24. ,
, firstName Vincent

CriteriaBuilder builder = em.getCriteriaBuilder();


CriteriaQuery<Customer> criteriaQuery = builder.createQuery(Customer.class);
Root<Customer> c= criteriaQuery.from(Customer.class);
criteriaQuery.select(c).where(builder.equal(c.get("firstName"), ""));
Query query = em.createQuery(criteriaQuery).getResultList();
List<Customer> customers = query.getResultList();

, , SELECT, FROM
WHERE API- select(), from() where().
JPQL. CriteriaBuilder,
( em 6.24 6.25). ( ,
desc(), asc(), avg(), sum(), max(), min(), count(), and(), or(), greaterThan(), lowerThan()...).
CriteriaBuilder (CriteriaQuery) . , select(), from(), where(), orderBy(),
groupBy() having(), JPQL. 6.24
c( SELECT cFROM Customer)
Root (Root<Customer> c). ,
SQL-, CriteriaBuilder,
CriteriaQuery Root: ( )
(, , CASE, ).
6.25. ,
40

CriteriaBuilder builder = em.getCriteriaBuilder();


CriteriaQuery<Customer> criteriaQuery = builder.createQuery(Customer.class);
Root<Customer> c= criteriaQuery.from(Customer.class);
criteriaQuery.select(c).where(builder.greaterThan(c.get("age").as(Integer.
class), 40));
Query query = em.createQuery(criteriaQuery).getResultList();
List<Customer> customers = query.getResultList();

. 6.25 , 40 . c.get("age")
age Customer , 40 .

256 6.
, , Criteria API
. . 6.24 6.25,
("firstName" "age"), Customer. , . 6.25 age Integer ((c.get("age").as(Inte
ger.class)), - , age
Integer. Criteria API
,
API-.
Criteria API. 6.24 6.25 :
JPQL
CriteriaBuilder CriteriaQuery.
, :
firstName Customer c.get("firstName"). get
. Criteria API ,
API , .
6.26 Customer
(Long, String, Integer, Address).
6.26. Customer

@Entity
public class Customer {
@Id @GeneratedValue
private Long id;
private String firstName;
private String lastName;
private Integer age;
private String email;
private Address address;
// , ,
}

JPA2.1 .
X X_ ( ). , Customer ,
Customer_, 6.27.
6.27. Customer_, Customer

@Generated("EclipseLink")
@StaticMetamodel(Customer.class)
public class Customer_ {
public static volatile SingularAttribute<Customer,
public static volatile SingularAttribute<Customer,
public static volatile SingularAttribute<Customer,
public static volatile SingularAttribute<Customer,

Long> id;
String> firstName;
String> lastName;
Integer> age;

257

public static volatile SingularAttribute<Customer, String> email;


public static volatile SingularAttribute<Customer, Address> address;
}

Customer javax.persistence.metamodel.Attribute (CollectionAttribute ,


ListAttribute, MapAttribute, SetAttribute SingularAttribute).
(,
SingularAttribute<Customer, Integer>, age). 6.28
, 6.25,
(c.get("age") c.get(Customer_.age)). ,
age Integer,
Integer as(Integer.class).
6.28. ,
40

CriteriaBuilder builder = em.getCriteriaBuilder();


CriteriaQuery<Customer> criteriaQuery = builder.createQuery(Customer.class);
Root<Customer> c= criteriaQuery.from(Customer.class);
criteriaQuery.select(c).where(builder.greaterThan(c.get(Customer_.age), 40));
Query query = em.createQuery(criteriaQuery).getResultList();
List<Customer> customers = query.getResultList();

- , Criteria
API. API-,
5 6 JPA2.1.

, , Attribute
SingularAttribute, javax.persistence.me
tamodel. . EclipseLink CanonicalModelProcessor.
,
Java-, Ant- Maven-.


JPQL ,
.
JPA . SQL-
(SELECT, UPDATE DELETE) Query
.
.
, JDBC? , JPA, ,

258 6.
. Customer
SQL,
EntityManager.createNativeQuery(), SQL -, .
Query query = em.createNativeQuery("SELECT * FROM t_customer", Customer.
class);
List<Customer> customers = query.getResultList();

, SQL-
, ( ,
JPQL-). - ,
, , . ,
SQL-.
@NamedNativeQuery, (. ).
JPQL-, .
@Entity
@NamedNativeQuery(name = "findAll", query="select * from t_customer")
@Table(name = "t_customer")
public class Customer {...}


(JPQL SQL) :
,
. ,
.
, , .
,
SQL- , . , , SQL,
,,
.
.
, .
, , .
, ,
.

.

259

, ,
( Java).

.

,
.
. -
, ,
. -
,
(, , T_Inventory, T_Warehouse, T_Book, T_CD, T_Transport ..).
, SQL- .
sp_archive_books, 6.29, archiveDate warehouseCode
T_Inventory T_Transport.
6.29. ,

CREATE PROCEDURE sp_archive_books @archiveDate DATE, @warehouseCode VARCHAR AS


UPDATE T_Inventory
SET Number_Of_Books_Left - 1
WHERE Archive_Date < @archiveDate AND Warehouse_Code = @warehouseCode;
UPDATE T_Transport
SET Warehouse_To_Take_Books_From = @warehouseCode;
END

6.29 ,
(sp_archive_books). ,
.
(@archiveDate @warehouseCode ) , , , .
.
JPA2.1 StoredProcedureQuery ( Query) . ,
, API- , , .
(@NamedStored
ProcedureQuery) .
6.30 Book, sp_archive_books . @NamedStoredProcedureQuery ,
(Date.class String.class),
(IN, OUT, INOUT, REF_CURSOR), ,

260 6.
( ). @StoredProcedureParameter
.
6.30. ,

@Entity
@NamedStoredProcedureQuery(name = "archiveOldBooks", procedureName =
"sp_archive_books",
parameters = {
@StoredProcedureParameter(name = "archiveDate", mode = IN, type = Date.class),
@StoredProcedureParameter(name = "warehouse", mode = IN,
type = String.class)
}
)
public class Book {
@Id @GeneratedValue
private Long id;
private String title;
private Float price;
private String description;
private String isbn;
private String editor;
private Integer nbOfPage;
private Boolean illustrations;
// , ,
}

sp_archive_books
, (archiveOldBooks). StoredProcedureQuery,
, 6.31.
6.31. StoredProcedureQuery

StoredProcedureQuery query =
em.createNamedStoredProcedureQuery("archiveOldBooks");
query.setParameter("archiveDate", new Date());
query.setParameter("maxBookArchived", 1000);
query.execute();

(@Named
StoredProcedureQuery), API- . ,
. registerStoredProcedure
Parameter StoredProcedureQuery, 6.32.
6.32. StoredProcedureQuery

StoredProcedureQuery query =
em.createStoredProcedureQuery("sp_archive_old_books");
query.registerStoredProcedureParameter("archiveDate", Date.class,
ParameterMode.IN);

261
Cache API
query.registerStoredProcedureParameter("maxBookArchived", Integer.class,
ParameterMode.IN);
query.setParameter("archiveDate", new Date());
query.setParameter("maxBookArchived", 1000);
query.execute();

Cache API
( Java EE) , ,
, ,
. , .
JPA .
JPA 2.0 . , , ,
.
SQL-
. ,
, UPDATE .
.
JPA ( ) ,
, .. .6.3,

.

,
( ). ,
. JPA2.0 ,
, API-. 6.33 API- ( JPA ,
), .
, javax.persistence.Cache ,
.
6.33. Cache API

public interface Cache {


//

262 6.

.6.3.

public boolean contains(Class cls, Object id);


//
public void evict(Class cls, Object id);
// ( )
public void evict(Class cls);
//
public void evictAll();
// ,
public <T> Tunwrap(Class<T> cls);
}

API , , . API, , , @Cacheable,


6.34. @Cacheable,
.
6.34. Customer

@Entity
@Cacheable(true)
public class Customer {
@Id @GeneratedValue
private Long id;

263
Cache API
private String firstName;
private String lastName;
private String email;
// , ,
}

@Cacheable . ,
, , .
JPA, shared-cache-mode persistence.xml.
:
ALL ,
;
DISABLE_SELECTIVE ,
@Cacheable(false);
ENABLE_SELECTIVE ,
@Cacheable(true);
NONE ;
UNSPECIFIED ( , ).
, ,
. , 6.35,
, .
Customer .
Customer (.6.34),
( EntityManagerFactory.getCache().con
tains() ). ache.evict(Customer.class)
.
6.35. Customer

Customer customer = new Customer("", "", "plecomte@mail.com");


tx.begin();
em.persist(customer);
tx.commit();
// EntityManagerFactory Cache
Cache cache = emf.getCache();
// Customer
assertTrue(cache.contains(Customer.class, customer.getId()));
// Customer
cache.evict(Customer.class);
// Customer
assertFalse(cache.contains(Customer.class, customer.getId()));

264 6.


JPA , JPQL , . , ,
, . ,
. , ,
, - .
,
, .6.4.
$2. , $5.
, ,
. $10.
, ,
$12 15.

.6.4. 1 (tx1) 2 (tx2),

,
, , JPA.
,
, . , , ,
SQL-.
JPA 2.1 ( JPA 1.0 ).
,
, ,
.
,
.

265

, ,
.
, ,
, , .
!
JPA API-.
,
EntityManager.find EntityManager.refresh (
lock), JPQL-. , Query , .6.5 6.6.
6.5.

<T> Tfind(Class<T> entityClass, Object


primaryKey, LockModeType lockMode)

void lock(Object entity, LockModeType


lockMode)

,
,

void refresh(Object entity, LockModeType


lockMode)


, , , ,

LockModeType getLockMode(Object entity)


6.6. Query JPQL-

LockModeType getLockMode()

Query setLockMode(LockModeType
lockMode)

LockModeType , ,
, :
OPTIMISTIC ;
OPTIMISTIC_FORCE_INCREMENT version,
(. );
PESSIMISTIC_READ
;

266 6.
PESSIMISTIC_WRITE
, ;
PESSIMISTIC_FORCE_INCREMENT version,
(. );
NONE , .
,
. , .
Book book = em.find(Book.class, 12);
// ,
em.lock(book, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
book.raisePriceByTwoDollars();

.
Book book = em.find(Book.class, 12, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
// Book,
book.raisePriceByTwoDollars();


Java : Java SE5.0, Java
SE6.0, EJB3.1, JAX-RS1.0 .. JAX-RS JAX-RS1.1. JPA ,
. ,
,
, 1. ,
, 2 ..
.
,
, @Version.
. ,
, int, Integer, short, Short, long, Long Timestamp. 6.36
, version Book.
6.36. Book @Version Integer

@Entity
public class Book {
@Id @GeneratedValue
private Long id;
@Version
private Integer version;
private String title;
private Float price;

267

private String description;
private String isbn;
private Integer nbOfPage;
private Boolean illustrations;
// , ,
}

version,
. version
. , ,
. 6.37
Book . ,
version 1. ,
, ,
2.
6.37. tx1 tx2,

Book book = new Book("H2G2", 21f, " IT-", "123-456", 321, false);
tx.begin();
em.persist(book);
tx.commit();
assertEquals(1, book.getVersion());
tx.begin();
book.raisePriceByTwoDollars();
tx.commit();
assertEquals(2, book.getVersion());

version , ,
. .
, , @Version.


, ,
. , , , , , . ,
. ,
.
, , OptimisticLockException,
.

268 6.
OptimisticLockException?
, (
lock find, , LockModeType),
, @Version.
@Version
,
version
. @Version,
().
. , tx1 tx2,
Book.
Book 1. $2 . , , 2.
$5 .
tx2 , ,
. ,
, - OptimisticLockException,
.6.5.

.6.5. OptimisticLockException,
tx2

, @Version : OptimisticLockException
( em.flush()).
, , , .
,
:
Book book = em.find(Book.class, 12);
// ,
em.lock(book, LockModeType.OPTIMISTIC);
book.raisePriceByTwoDollars();

269

LockModeType,
, : OPTIMISTIC OPTIMISTIC_FORCE_INCREMENT
( READ WRITE, ).
, OPTIMISTIC_FORCE_INCREMENT
() version, .

,
. , . , ,
.
,
.


,
, , .
,
SQL- SELECT ... FOR UPDATE .

.
.
, , ,
. ,
,
PessimisticLockException,
.
, .
,
, . , .
100
,
. ,
, ,
JPA.
,
@Version.

270 6.


, . ( new)
Java Java- ( ),
. , , , . ,
(,
set,
, ).
, .6.6, UML . Customer.

.6.6.

Customer, new.
, JPA .
- , -

271

, .
Customer EntityManager.
persist(). ,
. ,
, - (, customer.setFirstName()) EntityManager.refresh().
.
EntityManager.contains(customer), ,
true, Customer
( ).

. EntityManager.find()
JPQL- ,
.
, , EntityManager.remove(),
. Java- ,
,
.
, .
, EntityManager.clear()
EntityManager.detach(customer)
; . ,
: .
,
, java.io.Se
rializable. JPA-, Java-.
, , . , EntityManager.merge(). , JSF-. ,
Customer JSF-,
. ,
.
. , -
, , , . , .

-,
.

272 6.


, ,
: , , .
, , , . pre post,
-.
- , .6.7.
-,
- .
6.7.

@PrePersist

EntityManager.persist()

@PostPersist

, .
( @GeneratedValue),

@PreUpdate

(
EntityManager.merge())

@PostUpdate

@PreRemove

EntityManager.remove()

@PostRemove

@Postload

,
( JPQL- EntityManager.find())
. @Preload , ,
,

UML- , .6.6, , .6.7.


,
@PrePersist.
, , , , @PostPersist.
(@PreUpdate, @PostUpdate) (@PreRemove, @PostRemove). , @PostLoad,
( EntityMana
ger.find() JPQL-). , ,
- , (@PostLoad).
, (@PreUpdate, @PostUpdate).

273

.6.7.

? ,
, , -,
.
Java-, , ( ),
6.38.
.
6.38. Customer

@Entity
public class Customer {
@Id @GeneratedValue
private Long id;
private String firstName;
private String lastName;
private String email;
private String phoneNumber;
@Temporal(TemporalType.DATE)
private Date dateOfBirth;
@Transient
private Integer age;
@Temporal(TemporalType.TIMESTAMP)

274 6.
private Date creationDate;
@PrePersist
@PreUpdate
private void validate() {
if (firstName == null || "".equals(firstName))
throw new IllegalArgumentException(" ");
if (lastName == null || "".equals(lastName))
throw new IllegalArgumentException(" ");
}
@PostLoad
@PostPersist
@PostUpdate
public void calculateAge() {
if (dateOfBirth == null) {
age = null;
return;
}
Calendar birth = new GregorianCalendar();
birth.setTime(dateOfBirth);
Calendar now = new GregorianCalendar();
now.setTime(new Date());
int adjust = 0;
if (now.get(DAY_OF_YEAR) - birth.get(DAY_OF_YEAR) < 0) {
adjust = -1;
}
age = now.get(YEAR) - birth.get(YEAR) + adjust;
}
// , ,
}

6.38 Customer (
firstName lastName). @PrePersist @PreUpdate . ,
, , ,
, .
calculateAge() . age
. ,
calculateAge() ,
.
.
public, private, protected , static final. 6.38
, validate() private.

275

( validateData() @PrePersist
@PreUpdate). -
(,
@PrePersist).
( ),
.
.
JNDI, JDBC, JMS EJB-, - EntityManager Query.
, ,
. , 6.38
Customer Person, Person
@PrePersist Customer @PrePersist.
,
. , ,
. Customer Address @PreRemove, Customer @PreRemove.

, ,
-, .
-
. Java-, .
@EntityListeners.
Customer, calculateAge() validate() -: AgeCalculationListener (6.39)
DataValidationListener (6.40).
6.39. , age
Customer

public class AgeCalculationListener {


@PostLoad
@PostPersist
@PostUpdate
public void calculateAge(Customer customer) {
if (customer.getDateOfBirth() == null) {
customer.setAge(null);
return;
}
Calendar birth = new GregorianCalendar();

276 6.
birth.setTime(customer.getDateOfBirth());
Calendar now = new GregorianCalendar();
now.setTime(new Date());
int adjust = 0; if (now.get(DAY_OF_YEAR) - birth.get(DAY_OF_YEAR) < 0) {
adjust = -1;
}
customer.setAge(now.get(YEAR) - birth.get(YEAR) + adjust);
}
}
6.40. , Customer

public class DataValidationListener {


@PrePersist
@PreUpdate
private void validate(Customer customer) {
if (customer.getFirstName() == null || "".equals(customer.getFirstName()))
throw new IllegalArgumentException(" ");
if (customer.getLastName() == null || "".equals(customer.getLastName()))
throw new IllegalArgumentException(" ");
}
}

- .
, public .
, , 6.38.
,
(, firstName lastName Customer, ). , , , ,
, .
, ,
:
void <>();

, ,
. , Object:
void <>(Object anyEntity)

( ), :
void <>(Customer customerOrSubclasses)

,
Customer,
@EntityListeners (6.41).
.

277

,
, , , ,
.
( ).
6.41. Customer,

@EntityListeners({DataValidationListener.class, AgeCalculationListener.class})
@Entity
public class Customer {
@Id @GeneratedValue
private Long id;
private String firstName;
private String lastName;
private String email;
private String phoneNumber;
@Temporal(TemporalType.DATE)
private Date dateOfBirth;
@Transient
private Integer age;
@Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
// , ,
}

, 6.38. Customer DataValidationListener.validate()


age AgeCalculationListener.calcu
lateAge().
, , , .
. ,
,
( ).
,
, , , , . , , ,
@ExcludeSuperclassListeners ( XML-).
6.41 Customer, ,
.
, ,
. ,
DebugListener, ,
6.42.

278 6.
6.42. DebugListener,

public class DebugListener {


@PrePersist
void prePersist(Object object) {
System.out.println("prePersist");
}
@PreUpdate
void preUpdate(Object object) {
System.out.println("preUpdate");
}
@PreRemove
void preRemove(Object object) {
System.out.println("preRemove");
}
}

, Object , , DebugListener @EntityListeners.


,
.
JPA , , .
, , ,
XML.
, XML
. DebugListener . XML, 6.43,
.
6.43. DebugListener,

<?xml version="1.0" encoding="UTF-8"?>


<entity-mappings xmlns="http://xmlns.jcp.org/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://xmlns.jcp.org/xml/ns/persistence/orm
http://xmlns.jcp.org/xml/ns/persistence/orm_2_1.xsd"
version="2.1">
<persistence-unit-metadata>
<persistence-unit-defaults>
<entity-listeners>
<entity-listener class="org.agoncal.book.javaee7.chapter06.
DebugListener"/>
</entity-listeners>
</persistence-unit-defaults>
</persistence-unit-metadata>
</entity-mappings>

279

<persistence-unit-metadata> ,
- . <persistence-unit-defaults>
, <entity-listener>
. persistence.xml
, .
DebugListener .
,
,
XML. , @EntityListeners. ,
, @ExcludeDefaultListeners, 6.44.
6.44. Customer,

@ExcludeDefaultListeners
@Entity
public class Customer {
@Id @GeneratedValue
private Long id;
private String firstName;
private String lastName;
private String email;
private String phoneNumber;
@Temporal(TemporalType.DATE)
private Date dateOfBirth;
@Transient
private Integer age;
@Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
// , ,
}

,
.
1. @EntityListeners .
2. (
, ).
3. .
4. ( ,
).
5. .

, . ,

280 6.
. , , ,
, . JPA JPQL,
. , WHERE, ORDER BY GROUP BY,
, .
, , .
(@PrePersist, @PostPersist ..). (
).
, ( -,
, ).
-, , .

7.
.
EJB-
, JPA JPQL.
,
,
( , ..).
-. -, (Web, Swing,
..). ,

-. Java EE
EJB- (Enterprise JavaBeans EJB).
.
, JPA
, (Artist , CD , Book , Customer ..).
-, , ( ) ( , , ,
..). -
- ( - SOAP RESTful), ( JMS) .
,
- ( EJB- JSF, ), .
EJB- ,
. .
EJB-,
EJB-: , . EJB-
, - . EJB-

282 7. EJB-
. EJB3.1 EJB-
( ) . ,
EJB- .

EJB-
EJB- , , . , , ,
- (SOAP REST), ,
, - (AspectOriented Programming AOP) .. ,
EJB- Java SE Java
EE JDBC, JavaMail, JPA, Java Transaction API (JTA), Java Messaging Service
(JMS), Java (Java Authentication and
Authorization Service JAAS), Java Naming and Directory Interface (JNDI) (Remote Method Invocation RMI). - (.7.1),
-. EJB-
,
JavaServer Faces (JSF), (JMS -).

.7.1.

EJB- , . EJB-
Java, , -

283
EJB-

. Java, . EJB-
, , ,
, ,
. ,
, .
, EJB- -,
.
, 3.2, EJB-
, ,
. API-, JNDI, , CDI- EJB-
, .
12 , EJB-,
.

EJB-
EJB- -,
.
, JavaEE EJB-.

, .
, .
,
.
, .
EJB- . ,
.
, EJB- , . , . , EJB-
/ . EJB- ,
( JAR, WAR EAR) .
EJB-, (Message-Driven Beans MDB),
JMS. EJB-, , EJB,
(13),

284 7. EJB-
, (Message-Oriented Middleware MOM).
EJB-, , -
EJB-.
EJB- -.
14 15 - SOAP RESTful,
Java-, -, EJB-, EJB-.

EJB3.1 Entity CMP. EJB3.2. JPA
. Entity CMP.


(EJB1.0) EJB-
, Java.
GlassFish, JBoss, Weblogic .., ,
, EJB-.
, .
,
, , , .
, , ,
. ,
EJB-
.
, . EJB3.1
, .
,
EJB- JavaSE,
Java . ,
(, ) EJB-
. API-, , ,
JavaEE, . Java, , EJB -
.

285
EJB-

,
,
, ,
, , , .
EJB- ( EJB-,
, ..)
- .

EJB- ( JMS, EJB-,
, ..), POJO
CDI.
EJB- . ,
.
EJB-
EJB-, ,
, . , EJB- , , .

.
EJB-,
,
JMS.

EJB- , .
.
EJB-
, .
EJB-
, ,
EJB- .
,
, .
,
.

286 7. EJB-
EJB3.1,
.
EJB-,
, -,
- .
EJB- . MBean- (Managed Beans). EJB-, EJB, , .
, EJB-,
,
EJB-. , .
EJB- .
JavaEE EJB-
( JSF-),
(Application Client Container ACC) ( ), ( , ), ..
EJB- .
, EJB- , java.io, ServerSocket,
AWT (Abstract
Window Toolkit) API- Swing .

EJB Lite
EJB-
Java EE7, ,
-. EJB3.2 , ,
IIOP (Internet InterOrb Protocol ), , , EJB3.2, .
EJB- , .
EJB API EJB Lite. ,
EJB-,
-. EJB Lite
JavaEE, EJB3.2. EJB Lite EJB API, .7.1.

287
EJB
7.1. EJB Lite EJB

EJB Lite


EJB 3.2

EJB- ( , , )

Embeddable API

EJB-,

- JAX-WS

- JAX-RS

TimerService

RMI/IIOP


EJB
RMI/IIOP EJB- EJB- .
JavaEE.
EJB3.2 , RMI/IIOP -,
, , , SOAP REST.

EJB
EJB1.0 1998, EJB3.2 2013
Java EE7. 15 EJB
, - .
POJO-, Entity Bean
CMP JPA EJB- , .
EJB3.2 , ,
(, JNDI- ). EJB3.2 , , .

288 7. EJB-

EJB
, Java,
, ,
RMI JTA.
-,
IBM ,
EBJ-.
EJB1.0 EJB- ,
- EJB.

EJB- . EJB- :
, .
EJB 1.1 - EJB ,
XML-
( ).
, .
2001 EJB 2.0 , Java
Community Process ( JSR19). , ,
. , , EJB ( ,
). EJB-,
, - EJB (EJB QL).
EJB2.1 (JSR 153) -, EJB- SOAP/HTTP.
TimerService, EJB-
.
EJB2.1 EJB3.0 , . 2006 EJB3.0 (JSR 220) , , EJB-
POJO. - EJB (JPA), EJB-
EJB- .
,
.
2009 EJB3.1 (JSR 318) Java EE6
, .
3.1 , , , EJB-,
TimerService , , JNDI EJB Lite.

289
EJB

EJB3.2
EJB 3.2 (JSR 345) , . ,
Java EE 6 , .
EJB 3.1, 3.2:
- EJB 2.x;
- EJB 2.x;
EJB QL ( CMP);
- JAX-RPC;
- JAX-RPC.
:
EJB- (EJB Core Contracts and
Requirements) , EJB-;
EJB- (EJB Optional Features) , ,
.
EJB 3.2 .
MBean- (
EJB- ; 9).
EJB-
, .
EJB- .
/ EJB-.
, ,
java.io.
JMS 2.0.
Autocloseable ,
Java SE7.
RMI/IIOP . , Java EE8.
RMI ( IIOP).
.7.2 , EJB3.2
.

290 7. EJB-
7.2. EJB-

javax.ejb

,
EJB- ,
EJB-

javax.ejb.embeddable

Embeddable API

javax.ejb.spi

, EJB-


GlassFish Oracle JavaEE. Sun
2005, Java EE5 2006.
GlassFish 4 EJB3.2. (
Apache Felix OSGi), (, Java EE7, Ruby,
PHP ..).
GlassFish ,
EJB3.2. : OpenEJB,
JBoss, Weblogic, Websphere


EJB-
EJB- -
, , , .. ,
? Java- . 7.1 , ,
EJB-, .
7.1. EJB-

@Stateless
public class BookEJB {
@PersistenceContext(unitName = "chapter07PU")
private EntityManager em;
public Book findBookById(Long id) {
return em.find(Book.class, id);
}
public Book createBook(Book book) {
em.persist(book);
return book;
}
}

291
EJB-
J2EE , EJB-:
( ), ( )
. Java EE5 EJB3.0
,
-, - XML-.
7.1, EJB3.1
- . ,
Java- @Stateless.
, (
), BookEJB Book ,
.

EJB-
7.1
EJB- Java- . , , EJB- , ,
. EJB- , :
EJB-, - -.
EJB- @Stateless, @Stateful
@Singleton ;
-, -,
EJB-. EJB-
,
( ).
.7.2, EJB- (
) , EJB-.

.7.2. EJB- -

292 7. EJB-

EJB-
EJB- Java-,
-. EJB-
:
@Stateless, @Stateful, @Singleton
XML- ;
;
public final abstract;
public , ;
finalize();
- ejb,
final static;
RMI.

,

, EJB-,
EJB-
. ,
Java EJB-, .
.7.3, , Java, (Application Client
Container ACC), -, EJB-.
EJB- .
, EJB-
Java. EJB- EJB- - (, JSF), Java. , ,
EJB-.
EJB-
. - Java-, EJB- . Java, - ,
. :
@Remote -. ,
RMI;

.7.3. EJB-,

293
EJB-

294 7. EJB-
@Local -. EJB-.
.
EJB-, , .
, - EJB -.
7.2 (ItemLocal )
(ItemRemote), EJB-
ItemEJB. findCDs()
, . createCd()
RMI.
7.2. EJB- ,

@Local
public interface ItemLocal {
List<Book> findBooks();
List<CD> findCDs();
}
@Remote
public interface ItemRemote {
List<Book> findBooks();
List<CD> findCDs();
Book createBook(Book book);
CD createCD(CD cd);
}
@Stateless
public class ItemEJB implements ItemLocal, ItemRemote {
// ...
}

7.2
EJB-. @Local @Remote, 7.3. ,
,
, EJB.
7.3. EJB-,
,

public interface ItemLocal {


List<Book> findBooks();
List<CD> findCDs();
}
public interface ItemRemote {
List<Book> findBooks();
List<CD> findCDs();
Book createBook(Book book);

295
EJB-
CD createCD(CD cd);
}
@Stateless
@Remote(ItemRemote.class)
@Local(ItemLocal.class)
@LocalBean
public class ItemEJB implements ItemLocal, ItemRemote {
// ...
}

EJB- (
), . , , @LocalBean EJB-.
7.3, ItemEJB
, .

-
RMI EJB- - SOAP
RESTful. 14 15 -,
. ,
EJB-
. 7.4 EJB ,
- SOAP (@WebService) RESTful (@Path). ,
JAX-WS (. 14) JAX-RS (.15) EJB.
7.4. EJB- ,

@Local
public interface ItemLocal {
List<Book> findBooks();
List<CD> findCDs();
}
@WebService
public interface ItemSOAP {
List<Book> findBooks();
List<CD> findCDs();
Book createBook(Book book);
CD createCD(CD cd);
}
@Path(/items)
public interface ItemRest {
List<Book> findBooks();
}
@Stateless

296 7. EJB-
public class ItemEJB implements ItemLocal, ItemSOAP, ItemRest {
// ...
}

JNDI-
JNDI . API- .
JNDI-, . EJB- GlassFish JBoss
, , . EJB, GlassFish JBoss.
EJB3.1, JNDI- , . , EJB EJB-/
JNDI-. JavaEE
JNDI- :
java:< >[/< >]/< >/< EJB-
>[!< >]

JNDI- :
< > ,
Java EE;
global java:global , Java EE, ;
app java:app , Java EE, ,
;
module java:module ,
JavaEE, ,
;
comp java:comp ,
;
< > , EJB-
EAR WAR. , <
> EAR WAR ( );
< > , EJB-.
EJB- JAR WAR. < > ;
< EJB-> EJB-;
< >
-.
EJB-.

297
EJB-
, ItemEJB ( 7.5),
, ( @LocalBean).
org.agoncal.book.javaee7. ItemEJB < EJB->,
EJB- cdbookstore.jar (< >).
7.5. EJB- ,

package org.agoncal.book.javaee7;
@Stateless
@Remote(ItemRemote.class)
@Local(ItemLocal.class)
@LocalBean
public class ItemEJB implements ItemLocal, ItemRemote {
// ...
}

JNDI-,
ItemEJB,
JNDI-:
java:global/cdbookstore/ItemEJB!org.agoncal.book.javaee7.ItemRemote
java:global/cdbookstore/ItemEJB!org.agoncal.book.javaee7.ItemLocal
java:global/cdbookstore/ItemEJB!org.agoncal.book.javaee7.ItemEJB

, ItemEJB
EAR (, myapplication.ear), < >
:
java:global/myapplication/cdbookstore/ItemEJB!org.agoncal.book.javaee7.ItemRemote
java:global/myapplication/cdbookstore/ItemEJB!org.agoncal.book.javaee7.ItemLocal
java:global/myapplication/cdbookstore/ItemEJB!org.agoncal.book.javaee7.ItemEJB

, JNDI-
java:app java:module. , , , ItemEJB,
JNDI-:
java:app/cdbookstore/ItemEJB!org.agoncal.book.javaee7.ItemRemote
java:app/cdbookstore/ItemEJB!org.agoncal.book.javaee7.ItemLocal
java:app/cdbookstore/ItemEJB!org.agoncal.book.javaee7.ItemEJB
java:module/ItemEJB!org.agoncal.book.javaee7.ItemRemote
java:module/ItemEJB!org.agoncal.book.javaee7.ItemLocal
java:module/ItemEJB!org.agoncal.book.javaee7.ItemEJB

JNDI- EJB-:
, .

EJB-
EJB- JavaEE EJB-. ,

298 7. EJB-
, . , ,
- .
? ,
.
-
, .
Book , : Book ( new), - ,
(book.per
sistToDatabase() ). ,
Book :
Book book = new Book();
book.setTitle(" ");
book.setPrice(12.5F);
book.setDescription("- ,
");
book.setIsbn("1-84023-742-2");
book.setNbOfPage(354);
book.persistToDatabase();

- .
,
, (
). ,
. , , Book,
- ,
, Book
. Book,
:
Book book = new Book();
book.setTitle(" ");
book.setPrice(12.5F);
book.setDescription("- ,
.");
book.setIsbn("1-84023-742-2");
book.setNbOfPage(354);
statelessService.persistToDatabase(book);

EJB- ,
.
, EJB-
( ) -

299
EJB-
. EJB- , . EJB-
, .
. ,
EJB- , .7.4.
.

.7.4. , EJB-

7.6 , EJB- : Java- @Stateless. ,


, , . @PersistenceContext
. EJB- , ,
, EJB- (createBook(), createCD()
..), . 9. , - . , createBook()
Book
.
7.6. EJB- ItemEJB

@Stateless
public class ItemEJB {
@PersistenceContext(unitName = "chapter07PU")
private EntityManager em;
public List<Book> findBooks() {

300 7. EJB-
TypedQuery<Book> query = em.createNamedQuery(Book.FIND_ALL, Book.class);
return query.getResultList();
}
public List<CD> findCDs() {
TypedQuery<CD> query = em.createNamedQuery(CD.FIND_ALL, CD.class);
return query.getResultList();
}
public Book createBook(Book book) {
em.persist(book);
return book;
}
public CD createCD(CD cd) {
em.persist(cd);
return cd;
}
}

EJB-
-. , ItemEJB 7.5
, , CD-BookStore. , , Book CD , .
@Stateless Java- ItemEJB EJB- , Java- , . 7.7 @
javax.ejb.Stateless.
7.7. API- @Stateless

@Target({TYPE}) @Retention(RUNTIME)
public @interface Stateless {
String name() default "";
String mappedName() default "";
String description() default "";
}

name EJB-
(ItemEJB 7.6). ,
, EJB- JNDI. description
, EJB-. mappedName JNDI-, .
, JNDI- , ,
. mappedName JNDI, .
EJB-
, .

(
).

301
EJB-

EJB-
EJB- - , . EJB-
, , .
, .
,
. .
( ), ,
, .
, ( ). ,
( , ).
:
Book book = new Book();
book.setTitle(" ");
book.setPrice(12.5F);
book.setDescription("- ,
.");
book.setIsbn("1-84023-742-2");
book.setNbOfPage(354);
statefulComponent.addBookToShoppingCart(book);
book.setTitle(" ");
book.setPrice(18.25F);
book.setDescription(" , ");
book.setIsbn("0-553-29949-2");
book.setNbOfPage(276);
statefulComponent.addBookToShoppingCart(book);
statefulComponent.checkOutShoppingCart();

,
EJB- . Book,
, . checkOutShoppingCart()
.
EJB- ,
EJB-
. EJB-
. .7.5
EJB- . , ,
EJB- .
- , , ,
, , ,
EJB- .
,
EJB- ,

302 7. EJB-

.7.5. , EJB- .

. .
( , ..). , . ;
, ,
.
(, , ;
JMS, , ..),
EJB- . EJB3.2
, , .
EJB- (7.8). ,
( addItem()).
cartItems .
. , , , , , .
( getTotal()) , - . EJB- . ( checkout()) . ,
,
EJB- .
7.8. EJB- ShoppingCartEJB

@Stateful
@StatefulTimeout(value = 20, unit = TimeUnit.SECONDS)
public class ShoppingCartEJB {
private List<Item> cartItems = new ArrayList<>();
public void addItem(Item item) {

303
EJB-
if (!cartItems.contains(item))
cartItems.add(item);

}
public void removeItem(Item item) {
if (cartItems.contains(item))
cartItems.remove(item);
}
public Integer getNumberOfItems() {
if (cartItems == null || cartItems.isEmpty())
return 0;
return cartItems.size();
}
public Float getTotal() {
if (cartItems == null || cartItems.isEmpty())
return 0f;
Float total = 0f;
for (Item cartItem : cartItems) {
total += (cartItem.getPrice());
}
return total;
}
public void empty() {
cartItems.clear();
}
@Remove
public void checkout() {
// -
cartItems.clear();
}
}

EJB- , .
@javax.ejb.Stateful , API, @Stateless, 7.7.
@javax.ejb.StatefulTimeout @ja
vax.ejb.Remove. @Remove checkout(). ,
EJB-
checkout(). @StatefulTimeout , EJB- ( ), .
java.util.concurrent.TimeUnit,
DAYS, HOURS MILLISECONDS (
MINUTES). , , .
.
.

304 7. EJB-

EJB-
EJB- EJB-,
.
Singleton ()
- . (Design
Patterns: Elements of Reusable Object-Oriented Software),
, , . (Addison-Wesley,
1995). EJB- , ,
. , ,
:
, , , ..
,
(, Hashmap)
. , , , EJB-,
7.9.
.
getInstance() CacheSingleton. EJB-, :
CacheSingleton.getInstance().addToCache(myObject);

, , synchronized
. Map java.util.concurrent.ConcurrentMap, . , .
7.9. Java-, Singleton ()

public class Cache {


private static Cache instance = new Cache();
private Map<Long, Object> cache = new HashMap<>();
private Cache() {}
public static synchronized Cache getInstance() {
return instance;
}
public void addToCache(Long id, Object object) {
if (!cache.containsKey(id))
cache.put(id, object);
}
public void removeFromCache(Long id) {
if (cache.containsKey(id))
cache.remove(id);
}
public Object getFromCache(Long id) {

305
EJB-
if (cache.containsKey(id))
return cache.get(id);
else
return null;
}
}

EJB3.1 EJB-,
Singleton (). ,
EJB-.
,
.7.6. EJB- .

.7.6. , EJB-


EJB- . , ( ,
EJB- ..). , ,
, , EJB-.

7.9 Java-
EJB- (7.10),
. @Singleton,

getInstance(). , .
@javax.ejb.Singleton API-,
@Stateless, 7.7.
7.10. EJB-

@Singleton
public class CacheEJB {
private Map<Long, Object> cache = new HashMap<>();
public void addToCache(Long id, Object object) {
if (!cache.containsKey(id))
cache.put(id, object);
}

306 7. EJB-
public void removeFromCache(Long id) {
if (cache.containsKey(id))
cache.remove(id);
}
public Object getFromCache(Long id) {
if (cache.containsKey(id))
return cache.get(id);
else
return null;
}
}

, EJB-
, :
. EJB-
. ,
.



EJB-, , , .
EJB- . ,
CacheEJB ( 7.10)
. EJB- , .
, EJB- . EJB @Startup, , , .
, :
@Singleton
@Startup
public class CacheEJB {...}

Java EE7 @Startup
EJB, MBean-
. , Java EE8.

EJB-

, EJB-,
. , CacheEJB , EJB-

307

(, CountryCodeEJB, ISO- ). CountryCodeEJB
CacheEJB.
EJB- , @javax.ejb.DependsOn. :
@Singleton
public class CountryCodeEJB {...}
@DependsOn("CountryCodeEJB")
@Singleton
public class CacheEJB {...}
@DependsOn ,
EJB-. ,
CacheEJB CountryCodeEJB ZipCodeEJB. @DependsOn("Country
CodeEJB", "ZipCodeEJB") , Country
CodeEJB ZipCodeEJB CacheEJB.
@Singleton
public class CountryCodeEJB {...}
@Singleton
public class ZipCodeEJB {...}
@DependsOn("CountryCodeEJB", "ZipCodeEJB")
@Startup
@Singleton
public class CacheEJB {...}

, ,
. CacheEJB ( @Startup), , , CountryCodeEJB
ZipCodeEJB , CacheEJB.

EJB-,
. , CacheEJB CountryCodeEJB
( .ear), .jar (technical.jar business.jar ).
, CacheEJB CountryCodeEJB:
@DependsOn("business.jar#CountryCodeEJB")
@Singleton
public class CacheEJB {...}

,
( ).


,
EJB-, .

308 7. EJB-
, ,
@ConcurrencyManagement
.
, (CMC), EJB-, ( XML-).
, EJB- (BMC),
EJB-.
, , ,
. EJB-
, ,
. , @AccessTimeout
( ,
-, , ConcurrentAccessExcep
tion).

,
( )
EJB-.
@Lock , .
READ ( ) WRITE (
).
@Lock(LockType.WRITE) , ,
,
, . , C1
, C2 ,
C1 .
@Lock(LockType.READ) , ,

EJB-. , C1 C2
.
@Lock , .
, ,
. ,
@Lock(WRITE). , 7.11,
CacheEJB WRITE EJB-. , WRITE getFromCache(),
READ.

309

7.11. EJB- ,

@Singleton
@Lock(LockType.WRITE)
@AccessTimeout(value = 20, unit = TimeUnit.SECONDS)
public class CacheEJB {
private Map<Long, Object> cache = new HashMap<>();
public void addToCache(Long id, Object object) {
if (!cache.containsKey(id))
cache.put(id, object);
}
public void removeFromCache(Long id) {
if (cache.containsKey(id))
cache.remove(id);
}
@Lock(LockType.READ)
public Object getFromCache(Long id) {
if (cache.containsKey(id))
return cache.get(id);
else
return null;
}
}

7.11 @AccessTimeout.
,
.
addToCache() 20, ConcurrentAccessTimeoutException.

,
EJB-
, ,
EJB-, EJB-. .
Java- , synchronized volatile. , 7.12,
CacheEJB , EJB- (@Concurrency
Management(BEAN)), addToCache() removeFromCache() synchronized.
7.12. EJB- ,
EJB-

@Singleton
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
public class CacheEJB {

310 7. EJB-
private Map<Long, Object> cache = new HashMap<>();
public synchronized void addToCache(Long id, Object object) {
if (!cache.containsKey(id))
cache.put(id, object);
}
public synchronized void removeFromCache(Long id) {
if (cache.containsKey(id))
cache.remove(id);
}
public Object getFromCache(Long id) {
if (cache.containsKey(id))
return cache.get(id);
else
return null;
}
}



,
, ,
. @AccessTimeout
,
, . @AccessTimeout, -1,
,
, . @AccessTimeout, 0,
, . ConcurrentAccessException, , . ,
, , ,
EJB-, , .. 7.13 CacheEJB
addToCache(). , , ,

( -).
7.13. EJB-,

@Singleton
public class CacheEJB {
private Map<Long, Object> cache = new HashMap<>();
@AccessTimeout(0)
public void addToCache(Long id, Object object) {
if (!cache.containsKey(id))
cache.put(id, object);
}

311

public void removeFromCache(Long id) {
if (cache.containsKey(id))
cache.remove(id);
}
@Lock(LockType.READ)
public Object getFromCache(Long id) {
if (cache.containsKey(id))
return cache.get(id);
else
return null;
}
}


, . ,
, Java EE7 . JNDI,
. .
, , EJB-
, , JNDI-.
JNDI . JNDI , , ,
.
EJB ( ):
@EJB ,
EJB- ;
@PersistenceContext @PersistenceUnit EntityManager
EntityManagerFactory (.
6);
@WebServiceRef -;
@Resource , JDBC,
SessionContext, ,
JMS, , TimerService ..;
@Inject @Inject @Produces,
2.
7.14 EJB- . . ,
, -.

312 7. EJB-
7.14. EJB- ,

@Stateless
public class ItemEJB {
@PersistenceContext(unitName = "chapter07PU")
private EntityManager em;
@EJB
private CustomerEJB customerEJB;
@Inject
private NumberGenerator generator;
@WebServiceRef
private ArtistWebService artistWebService;
private SessionContext ctx;
@Resource
public void setCtx(SessionContext ctx) {
this.ctx = ctx;
}
//...
}

API- SessionContext
EJB- -, . ( , ,
..). , EJB- ( ). EJB-
(, ). javax.ejb.SessionContext.
API SessionContext , EJB-. javax.ejb.EJBContext. .7.3
API- SessionContext.
7.3. SessionContext

etCallerPrincipal

java.security.Principal,

getRollbackOnly

getTimerService

javax.ejb.TimerService. EJB EJB .


EJB-

getUserTransaction

javax.transaction.UserTransaction . EJB-,

313

, EJB-
(Bean-Managed Transaction BMT),

isCallerInRole

lookup

EJB- JNDI

setRollbackOnly

EJB-

wasCancelCalled

, cancel()
Future, -

7.15, EJB- SessionContext @Resource. createBook ,


Book.
, .
7.15. EJB- , .
API- SessionContext

@Stateless
public class ItemEJB {
@PersistenceContext(unitName = "chapter07PU")
private EntityManager em;
@Resource
private SessionContext context;
public Book createBook(Book book) {
if (!context.isCallerInRole("admin"))
throw new SecurityException("
");
em.persist(book);
if (inventoryLevel(book) == TOO_MANY_BOOKS)
context.setRollbackOnly();
return book;
}
}


EJB-
, . ,
, , ,
.
, ,

314 7. EJB-
. , ,
, , ,
. , , ,
.
EJB 3.1 JMS EJB-, (. 13). (
JMS), JMS API , EJB-, , . JMS
( , ,
..), , .
EJB3.1 ,
EJB- @javax.ejb.Asynchro
nous. 7.16 OrderEJB, .
,
@Asynchronous.
7.16. OrderEJB,

@Stateless
public class OrderEJB {
@Asynchronous
public void sendEmailOrderComplete(Order order, Customer customer) {
// ,
}
@Asynchronous
public void printOrder(Order order) {
// ,
}
}

printOrder() sendEmailOrderComplete(),
. 7.16,
void. ,
,
.
void, java.util.concurrent.Future<V>, V . Future , .
, API- Future,
.

315

7.17 , Future<Integer>.
sendOrderToWorkflow()
Order. , (, - ..) status (). sendOrderToWorkflow() ,
status . Future.get() , - , Future.cancel() .
Future.cancel(), , . ,
sendOrderToWorkflow() SessionContext.wasCancelCalled()
, . javax.ejb.AsyncResult<V>, Future<V>.
, AsyncResult
, .
7.17. , Future

@Stateless
@Asynchronous
public class OrderEJB {
@Resource
SessionContext ctx;
public Future<Integer> sendOrderToWorkflow(Order order) {
Integer status = 0;
//
status = 1;
if (ctx. wasCancelCalled()) {
return new AsyncResult<>(2);
}
//
return new AsyncResult<>(status);
}
}

7.17 , @Asynchronous . . sendOrderToWorkflow(),


Future.get(), .
Future<Integer> status = orderEJB.sendOrderToWorkflow (order);
Integer statusValue = status.get();


Java EE7 ,
, ,
.
.
, ,

316 7. EJB-
XML-. JPA, . EJB-.
(@Stateless, @Stateful ..) , ( , , , ,
, ..),
, XML.
, , , XML-
.
XML- , ,
XML-.
.
, XML- ( ejb-jar.xml),
. 7.18 ,
ejb-jar.xml, ItemEJB (
7.2). EJB-, , (Stateless). , ,
(CMT) (Container).
7.18. ejb-jar.xml

<ejb-jar xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/ejb-jar_3_2.xsd"
version="3.2">
<enterprise-beans>
<session>
<ejb-name>ItemEJB</ejb-name>
<remote>org.agoncal.book.javaee7.chapter07.ItemRemote</remote>
<local>org.agoncal.book.javaee7.chapter07.ItemLocal</local>
<local-bean/>
<ejb-class>org.agoncal.book.javaee7.chapter07.ItemEJB</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
</session>
</enterprise-beans>
</ejb-jar>

EJB- .jar,
META-INF/ejb-jar.xml. EJB-
.war
WEB-INF/ejb-jar.xml. XML- ,
, (,
EJB- /).

317


,

( , ,
..). , CD-BookStore ItemEJB (7.19) ,
( changeRate ).
EJB- - ,
0,80 .
7.19. EJB- ,

@Stateless
public class ItemEJB {
public Item convertPrice(Item item) {
item.setPrice(item.getPrice() * 0.80F);
item.setCurrency("Euros");
return item;
}
}

, , ,
,
.
, convertPrice(). . ,
-,
.
.
, (ejb-jar.xml) EJB3.2,
. (
JNDI). Java-: String, Character,
Byte, Short, Integer, Long, Boolean, Double Float. 7.20 ejbjar.xml, ItemEJB, : currencyEntry
String Euros changeRateEntry Float 0.80.
7.20. ItemEJB ejb-jar.xml

<ejb-jar xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/ejb-jar_3_2.xsd"
version="3.2">
<enterprise-beans>
<session>
<ejb-name>ItemEJB</ejb-name>
<env-entry>
<env-entry-name>currencyEntry</env-entry-name>

318 7. EJB-
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>Euros</env-entry-value>
</env-entry>
<env-entry>
<env-entry-name>changeRateEntry</env-entry-name>
<env-entry-type>java.lang.Float</env-entry-type>
<env-entry-value>0.80</env-entry-value>
</env-entry>
</session>
</enterprise-beans>
</ejb-jar>

, , ItemEJB , . 7.21 @Resource(name = "currencyEntry")


currencyEntry currency. ,
;
.
7.21. ItemEJB,

@Stateless
public class ItemEJB {
@Resource(name = "currencyEntry")
private String currency;
@Resource(name = "changeRateEntry")
private Float changeRate;
public Item convertPrice(Item item) {
item.setPrice(item.getPrice() * changeRate);
item.setCurrency(currency);
return item;
}
}

Java EE (, JSF-, - ..),


EJB- ,
.
EJB-, ,
, , (ejb-jar.xml). .jar, .
,
.jar .ear, .
.ear ,
(EJB- .jar -)
,
. , .7.7, -

319

-, , ,
EJB-
.jar, .war, .ear. EAR- ,
EJB-.

.7.7. EJB-

EJB 3.1 EJB Lite


- (WAR-). .7.7 , EJB-
WAR- . EJB- ,
META-INF/ejb-jar.xml WEB-INF/ejb-jar.xml. EJB Lite WAR- JAR-. EJB (, , JMS, ), .jar , .war.

EJB-
EJB- , ,
. ( , ,
, ..), -.
, EJB-
. ,
, - . ( ),

320 7. EJB-
EJB-, .
, EJB 3.1, EJB. EJB 3.1 API-
EJB- Java SE. Embeddable API ( javax.ejb.embeddable) EJB-, Java. ,
Java EE: , ,
.. EJB- API-
EJB Lite ( EJB-, ,
..), , EJB Lite ( , EJB).
7.22 Main, API- , ( javax.ejb.embeddable.
EJBContainer), EJB- .
7.22. Main,

public class Main {


public static void main(String[] args) throws NamingException {
//
Map<String, Object> properties = new HashMap<>();
properties.put(EJBContainer.MODULES, new File("target/classes"));
// JNDI-
try (EJBContainer ec = EJBContainer.createEJBContainer(properties)) {
Context ctx = ec.getContext();
// Book
Book book = new Book();
book.setTitle(" ");
book.setPrice(12.5F);
book.setDescription("- ");
book.setIsbn("1-84173-742-2");
book.setNbOfPage(354);
book.setIllustrations(false);
// EJB-
ItemEJB itemEJB = (ItemEJB) ctx.lookup("java:global/classes/ItemEJB");
// Book
itemEJB.createBook(book);
//
for (Book aBook : itemEJB.findBooks()) {
System.out.println(aBook);
}
}
}
}

321
EJB-
7.22, EJBContainer
(createEJBContainer()) . , ,
EJB- (
).
JNDI- (EJBContainer.getContext(), javax.na
ming.Context) ItemEJB ( JNDI-).
, ItemEJB ( 7.1)
EJB- , . ,
, , JPA Book.

. EJBContainer java.lang.AutoCloseable,
try-with-resources EJBContainer.close() .
7.22 Main, ,
EJB-. , EJB JavaSE:
Swing-, .

EJB-
, EJB-
, , , , EJB. EJB- :
POJO, (Swing), CDI MBean-, , EJB- JSF, , - (SOAP REST)
EJB- ( ).
. EJB, EJB- ( new).
EJB- ( ).
( @EJB @Inject)
JNDI-. EJB- .
, EJB- .


Java EE (@Re
source), (@PersistenceContext), - (@WebServiceRef)
.. @javax.ejb.EJB
EJB- . EJB-, -
.

322 7. EJB-
, EJB-
. EJB-,
EJB-. ,
ItemEJB @EJB:
@Stateless
public class ItemEJB {...}
// EJB-
@EJB ItemEJB itemEJB;

EJB- ,
, .
ItemEJB @LocalBean . EJB-
, :
@Stateless
@Remote(ItemRemote.class)
@Local(ItemLocal.class)
@LocalBean
public class ItemEJB implements ItemLocal, ItemRemote {...}
// EJB-
@EJB ItemEJB itemEJB;
@EJB ItemLocal itemEJBLocal;
@EJB ItemRemote itemEJBRemote;

API @EJB . JNDI- EJB, .


EJB-, :
@EJB(lookup = "java:global/classes/ItemEJB") ItemRemote itemEJBRemote;

CDI
, EJB-
@EJB, .
: . @EJB , , - CDI-. @Inject.
@EJB @Inject,
. ,
CDI, 2. ,
, EJB-
CDI :
@Stateless
@Remote(ItemRemote.class)

323
EJB-
@Local(ItemLocal.class)
@LocalBean
public class ItemEJB implements ItemLocal, ItemRemote {...}
// EJB- @Inject
@Inject ItemEJB itemEJB;
@Inject ItemLocal itemEJBLocal;
@Inject ItemRemote itemEJBRemote;

EJB-, ,
JNDI- . @Inject
, EJB, :
// EJB-
@Produces @EJB(lookup = "java:global/classes/ItemEJB") ItemRemote
itemEJBRemote;
// EJB-
@Inject ItemRemote itemEJBRemote;


( ).
JNDI EJB-
JNDI-.

JNDI
EJB-
JNDI, ,
. JNDI ,
, . . ,
, EJB- , , JNDI-. JNDI .
JNDI , , ,
.
JNDI API- ,
. JNDI
JavaSE ,
Lightweight Directory Access Protocol (LDAP)
(DNS), API-.
Ini
tialContext, JNDI, EJB-
JNDI-,
JNDI-

324 7. EJB-
EJB- .
:
Context ctx = new InitialContext();
ItemRemote itemEJB = (ItemRemote)
ctx.lookup("java:global/cdbookstore/ItemEJB!org.agoncal.book.javaee7.
ItemRemote");

EJB , EJB2.x,
, / XML-, Java-
.
: - (
).
EJB- , , -. EJB-: ,
. , , , . EJB-
, ,
. EJB- ,
,
.
, EJB-
. , ,
.
EJB- ( JDBC, , ..),
( SessionContext). EJB 3.1
, EJB- JNDI- EJB- Java
SE. EJB3.2 ,
.
EJB , . , , TimerService ,
.

8.
,

, . EJB,
- ( ,
..). : , .
, - . (/ )
. ,
, ,
.
EJB
. , ,
, -.
. , -

(,
, ,
).
, , ,
, , , . , ,
, .
EJB.
, , .


, new.
, JNDI.
. , ,

326 8. ,
,
, .
.
:
. , , ,
, . EJB , ,
, (@PostConstruct, @PreDestroy ..)
. , JNDI
.

, ,

, ,
, .
,
, ,
.
(.8.1),
.
1. , (
JNDI). ,
( @Startup).
.
2.
(@Inject, @Resource, @EJB, @PersistenceContext ..)
, .
3. @PostContruct, .
4. , ,
. ,
, ,
. ,
.
5. .
@PreDestroy, ,
.
, , , , .

327
,

.8.1. , ,

, ,
.
, ,
, . (
,
), .

EJB GlassFish
(GlassFish Administration Console). GlassFish EJB. (, ), , .
, . ;
EJB.

, ( @StartUp ), , (@DependsOn) , . ,
. , ,
-. , .

,
, ,
, , :

328 8. ,
(@Stateful @Stateless @Singleton). ,
, , , , .
. . , , (, ,
, , ).
, , , , ,
. .
, ( , ..),
. ,
, , .
. , (
java.io.Serializable). .8.2 , , .
1. , , ,
( JNDI).
.
2.
(@Inject, @Resource, @EJB, @PersistenceContext ..)
, .
3. @PostContruct, .
4. , .
5. ,
, @PrePassivate, , .
6. ,
@PostActivate,
.
7.
, .
8. 7, , @Remove,
@PreDestroy, , .

329

.8.2. ,

, ,
, .
,
,
.
/ , . , . , , @Stateful(passivationCapable = False).


, .
-, .
, , .8.1.
8.1. ,

@PostConstruct

@PreDestroy

, .

330 8. ,
8.1 ()

. ,
, , , @Remove

@PrePassivate

, . , . , ,
(, ,
, .)

@PostActivate

, .


Javax.ejb EJB3.2 (JSR 345) @PrePassivate
@PostActivate. EJB EJB. @PostConstruct
@PreDestroy CommonAnnotation 1.2 (JSR 250) javax.annotation (, , @Resource ,
, ).
( ).

.
void.
,
. , (
).
public, private, protected
, static final.
( init(),
, 8.2, @PostConstruct @PostActivate).
(, @PostConstruct
).

(.
7).
, , /
. 8.1
CacheEJB , @PostConstruct
. CacheEJB
initCache().

331

8.1. -,
@PostConstruct

@Singleton
public class CacheEJB {
private Map<Long, Object> cache = new HashMap<>();
@PostConstruct
private void initCache() {
cache.put(1L, " ");
cache.put(2L, " ");
}

public Object getFromCache(Long id) {


if (cache.containsKey(id))
return cache.get(id);
else
returnnull;
}

8.2 , . ,
, . ,
, ( ).
8.2. ,

@Stateful
public class ShoppingCartEJB {
@Resource(lookup = "java:comp/defaultDataSource")
private DataSource ds;
private Connection connection;

private List<Item> cartItems = new ArrayList<>();


@PostConstruct
@PostActivate
private void init() {
connection = ds.getConnection();
}
@PreDestroy
@PrePassivate
private void close() {
connection.close();
}
//...
@Remove
public void checkout() {
cartItems.clear();
}

332 8. ,
, ,
, (
, )
ds . ,
, @PostConstruct (init() ),
. ,
Close() (@PrePassivate). JDBC-,
,
. - , Init() (@PostActivate). checkout() ( @Remove), , Close() ( @PreDestroy ).
, , SQL.


Java EE ,
. , , CD-Bookstore

, ,
30.
EJB 2.1 ,
API Thread. (UNIX- cron,
Quartz .) . 3.1
EJB .
,
.
EJB , .
EJB
, , , . ,
. .8.3 , .
-, EJB ( ) ,
EJB.
-
. , , , ,
. , .

333

.8.3.


, , MDB , , ,
, API .

, , @Schedule.

@Timeout.


, ,
UNIX- cron.
( ScheduleExpression)
( @Schedule ). :
year = "2008,2012,2016" dayOfWeek = "Sat,Sun" minute = "0-10,30,40"

.8.2 8.3 .
8.2.

second


( )

[0,59]

minute


( )

[0,59]

hour


( )

[0,23]

dayOfMonth


( )

[1,31] {"1st", "2nd",


"3rd", , "30th", "31st"}
{"Sun", "Mon",
"Tue", "Wed", "Thu",
"Fri", "Sat"} "Last"
(

334 8. ,
8.2 ()

) x( x )
month

[1,12] {"Jan", "Feb",


( )
"Mar", "Apr", "May",
"Jun", "Jul", "Aug", "Sep",
"Oct, "Nov", "Dec"}

dayOfWeek


( )

year

timezone

,

zoneinfo ( tz)

[0,7] {"Sun", "Mon", *


"Tue", "Wed", "Thu",
"Fri", "Sat"} "0" "7"

*

(, , ..)
, . ,
. .8.3 ,
.
8.3.

year = "2010" month= "May"

second = "*" dayOfWeek = "*"

- year = "2008,2012,2016"
,
dayOfWeek = "Sat,Sun"
minute = "010,30,40"

second = "110"
dayOfWeek = "MonFri"

minute = "*/15"
second = "30/10"

UNIX- cron,
.
,
.8.4.

335

8.4.

dayOfWeek = "Wed"

second = "0", minute = "0", hour = "0",


dayOfMonth = "*", month = "*",
dayOfWeek = "Wed", year = "*"

6:55

minute = "55", hour = "6", dayOfWeek =


"MonFri"

6:55 minute = "55", hour = "6", dayOfWeek =

"MonFri", timezone = "Europe/Paris"


minute = "*", hour = "*"

second = "*", minute = "*", hour = "*"


30

second = "30", hour = "12", dayOfWeek =


"Mon, Fri"

minute = "*/5", hour = "*"

minute = "0,5,10,15,20,25,30,35,40,45,50,55",
hour = "*"

hour = "15", dayOfMonth = "Last Mon",


month = "Dec"

hour = "13", dayOfMonth = "3"

, hour = "12/2", dayOfMonth = "2nd Tue"


14
1 2

minute = "*/14", hour="1 , 2"

14
1 2

minute = "0,14,28,42,56", our = "1,2"

10 ,
30

second = "30/10"

10 ,
30

second = "30,40,50"



. ,
@javax.ejb.Schedule @Schedule ( XML-
ejb-jar.xml). @Schedule , .
8.3 StatisticsEJB, . statisticsItemsSold() ,
5:30 . generateReport()

336 8. ,
( @Schedule):
2 , 2 . RefreshCache() , .
8.3. Statistics EJB,

@Stateless
public class StatisticsEJB {
@Schedule(dayOfMonth = "1", hour = "5", minute = "30")
public void statisticsItemsSold() {
//...
}
@ Schedules({
@ Schedule(hour = "2"),
@ Schedule(hour = "14", dayOfWeek = "Wed")
})
public void generateReport() {
//...
}
@Schedule(minute = "*/10", hour = "*", persistent = false)
public void refreshCache() {
// ...
}
}


, EJB javax.ejb.TimerService ,
SessionContext (SessionContext.getTimerService(), . 7) JNDI. .8.5, API TimerService
,
.
8.5. TimerService API

createTimer

, .

createSingle
ActionTimer

,
.
,

createInterval
Timer

, ,

createCalendar
Timer

, , ScheduleExpression

getAllTimers

(
javax.ejb.Timer)

337

ScheduleExpression
. , ,
.8.2, ,
.8.4. , :
new
new
new
new

ScheduleExpression().dayOfMonth("Mon").month("Jan");
ScheduleExpression().second("10,30,50").minute("*/5").hour("10-14");
ScheduleExpression().dayOfWeek("1,5").timezone("Europe/Lisbon");
ScheduleExpression().dayOfMonth(customer.getBirthDay())

TimerService (createSingleActionTimer, createCalendarTimer


..) javax.ejb.Timer,
( , ..).
Timer EJB .
@javax.ejb.Timeout , Timer.
, @Timeout.
CustomerEJB (. 8.4) (
createCustomer()), . , ,
. , , ,
( @Resource).
CreateCustomer() ScheduleExpression. , ScheduleExpression customer, TimerConfig.
new TimerConfig(customer, true) ( true), customer.
8.4. CustomerEJB,

@Stateless
public class CustomerEJB {
@Resource
TimerService timerService;
@PersistenceContext(unitName = "chapter08PU")
private EntityManager em;

public void createCustomer(Customer customer) {


em.persist(customer);
ScheduleExpression birthDay = new ScheduleExpression().
dayOfMonth(customer.getBirthDay()).month(customer.getBirthMonth());
timerService.createCalendarTimer(birthDay, new TimerConfig(customer, true));
}
@Timeout
public void sendBirthdayEmail(Timer timer) {
Customer customer = (Customer) timer.getInfo();
// ...
}

338 8. ,
@Timeout (sendBirthday
Email() ) . Timer .
customer,
, getInfo(). ,
, @Timeout, ,
.

EJB
-. JavaEE - (
), EJB,
EJB ,
, .
, .
,
EJB. JAAS API.


XML. , (
) .
, .8.6. , .
8.6. ,

@PermitAll

, ( ) ( )

@DenyAll

,

( ).
, (,
launchNuclearWar()
, )

@RolesAllowed X

, ,
( )

@DeclareRoles

@RunAs

339

@RolesAllowed , ,
. ( - ).
String (
), String
( ). @DeclareRoles, ,
.

(@RolesAllowed, @DenyAll ..) Common Annotations1.2 (JSR 250) javax.annotation.se
curity.

8.5 ItemEJB, @RolesAllowed


. ,
, : user, employee admin.
deleteBook() ,
admin.
8.5. ,

@Stateless
@RolesAllowed({"user", "employee", "admin"})
public class ItemEJB {
@PersistenceContext(unitName = "chapter08PU")
private EntityManager em;
public Book findBookById(Long id) {
return em.find(Book.class, id);
}
public Book createBook(Book book) {
em.persist(book);
return book;
}
@RolesAllowed("admin")
public void deleteBook(Book book) {
em.remove(em.merge(book));
}
}

@RolesAllowed ,
. @PermitAll @DenyAll .
, @PermitAll, EJB,
, . , @DenyAll
.
8.6, findBookById() @PermitAll, , user,
employee admin. , findConfidentialBook()
(@DenyAll).

340 8. ,
8.6. ,
@PermitAll @DenyAll

@Stateless
@RolesAllowed({"user", "employee", "admin"})
public class ItemEJB {
@PersistenceContext(unitName = "chapter08PU")
private EntityManager em;
@PermitAll
public Book findBookById(Long id) {
return em.find(Book.class, id);
}
public Book createBook(Book book) {
em.persist(book);
return book;
}
@ RolesAllowed("admin")
public void deleteBook(Book book) {
em.remove(em.merge(book));
}
@DenyAll
public Book findConfidentialBook(Long secureId) {
return em.find(Book.class, secureId);
}
}

@DeclareRoles , . . EJB 8.6 user, employee


admin, @RolesAllowed.
( EJB) @DeclareRoles. ,
, .

. ,
. , , @DeclareRoles.
ItemEJB 8.7 (HR,
salesDpt, user, employee admin). @RolesAllowed
( ).
8.7. ,

@Stateless
@DeclareRoles({"HR", "salesDpt"})
@RolesAllowed({"user", "employee", "admin"})
public class ItemEJB {
@PersistenceContext(unitName = "chapter08PU")
private EntityManager em;
public Book findBookById(Long id) {

341

return em.find(Book.class, id);


}
public Book createBook(Book book) {
em.persist(book);
return book;
}
@RolesAllowed("admin")
public void deleteBook(Book book) {
em.remove(em.merge(book));
}
}

, @RunAs, ,
. ,
, , , EJB ,
EJB .
, ItemEJB 8.8 role, employee admin.
,
inventoryDpt (@RunAs("inventoryDpt")). ,
createBook() InventoryEJB.addItem() inventoryDpt.
8.8. ,

@Stateless
@RolesAllowed({"user", "employee", "admin"})
@RunAs("inventoryDpt")
public class ItemEJB {
@PersistenceContext(unitName = "chapter08PU")
private EntityManager em;
@EJB
private InventoryEJB inventory;
public List<Book> findBooks() {
TypedQuery<Book> query = em.createNamedQuery("findAllBooks", Book.class);
return query.getResultList();
}
public Book createBook(Book book) {
em.persist(book);
inventory.addItem(book);
returnbook;
}
}

, . , - -
? .


, .

342 8. ,
( , , ..). ,
. , JAAS java.security.Principal, EJB,
.
SessionContext , :
isCallerInRole() boolean ,
;
getCallerPrincipal() java.security.Principal, .
, , . ItemEJB
8.9 ,
- . , ( @Resource).
deleteBook() , admin.
, java.lang.Se
curityException, .
createBook() - .
, getCallerPrincipal() Principal,
. ,
"paul", "special user" .
8.9. ,

@Stateless
public class ItemEJB {
@PersistenceContext(unitName = "chapter08PU")
private EntityManager em;
@Resource
private SessionContext ctx;
public void deleteBook(Book book) {
if (!ctx.isCallerInRole("admin"))
throw new SecurityException(" ");
em.remove(em.merge(book));
}
public Book createBook(Book book) {
if (ctx.isCallerInRole("employee") && !ctx.isCallerInRole("admin")) {
book.setCreatedBy("employee only");
} else if (ctx.getCallerPrincipal().getName().equals("paul")) {
book.setCreatedBy("special user");
}
em.persist(book);
returnbook;
}
}

343


4 Book
( 4.3), Derby.
Main (.4.4),
(
: tx.begin() tx.commit()).
, Main, 4, , (BookEJB). EJB ( ),
CRUD- Book , (CMT). (DatabasePopulator), , , CDI, (
@Inject). BookEJB, Book, DatabasePopulator, CDI-
XML GlassFish. BookEJB Main (.8.4),
(BookEJBIT).
,
(jdbc/chapter08DS), GlassFish chapter08DB (
@DataSourceDefinition, ).
Maven, :
src/main/java Book, BookEJB, BookEJBRemote,
DatabasePopulator DatabaseProducer;
src/main/resources persistence.xml, ,
Derby, beans.xml,
CDI;
src/test/java BookEJBIT, ;
pom.xml Maven Project Object Model (),
, .

Entity
8.10 Book, 4 (.4.3),
( JPA Bean
Validation). , Book 8.10 Serializable,
Main.
8.10. Book, NamedQuery
BeanValidation

@Entity
@NamedQuery(name = FIND_ALL, query = "SELECT bFROM Book b")

.8.4.

344 8. ,

345

public class Book implements Serializable {
public static final String FIND_ALL = "Book.findAllBooks";
@Id @GeneratedValue
private Long id;
@NotNull
@Column(nullable = false)
private String title;
private Float price;
@Size(max = 2000)
@Column(length = 2000)
private String description;
private String isbn;
private Integer nbOfPage;
privateBooleanillustrations;
//
}

BookEJB,

BookEJB , ,
CRUD Book. 8.11 Java, @javax.ejb.Stateless.
@LocalBean
BookEJBRemote (.8.12). EJB
@Inject, EntityManager DatabaseProducer (8.13). -

-:
findBooks findAllBooks, Book, ;
createBook Book ( null)
, ;
updateBook Book (
null) . merge()

;
deleteBook Book
( merge()), .
8.11. , ,
CRUD

@Stateless
@LocalBean
public class BookEJB implements BookEJBRemote {
@Inject
private EntityManager em;

346 8. ,
public List<Book> findBooks() {
TypedQuery<Book> query = em.createNamedQuery(FIND_ALL, Book.class);
return query.getResultList();
}
public @NotNull Book createBook(@NotNull Book book) {
em.persist(book);
return book;
}
public @NotNull Book updateBook(@NotNull Book book) {
return em.merge(book);
}
public void deleteBook(@NotNull Book book) {
em.remove(em.merge(book));
}
}

Main , 4 (.4.4), 8.11 , EntityManager


, EntityManagerFactory. EJB EntityManager,
EJB. , JPA
tx.begin() tx.commit(), .
CMT, .
BookEJB Main, BookEJB .
Java @Remote, 8.12.
8.12.

@Remote
public interface BookEJBRemote {
List<Book> findBooks();
Book createBook(Book book);
void deleteBook(Book book);
Book updateBook(Book book);
}

CDI DatabaseProducer
8.11 BookEJB EntityManager
@Inject. , JPA
, ( "chapter08PU").
@Inject (
@Inject("chapter08PU")),
EntityManager : @PersistenceContext(unitName = "chapter08PU").
CDI- ( 2) -

347

8.13 EntityManager,
@Inject.
8.13. CDI , EntityManager

public class DatabaseProducer {


@Produces
@PersistenceContext(unitName = "chapter08PU")
private EntityManager em;
}

BookEJB
4 (.4.5) JDBC,
URL JDBC, Derby, (transaction-type = "RESOURCE_LOCAL").
, , , EJB
. transaction-type (8.14)
"JTA". , 4.5
, JPA
(EclipseLink), , . , ,
JPA ( EJB).
, (
<class> persistence.xml).
8.14. , chapter08DS

<?xml version="1.0" encoding="UTF-8"?>


<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="chapter08PU" transaction-type="JTA">
<jta-data-source>java:global/jdbc/chapter08DS</jta-data-source>
<properties>
<property name="eclipselink.target-database" value="DERBY"/>
<property name="eclipselink.ddl-generation" value="drop-and-createtables"/>
<property name="eclipselink.logging.level" value="INFO"/>
</properties>
</persistence-unit>
</persistence>

8.11 BookEJB EntityManager, chapter08PU. ( 8.14) , (jdbc/chapter08DS), (URL,


JDBC- ..).

348 8. ,

DatabasePopulator

jdbc/chapter08DS, ,
EJB. .
@DataSourceDefinition
(8.15).
. GlassFish,
.
8.15. ,

@Singleton
@Startup
@DataSourceDefinition(
className = "org.apache.derby.jdbc.EmbeddedDataSource",
name = "java:global/jdbc/chapter08DS",
user = "app",
password = "app",
databaseName = "chapter08DB",
properties = {"connectionAttributes=;create=true"}
)
public class DatabasePopulator {
@Inject
private BookEJB bookEJB;
private Book h2g2;
private Book lord;
@PostConstruct
private void populateDB() {
h2g2 = new Book(" Java EE7", 35F, " ",
"1-8763-9125-7", 605, true);
lord = new Book(" ", 50.4f, "", "1-84023-742-2",
1216, true);
bookEJB.createBook(h2g2);
bookEJB.createBook(lord);
}
@PreDestroy
private void clearDB() {
bookEJB.deleteBook(h2g2);
bookEJB.deleteBook(lord);
}
}

DatabasePopulator (.8.15)
(@Startup).
populateDB(), @PostConstruct. BookEJB
. clearDB() (
@PostConstruct) .

349

@DataSourceDefinition
,
GlassFish .
. , Derby
GlassFish .

@DataSourceDefinition , 13 (13.18), JMS2.0 (Connextion
Factory Destination) @JMSConnectionFactoryDefinition @JMS
DestinationDefinition.

. GlassFish
, .
:
$ asadmin create-jdbc-connection-pool
--datasourceclassname=org.apache.derby.jdbc.ClientDataSource
--restype=javax.sql.DataSource
--property portNumber=1527:password=APP:user=APP:serverName=localhost:
databaseName=chapter08DB:connectionAttributes=;create\=true Chapter08Pool

Chapter08Pool Derby
: (chapter08DB),
(localhost) (1527), , (APP) (APP)
. , Derby
( connectionAttributes=;crea
te\=TRUE). , :
$ asadmin ping-connection-pool Chapter08Pool


chapter08DB , Derby .

,
jdbc/chapter08DS
:
$ asadmin create-jdbc-resource --connectionpoolid
Chapter08Pool jdbc/chapter08DS

, GlassFish, :
$ asadmin list-jdbc-resources

BookEJBIT
1.x2.xEJB BookEJB :
. EJB
, ,

350 8. ,
Java SE. ,
, JAR ,
, pom.xml ( , 8.17) glassfish-embedded-all.
4 ,
,
. EJB,
Derby,
EJB.
,
JUnit (8.16). EJBContainer(EJBContainer.create
EJBContainer()), JNDI, EJB
,
. try-with-resources try.
8.16. BookEJB

public class BookEJBIT {


@Test
public void shouldCreateABook() throws Exception {
Map<String, Object> properties = new HashMap<>();
properties.put(EJBContainer.MODULES, new File("target/classes"));
try (EJBContainer ec = EJBContainer.createEJBContainer(properties)) {
Contextctx = ec.getContext();
// JNDI ( EJB)
assertNotNull(ctx.lookup("java:global/jdbc/chapter08DS"));
assertNotNull(
ctx.lookup("java:global/classes/BookEJB!org.agoncal.book.javaee7.chapter08.
BookEJBRemote"));
assertNotNull(
ctx.lookup("java:global/classes/BookEJB!org.agoncal.book.javaee7.chapter08.
BookEJB"));
// EJB
BookEJB bookEJB = (BookEJB)
ctx.lookup("java:global/classes/BookEJB!org.agoncal.book.javaee7.chapter08.
BookEJB");
// , (
// DBPopulator)
assertEquals(2, bookEJB.findBooks().size());
//
Book book = new Book("H2G2", 12.5F, " ", "1-24561-799-0",
354, false);
//
book = bookEJB.createBook(book);
assertNotNull("ID ", book.getId());
// ,
assertEquals(3, bookEJB.findBooks().size());
//

351

bookEJB.deleteBook(book);
// ,
assertEquals(2, bookEJB.findBooks().size());

}
}

ShouldCreateABook() , ( ,
DatabasePopulator ),
, , ,
, .
EJB, JNDI
BookEJB ( ).

,
Maven
Maven ,
Book, BookEJB, BookEJBRemote, DatabasePopulator CDI
DatabaseProducer. Maven
.jar (persistence.xml), CDI beans.xml. 8.17
Maven pom.xml .
glassfish-embedded-all, Java EE7 API, JUnit . chapter08-service-1.0.jar.
Maven , JavaSE7, maven-compiler-plugin , 8.17.
8.17. pom.xml , EJB

<?xml version="1.0" encoding="UTF-8"?>


<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>chapter08</artifactId>
<groupId>org.agoncal.book.javaee7</groupId>
<version>1.0</version>
</parent>
<groupId>org.agoncal.book.javaee7.chapter08</groupId>
<artifactId>chapter08-service</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>org.glassfish.main.extras</groupId>
<artifactId>glassfish-embedded-all</artifactId>

352 8. ,
<version>4.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.12.4</version>
<executions>
<execution>
<id>integration-test</id>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

, glassfishembedded-all ( <scope>provided</scope> ), test


(<scope>test</scope>) EJB.
Maven:
$ mvn package

BUILD SUCCESSFUL, ,
. , target, , Maven chapter08-services-1.0.jar.

353

(.8.16) Maven Failsafe, Maven:
$ mvn integration-test

GlassFish
, c .jar,
GlassFish. , , GlassFish Derby .
asadmin GlassFish.
.
$ asadmin deploy --force=true target\chapter08-service-1.0.jar

, EJB , ,
GlassFish; Derby , ,
, Main.

Main
Java EE -,
EJB ( 10, -
JSF EJB). Java.
Main (8.18) JNDI InitialContext,
BookEJBRemote ( JNDI).
, Main EJB,
. main()
EJB, , Book
EJB createBook() . , .
Main , Book
, Java
Java, JPA. EJB . ,
.
8.18. Main, BookEJBRemote

public class Main {


public static void main(String[] args) throws NamingException {
// EJB
Context ctx = new InitialContext();
BookEJBRemote bookEJB = (BookEJBRemote) ctx.lookup("java:global/
chapter08-service-1.0/BookEJB!org.agoncal.book.javaee7.chapter08.
BookEJBRemote");
//
List<Book> books = bookEJB.findBooks();
for (Book aBook : books) {
System.out.println(aBook);
}

354 8. ,
//
Book book = new Book("H2G2", 12.5F, " ", "1-24561-799-0",
354, false);
book = bookEJB.createBook(book);
System.out.println(" : " + book);
book.setTitle("H2G2");
book = bookEJB.updateBook(book);
System.out.println(" : " + book);
bookEJB.deleteBook(book);
System.out.println(" ");
}
}

Maven Exec , Maven


Main (. 8.18). ,
.
$ MVN Exec : Java

, , ,
, ,
, . , ,
,
(). - ,
- (@PostConstruct, @PreDestroy ..).
EJB3.1 ,
. cron, ,
, ,
.
, , -
.
, .
JAAS API.

9.

. .
, . EJB
:
, , .
Java EE7 Managed Beans .

: ( , ), , ..
, .
, , . EJB
.

. , EJB: BTM. , Managed Beans.


, , , ,
. , .
, , .
, MOM
( , ) . ,
.
- , .
,
( , ).
, (

356 9.
).
, ACID.

ACID
ACID ,
, : (Atomicity), (Consistency), (Isolation) (Durability)
( .9.1). ,
: , .
9.1. ACID

, .
(),
() , -

, :
SQL update, update,
, . (), ,
. , ,
(). ,
, ,
( , ,
, ). , ( , ) (, ,
).
().



(, ). -

357

, ,
.

.
,
, .
,
, .
, ,
, , . ,
, .


.
, .
, .
.
( ) . , .
. ,
.
, .
, .
( ) . , .
, ,
- ,
.
. , .

JTA
, , ACID.
, (, ). ,
, , JTA.

358 9.
, - , API. .9.1 ,
.

.9.1.

, .9.1,
- .
, . , , (,
) .
.
, JMS Java.
,
( , ..).
ACID. , ,
.

XA
, (
.9.1) JTA. . -

359

,
.
. XA Java (JTS).
.9.2 ,
. ,
, , JMS.

.9.2. XA,

,

XA (eXtendedArchitecture ). ,
Open Group (www.opengroup.org)
(DTP) ACID. JTA
. XA
(2pc), , ,
.
,
.
, , ,
.
. ,

, .9.3. 1
,
, - .
, . ,

360 9.
, , .

.9.3.

(.9.4). JTS, (OMG)


Object Transaction Service (OTS),
Internet
Inter-ORB Protocol (IIOP).
.9.2, , .9.4

IIOP. . JTS , .
EJB- , JTA, JTS .

Java EE7, EJB Managed Beans Java


Transaction API (JTA), JSR 907. JTA
, . , API,
. javax.transaction .

361

.9.4. XA

JTS , ,
JTA Java CORBA1.1
. JTS CORBA IIOP
. JTS ,
.
, , JTS/JTA API Java.
EJB, (, ,
JTS JTA).

JTA
JTA API Java EE.
, .
, JTA
XA.
JTA 1.0 1999
1.1 2002.
JTA1.2 Java EE7.

1.2 JTA
Java EE EJB, JTA API . JTA (JSR 907),

362 9.
EJB (JSR 345) 1999. EJB
, JTA, .
Managed Beans, Java EE7,
, EJB. JTA
. JTA1.2
EJB, @TransactionScope CDI.
JTA API , ,
.9.2.
9.2. JTA

javax.transaction

API JTA

javax.transaction.xa

,
XA


JTA
GlassFish. GlassFish, . , ,
, JBoss Transaction Manager, Atomikos Bitronix JTA.

EJB
-, EJB,
, JTA . EJB
, ,

,
. EJB , JTA
JTS, ,
EJB / .
Java EE ,
, JMS
.
EJB
. EJB,
.
(CMT), EJB ( ).
,
(BMT) ( -

363
EJB
). ,
.
. .
JTA ( JTA
), ,
. EJB MDB
(.13 MDB). , ,
EJB .
7 ,
, . 9.1 , CMT. , . EJB
. (REQUIRED , ,
).
9.1. , CMT

@Stateless
public class ItemEJB {
@PersistenceContext(unitName = "chapter09PU")
private EntityManager em;
@Inject
private InventoryEJB inventory;
public List<Book> findBooks() {
TypedQuery<Book> query = em.createNamedQuery(FIND_ALL, Book.class);
return query.getResultList();
}
public Book createBook(Book book) {
em.persist(book);
inventory.addItem(book);
return book;
}
}

, 9.1 . . .9.5 , , createBook(). ,


,
. , , , createBook().

( , ).

364 9.

.9.5.

4:addItem() ,
3:createBook() ( , ), . ,
. ( XML). (REQUIRED, REQUIRES_NEW, SUPPORTS,
MANDATORY, NOT_SUPPORTED NEVER) , : , ,
, ,
. .9.3 .
9.3. CMT

REQUIRED

( ) ,
. ,
, .
, -
. REQUIRED
, ,
, ,

REQUIRES_
NEW

,
. ,
, ,
, ,
. ,
.
REQUIRES_NEW, ,

365
EJB

SUPPORTS

MANDA
TORY

NOT_SUP
PORTED

NEVER

EJB .
, , .
SUPPORTS,

-,
.
, , javax.ejb.EJBTransactionRequiredException
EJB .
, , , , , ,
EJB , . ,
javax.ejb.EJBException

.9.6 ,
EJB . , createBook() (
) addItem(), MANDATORY,
. .9.6 , ,
.

.9.6. InventoryEJB,

366 9.
, @javax.ejb.Transac
tionAttribute ( <trans-attribute>
EJB-jar.xml). , . ,
- . 9.2 ,
ItemEJB SUPPORTS. , createBook(), REQUIRED.
9.2. , ,

@Stateless
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public class ItemEJB {
@PersistenceContext(unitName = "chapter09PU")
private EntityManager em;
@Inject
private InventoryEJB inventory;
public List<Book> findBooks() {
TypedQuery<Book> query = em.createNamedQuery(FIND_ALL, Book.class);
return query.getResultList();
}
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public Book createBook(Book book) {
em.persist(book);
inventory.addItem(book);
returnbook;
}
}


(@Asynchronous). MDB REQUIRES NOT_SUP
PORTED, 13.

CMT
, EJB , . ,
, ,
- -. , CMT . EJB (. 7) ,
.
9.3, InventoryEJB oneItemSold(),
JMS , ,
. ,
. , ,

367

, SessionContext , setRollbackOnly().
, , ,
. CMT ( BMT ,
, ).
9.3. , ,

@Stateless
public class InventoryEJB {
@PersistenceContext(unitName = "chapter09PU")
private EntityManager em;
@Resource
private SessionContext ctx;
public void oneItemSold(Item item) {
item.decreaseAvailableStock();
sendShippingMessage();
if (inventoryLevel(item) == 0)
ctx.setRollbackOnly();
}
}

SessionContext.getRollbackOnly(),
boolean, ,
.
.


Java ,
, .
EJB .
, , -
. , .
EJB3.2 .
-, EJB. , ,
,
. , . .9.4, (
java.lang.Exception), (
RuntimeException) .

368 9.
,
, JNDI-, JVM-, ..
RuntimeException java.rmi.RemoteException (, , javax.ejb.EJBException).
, .
, , ,
, ArithmeticException , ClassCastException ,
IllegalArgumentException NullPointerException, .
.
9.3 ,
9.4.
9.4. , ,

@Stateless
public class InventoryEJB {
@PersistenceContext(unitName = "chapter09PU")
private EntityManager em;
public void oneItemSold(Item item) throws InventoryLevelTooLowException{
item.decreaseAvailableStock();
sendShippingMessage();
if (inventoryLevel(item) == 0)
throw new InventoryLevelTooLowException();
}
}
InventoryLevelTooLowException ,
- oneItemSold(). ,
, -. @javax.ejb.Ap
plicationException ( XML ).
rollback,
true , . 9.5
InventoryLevelTooLowException,
.
9.5. , rollback = true

@ApplicationException(rollback = true)
public class InventoryLevelTooLowException extends Exception {
public InventoryLevelTooLowException() { }
public InventoryLevelTooLowException(String message) {
super(message);
}
}

InventoryEJB 9.4 , 9.5,

369

, . ,
InventoryLevelTooLowException @ApplicationException(rollback =
true). .9.4 .
Exception @ApplicationException,
,
.
9.4.

@ApplicationException

Exception

Exception

rollback = true

Exception

rollback = false

RuntimeException

RuntimeException

rollback = true

RuntimeException

rollback = false

, . CMT
,
.
CMT
(,
). , EJB
BMT. BMT
(, , ) JTA.
CMT BMT, @javax.ejb.
TransactionManagement ( XML- ejb-jar.xml) :
@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class ItemEJB {...}

BMT , EJB .
, .
, , javax.transaction.
UserTransaction. ,
, - .. EJB
UserTransaction, ,
JNDI SessionContext ( SessionContext.
getUserTransaction()). API .9.5.

370 9.
9.5. javax.transaction.UserTransaction

begin

commit

rollback

setRollbackOnly

getStatus

setTransactionTimeout

9.6 , BMT.
UserTransaction
@Resource. OneItemSold() , , , -,
. , catch
( ).
9.6. ,

@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class InventoryEJB {
@PersistenceContext(unitName = "chapter09PU")
private EntityManager em;
@Resource
private UserTransaction ut;
public void oneItemSold(Item item) {
try {
ut.begin();
item.decreaseAvailableStock();
sendShippingMessage();
if (inventoryLevel(item) == 0)
ut.rollback();
else
ut.commit();
} catch (Exception e) {
ut.rollback();
}
sendInventoryAlert();
}
}

CMT, 9.3, , CMT



. BMT, 9.6, .

371
Managed Beans


Managed Beans
, CMT
EJB.

(REQUIRED, REQUIRES_NEW), (SUPPORTS) , (MANDATORY). ,
, , JTA.
Managed Beans , Java EE7 EJB.
(.2).
Managed Beans CDI, 9.7.
9.7. @javax.transaction.Transactional

@Inherited
@InterceptorBinding
@Target({TYPE, METHOD})
@Retention(RUNTIME)
public @interface Transactional {
TxType value() default TxType.REQUIRED;
Class[] rollbackOn() default {};
Class[] dontRollbackOn() default {};
public enum TxType {
REQUIRED,
REQUIRES_NEW,
MANDATORY,
SUPPORTS,
NOT_SUPPORTED,
NEVER
}
}

javax.transaction.Transactional (.9.7) CDI


Managed Beans, , JAX-RS JAX-WS. EJB CDI
EJB, RMI .
, 9.8 - JAX-RS (
15), @Transactional,
EntityManager .
Java EE7.
- RESTful @Stateless,
.

372 9.
9.8. - RESTful,

@Path("book")
@Transactional
public class BookRestService {
@Context
private UriInfo uriInfo;
@PersistenceContext(unitName = "chapter09PU")
private EntityManager em;
@POST
@Consumes(MediaType.APPLICATION_XML)
public Response createBook(Book book) {
em.persist(book);
URI bookUri = uriInfo.getAbsolutePathBuilder().path(book.getId().toString()).
build();
return Response.created(bookUri).build();
}
@GET
@Produces(MediaType.APPLICATION_XML)
@Transactional(Transactional.TxType.SUPPORTS)
public Books getAllBooks() {
TypedQuery<Book> query = em.createNamedQuery(Book.FIND_ALL, Book.class);
Books books = new Books(query.getResultList());
return books;
}
}


(, SUPPORTS) . 9.8, @Transactional /
.
. Managed Beans EJB. EJB,
: ( ) ,
, ( ) .
@Transactional rollbackOn dontRollbackOn. , . , dontRollbackOn
.
, :
@Transactional(rollbackOn={Exception.class})

, , IllegalStateException (-

373

) , dontRollbackOn :
@Transactional(dontRollbackOn={IllegalStateException.class})

.
:
@Transactional(rollbackOn={SQLException.class},
dontRollbackOn={SQLWarning.class, ArrayIndexOutOfBoundsException.class})

EJB (
@ApplicationException). , , rollbackOn dontRollbackOn.

, EJB Managed Beans.


.
- ,
. ACID ( , JMS, - ..). CMT
EJB . ,
EJB .
BMT, JTA. Java EE7 , -,
CDI.

10.
JavaServer Faces
, ,
. :
, -, , ,
,
.
- .
-, , .
, , , . - , .
- , ,
. ,
- . Web2.0,
, -
. JavaServer Faces (JSF,
Faces) , .
Swing , JSF
, , - , , . -
,
( , , )
(RAD).
-, HTML, CSS
JavaScript. - JSF, .

-
-, , : (, - ), ,
, , , .. -

375
-
, ,
, , . , .
- .
, , HTML,
XHTML, CSS JavaScript.

HTML
Hypertext Markup Language (HTML) -. (SGML), , . HTML , ,
, , , , , ..
HTML- ,
.
, .html .htm. -
, , ,
, , JavaScript-
CSS-. 10.1 , HTML
.
10.1. newBook.html, HTML

<H1> </h1>
<hr>
<TABLE border=0>
<TR>
<TD>ISBN :</TD>
<TD><input type=text/></td>
</tr>
<tr>
<td> :</td>
<TD><input type=text/></td>
</tr>
<tr>
<td> :
<TD><input type=text/>
</tr>
<tr>
<td> :
<td><textarea name=textarea cols=20 rows=5></textarea>
</tr>
<TR>
<TD> :
<td><input type=text/>
</tr>
<tr>
<td> :
<td><input type="checkbox"/>

376 10. JavaServer Faces


</tr>
</table>
<input type=submit value=>
<hr>
<em>APress Java EE7</em>

, HTML <html>,
. <head> <body>.
<body> , HTML,
, , . 10.1, newBook.html ,
.
, .10.1.

.10.1. newBook.html

, .10.1, ,
10.1 XML.
<html>, <head> <body>.
<input type=submit value=> <hr> .
(border=0 border="0").
(,
<TR> </tr>).

. , , , XML-, . , ,
-,

377
-
XML-
(eXtensible HyperText Markup Language, XHTML).

HTML5 . HTML5
, <video>, <audio> <canvas>, (SVG).
,
API. HTML5 -
, .

XHTML
XHTML HTML4.01. HTML,
XML. , XHTML XML,
. XHTML- (
.xhtml) XML, .
HTML, ,

XML (XSL, XSLT, XSL- ..). , XHTML , HTML, .
10.2 , -
, XHTML.
10.2. newBook.xhtml XML

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title> </title>
</head>
<body>
<h1> </h1>
<hr/>
<table border="0">
<tr>
<td>ISBN :</td>
<td><input type="text"/></td>
</tr>
<tr>
<td> :</td>
<td><input type="text"/></td>
</tr>
<tr>

378 10. JavaServer Faces


<td> :</td>
<td><input type="text"/></td>
</tr>
<tr>
<td> :</td>
<td><textarea cols="20" rows="5"></textarea></td>
</tr>
<tr>
<td> :</td>
<td><input type="text"/></td>
</tr>
<tr>
<td> :</td>
<td><input type="checkbox"/></td>
</tr>
</table>
<input type="submit" value=""/>
<hr/>
<em>APress Java EE7</em>
</body>
</html>

10.1 10.2 : 10.2 <html>, <head> <body>.


, , ( <td> ,
<hr> <hr/>);
(<table border="0"> <table border='0'>, <table border=0>)
(<tr> <TR>). 10.1: , HTML-,
.
XML XHTML, , ,
. , XHTML, XML-, HTML4.01.
.
XHTML 1.0 Transitional XHTML, ( center, font strike),
.
XHTML 1.0 Frameset , ( 1990).
XHTML 1.0 Strict XHTML, HTML4.01.

CSS
, HTML, XHTML,
CSS JavaScript. (CSS)

379
-
, HTML XHTML. CSS , ,
. ( XHTML) ( CSS).
HTTP, HTML XHTML, CSS
World Wide Web (W3C).
, newBook.xhtml,
(font-style: italic;), (color: # 000099;)
(font-size: 22px;).
. CSS ( <style
type="text/css">) (, .row )
(, body, table h1). (10.3)
,
(<td class="row">).
10.3. NewBook.xhtml, CSS

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title> </title>
<style type="text/css">
body {
font-family: Arial, Helvetica, sans-serif;
}
table {
border: 0;
}
h1 {
font-size: 22px;
color: blue;
font-style: italic;
}
.row {
font-style: italic;
}
</style>
</head>
<body>
<h1> </h1>
<hr/>
<table>
<tr>
<td class="row">ISBN :</td>
<td><input type="text"/></td>
</tr>
<tr>
<td class="row"> :</td>
<td><input type="text"/></td>

380 10. JavaServer Faces


</tr>
<tr>
<td class="row"> :</td>
<td><input type="text"/></td>
</tr>
<tr>
<td class="row"> :</td>
<td><textarea cols="20" rows="5"></textarea></td>
</tr>
<tr>
<td class="row"> :</td>
<td><input type="text"/></td>
</tr>
<tr>
<td class="row"> :</td>
<td><input type="checkbox"/></td>
</tr>
</table>
<input type="submit" value=""/>
<hr/>
<em>APress Java EE7</em>
</body>
</html>

10.3 CSS XHTML.


,
-. -
CSS , .
.10.1 ,
(.10.2).

.10.2. newBook.xhtml
CSS

381
-

DOM
XHTML XML-
(DOM). DOM W3C, XML, API , . DOM
. 10.3 , newBo
ok.xhtml DOM. html,
head body, body tr.

.10.3. newBook.xhtml

DOM XML-.
( ). JavaScript - .
11, AJAX JavaScript DOM-
-.

JavaScript
,
-. ,
. , , JSF, , JavaScript.
JavaScript , -.
, Java,
, . JavaScript
-
, DOM . W3C DOM, (ECMA) JavaScript ECMAScript.

382 10. JavaServer Faces


, (XHTML, CSS JavaScript),
,
.
JavaScript DOM newBook.xhtml,
10.4. ,
. , .
, JavaScript (priceRequired()), , .
10.4. newBook.xhtml, JavaScript

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title> </title>
<script type="text/javascript">
function priceRequired() {
if (document.getElementById("price").value == "") {
document.getElementById("priceError").innerHTML =
", !";
}
}
</script>
</head>
<body>
<h1> </h1>
<hr/>
<table border="0">
<tr>
<td>ISBN :</td>
<td><input type="text"/></td>
</tr>
<tr>
<td> :</td>
<td><input type="text"/></td>
</tr>
<tr>
<td> :</td>
<td><input id="price" type="text" onblur ="javascript:priceRequired()"/>
<span id="priceError"/>
</td>
</tr>
<tr>
<td> :</td>
<td><textarea cols="20" rows="5"></textarea></td>
</tr>

383
-
<tr>
<td> :</td>
<td><input type="text"/></td>
</tr>
<tr>
<td> :</td>
<td><input type="checkbox"/></td>
</tr>
</table>
<input name="" type="submit" value=""/>
<hr/>
<em>APress Java EE7</em>
</body>
</html>

10.4 JavaScript priceRequired() <script> ( ). , price ( onblur).


priceRequired() document, DOM XHTML. GetElementById("price")
price (<input id="price">) , .
, , priceError
(getElementById("priceError")), ", !".
, , .10.4.

.10.4. NewBook.html

JavaScript . , JavaScript DOM.


, JavaScript (

384 10. JavaServer Faces


ID, GetElementById())
. . AJAX 11.

JSF
, ,
XHTML CSS,
-.
-,
JavaScript, .
- EJB, .
JSF .
JSF (.10.5), -.
JSF -,
HTTP- Faces HTML.
(
), (, ,
..), ,
, Swing. Swing Java
JavaSE, 1.2.
GUI-, (
-)
, . JSF
(UI) (, , , ..) . .10.5 JSF
.

.10.5. JSF

385
JSF
.10.5 JSF,
.
FacesServlet faces-config.xml. FacesServlet
faces-config.xml.
. JSF PDL,
Facelets JSF2.0.
. .
. (Date, Boolean ..),
(String).
. , , ,
( Bean Validation).
. - , .
AJAX. JSF2.2 AJAX,
11.
(EL). EL JSF -.

FacesServlet
- Model
View Controller (MVC ), JSF
. MVC ,
() (, ).
, . JSF
FacesServlet. , -.
FacesServlet,
-.
JSF.
. JSF1.2
faces-config.xml. ,
JSF2.2,
( -, ,
, ).


JSF (, ), . PDL. JSF

386 10. JavaServer Faces


PDL, Facelets
JSF2.2 ( Facelets ).
Facelets ( , ), ( , ,
..). JSF . ,
(, ,
..).
, 10.5, XHTML- Facelets, JSF (xmlns:h="http://xmlns.jcp.org/jsf/html")
(ISBN ) .
JSF-.
, , (<h:head>), (<h:body>)
(<h:form>). ,
(<h:outputLabel>), (<h:inputText>) (<h:commandButton>).
, HTML-
(<table>, <tr>, <hr/> ..).
10.5. JSF, JSF HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/
html">
<h:head>
<title> </title>
</h:head>
<h:body>
<h1> </h1>
<hr/>
<h:form>
<table border="0">
<tr>
<td><h:outputLabel value="ISBN : "/></td>
<td><h:inputText value="#{bookController.book.isbn}"/></td>
</tr>
<tr>
<td><h:outputLabel value=" :"/></td>
<td><h:inputText value="#{bookController.book.title}"/></td>
</tr>
</table>
<h:commandButton value=" "
action="#{bookController.doCreateBook}" styleClass="submit"/>
</h:form>
<hr/>
<em>APress Java EE7</em>
</h:body>
</html>

387
JSF

Facelets
JSF JSP
(JavaServer Page) PDL, JavaEE.
JSP JSTL EL (JSP Standard Tag Library
JSP), ,
JSF. JSP , JSF ,
. JSP JSF
. JSP , .
JSF , .
Facelets, JSF.
Facelets JSP
. JSP, EL JSTL JSR Java EE. Facelets
JSP XML (XHTML)
JSF-. Facelets JSF,
. - Facelets
JSF2.0 JavaEE7 PDL JSF.

JSF :
.

. ,
(, ..)
.
.
: ,
, ,
.
,
. JSF

HTML4.01. JSF

(WML), (SVG) ..


,
. , , .
: ( Integer, Date, Boolean

388 10. JavaServer Faces


..) . JSF ( javax.faces.con
vert), .

. , , ,
.
. JSF (LengthValidator,
RegexValidator ..).
.
, . JSF2.0 Bean Validation (
3).

-
: , , , ?
- - (, EJB RESTful--). , EJB
.
- Java, , - ( -
11).
- EL. isbn book -
doCreateBook:
<h:inputText value="#{bookController.book.isbn}"/>
<h:commandButton value="Create" action="#{bookController.doCreateBook}"/>


book.isbn -, BookController .
book.isbn
-. - .
, . Submit (), , ( doCreate
Book()).
10.6 - BookController. Java
CDI- @Named, EL.
book, (value="#{book
Controller.book.isbn}"). doCreateBook() EJB, , ,
(listBooks.xhtml):

389
JSF
10.6. - BookController

@Named
@RequestScoped
public class BookController {
@Inject
private BookEJB bookEJB;
private Book book = new Book();
public String doCreateBook() {
book = bookEJB.createBook(book);
return "listBooks.xhtml";
}
//
}


JSF - Java
EL. EL , . EL :
#{expr}

#{expr} JSF. EL
Java:
: +, , *, / (), % ( );
: == (), != ( ), < (), > (), <= ( ), >= ( );
: && (), || (), ! ();
: (), empty, [].
, , (> gt; / div ..).
JSF XML- .
< #{2 lt 3}, #{2 < 3}.
empty ,
, , . true,
, false. ,
null.
#{empty book}
#{empty book.isbn}

(.) isbn book.


[]. isbn :
#{book.isbn}
#{book[isbn]}

390 10. JavaServer Faces


EL 3.0 . , ,
book.buy(), ( ):
# {book.buy()}
# {book.buy(EURO)}

AJAX
- .
, AJAX.
(1.x) JSF ,
, a4jsf. JSF2.0, AJAX
JavaScript (jsf.js),
<f:ajax>. , <f:ajax>
, :
<h:commandButton value=" " action="#{bookController.
doCreateBook}">
<f:ajax execute="@form" render=":booklist"/>
</h:commandButton>

, : 11
AJAX.

JSF
- Java 1996 Servlet API,
-.
HTTP API (HttpServletRequest,
HttpServletResponse, HttpSession ..), HTML-
Java. JSP 1999 , . 2004 JSF. 1.2,
2006, JSF JavaEE5. JSF2.2 JavaEE7.

-
- . (, , ..),
, .
.
Common Gateway Interface
(CGI). HTML- CGI,
( Perl Visual Basic), , , CGI ( HTTP-, HTTP
..) .

391
JSF
1995 Java.
API Annotation Window Toolkit
(AWT). , Java SE1.2, AWT, , Swing API (
, Java2D). Java
Netscape Navigator , . ,
. AWT
Swing -. .
Netscape JavaScript, . ,
JavaScript
-.
, Sun
-.
CGI,
HTTP, Java API ( , ..) HTML
, .
Sun JSP 1999 .
, JSP Java HTML, 2001

Struts. Servlet API MVC. ,
(Tapestry, Wicket, WebWork, DWR,
Spring MVC ..). JSF2.2 - Java
EE7. Struts Tapestry Java. Google Web Toolkit
(GWT), Flex JavaFX JSF.

JSP 1.2 Servlet 2.3 JSR53. JSTL
JSR52. 2002 JSP2.0 JSR152. 2006 JSP2.1 Java EE5
JSF JSP EL. Java EE7 JSP, EL (JSP2.3 Expression Language3.0). JSP, , JSF
- Java EE.

JSF
JSF 1.0 2001 JSR127, 2004 1.1.
1.2 JavaEE JSR252 2006.
, JSP EL. , JSF JSP ,
JSP ,
Facelets.

392 10. JavaServer Faces


JSF2.0 , JSR314 Java
EE6. ,
( -, , ),
, GET,
POST ( ),
( , CSS, JavaScript...).
, AJAX. JSF2.2 (JSR344)
.

JSF2.2
JSF2.2 (JSR344) 2.1,
, .
HTML
HTML- JSF .
id HTML5 HTML, HTML5
id .
Faces Flow JSF.
JSF2.2. ,
, , ..
AJAX JSF
AJAX-.
, .
JSF JSF2.1
JSF . JSF2.2 ( , , ..).
CDI JSF2.0
-. CDI
- JSF, JSF2.2 CDI ( , javax.faces.bean
JSF).
.10.1 , JavaServer
Faces2.2.
10.1. JavaServer Faces

javax.faces

API JavaServer Faces

javax.faces.application API, -
JavaServer Faces
javax.faces.component API

javax.faces.context

393
JSF-

javax.faces.convert

javax.faces.event

, ,

javax.faces.flow

API Faces Flow

javax.faces.lifecycle

,
JSF

javax.faces.render

javax.faces.validator

javax.faces.webapp

, JSF -, Faces


Mojarra, ,
, JSF2.2
Oracle. Mojarra GlassFishv4
.
MyFaces Apache Software Foundation, , JavaServer Faces, MyFaces
Core JSF.

JSF-
JSF HTML- , JSF
. JSF-
, .
JSF HTML . JSF- HTML CSS , , .
JSF , ( JSF, ).
Java, -. ,
, .

JSF
JSF XHTML,
. . ,
( .10.1). 10.7 .
xmlns:h="http://xmlns.jcp.org/jsf/html" ,

394 10. JavaServer Faces


http://xmlns.jcp.org/jsf/html h. , , (<h:panelGrid>
<h:inputText>). ,
, .
10.7. JSF

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<title> </title>
</h:head>
<h:body>
<h1> </h1>
<hr/>
<h:form>
<h:panelGrid columns="2">
<h:outputLabel value="ISBN : "/>
<h:inputText value="#{bookController.book.isbn}"/>
<h:outputLabel value=" :"/>
<h:inputText value="#{bookController.book.title}"/>
<h:outputLabel value=" : "/>
<h:inputText value="#{bookController.book.price}"/>
<h:outputLabel value=" : "/>
<h:inputTextarea value="#{bookController.book.description}" cols="20"
rows="5"/>
<h:outputLabel value=" : "/>
<h:inputText value="#{bookController.book.nbOfPage}"/>
<h:outputLabel value=" : "/>
<h:selectBooleanCheckbox value="#{bookController.book.illustrations}"/>
</h:panelGrid>
<h:commandButton value=" " action="#{bookController.
doCreateBook}"/>
</h:form>
<hr/>
<h:outputText value="APress Java EE7" style="font-style:
italic"/>
</h:body>
</html>

395
JSF-

JSF Java:
, , . XML (DTD) xhtml1-transitional.dtd. html http://www.w3.org/1999/xhtml.
XML, , JSF (hf):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">

.10.2 , JSF JSTL Facelets. JSF Core HTML,


(
). , JSTL.
10.2. , Facelets PDL

URI

http://xmlns.jcp.org/jsf/html

HTML-
(h:commandButton, h:comandLink,
h:inputText ..)

http://xmlns.jcp.org/jsf/core

,
(f:selectItem,
f:validateLength, f:convertNumber ..)

http://xmlns.jcp.org/jsf/facelets

ui

http://xmlns.jcp.org/jsf/composite composite

http://xmlns.jcp.org/jsp/jstl/core

Facelets- JSP
(<c:if/>,<c:forEach/> <c:catch/>)

http://xmlns.jcp.org/jsp/jstl/
functions

fn

Facelets-
JSP

Body
10.7, JSF () , ,

396 10. JavaServer Faces


, HTML-. JSF , <h:outputText>, .
Java, javax.faces.component.UIComponent. , , ,
.
JSF HTML-
, -. UIComponent .10.3. ,
javax.faces.component. HTML JSF HTML-, ja
vax.faces.component.html.
10.3. JSF

UIColumn

UIData

UICommand

, ,

UIComponent

JSF

UIComponentBase

, , , UIComponent

UIData

,
,

UIForm

UIGraphic

UIInput

, ,
, ..

UIMessage,
UIMessages

UIComponent

UIOutcomeTarget

UIOutput

, ,

UIPanel

, ,

UIParameter

UISelectBoolean

UISelectItem,
UISelectItems

397
JSF-

UISelectOne,
UISelectMany

,
,

UIViewAction

UIViewParameter

UIViewRoot

HTML- , 10.7, JSF HTML- , . HTML


, .10.3. , <h:outputLabel>
javax.faces.component.html.HtmlOutputLabel, UIOutput. <h:panelGrid> javax.faces.compo
nent.html.HtmlPanelGrid, UIPanel, .. XML 10.8
, 10.7.
10.8. XML newBook

<UIViewRoot>
<html xmlns="http://www.w3.org/1999/xhtml">
<UIOutput><title> </title></UIOutput>
<UIOutput>
<h1> </h1>
<hr/>
<HtmlForm>
<HtmlPanelGrid>
<HtmlOutputLabel value="ISBN : "/>
<HtmlInputText/>
<HtmlOutputLabel value=" :"/>
<HtmlInputText/>
<HtmlOutputLabel value=" : "/>
<HtmlInputText/>
<HtmlOutputLabel value=" : "/>
<HtmlInputTextarea/>
<HtmlOutputLabel value=" : "/>
<HtmlInputText/>
<HtmlOutputLabel value=" : "/>
<HtmlSelectBooleanCheckbox/>

398 10. JavaServer Faces


</HtmlPanelGrid>
<HtmlCommandButton value=" "/>
</HtmlForm>
<hr/>
<HtmlOutputText value="APress Java EE7"
style="font-style: italic"/>
</UIOutput>
</html>
</UIViewRoot>

JSF,
<ui:debug> Ctrl+Shift+D.


JSF .
, ,
. . , .
-. JSF
, ( , ) . .10.6
JSF.
JSF .
1. . JSF
. , JSF
UIViewRoot ( ,
, 10.8).
, UIViewRoot HTTP.
2. . , (
-, cookies ),
. ,
, , .
3. .
. JSF
, ,
.
, . ,
.

.10.6. JSF

399
JSF-

400 10. JavaServer Faces


4. . -.
5. . -. -,
, .
6. . .
,
, .
/ ,
, ,
. , . , : , , . ,
, .

JSF
JSF . HTML-, ,
, AJAX.
-:
JSF: HTML, Core Templating;
JSTL;
;
(
).
, , CSS
JavaScript. JSF ,
, ( ). , JSF
, HTTP, cookies HTTP.

HTML- JSF
JSF ,
HTML-,
HTTP. .
(, , ..). JSF
HTML, .

401
HTML- JSF
. ,
javax.faces.component.UIComponent ,
.
, ,
UIViewRoot (.10.8).
-. javax.faces.component.html
HTML-.

(UICommand) ,
, . , ,
. .10.4 ,
.
10.4.

<h:command
Button>

HtmlCommand
Button

HTML-,

<h:command
Link>

HtmlCommand
Link

HTML- ,
.

,
, , , , :
<h:commandButton value=""/>
<h:commandButton type="reset" value=""/>
<h:commandButton image="book.gif" title=""/>
<h:commandLink></h:commandLink>

commandButton submit, reset


(type="reset"). ,
value ( ), image,
, .
.

402 10. JavaServer Faces


action . , doNew() BookController, EL , action:
<h:commandLink action="#{bookController.doNew}">

</h:commandLink>

-
HTTP- POST.
HTTP- GET,
(UIOutcomeTarget), .10.5. ,
JSF.
10.5.

<h:button> HtmlOutcomeTarget
Button

HTML
( HTTP- GET)

<h:link>

HTML <a> (
HTTP- GET)

HtmlOutcomeTarget
Link

, ,
<h:button outcome="newBook.xhtml" value="Abookmarkable button link"/>
<h:link outcome="newBook.xhtml" value="Abookmarkable link"/>

, .


(UIInput) ,
. , ,
.
.10.6.
10.6.

<h:input
Hidden>

HtmlInputHidden

HTML-
( )

403
HTML- JSF

<h:input
Secret>

HtmlInputSecret

HTML- .
( ), redisplay
true

<h:input
Text>

HtmlInputText

HTML-

<h:input
Textarea>

HtmlInputTextarea

HTML

<h:input
File>

HtmlInputFile

- ,
.
, , , :
<h:inputHidden value=" "/>
<h:inputSecret maxlength="8"/>
<h:inputText value=" "/>
<h:inputText size="40" value=" "/>
<h:inputTextarea rows="4" cols="20" value=" "/>
<h:inputFile/>

value,
. maxlength ,
, size
.
.


(, UIOutput) ,
-, . ,
.
.10.7 .

404 10. JavaServer Faces


10.7.

<h:outputLabel>
<h:outputLink>
<h:outputText>
<h:outputFormat>

HtmlOutputLabel
HtmlOutputLink
HtmlOutputText
HtmlOutputFormat

HTML <label>
HTML <a>

- .
HTML-, JSF
, - EL. <h:outputText>
<h:outputLink> . , <h:commandLink>
<h:outputLink> , , - .
.
<h:outputLabel value="#{bookController.book.title}"/>
<h:outputText value=""/>
<h:outputLink value=" http://www.apress.com/"></h:outputLink>
<h:outputFormat value=" {0}. {1} ">
<f:param value="#{user.firstName}" />
<f:param value="#{user.itemsBought}" />
</h:outputFormat>

,
. HTML-:
<label> </label>

<ahref=" http://www.apress.com/"></a>
, . 5


, (.10.8),
.
.
10.8.

<h:selectBoolean
Checkbox>

HtmlSelectBoolean
Checkbox

<h:selectMany
Checkbox>
<h:selectMany
Listbox>

HtmlSelectMany
Checkbox
HtmlSelectMany
Listbox

,
.


,

405
HTML- JSF

<h:selectMany
Menu>

HtmlSelectMany
Menu

HTML- <select>

<h:selectOne
Listbox>

HtmlSelectOne
Listbox

<h:selectOneMenu>

HtmlSelectOneMenu
,
.

<h:selectOneRadio>

HtmlSelectOneRadio

, , ,
: <f:selectItem>
<f:selectItems>. . ,
<f:selectItem> <h:selectOneMenu>.
<h:selectOneMenu>
<f:selectItem itemLabel=""/>
<f:selectItem itemLabel=""/>
<f:selectItem itemLabel=""/>
<f:selectItem itemLabel=""/>
<f:selectItem itemLabel=""/>
<f:selectItem itemLabel=""/>
</h:selectOneMenu>

.
, , ,
, -
(List, Set ..) .

406 10. JavaServer Faces

: <h:graphicImage>
( HtmlGraphicImage). ,
. HTML- <img>.
, , .. , -
.
:
<h:graphicImage value="book.gif" height="200" width="320"/>


(.10.9). JSF
<h:dataTable>,
. , .
<h:panelGrid> <h:panelGroup> . <h:dataTable> ,
, <h:panelGrid>
.
10.9.

<h:dataTable>

HtmlDataTable

, HTML- <table>

<h:column>

HtmlColumn

<h:dataTable>

<h:panelGrid>

HtmlPanelGrid

HTML- <table>

<h:panelGroup> HtmlPanelGroup ,
<h:panelGrid>

<h:dataTable> <h:panelGrid> . ,
, JSF .
, ,
<h:panelGrid> , . columns
, ,
. , ( , ):
<h:panelGrid columns="3" border="1">
<h:outputLabel value=""/>
<h:outputLabel value=""/>
<h:outputLabel value=""/>
<h:outputLabel value=""/>

407
HTML- JSF
<h:outputLabel value=""/>
<h:outputLabel value=""/>
</h:panelGrid>

,
<h:panelGroup>, .
<f:facet>:
<h:panelGrid columns="3" border="1">
<f:facet name="header">
<h:outputText value=""/>
</f:facet>
<h:outputLabel value=""/>
<h:outputLabel value=""/>
<h:outputLabel value=""/>
<h:outputLabel value=""/>
<h:outputLabel value=""/>
<h:outputLabel value=""/>
<f:facet name="footer">
h:outputText value="Footer"/>
</f:facet>
</h:panelGrid>

, , , .


-
. ,
, (, ,
).
<h:message> <h:messages> (.10.10). <h:message>
, <h:messages> .

408 10. JavaServer Faces


10.10.

<h:message>

HtmlMessage

<h:messages>

HtmlMessages

(INFO, WARN, ERROR FATAL),


CSS ( infoStyle , warnStyle , errorStyle
fatalStyle). , . ,
:
<h:messages style="color:red"/>
<h:form>
:
<h:inputText value="#{bookController.title}" required="true"/>
<h:commandButton action="#{bookController.save}" value=""/>
</h:form>

, -.
, ,
, , .

, , HTML. HTML- . JSF ,


. , , JavaScript HTML <script type="text/
javascript">. JSF <h:outputScript>
, . .10.11
.
10.11.

<h:body>

HtmlBody

HTML- <body>

<h:head>

HtmlHead

HTML- <head>

<h:form>

HtmlForm

HTML- <form>

<h:doctype>

HtmlDoctype

HTML- <doctype>

<h:outputScript>

Output

<script>

<h:outputStylesheet> Output


<link>

409
JSF


HTML, ,
. , <h:message> , CSS (, <h:messages style="color:red"/>),
<h:inputFile>, , ( , ..). HTML , .10.12.
10.12.

id

rendered

, ,

value

( EL)

converter

validator

required

true,

JSF
HTML- JSF
HTML (, JSF ).
JavaServer Faces .

,
. .10.13.
10.13. JSF

<f:facet>

<f:attribute>

<f:param>

<f:actionListener>

<f:valueChangeListener>
<f:propertyActionListener>
<f:phaseListener>

<f:converter>

<f:convertDateTime>
<f:convertNumber>

410 10. JavaServer Faces


10.13 ()

<f:validator>

<f:validatorDoubleRange>
<f:validatorLongRange>
<f:validateLength>
<f:validateRegex>
<f:validateBean>

Bean Validation
(.3)

<f:loadBundle>

<f:selectItem>
<f:selectItems>

<f:ajax>

AJAX

JSF
- ,
, .. Facelets
, . ( <ui:insert>), . <ui:component>,
<ui:composition>, <ui:fragment> <ui:decorate> . .10.14 .
10.14.

<ui:composition>

, .

<ui:component>

<ui:debug>

<ui:define>

<ui:decorate>

<ui:fragment>

<ui:include>


XHTML

<ui:insert>

<ui:param>

( <ui:include> )

<ui:repeat>

<ui:remove>

411
JSF
,
( .10.1). , ( ), Apress
Java EE7. , , layout.xhtml,
10.9.
10.9. layout.xhtml,

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<h:head>
<title><ui:insert name="title"> </ui:insert></title>
</h:head>
<h:body>
<h1><ui:insert name="title"> </ui:insert></h1>
<hr/>
<ui:insert name="content"> </ui:insert>
<hr/>
<h:outputText value="APress Java EE7" style="font-style:
italic"/>
</h:body>
</html>

10.9
(xmlns:ui="http://xmlns.jcp.org/jsf/Facelets").
<ui:insert> , title <title> <h1>. content.
, newBook.xhtml, 10.10, , (<ui:composition Template="lay
out.xhtml">). , <ui:define>,
<ui:insert> . , . title (<ui:define name="title">),
<ui:insert name="title"> .
,
content (<ui:define name="content">).
10.10. newBook.xhtml,
layout.xhtml

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<ui:composition template="layout.xhtml">
<ui:define name="title"> </ui:define>

412 10. JavaServer Faces


<ui:define name="content">
<h:form>
<h:panelGrid columns="2">
<h:outputLabel value="ISBN : "/>
<h:inputText value="#{bookController.book.isbn}"/>
<h:outputLabel value=" :"/>
<h:inputText value="#{bookController.book.title}"/>
<h:outputLabel value=" : "/>
<h:inputText value="#{bookController.book.price}"/>
<h:outputLabel value=" : "/>
<h:inputTextarea value="#{bookController.book.description}" cols="20"
rows="5"/>
<h:outputLabel value=" : "/>
<h:inputText value="#{bookController.book.nbOfPage}"/>
<h:outputLabel value=" : "/>
<h:selectBooleanCheckbox value="#{bookController.book.
illustrations}"/>
</h:panelGrid>
<h:commandButton value=" " action="#{bookController.
doCreateBook}"/>
</h:form>
</ui:define>
</ui:composition>
</html>

JSTL
JSP
.
, ,
XML . 10.15 URI
( ), .
10.15. JSTL

URI

http://xmlns.jcp.org/jsp/jstl/core

XML

http://xmlns.jcp.org/jsp/jstl/xml

I18N

http://xmlns.jcp.org/jsp/jstl/fmt

fmt

413
JSTL

URI

http://xmlns.jcp.org/jsp/jstl/sql

sql

http://xmlns.jcp.org/jsp/jstl/
functions

fn

Facelets JSTL-.
i18n (
XML, ).


,
, . .10.16
, Facelets.
10.16. , Facelets

<c:set>

<c:catch>

, java.lang.Throwable

<c:if>

<c:choose>

<c:when>

<c:choose>

<c:otherwise>

<c:choose>

<c:forEach>

, JSF,
3 15, , ,
(10.11).
10.11. JSF,

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:c="http://xmlns.jcp.org/jsp/jstl/core">
<h:head>
<title> </title>
</h:head>
<h:body>
<h1> </h1>
<hr/>
<c:set var="upperLimit" value="20"/>
< c:forEach var="i" begin="3" end="#{upperLimit - 5}">
<c:choose>

414 10. JavaServer Faces


<c:when test="#{i%2 == 0}">
<h:outputText value="#{i} "/><br/>
</c:when>
<c:otherwise>
<h:outputText value="#{i} "/><br/>
</c:otherwise>
</c:choose>
</c:forEach>
<hr/>
<h:outputText value="APress Java EE7" style="font-style:
italic"/>
</h:body>
</html>


URI ( XML). 10.11 20 upperlimit <c:set>, 3 15 (205). EL
#{upperlimit-5}. ( i) (<c:when test="#{i%2 == 0}">). <h:outputText>
("#{i} ").
, XML, , ,
Java, .


, ,
, (i18n).
, -. .10.17
, .
10.17.

<fmt:message>

<fmt:param>

<fmt:message>

<fmt:bundle>

<fmt:setLocale>

<fmt:requestEncoding>
<fmt:timeZone>

<fmt:setTimeZone>

<fmt:formatNumber>

(, , )

415
JSTL

<fmt:parseNumber>

<fmt:formatDate>

<fmt:parseDate>

JSF, 10.12,
, .
10.12. JSF

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:c="http://xmlns.jcp.org/jsp/jstl/core"
xmlns:fmt="http://xmlns.jcp.org/jsp/jstl/fmt">
<h:head><title> </title></h:head>
<h:body>
<br/>
<c:set var="now" value="#{bookController.currentDate}"/>
<fmt:formatDate type="time" value="#{now}"/><br/>
<fmt:formatDate type="date" value="#{now}"/><br/>
<fmt:formatDate type="both" dateStyle="short" timeStyle="short"
value="#{now}"/><br/>
<fmt:formatDate type="both" dateStyle="long" timeStyle="long"
value="#{now}"/><br/>
<br/>
<fmt:setLocale value="en_us"/>
<fmt:formatNumber value="20.50" type="currency"/><br/>
<fmt:setLocale value="en_gb"/>
<fmt:formatNumber value="20.50" type="currency"/><br/>
</h:body>
</html>

core format
c fmt. <c:ser var="now" value="#{}bookController.currentDate}"/> now. <fmt:formatDate> :
, , . <fmt:setlocale value="en_US"/>
, $20,50. , . JSF
:

11:31:12
14 may 2013
14/05/1311:31

416 10. JavaServer Faces


14 may 201311:31:12 CET

$20.50
20.50


,
. <h:graphicImage>
, <h:commandButton>
, <h:outputScript>
JavaScript. , CSS (
<h:outputStylesheet>). JSF ,
, ()
(JavaScript, CSS) .
JSF .
, -,
. , ,
(,
). JSF2.0
, resources JAR- ( / ). - :
resources/<resourceIdentifier>

JAR- WEB-INF/lib:
WEB-INF/lib/{*.jar}/META-INF/resources/<resourceIdentifier>

<resourceIdentifier> , :
[localePrefix/][libraryName/][libVersion/]resourceName[/resourceVersion]

, ,
.
(EN, en_US, Pt, pt_BR). ,
. , :
book.gif
en/book.gif
en_us/book.gif
en/myLibrary/book.gif
myLibrary/book.gif
myLibrary/1_0/book.gif
myLibrary/1_0/book.gif/2_3.gif

417

, book.gif, <h:graphicImage> (value="book.gif")
(library="MyLibrary"). .
, resource (
) resource['book.gif']
resource['MyLibrary:book.gif'] .
<h:graphicImage
<h:graphicImage
<h:graphicImage
<h:graphicImage

value="book.gif" />
value="book.gif" library="myLibrary" />
value="#{resource['book.gif']}" />
value="#{resource['myLibrary:book.gif']}" />


resource. JSF 2.2, , javax.fa
ces.WEBAPP_RESOURCES_DIRECTORY web.xml.
, JSF
-, .


, ,
resources (, #{resources['book.gif']}).
, JSF. ( ). , . ,
.
EL. .10.18
, .
10.18.

application

-. Object

applicationScope

Map

component

UIComponent

cc

UIComponent

cookie

Map,
cookies ( )
Cookie

facesContext

FacesContext FacesContext

Map

418 10. JavaServer Faces


10.18 ()

flash

,
(
11)

Object

header

HTTP- String

Map

headerValues

HTTP-
String[]

Map

initParam

String

Map

param


String

Map

paramValues



String[]

Map

request

HTTP

Object

requestScope

Map

resource

Object

session

Object

sessionScope

Map

view

UIViewRoot

viewScope

Map

, ,
API ( ), EL. , #{}view.locale
(en_US, pt_PT ..).
book ,
: #{sessionScope.book}.
HTTP- , 10.13.
10.13. ,
HTTP-

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:c="http://xmlns.jcp.org/jsp/jstl/core">
<h:body>
<h1> </h1>
<hr/>
<h3></h3>

419

<h:outputText value="#{view.locale}"/>
<h3>headerValues</h3>
<c:forEach var="parameter" items="#{headerValues}">
<h:outputText value="#{parameter.key}"/> =
<c:forEach var="value" items="#{parameter.value}">
<h:outputText value="#{value}" escape="false"/><br/>
</c:forEach>
</c:forEach>
<hr/>
<h:outputText value="APress Java EE7" style="font-style:
italic"/>
</h:body>
</html>

10.13, ,
.10.7.

.10.7. JSF,


JSF
, .
JSF , ,
.

420 10. JavaServer Faces


, javax.faces.component.UIComponent. JSF2.0,
,
, (UICommand, UIGraphic, UIOutput
.), faces-config.xml,
. , -,
Facelets, , .
:
,
JSF Java XML.
XHTML,
, .
XHTML ,
, .
, .
, , resources.
.10.19 , .
10.19. ,

<composite:interface>

<composite:implementation>
<composite:attribute>

, .
<composite:interface>

<composite:facet>

<composite:insertFacet>

<composite:interface>.

<composite:insertChildren>

<composite:interface>.
-

<composite:valueHolder>

, , <composite:interface>,
, ValueHolder

<composite:renderFacet>

<composite:interface>

<composite:extension>

<composite:interface> ,
XML-,
JSF

<composite:editableValue
Holder>

, , <composite:interface>, , EditableValueHolder

421

<composite:clientBehavior>

<composite:actionSource>

, , <composite:interface>,
, ActionSource

, ,
. , ,
, CD-BookStore :
-. 4 : Book
CD, Item. Item (,
), Book CD
(isbn, publisher, nbOfPage illustrations Book; musicCompany, numberOfCDs,
totalDuration genre CD). , -
-,
. Item , . .10.8
.

.10.8. , -,

( )
( ). JSF2.2
Java. <composite:interface> (10.14), . ,
( item CSS- style).

422 10. JavaServer Faces


<composite:implementation>. , , XHTML, JSF, . XHTML-.
10.14. newItem.xhtml

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:composite="http://xmlns.jcp.org/jsf/composite">
<composite:interface>
<composite:attribute name="item" required="true"/>
<composite:attribute name="style" required="false"/>
</composite:interface>
<composite:implementation>
<h:panelGrid columns="2" style="#{cc.attrs.style}">
<h:outputLabel value=" : "/>
<h:inputText value="#{cc.attrs.item.title}"/>
<h:outputLabel value=" : "/>
<h:inputText value="#{cc.attrs.item.price}"/>
<h:outputLabel value=" : "/>
<h:inputTextarea value="#{cc.attrs.item.description}" cols="20" rows="5"/>
</h:panelGrid>
</composite:implementation>
</html>

10.14 : item,
Item ( Book CD), style, CSS, .
:
#{cc.attrs.[attributeName]}

, GetAttributes() ( .10.18 , cc ,
). Map
attributeName. ,
.
, ,
, ,
. , . ,
newItem.xhtml /resources/apress.
, apress XML (ago ):
<html xmlns:ago="http://xmlns.jcp.org/jsf/composite/apress">

423

newItem ( ), : item, Item, style,
, CSS.
<ago:newItem item="#{itemController.book} "style="myCssStyle"/>
<ago:newItem item="#{itemController.cd} "/>

, , 10.15 newBook.xhtml, , . newItem


ISBN, , ,
, .
10.15. newBook.xhtml, newItem

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ago="http://xmlns.jcp.org/jsf/composite/apress">
<h:head>
<title> </title>
</h:head>
<h:body>
<h1> </h1>
<hr/>
<h:form>
<ago:newItem item="#{itemController.book}"/>
<h:panelGrid columns="2">
<h:outputLabel value="ISBN : "/>
<h:inputText value="#{itemController.book.isbn}"/>
<h:outputLabel value=" : "/>
<h:inputText value="#{itemController.book.nbOfPage}"/>
<h:outputLabel value=" : "/>
<h:selectBooleanCheckbox value="#{itemController.book.illustrations}"/>
</h:panelGrid>
<h:commandButton value=" " action="#{itemController.
doCreateBook}"/>
</h:form>
<hr/>
<h:outputText value="APress - Java EE7" style="font-style:
italic"/>
</h:body>
</html>

, -, . (, , ,
...), ,
.
, : PrimeFaces,
RichFaces IceFaces. , , .

424 10. JavaServer Faces

- , HTML, XHTML CSS,


JSF.
,
(RDA), (RIA), (
) .. JSF ,
2.2, .
JSF API
, , .. , PDL
- Facelets. JSF
(, , ..) ( ). ,
.
JSF -
. 11 , ,
-,
.

11.

10 , - JSF-.
, ,
,
. JSF -
- .
, -.
Bean Validation JSF2.2. -,
.
JSF2.2 . AJAX. JavaScript,
.
,
- , JSF (Model View Controller, MVC).
,
- . , 10.

MVC
JSF, - MVC. MVC
, - . - . ,
. MVC ;

-, .
MVC , ,
(.11.1).

426 11.

.11.1. MVC

, . , , . JSF , EJB, JPA ..


JSF XHTML,
-. 10,
. , , , .
, . ,
, - XHTML. JSF
FacesServlet.

FacesServlet
FacesServlet javax.servlet.Servlet. -

, .
.11.2, (,
) HTTP javax.faces.webapp.FacesServlet. -.
FacesServlet
javax.faces.lifecycle.Lifecycle. , ja
vax.faces.context.FacesContext,
. Lifecycle
FacesContext (
10) .

427
MVC

.11.2. FacesServlet

JSF, FacesServlet, , . -
, FacesServlet web.xml .
11.1.
11.1. FacesServlet web.xml

<?xml version='1.0' encoding='UTF-8'?>


<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<context-param>
<param-name>javax.faces.FACELETS_SKIP_COMMENTS</param-name>
<param-value>true</param-value>

428 11.
</context-param>
</web-app>

javax.faces.webapp.FacesServlet: (Faces Servlet) . ,


.jsf, ,
http://localhost:8080/chapter11-1.0/newBook.jsf JSF.

JSF- *.faces /faces/*. 11.1 .jsf, , .faces ,
.

, JSF,
<context-param>. .11.1.
11.1. JSF

javax.faces.CONFIG_FILES


, JSF

javax.faces.DEFAULT_
SUFFIX

- ,
JSF ( .jsf)

javax.faces.FACELETS_
BUFFER_SIZE

. 1

javax.faces.FACELETS_
REFRESH_PERIOD

,
, . 1

javax.faces.FACELETS_
SKIP_COMMENTS

true, , XML- Facelets


javax.faces.LIFECYCLE_ID

Lifecycle JSF

javax.faces.STATE_
SAVING_METHOD

.
server, ( HttpSession),
client (
)

javax.faces.PROJECT_
STAGE

,
JSF (Development, UnitTest,
SystemTest Production).
JSF ,
,

429
MVC

javax.faces.DISABLE_
FACELET_JSF_
VIEWHANDLER

true Facelets
(PDL)

javax.faces.WEBAPP_
RESOURCES_
DIRECTORY

, JSF -,

javax.faces.LIBRARIES

, ,
, Facelets

FacesContext
JSF javax.faces.context.FacesContext ,
.
JSF.
,
FacesContext (.10 )
-
getCurrentInstance(). FacesContext ,
, .11.2.
11.2. FacesContext

AddMessage

(, , )

GetApplication

Application,
-

GetAttributes

Map, ,
FacesContext

getCurrentInstance

FacesContext ,

getELContext

ELContext
FacesContext

getMaximumSeverity

,
FacesMessage,

GetMessages

FacesMessage

getPartialViewContext

PartialViewContext
.
/ (, AJAX)

getViewRoot

430 11.
11.2 ()

release
renderResponse

responseComplete

,
FacesContext
JSF ,

, , ,

JSF , HTTP-
(,
), ,
,

Faces-config.xml
FacesServlet JSF, , , ,
web.xml, 11.1.
JavaEE7: XML (/WEB-INF/faces-config.xml).
JSF2.0 XML,
-, , , , XML-
.
XML, Java-. 11.2 faces-config.xml. (fr), ,
. ,
faces-config.xml.
11.2. faces-config.xml

<?xml version='1.0' encoding='UTF-8'?>


<faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
version="2.2">
<application>
<locale-config>
<default-locale>fr</default-locale>
</locale-config>
<resource-bundle>
<base-name>messages</base-name>
<var>msg</var>
</resource-bundle>
</application>

431
-
<navigation-rule>
<from-view-id>*</from-view-id>
<navigation-case>
<from-outcome>doCreateBook-success</from-outcome>
<to-view-id>/listBooks.htm</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>

-
, MVC , : JSF- ,
FacesServlet . - .
- Java, -. - (
EJB),
. JSF-
-, . -,
, , . - (, #{bookController.book.title}).

-, , JSF.
Java EE, 2
CDI. Java EE POJO (Plain Old Java Object Java- ), , . - , JSF.

- , EJB JPA:
Java CDI- @Named (11.3)
CDI ( @RequestScoped). facesconfig.xml, . JSF2.2
, ,
,
-, -.
11.3. - BookController

@Named
@RequestScoped
public class BookController {
private Book book = new Book();
public String doCreateBook() {
createBook(book);

432 11.
return "newBook.xhtml";
}
//
}

11.3 -: ( book) (
), (doCreateBook())
( newBook.xhtml).
(, <h:outputText value="#{bookController.book.isbn}"/>)
(<h:commandLink action="#{bookController.doCreateBook}">).

-
- Java, FacesServlet.
. -
.
@javax.inject.Named XML- faces-config.xml.
(, @RequestScoped).
,
.
,
.
finalize().

, .
Java EE7, -
POJO, .
, 2 CDI. @javax.enterprise.inject.Model
-,
@Named @RequestScoped ( 11.4). , BookController, 11.3,
@Model (11.5), .
11.4. CDI @Model

@Named
@RequestScoped
@Documented
@Stereotype
@Target({ TYPE, METHOD, FIELD })
@Retention(RUNTIME)
public @interface Model {
}

433
-
11.5. BookController, @Model

@Model
public class BookController {
private Book book = new Book();
public String doCreateBook() {
createBook(book);
return "listBooks.xhtml";
}
// ,
}

@javax.inject.Named
. @Named
- (
). -, . , 11.6, - MyBean.
11.6. -

@Named("myBean")
@RequestScoped
public class BookController06 {
private Book book = new Book();
public String doCreateBook() {
createBook(book);
return "listBooks.xhtml";
}
// ,
}

-
, :
<h:outputText value="#{myBean.book.isbn}"/>
<h:form>
<h:commandLink action="#{myBean.doCreateBook}">
</h:commandLink>
</h:form>

JSF 2.2 - @javax.faces.bean.ManagedBean. ,
Managed Bean ( ),
Java EE, JSR-250
Common Annotations (@javax.annotation.ManagedBean). ,
JSF2.2 CDI CDI @Named, CDI. javax.faces.bean JSF.

434 11.


, -,
-.
. - ( -
) , .
(
@ApplicationScoped -) . /
, -, ,
. ,
(
syncronized).
, .
/, (@SessionScoped). , ,
.
, ,
.
,
, ,
( ).
, ,
. - @ViewScoped.
,
( @RequestScoped). , .
@ViewScoped , @RequestScoped.
, ,
.
JSF2.0
. ,
.
, .
,
, , (
@FlowScoped).

435


, JSF2.2, CDI ( @javax.enterprise.context.NormalScope).
: @ApplicationScoped, @RequestScoped
@SessionScoped CDI, @ViewScoped @FlowScoped JSF.


-. , .
- (, @ApplicationScoped)
,
.
,
. ,
.
. ,
, ,
.
11.7 -
. , (@PostConstruct) defaultBook.
11.7. -

@Named
@ApplicationScoped
public class InitController {
private Book defaultBook;
@PostConstruct
private void init() {
defaultBook = new Book("default title", 0F, "default description");
}
// ,
}

10 ( ,
). -
(.11.3),
. - , ,
, , .
-, -,
@PostConstruct @PreDestroy .
-, @PostConstruct,
. -

436 11.

.11.3. -

.
- @PreDestroy.

(.11.7).


- -, EJB,
.., ,
. ,
. , , : ( -,
) ( ISBN ).
, , , .
,
. , ,
.
10 ,
(<h:message> <h:messages>). JSF , -
facesContext.addMessage(). :
void addMessage(String clientId, FacesMessage message)

FacesMessage ,
. . , , (DOM) (, bookForm:isbn

437

, isbn bookForm). ClientId null, .
,
( , , ).
.
FacesMessage(Severity severity, String summary, String detail)

11.8 -, .
, (FacesMessage SEVERITY_INFO). ,
. , , ClientId null. ,
isbn , ,
(SEVERITY_WARN),
(, bookForm:title DOM title, bookForm).
11.8.

@Named
@RequestScoped
public class BookController {
@Inject
private BookEJB bookEJB;
private Book book = new Book();
public String doCreateBook() {
FacesContext ctx = FacesContext.getCurrentInstance();
if (book.getIsbn() == null || "".equals(book.getIsbn())) {
ctx.addMessage("bookForm:isbn",
new FacesMessage(FacesMessage.SEVERITY_WARN,
" ISBN", " ISBN"));
}
if (book.getTitle() == null || "".equals(book.getTitle())) {
ctx.addMessage("bookForm:title",
new FacesMessage(FacesMessage.SEVERITY_WARN,
" ", " "));
}
if (ctx.getMessageList().size() != 0)
return null;
try {
book = bookEJB.createBook(book);
ctx.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,
" ", "" + book.getTitle() + "

438 11.
with id=" + book.getId()));
} catch (Exception e) {
ctx.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
" ", e.getMessage()));
}
return null;
}
// ,
}

FacesContext FacesMessage.
( clientId null)
<h:messages>.
(
), <h:message>. .11.4 , ISBN title.

.11.4. , .

(id="isbn"),
<h:message> (for="ISBN"). .
<h:messages infoStyle="color:blue" warnStyle="color:orange"
errorStyle="color:red"/>
<h:form id="bookForm">
<h:inputText id="isbn" value="#{bookController.book.isbn}"/>
<h:message for="isbn"/>
</h:form>

439

ISBN , ISBN
. JSF
, Bean Validation. ,
<h:messages> (
, ).

JSF EJB
-
-. , - . , - , ,
-. EJB, ,
, .
-, EJB. EJB ?
CDI JSF EJB. ?
: @Named EJB, . 11.9 EJB,
, JPA,
. CDI @Named , ,
JSF.
11.9. EJB, , CDI- @Named

@Named
@Stateless
public class BookEJB {
@Inject
private EntityManager em;
public List<Book> findAllBooks() {
return em.createNamedQuery("findAllBooks", Book.class).getResultList();
}
}

findAllBooks() 11.9 .
, -.
bookEJB.findAllBooks() <h:dataTable> EL.
<h:dataTable value="#{bookEJB.findAllBooks()}" var="book">
<h:column>
<h:outputText value="#{book.title}"/>
</h:column>
</h:dataTable>

- , .

440 11.
, .
, , , ,
.. JSF ,
, .


JSF , .
-, JSF.
FacesServlet, , : , ,
. .
,
, , <h:button>, <h:link> <h:outputLink>:
<h:link value=" " outcome="newBook.xhtml"/>

, . <h:commandButton> <h:commandLink> action,


-,
<h:link> <h:button>:
<h:commandButton value=" " action="#{bookController.doCreateBook}">

, (newBook.xhtml),
. ,
-,
listBooks.xhtml, .
, - (.11.5).

.11.5. newBook.xhtml listBooks.xhtml

, - - (BookController), . ( )

441

-. newBook.xhtml
- doCreateBook()
(<h:commandButton action="#{bookController.doCreateBook}"/>). doCreateBook()
EJB Book
, . listBooks.xhtml
, newBook.xhtml
- (<h:link outcome="newBook.xhtml"/>).
<h:commandButton> , . -,
, . , . - 11.10 , .
11.10. -,

@Named
@RequestScoped
public class BookController {
@Inject
private BookEJB bookEJB;
private Book book = new Book();
private List<Book> bookList = new ArrayList<>();
public String doCreateBook() {
book = bookEJB.createBook(book);
bookList = bookEJB.findBooks();
return "listBooks.xhtml";
}
//,
}


- ,
. 11.10 .
.xhtml,
, FacesServlet web.xml, .
JSF faces-config.xml .
<navigation-rule>, , , .
, . - 11.10 success, 11.11.
11.11. -,

@Named
@RequestScoped
public class BookController {

442 11.
// ...
public String doCreateBook() {
book = bookEJB.createBook(book);
bookList = bookEJB.findBooks();
return "success";
}
// ,
}

11.12 faces-config.xml. <from-view-id>


, .
newBook.xhtml , . success ( <from-outcome> ),
FacesServlet listBooks.xhtml (<to-view-id>).
11.12. faces-config.xml,

<?xml version='1.0' encoding='UTF-8'?>


<faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
version="2.2">
<navigation-rule>
<from-view-id>newBook.xhtml</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>listBooks.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>

-
faces-congfig.xml, ,
? . Java , XML,
. -
, , ,
. ,
-, faces-config.xml.
, XML- .
(, ),
. XML ( -).
<navigation-rule>
<from-view-id>*</from-view-id>
<navigation-case>
<from-outcome>logout</from-outcome>

443

<to-view-id>logout.xhtml</to-view-id>
</navigation-case>
</navigation-rule>

, ,
navigation-rule <from-view-id>
(*). ,
, , ,
- logout,
logout.xhtml.
, ,
. , ,
, .
-,
faces-config.xml. switch,
. ,
null, :
public String doCreateBook() {
book = bookEJB.createBook(book);
bookList = bookEJB.findBooks();
switch (value) {
case 1: return "page1.xhtml"; break;
case 2: return "page2.xhtml"; break;
default: return null; break;
}
}

JSF2.0 , . ,
.
<fr>. , admin,
logout_admin.xhtml:
<navigation-rule>
<from-view-id>*</from-view-id>
<navigation-case>
<from-outcome>logout</from-outcome>
<to-view-id>logout_admin.xhtml</to-view-id>
<if>#{userController.isAdmin}</if>
</navigation-case>
</navigation-rule>


JSF2.0
HTTP POST (<h:commandButton> <h:commandLink>). ,

444 11.
- . JSF2.0
<h:button>, <h:link>,
ViewParam. HTTP-
GET. ,
preRenderView. JSF2.2 ViewAction,
.
ViewParam ViewAction GET- , HTTP-, , EL. <f:viewParam> GET-
.
viewBook.xhtml id (,
viewBook.xhtml?id=123) bookController.book.id:
<f:metadata>
< f:viewParam name="id" value="#{bookController.book.id}"/>
</f:metadata>

id HTTP , -. JSF2.2
<f:viewAction>, , . , id,
doFindBookById :
<f:metadata>
<f:viewParam name="id" value="#{bookController.book.id}"/>
<f:viewAction action="#{bookController.doFindBookById}"/>
</f:metadata>

URL , (, viewBook.xhtml?id=123 viewBook.xhtml?id=456)


.


, ,
, .
(, ISBN). JSF , , , .
- .
, null,
..
, .
, ,
java.util.Date Integer

445

. , , ( dd/MM/yyyy,
3,14 3,15 ..).
( ), .11.6.
.11.6
(, ) . ,

- ( ). ,
,
( <h:messages/>). -
, .
JSF .

,
,
HTTP, . (Float,
Integer, BigDecimal ..). , .
JSF , .
- (Integer, int, Float,
float ..), JSF .
, . .11.3
, javax.faces.convert.
11.3.

BigDecimalConverter

java.math.BigDecimal

BigIntegerConverter

java.math.BigInteger

BooleanConverter

Boolean ( boolean)

ByteConverter

Byte ( byte)

CharacterConverter

Character ( char)

DateTimeConverter

java.util.Date

.11.6.

446 11.

447

11.3 ()

DoubleConverter

Double ( double)

EnumConverter

Enum ( enum)

FloatConverter

Float ( float)

IntegerConverter

Integer ( int)

LongConverter

Long ( long)

NumberConverter

java.lang.Number

ShortConverter

Short ( short)

JSF ,
- ,
, . ,
convertNumber convertDateTime. ,
. JSF .
convertNumber ,
( ), .
, ,
, :
<h:inputText value="#{bookController.book.price}">
<f:convertNumber currencySymbol="$" type="currency"/>
</h:inputText>

convertDateTime (,
). , . pattern
, :
<h:inputText value="#{bookController.book.publishedDate}">
<f:convertDateTime pattern="MM/dd/yy"/>
</h:inputText>


, , ..
. JSF.
, javax.faces.convert.Converter,
. :
Object getAsObject(FacesContext ctx, UIComponent component, String value)
String getAsString(FacesContext ctx, UIComponent component, Object value)

448 11.
getAsObject()
. ConverterException, . , getAsString() , (, XHTML).
, , -.
faces-config.xml,
@FacesConverter.
11.13 , , .
euroConverter @FacesC onver
ter("euroConverter") Converter.
getAsString() , .
11.13.

@FacesConverter("euroConverter")
public class EuroConverter implements Converter {
@Override
public Object getAsObject(FacesContext context, UIComponent component, String
value) {
return value;
}
@Override
public String getAsString(FacesContext ctx, UIComponent component, Object
value) {
float amountInDollars = Float.parseFloat(value.toString());
double ammountInEuros = amountInDollars * 0.8;
DecimalFormat df = new DecimalFormat("###,##0.##");
return df.format(ammountInEuros)
}
}

,
converter <h:outputText>, <f:converter>. , @FacesConverter
(euroConverter). , -

,
:
<h:outputText value="#{book.price}"/> //
<h:outputText value="#{book.price}"> //
<f:converter converterId="euroConverter"/>
</h:outputText>

converter outputText:
<h:outputText value="#{book.price}" converter="euroConverter"/>

449

-
. JavaScript
Bean Validation. JSF .
,
, -.
, ,
, , . , ,
, :
<h:inputText value="#{bookController.book.title}" required="true"/>

, JSF ,
( <h:messages>).
, . JSF ( .11.4).
javax.faces.validator.
11.4.

DoubleRangeValidator

, double

LengthValidator

LongRangeValidator


, long

MethodExpression
Validator

RequiredValidator

true required

RegexValidator

, , .
, ( ).
, 2 20
, $1 500:
<h:inputText value="#{bookController.book.title}" required="true">
<f:validateLength minimum="2" maximum="20"/>
</h:inputText>
<h:inputText value="#{bookController.book.price}">
<f:validateLongRange minimum="1" maximum="500"/>
</h:inputText>

450 11.


, JSF
, , , , , .
. , ,
.
javax.faces.validator.Validator, validate():
void validate(FacesContext context, UIComponent component, Object value)

value -
- . ,
.
, ValidatorException FacesMessage, .
faces-config.xml, @FacesValidator.
ISBN, , ISBN (
). 11.14 IsbnValidator.
11.14. ISBN

@FacesValidator("isbnValidator")
public class IsbnValidator implements Validator {
private Pattern pattern;
private Matcher matcher;
@Override
public void validate(FacesContext context, UIComponent component,
Object value) throws ValidatorException {
String componentValue = value.toString();
pattern = Pattern.compile("(?=[-0-9xX]{13}$)");
matcher = pattern.matcher(componentValue);
if (!matcher.find()) {
String message = MessageFormat.format("{0} isbn",
componentValue);
FacesMessage facesMessage =
new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg);
throw new ValidatorException(facesMessage);
}
}
}

11.14 isbnValidator,
. Validator
validate(). -

451
AJAX
, ISBN . . JSF , ,
.
validator <f:validator>.
<h:inputText value="#{bookController.book.isbn}" validator="isbnValidator"/>
//
<h:inputText value="#{bookController.book.isbn}">
<f:validator validatorId="isbnValidator" />
</h:inputText>

Bean Validation
JSF 2.0, Bean Validation (
JSF ). .
JSF -,
Bean Validation, javax.va
lidation.Validator.validate(). Bean Validation ,
JSF
Bean Validation -. JSF ,
ConstraintViolation, , FacesMessage FacesContext, . , <h:messages> , ConstraintViolation.
3 .
, <f:validateBean>.
Delivery:
<f:validateBean validationGroups="org.agoncal.book.javaee7.Delivery">
<h:inputText value="#{bookController.book.title}"/>
<h:inputText value="#{bookController.book.price}"/>
</f:validateBean>

AJAX
HTTP /:
-, , , . : -
, . -
, ,
, .. / -,
. ,
, .

452 11.
, .
AJAX.
AJAX (Asynchronous JavaScript and XML JavaScript XML)
-,
-. AJAX - ,
. ,
, DOM JavaScript.


AJAX 2005. 1999 Microsoft XMLHttpRequest ActiveX Internet Explorer5.
2006 W3C XMLHttpRequest,
. AJAX
.
OpenAjax Alliance, , ,
AJAX.
.11.7, -
HTML- . ,
, , , . AJAX, ,
(HTTP-)
, - (JSON- XML-), .
, JavaScript ,
- .
, AJAX :
XHTML CSS ;
DOM ;
XML XSLT , XML-;
XMLHttpRequest ;
JavaScript, .
XMLHttpRequest AJAX, DOM API, JavaScript XML .
JavaScript. ,
XHTML, JSON .
AJAX JSF 2.0,
JavaScript XMLHttpRequest.
JavaScript, JSF.

453
AJAX

.11.7. HTTP HTTP- AJAX

JSF
JSF AJAX, ,
, . . JSF 2.0,
, AJAX JSF.
, JavaScript (jsf.js) AJAX, ,
XMLHttpRequest .
JavaScript
.
, jsf.js
:
<h:outputScript name="jsf.js" library="javax.faces" target="head"/>

<h:outputScript> <script> ,
JavaScript- jsf.js javax.faces ( JSF, , jsf.js META-INF/resources/javax/faces). ,

454 11.
javax OpenAjax Alliance.
JavaScript API JSF
, .
, , request, AJAX . :
jsf.ajax.request(ELEMENT, |event|, { |OPTIONS| });
ELEMENT JSF XHTML, . , .
EVENT JavaScript, ,
onmousedown, onclick, onblur .. OPTIONS ,
/:
execute: '< >' ID ,
;
render: '< >' ID ,
.

, ,
doCreateBook,
. jsf.ajax.request,
( onclick). this (),
ID (isbn, title, price):
<h:commandButton value=" " onclick="jsf.ajax.request(this, event,
{execute:'isbn title price description nbOfPage illustrations',
render:'booklist'}); return false;"
actionListener="#{bookController.doCreateBook}" />

AJAX , ( ). , ,
HTML- . ,
, PartialViewContext
.
, . AJAX (, ,
) .
XHTML-, XML- JSON-, JavaScript
.
JSF 2 , . <f:ajax>.
JavaScript AJAX ,
JavaScript.

455

<h:commandButton value=" " action="#{bookController.
doCreateBook}">
<f:ajax execute="@form" render=":booklist"/>
</h:commandButton>

render ,
( Booklist). execute , . .11.5 , render execute.
11.5. render execute

@all

@none

( ,
)

@this

(, AJAX)

@form

( AJAX)

- ,
-


-,
, . -
-:
newBook.xhtml , ,
.
, AJAX. -
;
viewBook.xhtml (, ,
..). , , URL (, viewBook.xhtml?id=123
viewBook.xhtml?id=456).
, ( newBook.xhtml) .
.11.8 ( <h:link>, <h:commandButton>).

456 11.

.11.8. newBook.xhtml viewBook.xhtml

- BookController
. JPA - EJB,
(JSF, EJB, JPA, Bean Validation CDI). -
- BookEJB, :
( createBook() ),
(findAllBooks()), (findBookById()).
, , API
Book (
Bean Validation).
.11.9 -.
.war GlassFish Derby.
- Maven, ,
- :
src/main/java Book , BookEJB -
BookController;
src/main/resources META-INF/persistence.xml,
;
src/main/webapp - newBook.xhtml viewBook.xhtml;
src/main/webapp/WEB-INF faces-config.xml beans.xml, JSF CDI;
pom.xml Maven (POM)
, .

457

.11.9. -

Book
, 11.15,
Book. JPA
Bean Validation, findAllBooks,
, .
11.15. Book, Bean
Validation

@Entity
@NamedQuery(name = "findAllBooks", query = "SELECT bFROM Book b
ORDER BY b.title DESC")
public class Book {
@Id @GeneratedValue
private Long id;
@NotNull @Size(min = 4, max = 50)
@Column(nullable = false)
private String title;
private Float price;
@Column(length = 2000)
private String description;
private Integer nbOfPage;
private Boolean illustrations;
// ,
}

, persistence.xml,
(.4).

458 11.

BookEJB
11.16 , . , ( -)
( )
EJB. EJB @Inject. CDI DatabaseProducer,
, 8.13 ( , .8).
Book ( createBook()), ( findAllBooks)
. , EJB
@Named, JSF (
)
@DataSourceDefinition. EJB .
11.16. EJB, ,

@Named
@Stateless
@DataSourceDefinition(name = "java:global/jdbc/lab11DS",
className = "org.apache.derby.jdbc.EmbeddedDriver",
url = "jdbc:derby:memory:lab11DB;create=true;user=app;password=app"
)
public class BookEJB {
@Inject
private EntityManager em;
public Book createBook(Book book) {
em.persist(book);
return book;
}
public List<Book> findAllBooks() {
return em.createNamedQuery("findAllBooks", Book.class).getResultList();
}
public Book findBookById(Long id) {
return em.find(Book.class, id);
}
}

-
BookController
- (, EJB) . BookController
11.17 @Named,
JSF. @RequestScoped .
.

459

- book, . , ( newBook.xhtml ), viewBook.xhtml
.
11.17. - BookController, EJB

@Named
@RequestScoped
public class BookController {
@Inject
private BookEJB bookEJB;
private Book book = new Book();
public String doCreateBook() {
bookEJB.createBook(book);
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_INFO, "Book created",
"" + book.getTitle() + " id=" + book.getId()));
return "newBook.xhtml";
}
public void doFindBookById() {
book = bookEJB.findBookById(book.getId());
}
//
}

- ( ) BookEJB. EJB @Inject.


, .
doCreateBook() EJB, , Book. , .
, .
doFindBookById() viewBook.xhtml EJB, .
11.17 - BookController. , book.

layout.xhtml
newBook.xhtml, viewBook.xhtml (layout.xhtml,
11.18). .11.8,
, <h:link>,
, newBook.xhtml ,
<h:messages>, , .

460 11.
11.18. Layout.xhtml,

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<title><ui:insert name="title"> </ui:insert></title>
</h:head>
<h:body>
<h:link value="Create abook" outcome="newBook.xhtml"/>
<h1><ui:insert name="title"> </ui:insert></h1>
<hr/>
<h:messages id="errors" infoStyle="color:blue" warnStyle="color:orange"
errorStyle="color:red"/>
<ui:insert name="content"> </ui:insert>
<hr/>
<h:outputText value="APress Java EE7" style="font-style:
italic"/>
</h:body>
</html>

newBook.xhtml
newBook.xhtml , , -

(, , ,
), (..11.8). , , , .
, . AJAX.
11.19 , . BookController -
BookController, - (.11.17).
Book ,
(#{bookController.book.title} ).
11.19. newBook.xhtml

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<ui:composition template="layout.xhtml">
<ui:define name="title"> </ui:define>
<ui:define name="content">

461

<h:form id="bookForm">
<h:panelGrid columns="2">
<h:outputLabel value=" : "/>
<h:inputText value="#{bookController.book.title}"/>
<h:outputLabel value=" : "/>
<h:inputText value="#{bookController.book.price}"/>
<h:outputLabel value=" : "/>
<h:inputTextarea value="#{bookController.book.description}" cols="16"
rows="3"/>
<h:outputLabel value=" : "/>
<h:inputText value="#{bookController.book.nbOfPage}"/>
<h:outputLabel value=" : "/>
<h:selectBooleanCheckbox value="#{bookController.book.
illustrations}"/>
</h:panelGrid>
<h:commandButton value=" " action="#{bookController.
doCreateBook}">
<f:ajax execute="@form" render=":booklist :errors"/>
</h:commandButton>
</h:form>
...

<h:commandButton> , AJAX.
, <f:ajax>
@form ( ).
,
, .
doCreateBook() - , , .
, , :
newBook.xhtml. .
AJAX.
render ID booklist ,
(11.20), ID errors,
layout.xhtml (.11.18), .
11.20. newBook.xhtml

...
<hr/>
<h1> </h1>
<h:dataTable id="booklist" value="#{bookEJB.findAllBooks()}" var="bk"
border="1">
<h:column>
<f:facet name="header">

462 11.
<h:outputText value=""/>
</f:facet>
<h:link outcome="viewBook.xhtml?id=#{bk.id}" value="#{bk.title}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value=""/>
</f:facet>
<h:outputText value="#{bk.price}"/>
</h:column>
</h:dataTable>
</ui:define>
</ui:composition>
</html>

11.20 .
<h:dataTable>, BookEJB (
BookController) @Named (.11.16). <h:dataTable>
bookEJB.findAllBooks(),
List<Book> bk .
<h:dataTable> , #{bk.price},
price . <h:link> HTML-, viewBook.xhtml (viewBook.xhtml?ID=#{bk.id}).

viewBook.xhtml
viewBook.xhtml (, ,
, ). JSF2, ,
, URL ViewAction.
11.21, id (,
viewBook.xhtml?id=123) #{bookController.book.id}. , #{bookController.doFindBookById}.
BookController.doFindBookById (.11.17) EJB
, (,
#{bookController.book.title}) .
11.21. ViewBook.xhtml

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<ui:composition template="layout.xhtml">
<f:metadata>
<f:viewParam name="id" value="#{bookController.book.id}"/>

463

<f:viewAction action="#{bookController.doFindBookById}"/>
</f:metadata>
<ui:define name="title"> </ui:define>
<ui:define name="content">
<h:panelGrid columns="2">
<h:outputLabel value=" : "/>
<h:outputText value="#{bookController.book.title}"/>
<h:outputLabel value=" : "/>
<h:outputText value="#{bookController.book.price}"/>
<h:outputLabel value=" : "/>
<h:outputText value="#{bookController.book.description}" cols="16"
rows="3"/>
<h:outputLabel value=" : "/>
<h:outputText value="#{bookController.book.nbOfPage}"/>
<h:outputLabel value=" : "/>
<h:selectBooleanCheckbox value="#{bookController.book.illustrations}"/>
</h:panelGrid>
</ui:define>
</ui:composition>
</html>

Maven
-
.war (<packaging>war</packaging>). pom.xml, 11.22, (glassfish-embedded-all)
JDK 1.7.
11.22. pom.xml -

<?xml version="1.0" encoding="UTF-8"?>


<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>chapter11</artifactId>
<groupId>org.agoncal.book.javaee7</groupId>
<version>1.0</version>
</parent>
<groupId>org.agoncal.book.javaee7.chapter11</groupId>
<artifactId>chapter11</artifactId>
<version>1.0</version>

464 11.
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.glassfish.main.extras</groupId>
<artifactId>glassfish-embedded-all</artifactId>
<version>4.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.2</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>


, pom.xml ,
Maven:
$ mvn package

target chapter11-1.0.war. ,
, Book , BookEJB , -
BookController, (persistence.xml, faces-config.xml
beans.xml) - (newBook.xhtml viewBook.xhtml).

GlassFish
-, GlassFish.
, GlassFish . ,
target, chapter11-1.0.war,
:
$ asadmin deploy chapter11-1.0.war

465

,
. : web,
-, EJB, EJB.
$ asadmin list components
chapter11-1.0 <ejb, web>


, ,
URL: http://localhost:8080/chapter11-1.0/newBook.faces.
newBook.faces, newBook.xhtml -
FacesServlet. .faces JSF , . newBook,
.
.
- , GlassFish, AJAX . XML-, HTML-. XHTML, . JavaScript
errors booklist ( DOM). 11.23 . ,
,
errors booklist (<update id="booklist">). <update> XHTML, . , XML AJAX,
JSF, .
11.23. ,

<?xml version='1.0' encoding='UTF-8'?>


<partial-response>
<changes>
<update id="errors">
<![CDATA[
<ul id="errors"><li style="color:blue"> </li></ul>
]]>
</update>
<update id="booklist">
<![CDATA[
<table id="booklist" border="1">
<thead>
<tr>
<th scope="col"></th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr>
<td><ahref="/chapter11-1.0/viewBook.faces?id=54">Java EE 6</a></td>

466 11.
<td>31.49</td>
</tr>
<tr>
<td><ahref="/chapter11-1.0/viewBook.faces?id=1"> </a></td>
<td>19.79</td>
</tr>
<tr>
<td><ahref="/chapter11-1.0/viewBook.faces?id=51">H2G2</a></td>
<td>23.99</td>
</tr>
</tbody>
</table>
]]>
</update>
</changes>
</partial-response>

10 JSF,
. JSF MVC,
: -.
- JSF,
-, EJB ,
. (
, ), ,
, . JSF 2.2,
XML- .
,
, . JSF
,
.
Bean Validation , JSF.
AJAX , JSF
, - . JSF JavaScript, .
.
, - SOAP RESTful XML JSON.

12.
XML JSON
XML Java EE . XML, persistence.xml, beans.xml ejb-jar.xml. Java
XML. , XML -
EJB.
XML , W3C.
,
. XML , ,
, (, - SOAP, 14).
, JSON JavaScript , XML, .
, JSON . ,
/ JSON. JavaScript, JSON (,
- RESTful,
15).
, XML JSON,
API-,
. XML , , , XML Java. ,
XML- Java SE. JSON
Java , , Java
SE/EE.

XML
(XML), SGML (Standard
Generalized Markup Language ),

468 12. XML JSON


. XML , . ,
, MathML (Mathematical Markup
Language ), VXML (Voice Markup Language
) OpenOffice LibreOffice (OpenDocument).
XML ,
, , . XML-
XML, . XML-
, (, '<' '>').

XML-
12.1 XML-, CD-BookStore (.1). ,
, , ,
. , ,
, .
12.1. XML-,

<?xml version="1.0" encoding="UTF-8" ?>


<order id="1234" date="05/06/2013">
<customer first_name="" last_name="">
<email>j.rorri@me.com</email>
<phoneNumber>+4412341234</phoneNumber>
</customer>
<content>
<order_line item="H2G2" quantity="1">
<unit_price>23.5</unit_price>
</order_line>
<order_line item=" " quantity="2">
<unit_price>34.99</unit_price>
</order_line>
</content>
<credit_card number="1357" expiry_date="10/13" control_number="234"
type="Visa"/>
</order>

XML (,
XML ), . , ,
,
.
.12.1, XML .
, XML
, ,
Java .

469
XML
12.1. XML

Unicode XML- ,
Unicode

Unicode . < > (, <email>), , , (, j.rorri@me.com)

(<email>),
(</email>) (email/)

( ).
, . : <email>j.rorri@me.com</email>

/, .
item order_line: <order_line item="H2G2">

XML

XML-
, : <?xml version="1.0"
encoding="UTF-8" ?>

XML
XML , XML
.
, XML , .
XML. XML-, XML XML. ,
XML-.


(DTD). , DTD XSD DTD. , DTD XML-,
XML- XML. DTD XML-.

XML (XSD) XML ,


XML-. , 12.2 XML, (.12.1),
: , , , .
XSD ,
XML- .

470 12. XML JSON


12.2. XSD, XML-,

<?xml version="1.0" encoding="UTF-8" ?>


<xs:schema version="1.0" xmlns:xs= "http://www.w3.org/2001/XMLSchema">
<xs:element name="order" type="order"/>
<xs:complexType name="creditCard">
<xs:sequence/>
<xs:attribute name="number" type="xs:string"/>
<xs:attribute name="expiry_date" type="xs:string"/>
<xs:attribute name="control_number" type="xs:int"/>
<xs:attribute name="type" type="xs:string"/>
</xs:complexType>
<xs:complexType name="customer">
<xs:sequence>
<xs:element name="email" type="xs:string" minOccurs="0"/>
<xs:element name="phoneNumber" type="xs:string" minOccurs="0"/>
</xs:sequence>
<xs:attribute name="first_name" type="xs:string"/>
<xs:attribute name="last_name" type="xs:string"/>
</xs:complexType>
<xs:complexType name="order">
<xs:sequence>
<xs:element name="customer" type="customer" minOccurs="0"/>
<xs:element name="content" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="order_line" type="orderLine" minOccurs= "0"
maxOccurs= "unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="credit_card" type="creditCard" minOccurs="0"/>
</xs:sequence>
<xs:attribute name="id" type="xs:long"/>
<xs:attribute name="date" type="xs:dateTime"/>
</xs:complexType>
<xs:complexType name="orderLine">
<xs:sequence>
<xs:element name="unit_price" type="xs:double" minOccurs="0"/>
</xs:sequence>
<xs:attribute name="item" type="xs:string"/>
<xs:attribute name="quantity" type="xs:int"/>
</xs:complexType>
</xs:schema>

, XSD (<xs:attribute
name="expiry_date" type="xs:string"/>), (<xs:complexType

471
XML
name="creditCard">) .

, , , . XSD
, . XML
, JAXB, .
.12.2 XSD- .
XSD , .
XSD, , , W3C.
12.2. XSD

schema

XML.
,

xmlns

xs: (
xsd:, ),
XML (xmlns) :
xmlns:xsd="http://www.w3.org/2001/XMLSchema"

element

element. ,order ,
<orderid="1234" date="11/08/2013" total_amount="93.48">

type

, string, decimal, long


double (type="xs:long") (type="customer")

minOccurs,
maxOccurs


.
unbounded, ,

complexType

, ,
. complexType
complexType. , order

Sequence

, -. ,
- .
0

attribute

, attribute. orderLine
: item quantity

choice

complexContent complexContent
extension


simpleType complexType

472 12. XML JSON


XML- XML,
, .
: DOM SAX.

SAX DOM
,
XML. , , , XML,
. XML- . (DOM), XML .
API XML (SAX),
XML ,
( ).

DOM
API (Document Object Model, DOM), ,
. ,
, .
DOM, , ,
XML- .
, DOM XML ,
.
, JDOM DOM4J,
- XML
.

SAX
,
.
API XML (SAX) ,
.
SAX ,
.
SAX SAX , XML.
, . SAX , XML, .
SAX XML
, . ,
, -

473
SAX DOM
, .
.

XPath
XPath , XML-,
XML-, XSLT, XPointer XQuery.
, XML-.
XPath , ,
. XPath ,
. , XPath / ,
XML-, . XPath, unit_price,
20 ( XML- (.12.1)).
//content/order_line[unit_price>=20]/unit_price

, XPath , . - unit_price:
//content/order_line[unit_price>=20]/unit_price/text()

XQuery ,
XML XPath. XQuery SQL,
FOR, LET, WHERE, ORDER BY RETURN.
XQuery, doc() (
Order.xml), order_line,
quantity 1, unit_price 50;
for $orderLine in doc("order.xml")//content/order_line[@quantity>1]
where $orderLine/unit_price < 50
return $orderLine/unit_price/text()

XQuery ,
.
XML- API , - ,
.
XML, XPath 1.0 XQuery, XML-.

XSLT
XML, , XML-
. , XML- , , -. , , (XSLT).

474 12. XML JSON


, XSLT XML-, XSL . , , XSL,
. XSLT ,
XML .
XPath,
. .
, .
XSLT, 12.3,
order.xml , (.12.1), -
XHTML, , 30.
12.3. XSLT ,

<?xml version="1.0" encoding="UTF-8"?>


<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/
Transform">
<xsl:template match="/">
<html>
<body>
<h2> </h2>
<table border="1">
<tr>
<th></th>
<th></th>
<th> </th>
</tr>
<xsl:for-each select="order/content/order_line">
<tr>
<td>
<xsl:value-of select="@item"/>
</td>
<td>
<xsl:value-of select="@quantity"/>
</td>
<xsl:choose>
<xsl:when test="unit_price> 30">
<td bgcolor="#FF0000">
<xsl:value-of select="unit_price"/>
</td>
</xsl:when>
<xsl:otherwise>
<td>
<xsl:value-of select="unit_price"/>
</td>

475
XML
</xsl:otherwise>
</xsl:choose>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

API XSLT javax.xml.transform


XML XML-. XSLT SAX API,
XML.

XML
XML- W3C 1998, XML-, XSLT, XPath, XML
XQuery, W3C. Java
XML
, Java API
XML. Java, XML, .

XML-
W3C , , HTML, XHTML, RDF CSS. W3C
XML XML XML,
XSLT, XPATH DOM.
XML 1996 XML W3C
W3C 1998.
. SGML,
1980- ISO 1986.
XSD ( XML) XML-
.xsd.
XML- , , .
XSD XML. XML, W3C
2001.
XSLT XML,
. XML-.
DSSSL (Document Style Semantics and Specification Language ), SGML ,
XSLT XML. XSLT 1.0 W3C 1999,

476 12. XML JSON


XPath. Xalan, Saxon AltovaXML XSLT, XML.
XPath 1.0 XML. W3C 1999. XPointer XSLT. XPath1.0
Java ,
XSLT, XQuery XML.
XML Query
. XQuery 1.0
XML Query XSLT 2.0
XSL. XPath 2.0,
XQuery 1.0. XQuery 1.0 W3C 232007.
DOM
, HTML-, XHTML- XML-.
DOM
, . DOM, DOM
Level 3, XPath,
XML.
SAX API XML Java. ,
XML-. SAX Java, .
XML
XML.
.12.3 XML.
12.3. W3C XML

URL

Extensible Markup Language


(XML)

1.1

http://www.w3.org/TR/xml11/

XML Schema

1.0

http://www.w3.org/TR/xmlschema-1

Extensible Stylesheet (XSLT)

1.0

http://www.w3.org/TR/xslt

XML Path (XPath)

1.0

http://www.w3.org/TR/xpath

Document Object Model (DOM) level 3

http://www.w3.org/TR/DOM-Level-3-Core/

Simple API for XML (SAX)

http://sax.sourceforge.net/

2.0.2

XML Java
XML W3C.
Java, XML ,
JCP. XML Java.
JAXP (Java Architecture for XML Processing Java
XML) (JSR 206),

477
Java XML
XML, SAX, DOM
XSLT. API JAXB StAX.
JAXB API-
XML- Java, Java. JAXB (JSR 222)
XML . JAXB
XML, JAX-WS ( 14).
StAX (Streaming API for XML API XML) 1.0 (JSR 173)
API XML-.
API ( DOM) API, ( SAX).
, ,

.
.12.4 Java, XML.
12.4. , XML

JSR

URL

JAXP

1.3

206

http://jcp.org/en/jsr/detail?id=206

JAXB

2.2

222

http://jcp.org/en/jsr/detail?id=222

StAX

1.0

173

http://jcp.org/en/jsr/detail?id=173


(Reference Implementation, RI) . StAX RI
JSR-173, . StAX JDK, 1.6,
JDK 1.4 1.5. RI JAXP
Java SE, Metro, JAXB.
Metro JAXB, Oracle.

Java XML
Java XML (Java Architecture for XML Processing, JAXP)
API , ,
SAX, DOM XSLT API Java.
JAXP
XML . JAXP
API
XML-.
, JAXP XML-.

478 12. XML JSON


XML API. .
JAXP, XML- SAX
DOM XSLT. JAXP
API .12.1.

.12.1. JAX

JAXP , .12.5. ,
XML-.
12.5. JAXP

javax.xml.parsers

DOM SAX

org.w3c.dom

API DOM Java

org.xml.sax

, SAX

javax.xml.transform

API XLST XML

JAXP
JAXP . (JAXP Xerces XML Xalan XSLT XML-).
, JAXP
. JAXP,
API . , , XML
. , jaxp.properties ( ,
java.util.Properties) lib JRE
JAXP .
jaxp.properties, , DOM, SAX XSLT :

479
Java XML
javax.xml.parsers.DocumentBuilderFactory=org.apache.xerces.jaxp.
DocumentBuilderFactoryImpl
javax.xml.parsers.SAXParserFactory=org.apache.xerces.jaxp.SAXParserFactoryImpl
javax.xml.transform.TransformerFactory=org.apache.xalan.processor.
TransformerFactoryImpl

Java
. , JVM Xerces XML:
-Djavax.xml.parsers.DocumentBuilderFactory=org.apache.xerces.jaxp.
DocumentBuilderFactoryImpl

, ,
, .12.6.
12.6. .
/ XML

javax.xml.parsers.DocumentBuilderFactory

DOM

javax.xml.parsers.SAXParserFactory

SAX

javax.xml.transform.TransformerFactory

, XSLT

JAXP SAX
SAX
. SAX , XML-.
,
XML-. , SAX , , ,
.
XML-
,
. XML-
SAX. , ,
, StAX.
12.4 , order.xml SAX, . SaxParsing
DefaultHandler,
(ContentHandler, ErrorHandler, DTDHandler
EntityResolver). SAXParserFactory SAX.
, javax.xml.par
sers.SAXParserFactory SAX. SAXParser
SAXReader, getXMLReader(),
, parse() SAX,

480 12. XML JSON


, (,
StartElement).
12.4. SAX, ,

public class SaxParsing extends DefaultHandler {


private
private
private
private

List<OrderLine> orderLines = new ArrayList<>();


OrderLine orderLine;
Boolean dealingWithUnitPrice = false;
StringBuffer unitPriceBuffer;

public List<OrderLine> parseOrderLines() {


try {
File xmlDocument = Paths.get("src/main/resources/order.xml").toFile();
// SAX
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
//
saxParser.parse(xmlDocument, this);
} catch (SAXException | IOException | ParserConfigurationException e) {
e.printStackTrace();
}
return orderLines;
}
@Override
public void startElement(String namespaceURI, String localName, String
qualifiedName,
Attributes attrs) throws SAXException {
switch (qualifiedName) {
// order_line
case "order_line":
orderLine = new OrderLine();
for (int i= 0; i< attrs.getLength(); i++) {
switch (attrs.getLocalName(i)) {
case "item":
orderLine.setItem(attrs.getValue(i));
break;
case "quantity":
orderLine.setQuantity(Integer.valueOf(attrs.getValue(i)));
break;
}
}
break;
case "unit_price":

481
Java XML
dealingWithUnitPrice = true;
unitPriceBuffer = new StringBuffer();
break;

}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException
if (dealingWithUnitPrice)
unitPriceBuffer.append(ch, start, length);
}

@Override
public void endElement(String namespaceURI, String localName, String
qualifiedName)
throws SAXException {
switch (qualifiedName) {
case "order_line":
orderLines.add(orderLine);
break;
case "unit_price":
orderLine.setUnitPrice(Double.valueOf(unitPriceBuffer.toString()));
dealingWithUnitPrice = false;
break;
}
}
}

ContentHandler
, , startDocument,
endDocument, startElement endElement. ,
XML. , (.12.4), startElement , order_Line
unit_price, OrderLine,
. ContentHandler characters(), , XML
( (.12.4) characters()
).
XML Error
Handler SAXReader. ErrorHandler
(warning, error fatalError) .
DTDHandler ,
DTD. DTDHandler, . DTD

.

482 12. XML JSON

JAXP DOM
JAXP XML- DOM API. javax.xml.parsers.DocumentBuilderFactory.
DocumentBuilder, 12.5. parse DocumentBuilder,
XML- org.w3c.dom.Document.
(, ),
org.w3c.dom.Node. , , newDocument() DocumentBuilder.
12.5. DOM, ,

public class DomParsing {


public List<OrderLine> parseOrderLines() {
List<OrderLine> orderLines = new ArrayList<>();
try {
File xmlDocument = Paths.get("src/main/resources/order.xml").toFile();
// DOM
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//
DocumentBuilder documentBuilder = factory.newDocumentBuilder();
Document document = documentBuilder.parse(xmlDocument);
// order_line
NodeList orderLinesNode = document.getElementsByTagName("order_line");
for (int i= 0; i< orderLinesNode.getLength(); i++) {
Element orderLineNode = (Element) orderLinesNode.item(i);
OrderLine orderLine = new OrderLine();
orderLine.setItem(orderLineNode.getAttribute("item"));
orderLine.setQuantity(Integer.valueOf(orderLineNode.
getAttribute("quantity")));
Node unitPriceNode = orderLineNode.getChildNodes().item(1);
orderLine.setUnitPrice(Double.valueOf(unitPriceNode.getFirstChild().
getNodeValue()));
}
}

orderLines.add(orderLine);

catch (SAXException | IOException | ParserConfigurationException e) {


e.printStackTrace();

}
return orderLines;

483
Java XML
order.xml, .
Document order_Line quantity (, GetAttribute("quantity")), OrderLine.
,
DOM,
javax.xml.parsers.DocumentBuilderFactory.

JAXP XSLT
JAXP XML- XSLT
API. XSLT XML- XML
XML- (.12.3).
12.6 order.xml (.12.1) HTML- XSLT, (. 12.3). newInstance() javax.xml.trans
form.TransformerFactory TransformerFactory.
newTransformer()
XSLT. order.xml HTML.
12.6. XML- XSLT

public class XsltTransforming {


public String transformOrder() {
StringWriter writer = new StringWriter();
try {
File xmlDocument = Paths.get("src/main/resources/order.xml").toFile();
File stylesheet = Paths.get("src/main/resources/order.xsl").toFile();
TransformerFactory factory =
TransformerFactory.newInstance("net.sf.saxon.TransformerFactoryImpl",

null);

//
Transformer transformer = factory.newTransformer(new
StreamSource(stylesheet));
transformer.transform(new StreamSource(xmlDocument), new
StreamResult(writer));
}
}

catch (TransformerException e) {
e.printStackTrace();

return writer.toString();

484 12. XML JSON

Java XML
Java XML: API,
JDK, javax.xml.stream.XMLStreamWriter java.beans.XMLEncoder,
, SAX, DOM JAXP.
(JSR 222) Java XML (JAXB) , SAX DOM,
. JAXB Java XML
. Java, XML.
12.7 CreditCard JAXB @ja
vax.xml.bind.annotation.XmlRootElement. JAXB CreditCard XML.
12.7. CreditCard JAXB

@XmlRootElement
public class CreditCard {
private
private
private
private

String number;
String expiryDate;
Integer controlNumber;
String type;

// ,
}

@XmlRootElement
Java. JAXB XML CreditCard , XML-,
12.8.
12.8. XML-,

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>


<creditCard>
<controlNumber>566</controlNumber>
<expiryDate>10/14</expiryDate>
<number>12345678</number>
<type>Visa</type>
</creditCard>

XML (.12.2). JAXB. XML- 12.8


CreditCard , .
JAXB XML- XML- (XSD) , - ,
XSD. JAXB ,
XML- , ,
( schemagen, JDK).
12.9 XML- (XSD) CreditCard.

485
Java XML

.12.2. JAXB
12.9. XML-

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>


<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="creditCard" type="creditCard"/>
<xs:complexType name="creditCard">
<xs:sequence>
<xs:element name="controlNumber" type="xs:int" minOccurs="0"/>
<xs:element name="expiryDate" type="xs:string" minOccurs="0"/>
<xs:element name="number" type="xs:string" minOccurs="0"/>
<xs:element name="type" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:schema>

, , ( controlN umb er ,
ExpiryDate ..) (creditCard). , xs (xs:element, s:string ..). xmlns (
XML):
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema" >

486 12. XML JSON



, . , , ,
(,
<element> ).
JAXB
Java XML-. Java XML , . , JAXB
XML- . ,
JAXB XML-, Java SAX DOM
.

JAXB API, javax.xml.bind, XML- Java.


, . JAXB . .12.7
JAXB.
12.7. JAXB

javax.xml.bind

,
,

javax.xml.bind.annotation


Java XML-

javax.xml.bind.annotation.adapters - JAXB
javax.xml.bind.attachment

javax.xml.bind.helpers

javax.xml.binding

javax.xml.bind.util

(..12.2),
JAXB- XML-.
, XML- . / JAXB
XML XSD (.12.9). JAXB

.

487
Java XML
JAXB API javax.xml.bind.JAXBContext. XML- Java,
:
Unmarshaller, XML- , , XML;
Marshaller, XML.
, CreditCard XML (12.10), Marshaller.marshal(). ;
(StringWriter XML, FileOutputStream ).
12.10. Main, CreditCard

public class Main {


public static void main(String[] args) throws JAXBException {
CreditCard creditCard = new CreditCard("1234", "12/09", 6398, "Visa");
StringWriter writer = new StringWriter();
JAXBContext context = JAXBContext.newInstance(CreditCard.class);
Marshaller m= context.createMarshaller();
m.marshal(creditCard, writer);
System.out.println(writer.toString());
}
}

JAXBContext newInstance(), ,
(CreditCard.class). Marshaller
marshal(), XML- (.12.8) , ,
StringWriter . XML- Unmarshaller.unmarshal().
Metro, JAXB, ,
(xjc) (schemaGen). /
XML-,
XML-.
( Java SE7) Maven.

JAXB JPA.
, , JAXB
XML-. , JPA, JAXB ( javax.xml.bind.annotation), ,

488 12. XML JSON



. @Entity, JAXB
@XmlRootElement (12.11).
12.11. CreditCard

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class CreditCard {
@XmlAttribute(required = true)
private String number;
@XmlElement(name = "expiry-date", defaultValue = "01/10")
private String expiryDate;
private String type;
@XmlElement(name = "control-number")
private Integer controlNumber;
// ,
}

@XmlRootElement JAXB, CreditCard XML-. , JAXB


.
, 12.12 JAXB ( ).
12.12.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>


<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="creditCard" type="creditCard"/>
<xs:complexType name="creditCard">
<xs:sequence>
<xs:element name="expiry-date" type="xs:string" default="01/10"
minOccurs="0"/>
<xs:element name="type" type="xs:string" minOccurs="0"/>
<xs:element name="control-number" type="xs:int" minOccurs="0"/>
</xs:sequence>
<xs:attribute name="number" type="xs:string" use="required"/>
</xs:complexType>
</xs:schema>

Marshaller XML-
CreditCard (.12.10). <creditCard> CreditCard .
JAXB XML. XML (<element></element> )
(<element attribute=""/>). JAXB , -

489
Java XML
: @XmlAttribute @XmlElement. , ,
, ..
XML- , @XmlAttribute.
, (.12.11), , ( )
.
, <xs:attribute>,
01/10 (.12.12).
XML- CreditCard ,
12.13 ( (.12.8)).
12.13. XML-, CreditCard

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>


<creditCard number="1234">
<expiry-date>12/09</expiry-date>
<type>Visa</type>
<control-number> 6398</control-number>
</creditCard>

.12.8 JAXB.
( ), ,
(, @XmlSchema).
12.8. JAXB

@XmlAccessorType


(FIELD, NONE, PROPERTY, PUBLIC_MEMBER)

@XmlAttribute

XML- (String, Boolean, Integer ..)

@XmlElement

transient XML-

@XmlElements


@XmlElement

@XmlEnum

XML

@XmlEnumValue

@XmlID

XML (
String), @XmlIDREF (
XML Schema ID IDREF)

@XmlIDREF

XML IDREF

@XMLList

@XmlMimeType

MIME

490 12. XML JSON


12.8 ()

@Xmlns

XML

@XmlRootElement

,
XML

@XmlSchema

XML

@XmlTransient

JXB,
( transient Java
@Transient JPA)

@XmlType

XML

@XMLValue


XML-. -, . JPA,
,
, (, , ..).
- : WSDL,
XML. , WSDL . , JAXB
-.

JPA , JPA JAXB , ( XML).
, JAXB XML. . 14,
@Entity, @XmlRootElement.

JSON
JavaScript (JSON)
, , XML.
-.
XML JSON
JavaScript -. JSON, . 12.14 JSON-
XML,
(.12.1).

491
JSON
12.14. JSON

{
"order": {
"id": "1234",
"date": "05/06/2013",
"customer": {
"first_name": "",
"last_name": "",
"email": "j.rorri@me.com",
"phoneNumber": "+4412341234"
},
"content": {
"order_line": [
{
"item": "H2G2",
"quantity": "1",
"unit_price": "23.5"
},
{
"item": " ",
"quantity": "2",
"unit_price": "34.99"
}
]
},
"credit_card": {
"number": "1357",
"expiry_date": "10/13",
"control_number": "234",
"type": "Visa"
}
}
}

JSON- JSON,
, XML. , , .
, "":"",
. , JSON,
.
JSON. JSON , ,
. API JSON. JSON
Java. JSON
(, , null) (
). .12.9 JSON
.

492 12. XML JSON


12.9. JSON

JSON Java, ,
JSON


Unicode, ,

JSON
: , , ,

.
([,]) . (,)

JSON Java . JSON


/. ({,})
. / JSON
(,) POJO Java

JSON , . JSON , . , JSON JSON. ,


(.12.14), content ,
order_line.

JSON
JSON JavaScript. JSON
RFC 4627 IETF (Internet Engineering Task Force
) 2006. IETF
, , ,
.
JSON application/json (.15 RESTful), JSON .json. JSON W3C, W3C
API JSON , JSON-LD, JSONPath, JSONT JSONiq. ,
API JSON.
Java , , / JSON, JSON-Lib, fastjson,
Flexjson, Jettison, Jackson .. ( http://json.org, Java API JSON);
.

493
JSON
Java API JSON, JSR 353
(Java API JSON) JCP 2011
Java EE7.

JSON-P
Java API JSON (JSR 353), JSON-P, ,
JSON Java.
, , JSON. JSON-P Java JSON API, DOM XML.
JSON , StAX XML.
JSR,
JSON-P JSON
Java ( JSR, JSON-B, B binding ()). .12.10
JSON-P.
12.10. JSON-P

javax.json

API JSON (, JsonArray JSON JsonObject JSON), , ,


JSON

javax.json.spi

(Service Provider Interface)


JsonParser JsonGenerator

javax.json.stream

API JSON


JSON Java,
JSON-P(JSR 353) JSON RI.

JSON
JSON-P
JSON-: API , API. DOM
API XML, API JSON-
, JSON- . DOM API, API .
API API,
JSON. API StAX
API XML. JSON
. API ,

494 12. XML JSON


, ( ).
JSON JSON .
JSR 353 API javax.json.Json,
, JSON. API JsonParser , JsonGenerator , JsonWriter , JsonReader ,
JsonArrayBuilder JsonObjectBuilder.

JSON
JSON javax.json.JsonObject
javax.json.JsonArray. API
.
JsonObject
/. JSONArray
. API
JsonObject JSONArray javax.json.Json
ObjectBuilder javax.json.JsonArrayBuilder.
12.15 , JSON,
(.12.14). , Json
JsonObjectBuilder JsonArrayBuilder, JsonObject ( build()). JsonObject / JSON.
12.15. OrderJsonBuilder JSON,

public class OrderJsonBuilder {


public JsonObject buildPurchaseOrder() {
return

Json.createObjectBuilder().add("order", Json.createObjectBuilder()
.add("id", "1234")
.add("date", "05/06/2013")
.add("customer", Json.createObjectBuilder()
.add("first_name", "")
.add("last_name", "")
.add("email", "j.rorri@me.com")
.add("phoneNumber", "+4412341234"))
.add("content", Json.createObjectBuilder()
.add("order_line", Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("item", "H2G2")
.add("quantity", "1")
.add("unit_price", "23.5"))
.add(Json.createObjectBuilder( )
.add("item", " ")
.add("quantity", "2")
.add("unit_price", "34.99"))))
.add("credit_card", Json.createObjectBuilder( )
.add("number", "1357")

495
JSON
.add("expiry_date", "10/13")
.add("control_number", "234")
.add("type", "Visa"))).build();
}
}

JsonObject
(, InputStream Reader), javax.json.JsonReader.
, JsonObject
JsonReader. JsonReader order.json (.12.14). , order,
getJsonObject(), JsonObject. , null:
JsonReader reader = Json.createReader(new FileReader("order.json"));
JsonObject jsonObject = reader.readObject();
jonObject = jsonObject.getJsonObject("order");
JsonReader read() javax.json.JsonStructure (JsonObject JSONArray).
JsonStructure.getValueType() ValueType (ARRAY, OBJECT, STRING,
NUMBER, TRUE, FALSE, NULL), . toString()
JsonStructure JSON .
JsonObject JSONArray (, OutputStream Writer) javax.json.JsonWriter. Json.createWriter() JsonWriter
.

JSON
API ( javax.json.stream) JSON ,
. javax.json.stream.JsonParser JSON. - javax.json.Json, createParser(),
javax.json.stream.JsonParser
(, Reader InputStream). , JSON, JSON, :
StringReader reader = new StringReader("{}");
JsonParser parser = Json.createParser(reader);

, createParserFactory()
Map. JsonParser,
JSON:
StringReader reader = new StringReader("{}");
JsonParserFactory factory = Json.createParserFactory(properties);
JsonParser parser = factory.createParser(reader);
JsonParser .
, , /

496 12. XML JSON


JSON / /. .12.11
, .
12.11. JSon

START_OBJECT

JSON (,
{)

END_OBJECT

JSON (,
})

START_ARRAY

JSON (,
[)

END_ARRAY

JSON (,
])

KEY_NAME

()/ JSON

VALUE_STRING

string

VALUE_NUMBER

number

VALUE_TRUE

true

VALUE_FALSE

false

VALUE_NULL

null

12.16 JSON, (.12.14)


( order.json), .
, email. next()
.
javax.json.stream.JsonParser.Event (..12.11)
.
email, .
12.16. OrderJsonParser,
JSON

public class OrderJsonParser {


public String parsePurchaseOrderAndReturnEmail() throws
FileNotFoundException {
String email = null;
JsonParser parser = Json.createParser(new FileReader("src/main/resources/
order.json"));
while (parser.hasNext()) {
JsonParser.Event event = parser.next();
while (parser.hasNext() && !(event.equals(JsonParser.Event.KEY_NAME) &&
parser.getString().matches("email"))) {
event = parser.next();
}
if (event.equals(JsonParser.Event.KEY_NAME) &&

497
JSON
parser.getString().matches("email")) {
parser.next();
email = parser.getString();
}
}
return email;
}
}

Event.equals(),
JSON . JsonParser JSON,
getString(), ,
() . , KEY_NAME, ,
VALUE_STRING, ,
VALUE_NUMBER. getString(),
, , getIntValue(),
getLongValue() getBigDecimalValue() .
,
, javax.json.stream.Json
ParsingException java.lang.IllegalStateException,
.

JSON
API JSON JSON . JsonParser
JSON , ja
vax.json.stream.JsonGenerator JSON ,
.
12.17 createGenerator()
javax.json.Json JsonGenerator JSON-
, (.12.14). /
JSON JSON.
12.17. , , JSON

public class OrderJsonGenerator {


public StringWriter generatePurchaseOrder() throws IOException {
StringWriter writer = new StringWriter();
JsonGenerator generator = Json.createGenerator(writer);
generator.writeStartObject()
.write("id", "1234")
.write("date", "05/06/2013")
.writeStartObject("customer")
.write("first_name", "")
.write("last_name", "")
.write("email", "j.rorri@me.com")
.write("phoneNumber", "+4412341234")
.writeEnd()

498 12. XML JSON


.writeStartArray("content")
.writeStartObject()
.write("item", "H2G2")
.write("unit_price", "23.5")
.write("quantity", "1")
.writeEnd()
.writeStartObject()
.write("item", " ")
.write("unit_price", "34.99")
.write("quantity", "2")
.writeEnd()
.writeEnd()
.writeStartObject("credit_card")
.write("number", "123412341234")
.write("expiry_date", "10/13")
.write("control_number", "234")
.write("type", "Visa")
.writeEnd()
.writeEnd()
.close();
return writer;
}
}

JSON . JSON- / , JSON . writeStartObject()


JSON ({), writeStartArray() JSON ([).
writeEnd().
.
writeStartObject() , , writeStartArray() -.

, , .
, .
JsonGenerator , write(),
/ JSON
.
flush()
, close()
.


, POJO CreditCard JAXB
JSON-P, XML- JSON- .
. CreditCardXMLTest -

499

CreditCard, ,
XML . CreditCardJSonTest ,
JSON.

CreditCard
CreditCard 12.18 JAXB- @XmlRootElement, XML. JAXB @XmlAccessorType
XmlAccessType.FIELD JAXB , .
12.18. CreditCard JAXB

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class CreditCard {
@XmlAttribute
private String number;
@XmlElement(name = "expiry_date")
private String expiryDate;
@XmlElement(name = "control_number")
private Integer controlNumber;
private String type;
//,
}

CreditCard , ,
( MM/YY), (Visa, Master Card,
American Express ..), .
@XmlAttribute XML.
@XmlElement XML.

CreditCardXMLTest
CreditCardXMLTest, 12.19, CreditCard JAXB.
ShouldMarshallACreditCard CreditCard ,
XML. shouldUnmarshallACreditCard XML-
CreditCard , .
12.19. CreditCardXMLTest XML

public class CreditCardXMLTest {


public static final String creditCardXML =
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
"<creditCard number=\"12345678\">\n" +
"<expiry_date>10/14</expiry_date>\n" +
"<control_number>566</control_number>\n" +
"<type>Visa</type>\n" +
"</creditCard>";
@Test

500 12. XML JSON


public void shouldMarshallACreditCard() throws JAXBException {
CreditCard creditCard = new CreditCard("12345678", "10/14", 566, "Visa");
StringWriter writer = new StringWriter();
JAXBContext context = JAXBContext.newInstance(CreditCard.class);
Marshaller m= context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(creditCard, writer);
System.out.println(writer);
assertEquals(creditCardXML, writer.toString().trim());
}
@Test
public void shouldUnmarshallACreditCard() throws JAXBException {
StringReader reader = new StringReader(creditCardXML);
JAXBContext context = JAXBContext.newInstance(CreditCard.class);
Unmarshaller u= context.createUnmarshaller();
CreditCard creditCard = (CreditCard) u.unmarshal(reader);
assertEquals("12345678", creditCard.getNumber());
assertEquals("10/14", creditCard.getExpiryDate());
assertEquals((Object) 566, creditCard.getControlNumber());
assertEquals("Visa", creditCard.getType());
}
}

CreditCardJSonTest
CreditCardJSonTest, 12.20, API JsonGenerator
CreditCard JSON. ,
JsonObject , creditCardJSon.
12.20. CreditCardJSonTest JSon

public class CreditCardJSonTest {


public static final String creditCardJSon =
"{\"creditCard\":" +
"{\"number\":\"12345678\"," +
"\"expiryDate\":\"10/14\"," +
"\"controlNumber\":566," +
"\"type\":\"Visa\"}" +
"}";
@Test
public void shouldGenerateACreditCard(){
CreditCard creditCard = new CreditCard("12345678", "10/14", 566, "Visa");
StringWriter writer = new StringWriter();
JsonGenerator generator = Json.createGenerator(writer);

501

generator.writeStartObject()
.writeStartObject("creditCard")
.write("number", creditCard.getNumber())
.write("expiryDate", creditCard.getExpiryDate())
.write("controlNumber", creditCard.getControlNumber())
.write("type", creditCard.getType())
.writeEnd()
.writeEnd()
.close();
assertEquals(creditCardJSon, writer.toString().trim());
}
}

XML , .
. Java , API , XML-. Java , DOM, SAX StAX.
Java API XML DOM SAX, JAXP API - XML- DOM-
SAX- XML- XSLT XPath.
Java XML (JAXB)
Java- XML . , . JAXB Java,
-, , , XML, 14.
JSON . XML,
. JSON-P JSON
. JAXB JSON , ,
JAX-RS, JSON-P JSON- -
RESTful (.15).

13.

, ,
: , EJB, , ..
, ,
. EJB (
@Asynchronous), Java EE
( ). ,
.
, (MOM), (),
.
,
(, ,
). , ,
, .
,
.
, . MOM , RMI, .
,
, . MOM , .
,
, . , , .

, (MOM), . , -

503

, ,
( ). , , , . ,
, . , , , .
.13.1.

.13.1. MOM

Java EE API, , JMS (Java


Message Service Java). ,
, ,
. JMS , API,
, .
EJB MDB (Message-Driven Beans ) , .

(.13.2).
. JMS API,
, (
). .
. Java ,
.
, , , , .
. , .
.
( ) JNDI ( ).
,
, ,
(..13.1). ,
.

504 13.

.13.2.

(point-to-point, P2P). , , .
, . ,
.
- (publish-subscribe, pub-sub). .
.


P2P . , (.13.3). ,
,
. ,
, , ,
. ,
, , .

.13.3. P2P

,
. .

505

P2P , . , , ,
. .13.4
, .

.13.4.

, P2P
( ). , , -
.

-
- . , (.13.5). , .
/, .

.13.5. /

, . P2P,
, , ,
, ,
. , ,
JMS API ,
.

506 13.
. /
, . .13.6 , (
).

.13.6.


, , .
JNDI. JDBC,
. :

;
, ,
;
(P2P) (pub-sub).
,
JNDI .
GlassFish , :
, asadmin
REST. JMS 2.0,
@JMSConnectionFactoryDefinition @JMSDestinationDefinition, .

,
, (Message-Driven Beans, MDB)
, EJB. 79, EJB
(, , ,
..), MDB . MDB
, , EJB ,

507

, ,
. , , MDB; MDB
, MDB.
MDB ( )
. - , ,
. , MDB .
MDB , , , ,
(, ).


Java JMS, , (Java SE) (Java EE) . MDB
EJB, ,
EJB.


1980- .
, ,
(). - ,
,
. . 1980- , .
MOM ,
.
, , .
JMS 1998.
,
Java. JSR 914
(JMS 1.0.1, 1.0.2 1.0.2b),
1.1 2002. JMS 1.1 J2EE 1.2
Java EE. JMS MDB Web Profile. , ,
Java EE7.

508 13.

JMS 2.0
JMS 1.1 . API Java EE 5, JMS, , (, ...). JMS
, API. , JMS API
, :
Connection, Session close() java.jang.AutoCloseable,
try-with-resources Java SE 7;
API, API;
getBody, Message
;
,
JMSRuntimeException;
,
.

EJB 3.2
EJB 2.0 MDB, EJB 3.0,
Java EE 5 . ,
,
. EJB 3.2 (JSR 345) MDB,
( ).
7,
, ( @Asynchronous). Java EE
EJB. , JMS MDB ,
( JMS, , ..),
. MDB, .


Open Message Queue (OpenMQ) JMS. 2006 JMS . OpenMQ
GlassFish.
, (UMS),
, XML, .

509
Java Messaging Service API

Java Messaging Service API


JMS API Java, ,
, .
, . JMS JDBC: (Derby, MySQL, Oracle, DB2 .), JMS
(OpenMQ, MQSeries, SonicMQ ..).
JMS API . JMS

. JMS 1.0, 1.1 2.0
, API.
JMS 1.0 . - API,
() - ().
, , QueueConnectionFactory TopicConnectionFactory API
ConnectionFactory. :
P2P pub-sub.
JMS 1.1 API ( API) , P2P, pub-sub.
.13.1 (, Session)
(QueueSession, TopicSession).
13.1. JMS

API

API

API
(P2P)

API
(pub-sub)

ConnectionFactory

ConnectionFactory

QueueConnection
Factory

TopicConnection
Factory

Connection

JMSContext

QueueConnection

TopicConnection

Session

JMSContext

QueueSession

TopicSession

Destination

Destination

Queue

Topic

Message

Message

Message

Message

MessageConsumer

JMSConsumer

QueueReceiver

TopicSubscriber

MessageProducer

JMSProducer

QueueSender

TopicPublisher

JMSException

JMSRuntime
Exception

JMSException

JMSException

JMS 1.1 API


JPA EJB. JMS 2.0 API,
API, , . (..13.1)
API ( javax.jms).
API,
API, -, ,

510 13.
API JMS 1.1, -, , API
.

API
API JMS , (.13.7).
, , , . .

.13.7. API JMS

ConnectionFactory
,
Connection. javax.jms.ConnectionFactory ,
, .
, ConnectionFactory,
JNDI ( ). ,
JNDI InitialContext
ConnectionFactory JNDI:

511
Java Messaging Service API
Context ctx = new InitialContext();
ConnectionFactory ConnectionFactory =
(ConnectionFactory) ctx.lookup("jms/javaee7/
ConnectionFactory");

, (13.1), createConnection, Connection, createContext, JMS 2.0, JMSContext . Connection


JMSContext
.
13.1. ConnectionFactory

public interface ConnectionFactory {


Connection createConnection() throws JMSException;
Connection createConnection(String userName, String password) throws
JMSException;
JMSContext createContext();
JMSContext createContext(String userName, String password);
JMSContext createContext(String userName, String password, int sessionMode);
JMSContext createContext(int sessionMode);
}


, , . JMS javax.jms.De
stination . ,
JNDI:
Context ctx = new InitialContext();
Destination queue = (Destination) ctx.lookup("jms/javaee7/Queue");

Javax.jms.Connection, , create
Connection() , JMS.
, .
(javax.jms.Session)
,
. , :
Connection connection = connectionFactory.createConnection();

,
start(). ,
stop():
connection.start();
connection.stop();

512 13.
, .
, :
connection.close();

createSession().
, ,
, .
, , ,
JMS , . :
Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);

, .
true, , commit(), . false, send().
, , . ,
.

;
, .
, (.13.8):
;
/,
;
;

(, , ..).

/, , . ,
. ,
javax.jms.Message. , send() publish(). .13.2 JMS.

513
Java Messaging Service API

.13.8. JMS
13.2. ,

JMSDestination

send()
publish()

JMSDeliveryMode

JMS . PERSISTENT
,
- . NON_ PERSISTENT
,

send()
publish()

JMSMessageID

, ,

send()
publish()

JMSTimestamp

send()
publish()

JMSCorrelationID

, -
,

JMSReplyTo

,
-

JMSRedelivered

JMSType

JMSExpiration

,

send()

send()
publish()

JMSPriority

JMS
send()
, 0 , publish()
9

514 13.

, javax.jms.Message
, , , .
, .
boolean, byte, short, int, long, float, double String. :
message.setFloatProperty("orderAmount", 1245.5f);
message.getFloatProperty("orderAmount");


,
.
, .13.3.
13.3.

StreamMessage
MapMessage
TextMessage
ObjectMessage
BytesMessage

,
Java.
, /,
String, Java
, (, XML)
,

,

, , javax.jms.Message. , . ,
. getText() setText(),
- getObject() setObject() ..:
textMessage.setText("This is atext message");
textMessage.getText();
bytesMessage.readByte();
objectMessage.getObject();

JMS 2.0 <T>TgetBody(Class<T> c)


.


API
, , JMS API . JMS

515
API
, .
, . : ( ) ( -). 13.2
, .
13.2. -
API

public class Producer {


public static void main(String[] args) {
try {
// JNDI
Context jndiContext = new InitialContext();
//
ConnectionFactory connectionFactory = (ConnectionFactory)
jndiContext.lookup("jms/javaee7/ConnectionFactory" );
Destination queue = (Destination) jndiContext.lookup("jms/javaee7/Queue");
//
Connection connection = connectionFactory.createConnection();
Session session = connection.createSession(false, Session.AUTO_
ACKNOWLEDGE);
MessageProducer producer = session.createProducer(queue);
//
TextMessage message = session.createTextMessage("
" + new
Date());
producer.send(message);
connection.close();
}

catch (NamingException | JMSException e) {


e.printStackTrace();

}
}
}

Producer, main().
, , JNDI ConnectionFactory Destination.
( ) ( OpenMQ GlassFish). JNDI (, jms/javaee7/Queue); JNDI.
, Producer
ConnectionFactory, Connection,
Session. MessageProducer (session.createProducer(queue)).

516 13.
( ). ,
main JNDI NamingException, JMSException.
, ,
. , Consumer 13.3
: JNDI, , . , MessageProducer MessageConsumer
, ( , ,
). ,
.
13.3. -
API

public class Consumer {


public static void main(String[] args) {
try {
// JNDI
Context jndiContext = new InitialContext();
//
ConnectionFactory connectionFactory = (ConnectionFactory)
jndiContext.lookup("jms/javaee7/ConnectionFactory");
Destination queue = (Destination) jndiContext.lookup("jms/javaee7/Queue");
//
Connection connection = connectionFactory.createConnection();
Session session = connection.createSession(false, Session.AUTO_
ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(queue);
connection.start();
//
while (true) {
TextMessage message = (TextMessage) consumer.receive();
System.out.println(" : " + message.getText());
}
} catch (NamingException | JMSException e) {
e.printStackTrace();
}
}
}

API
, , (.13.2 13.3),
. , (ConnectionFactory, Connection, Session...).
JMSException, -

517
API
(JMSException ). API JMS 1.1
2002 JMS 2.0.
JMS 2.0 , API,
(JMSContext , JMSProducer JMSConsumer ).
ConnectionFactory API, .
JMSRuntimeException, ,
( ).
.13.9 API. , , API javax.jms.

.13.9. JMS API

API , , . :
JMSContext JMS
;
JMSProducer , JMSContext, ;
JMSConsumer , JMSContext,
, .

JMSContext
JMSContext JMS API, JMS2.0.

API

518 13.
JMS 1.1: Connection ( JMS) Session ( ).
JMSContext
CreateContext ConnectionFactory (.13.1),
( ). ,
(EJB Web), JMSContext
@Inject ( ).
,
createProducer JMSProducer,
. ,
.
createConsumer JMSConsumer .
.13.4 API JMSContext.
13.4. API JMSContext

void start()

( )

void stop()

void close()

JMSContext

void commit()

,
,

void rollback()

,
,

ByteMessage createByteMessage()

ByteMessage

MapMessage create MapMessage()

MapMessage

Message createMessage()

Message

ObjectMessage create
ObjectMessage()

ObjectMessage

StreamMessage
createStreamMessage()

StreamMessage

TextMessage createTextMessage()

TextMessage

TopicMessage createTopic(String
topicName)

Topic

Queue createQueue(String
queueName)

Queue

JMSConsumer create
JMSConsumer
Consumer(Destination destination)
JMSConsumer
createConsumer(Destination
destination, String message
Selector)

JMSConsumer

519
API

JMSProducer createProducer()

JMSProducer,

JMSContext createContext(int
sessionMode)

JMSContext

JMSProducer
JMSProducer JMSContext. -

. JMSProducer JMSContext createProducer.


, ,
(. .13.8) . .13.5
JMSProducer API.
13.5. JMSProducer API

get/set[Type]Property

,
[Type] ,
Boolean, Byte, Double, Float, Int, Long, Object, Short,
String

JMSProducer clearProperties()

Set<String> getPropertyNames()

boolean propertyExists(String
name)

get/set[Message Header]

, [Message Header]
DeliveryDelay, DeliveryMode, JMSCorrelationID,
JMSReplyTo, JMSType, Priority, TimeToLive

JMSProducer send(Destination
destination, Message message)

, ,

JMSProducer send(Destination
destination, String body)

TextMessage

JMSConsumer
JMSConsumer . JMSContext createConsumer, . , JMSConsumer

, .
.
JMSConsumer MessageListener.

520 13.
, OnMessage MessageListener. .13.6 JMSConsumer API.
13.6. JMSConsumer API

void close()

JMSConsumer

Message receive()

Message receive(long timeout)

<T> TreceiveBody(Class<T> c)

Message receiveNoWait()

void setMessageListener(MessageListener
listener)

MessageListener

MessageListener getMessageListener()

MessageListener

String getMessageSelector()


JMS API
, API.
: ConnectionFactory Destination. , (EJB , Web ACC),
JNDI, . ,
API JMSContext API . , JMSContext ( ).
,
.


(JMSProducer) , JMSContext,
.
, ,
(13.4) - ( Java SE).
1. JNDI.
2. JMSContext (
try-with-resources, JMSContext).
3. javax.jms.JMSProducer JSMContext.
4. JMSProducer.
send().

521

13.4.

public class Producer {


public static void main(String[] args) {
try {
// JNDI
Context jndiContext = new InitialContext();
//
ConnectionFactory connectionFactory = (ConnectionFactory)
jndiContext.lookup("jms/javaee7/ConnectionFactory");
Destination queue = (Destination) jndiContext.lookup("jms/javaee7/Queue");
//
try (JMSContext context = connectionFactory.createContext()) {
context.createProducer().send(queue, " " + new
Date());
}
} catch (NamingException e) {
e.printStackTrace();
}
}
}

, API
(.13.2), , . , API JMSRuntime
Exception, .


,

JNDI, JNDI API . ,
. Java EE7 : EJB, ,
(ACC). , @Resource . Java EE7 , ,
JNDI, . .
.13.7 , @Resource.
13.7. API @javax.annotation.Resource

name

JNDI ( )

type

Java (, javax.sql.DataSource javax.jms.Topic)


522 13.
13.7 ()

authentication , ( ,
Type
)
shareable

mappedName

lookup

JNDI, .

JNDI

description

@Resource, (.13.4), ,
, JNDI.
(.13.4)
JNDI. 13.5 JNDI @Resource.
ProducerEJB , ConnectionFactory Queue
.
13.5. ProducerEJB,
@Resource

@Stateless
public class ProducerEJB {
@Resource(lookup = "jms/javaee7/ConnectionFactory")
private ConnectionFactory connectionFactory;
@Resource(lookup = "jms/javaee7/Queue")
private Queue queue;
public void sendMessage() {
try (JMSContext context = connectionFactory.createContext()) {
context.createProducer().send(queue, " " + new Date());
}
}
}

, (.13.4),
JNDI NamingException.
, EJB.


CDI
(EJB )
CDI, JMSContext.
( JMSContext).
@Inject @JMSConnectionFactory.

523

javax.jms.JMSConnectionFactory ,
ConnectionFactory JNDI, JMSContext
(13.6). JMSConnectionFactory , JMS.
13.6.
@Inject

public class Producer {


@Inject
@JMSConnectionFactory("jms/javaee7/ConnectionFactory")
private JMSContext context;
@Resource(lookup = "jms/javaee7/Queue")
private Queue queue;
public void sendMessage() {
context.createProducer().send(queue, " " + new Date());
}
}

.
.
, .
javax.jms.JMSPasswordCredential ,
, JMSContext:
@Inject
@JMSConnectionFactory("jms/connectionFactory")
@JMSPasswordCredential(userName="admin",password="mypassword")
private JMSContext context;


JMSConsumer, .
JMSConsumer Queue Topic create
Consumer() JMSContext.
, . :
,
receive();
,
, ; MessageListener, , ,
, onMessage().
.13.10 .


JMSContext, ,
,

524 13.

.13.10.

receive() (..13.6). receive(), . , ,


(13.7).
1. , JNDI ( ).
2. JMSContext .
3. javax.jms.JMSConsumer JSMContext.
4. receive() ( receiveBody)
-. receive() ,
, . .
13.7. -

public class Consumer {


public static void main(String[] args) {
try {
// JNDI
Context jndiContext = new InitialContext();
//
ConnectionFactory connectionFactory = (ConnectionFactory)
jndiContext.lookup("jms/javaee7/ConnectionFactory");
Destination queue = (Destination) jndiContext.lookup("jms/javaee7/Queue");
//
try (JMSContext context = connectionFactory.createContext()) {
while (true) {
String message = context.createConsumer(queue).receiveBody
(String.class);
}

525

}
}

catch (NamingException e) {
e.printStackTrace();

}
}
}

, (.13.3), , API .

, @Resource, @Inject @JMSConnectionFactory (.13.5 13.6), . ,
Java SE, , ,
.


. ( ), MessageListener.
,
.
, onMessage(), Message. .
MDB ( ).
(13.8).
1. javax.jms.MessageListener,
onMessage().
2. JNDI (
).
3. javax.jms.JMSConsumer JSMContext.
4. setMessageListener()
MessageListener (13.8 Listener
MessageListener).
5. onMessage() .
, , , .
13.8.

public class Listener implements MessageListener {


public static void main(String[] args) {
try {

526 13.
// JNDI
Context jndiContext = new InitialContext();
//
ConnectionFactory connectionFactory = (ConnectionFactory)
jndiContext.lookup("jms/javaee7/ConnectionFactory");
Destination queue = (Destination) jndiContext.lookup("jms/javaee7/
Queue");
try (JMSContext context = connectionFactory.createContext()) {
context.createConsumer(queue).setMessageListener(new Listener());
}
}

catch (NamingException e) {
e.printStackTrace();

}
}
public void onMessage(Message message) {
System.out.println(" : " +
message.getBody(String.class));
}
}


, , , . ,
JMS ? JMS , , ,
, ,
? :
, , ;

, , ;
,
;
;
, pub-sub;
.

527


. ,
, .
,
, .
, : ,
(..13.8). ( ),
/, .
.
,
-. , . JMS, .
, . SQL92
:
context.createConsumer(queue, "JMSPriority < 6").receive();
context.createConsumer(queue, "JMSPriority < 6 AND orderAmount < 200").
receive();
context.createConsumer(queue, "orderAmount BETWEEN 1000 AND 2000" ).receive();


JMSContext.createConsumer(), -.
(JMSPriority < 6) (orderAmount < 200). -

:
context.createTextMessage().setIntProperty("orderAmount", 1530);
context.createTextMessage().setJMSPriority(5);

(NOT, AND, OR),


(=, >, >=, <, <=, <>), (+, -, *, /), ([NOT] BETWEEN, [NOT] IN, [NOT] LIKE, IS [NOT] NULL) ..

,
, .
API JMSProducer,
JMSExpiration. JMSProducer setTimeToLive(), :
context.createProducer().setTimeToLive(1000).send(queue, message);

528 13.


JMS : .
, ,
. ( ) , ,
, . setDeliveryMode() JMSProducer:
context.createProducer().setDeliveryMode(DeliveryMode.NON_PERSISTENT).
send(queue, message);


, , ,
. , (.13.11).
JMS, ,
.

.13.11.


. , .
.
AUTO_ACKNOWLEDGE .
CLIENT_ACKNOWLEDGE
Message.acknowledge().
DUPS_OK_ACKNOWLEDGE
.
, JMS, , .
,
JMSRedelivered true.
@JMSSessionMode
JMSContext . , acknowledge():
//
@Inject

529
,
@JMSConnectionFactory("jms/connectionFactory")
@JMSSessionMode(JMSContext.AUTO_ACKNOWLEDGE)
private JMSContext context;
...
context.createProducer().send(queue, message);
//
message.acknowledge();


pub-sub , , ,
. JMS API , . ,
, , , , . ,
JMSContext:
context.createDurableConsumer(topic, "javaee7DurableSubscription").receive();

. javaee7DurableSubscription .
,
.


, JMS . JMS
, 0 ( ) 9 ( ). setPriority() JMSProducer:
context.createProducer().setPriority(2).send(queue, message);

JMSProducer.
, . :
context.createProducer().setPriority(2)
.setTimeToLive(1000)
.setDeliveryMode(DeliveryMode.NON_PERSISTENT)
.send(queue, message);

530 13.
JMS API. , (MDB),

, EJB.
MDB , . MDB
, , .
MDB EJB,
,
EJB. MDB . EJB, MDB , ( EJB, JDBC, JMS,
..).
MDB,
JMS, ? , , , JMS. MDB ( ),
.
, MDB . MDB
13.9.
13.9. MDB

@MessageDriven(mappedName = "jms/javaee7/Topic")
public class BillingMDB implements MessageListener {
public void onMessage(Message message) {
System.out.println(" : " + message.getBody(String.
class));
}
}

( ) ,
MDB
, . MDB MessageListener onMessage(),
. MDB
, , (. @Mes
sageDriven).

MDB
MDB ,
-. ja
vax.jms.MessageListener. MDB,
, , MDB , ,

531
,
, , .
.
, MDB EJB Lite, ,
- , Java EE.
MDB:
@javax.ejb.MessageDriven XML;
, , MessageListener;
;
,
MDB;
finalize().
MDB ,
.. MDB
ejb-jar.xml. Java EE7, MDB
POJO, .
JMS, @MessageDriven
@ActivationConfigProperty (XML ).

@MessageDriven
MDB EJB ,
. @Message
Driven ( XML) , , , , Java
MDB.
API @MessageDriven, 13.10, ,
.
13.10. API @MessageDriven

@Target(TYPE) @Retention(RUNTIME)
public @interface MessageDriven {
String name() default "";
Class messageListenerInterface default Object.class;
ActivationConfigProperty[] activationConfig() default {};
String mappedName();
String description();
}

name MDB ( ).
messageListenerInterface , MDB
( MDB , EJB,
MessageListener). mappedName

532 13.
JNDI , MDB. Description , , MDB .
activationConfig
@ActivationConfigProperty.

@ActivationConfigProperty
JMS , ,
, .. MDB @ActivationConfigProperty.
@MessageDriven, ,
JMS, @ActivationConfigProperty
/ (13.11).
13.11. API ActivationConfigProperty

@Target({}) @Retention(RUNTIME)
public @interface ActivationConfigProperty {
String propertyName();
String propertyValue();
}

activationConfig ( ) . 13.12 .
13.12. MDB

@MessageDriven(mappedName = "jms/javaee7/Topic", activationConfig = {


@ActivationConfigProperty(propertyName = "acknowledgeMode",
propertyValue = "Auto-acknowledge"),
@ActivationConfigProperty(propertyName = "messageSelector",
propertyValue = "orderAmount < 3000")
})
public class BillingMDB implements MessageListener {
public void onMessage(Message message) {
System.out.println(" : " +
message.getBody(String.class));
}
}

/,
MDB.
.13.8 .
13.8. OpenMQ

acknowledgeMode

( AUTO_ACKNOWLEDGE)

messageSelector

, MDB

destinationType

, TOPIC QUEUE

destinationLookup

533
,

connectionFactory
Lookup
destination
subscriptionDurability
subscriptionName
shareSubscriptions
clientId


( NON_DURABLE)

,
, JMS


EJB, (.7), MDB
, ,
JDBC, EJB . ,
.
, MDB:
@PersistenceContext
private EntityManager em;
@Inject
private InvoiceBean invoice;
@Resource(lookup = "jms/javaee7/ConnectionFactory")
private ConnectionFactory connectionFactory;

MDB @Resource:
@Resource private MessageDrivenContext context;

MDB
MessageDrivenContext ,
MDB. MessageDrivenContext, MDB. MDB
, .. MessageDrivenContext
javax.ejb.EJBContext - .
MDB ,
, .13.9.
13.9. MessageDrivenContext

getCallerPrincipal

java.security.Principal,

getRollbackOnly

534 13.
13.9 ()

getTimerService

javax.ejb.TimerService

getUserTransaction

javax.transaction.UserTransaction, .
MDB, (BMT),

isCallerInRole

Lookup

MDB
JNDI

setRollbackOnly

.
MDB BMT

MDB (.13.12) : MDB , .


MDB , ,
, (@Resource,
@Inject, @EJB ..) .
@PostConstruct, .
MDB , . @PreDestroy , MDB
.

.13.12. MDB

535
,
,
(
.8), , EJB,
@javax.ejb.AroundInvoke.

MDB

, ,
, Message
Listener. MDB , . MDB ,
.
MDB ? , .

(EJB , ,
). MDB, , ,
. ,
.
,
. EJB
MDB, .
MDB
. .13.10 MDB .
13.10. MDB

MDB

MDB
MDB , ,
,
, . , JMS API.
@Resource @JMSConnectionFactory JNDI.
javax.jms.JMSContext . BillingMDB (13.13) (jms/javaee7/Topic),
( onMessage() ) (jms/
javaee7/Queue).

536 13.
13.13. MDB,

@MessageDriven(mappedName = "jms/javaee7/Topic", activationConfig = {


@ActivationConfigProperty(propertyName = "acknowledgeMode",
propertyValue = "Auto-acknowledge"),
@ActivationConfigProperty(propertyName = "messageSelector",
propertyValue = "orderAmount BETWEEN 3 AND 7")
} )
public class BillingMDB implements MessageListener {
@Inject
@JMSConnectionFactory("jms/javaee7/ConnectionFactory")
@JMSSessionMode(JMSContext.AUTO_ACKNOWLEDGE)
private JMSContext context;
@Resource(lookup = "jms/javaee7/Queue")
private Destination printingQueue;
public void onMessage(Message message) {
System.out.println(" : " +
message.getBody(String.class));
sendPrintingMessage();
}
private void sendPrintingMessage() throws JMSException {
context.createProducer().send(printingQueue, " ,
");
}
}

MDB , .
-, @MessageDriven JNDI
, (mappedName = "jms/javaee7/Topic").
,
@ActivationConfigProperty, MessageListener onMessage().
MDB . , : ( JMSContext) ( jms/javaee7/Queue).
, -, ( sendPrintingMessage()),
, : JMSProducer . .

MDB EJB (
.7 8). MDB BMT
(CMT),
MessageDrivenContext.setRollbackOnly() .. MDB , .

537
,
, .
, ,
. , (.9).
,
() () . ?
, ,
.
onMessage() ( ,
setRollbackOnly()).
MDB ,
, .
MDB, .
MDB, onMessage(). .13.11 , CMT MDB.
13.11. MDB .

MDB

NOT_SUPPORTED

REQUIRED

MANDATORY

REQUIRES_NEW

SUPPORTS

NEVER

CMT MDB @javax.ejb.TransactionAttribute


- :
REQUIRED ( ) MDB ,
; , ;
NOT_SUPPORTED MDB , .


, , , JMS API . API
,
javax.jms.JMSException. API , javax.jms.JMSRuntimeException.
, JMSException (.9 ( )),

538 13.
JMSRuntimeException . EJB
:
,
Exception ;
,
RuntimeException .
JMSRuntimeException ,
JMSException . ,
setRollBackOnly() (,
EJBException):
public void onMessage(Message message) {
try {
System.out.println(" : " + message.getBody(String.
class));
} catch (JMSException e) {
context.setRollBackOnly();
}
}


(
P2P pub-sub) ( ), , ,
, ,
(MDB) . , , ,
Maven GlassFish.
(OrderProducer), ( jms/javaee7/Topic). ,
-. (OrderDTO)
, . , , OrderConsumer ExpensiveOrderMDB (.13.13).
OrderConsumer , MDB , $1000 ( ).
Maven , , ExpensiveOrderMDB OrderDTO .jar
(chapter13-MDB-1.0.jar), GlassFish. OrderProducer, OrderConsumer
OrderDTO Java SE.

OrderDTO
, JMS, POJO,
Serializable. OrderDTO, 13.14, , .

539

.13.13.

, JMS ObjectMessage
OrderProducer , OrderConsumer ExpensiveOrderMDB.
13.14. OrderDTO JMS ObjectMessage

public class OrderDTO implements Serializable {


private Long orderId;
private Date creationDate;
private String customerName;
private Float totalAmount;
// ,
}

OrderProducer
OrderProducer, 13.15, ,
JMS API ObjectMessage jms/
javaee7/Topic. , main() OrderDTO. ,
totalAmount , (args[0]).
JSMProducer orderAmount, -

, .
13.15. OrderProducer OrderDTO

public class OrderProducer {


public static void main(String[] args) throws NamingException {
// orderDto totalmount
Float totalAmount = Float.valueOf(args[0]);
OrderDTO order = new OrderDTO(1234l, new Date(), " ", totalAmount);
// JNDI
Context jndiContext = new InitialContext();
//
ConnectionFactory connectionFactory = (ConnectionFactory)
jndiContext.lookup("jms/javaee7/ConnectionFactory");

540 13.
Destination topic = (Destination) jndiContext.lookup("jms/javaee7/Topic");
try (JMSContext jmsContext = connectionFactory.createContext()) {
//
jmsContext.createProducer().setProperty("orderAmount", totalAmount).
send(topic, order);
}
}
}

OrderConsumer
OrderConsumer, 13.16,
JMS, jms/javaee7/Topic JMSConsumer API,
OrderDTO ( ).
13.16. OrderConsumer OrderDTO

public class OrderConsumer {


public static void main(String[] args) throws NamingException {
// JNDI
Context jndiContext = new InitialContext();
//
ConnectionFactory connectionFactory = (ConnectionFactory)
jndiContext.lookup("jms/javaee7/ConnectionFactory");
Destination topic = (Destination) jndiContext.lookup("jms/javaee7/Topic");
//
Try (JMSContext jmsContext = connectionFactory.createContext()) {
while (true) {
OrderDTO order = jmsContext.createConsumer(topic).receiveBody(OrderDTO.
class);
System.out.println(" : " + order);
}
}
}
}

ExpensiveOrderMDB
ExpensiveOrderMDB (13.17) MDB @MessageDriven,
jms/javaee7/Topic. MDB , $1000,
(orderAmount > 1000). onMessage() , OderDTO (getBody(OrderDTO.class))
. (system.out.println),
(, , ).

541

13.17. ExpensiveOrderMDB, $1000

@MessageDriven(mappedName = "jms/javaee7/Topic", activationConfig = {


@ActivationConfigProperty(propertyName = "acknowledgeMode",
propertyValue = "Auto-acknowledge"),
@ActivationConfigProperty(propertyName = "messageSelector",
propertyValue = "orderAmount > 1000")
} )
public class ExpensiveOrderMDB implements MessageListener {
public void onMessage(Message message) {
try {
OrderDTO order = message.getBody(OrderDTO.class);
System.out.println(" : " + order.toString());
} catch (JMSException e) {
e.printStackTrace();
}
}
}

Maven
ExpensiveOrderMDB OrderDTO
.jar, GlassFish. MDB EJB (@MessageDriven) JMS API (ConnectionFactory, Destination ..),
pom.xml, 13.18, glassfishembedded-all ( API Java EE7).
provided, GlassFish, EJB JMS, -

API . Maven ,
Java SE 7, maven-compiler-plugin.
13.18. pom.xml, MDB

<?xml version="1.0" encoding="UTF-8"?>


<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd" >
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>chapter13</artifactId>
<groupId>org.agoncal.book.javaee7</groupId>
<version>1.0</version>
</parent>
<groupId>org.agoncal.book.javaee7.chapter13</groupId>
<artifactId>chapter13-mdb</artifactId>
<version>1.0</version>
<dependencies>
<dependency>

542 13.
<groupId>org.glassfish.main.extras</groupId>
<artifactId>glassfish-embedded-all<artifactId>
<version>4.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

, pom.xml, Maven:
$mvn package

target, chapter13-MDB-1.0.jar.
, , ExpensiveOrderMDB
OrderDTO.


, ,
JMS. JNDI, JNDI:
jms/javaee7/ConnectionFactory;
jms/javaee7/Topic.
, GlassFish . , asadmin
, :
$ asadmin create-jms-resource --restype javax.jms.ConnectionFactory
jms/javaee7/ConnectionFactory
$ asadmin create-jms-resource --restype javax.jms.Topic jms/javaee7/Topic

- GlassFish
. , ,
GlassFish asadmin. ,
JMS-
:

543

$ asadmin list-jms-resources
jms/javaee7/Topic
jms/javaee7/ConnectionFactory

JMS 2.0, . ,
( , EJB, MDB...) @JMSConnection
FactoryDefinition @JMSDestinationDefinition, ,
.
(.8, 8.15), @DataSourceDefinition. 13.19 ExpensiveOrderMDB
.
13.19. ExpensiveOrderMDB,

@JMSConnectionFactoryDefinition(name = "jms/javaee7/ConnectionFactory",
className = "javax.jms.ConnectionFactory")
@JMSDestinationDefinition(name = "jms/javaee7/Topic",
className = "javax.jms.Topic")
public class ExpensiveOrderMDB implements MessageListener {...}

MDB GlassFish
MDB .jar,
GlassFish. ,
-. asadmin
: , ,
chapter13-MDB-1.0.jar, , GlassFish
, :
$ asadmin deploy chapter13-MDB-1.0.jar

,
.jar ( EJB):
$ asadmin list-components
chapter13-MDB-1.0 <ejb>


MDB GlassFish jms/javaee7/Topic,
. OrderConsumer Order
Producer. ,
main, GlassFish, Java SE. OrderConsumer:
$ java cp target/classes OrderConsumer

. , $2000:
$ java cp target/classes OrderProducer 2000

544 13.
$1000 ( ),
OrderExpensiveMD, OrderConsumer . GlassFish, .
$1000, MDB , OrderConsumer:
$ java cp target/classes OrderProducer 500

,
, . MOM ,
. RPC (, RMI), .
JMS API ( ) . API,
Java SE Java EE. P2P
pub-sub, , , , , (, , ) (, , , ,
), ,
.
Java EE MDB.
, MDB ,
( , , ,
, , ..).
, Maven,
GlassFish OpenMQ,
MDB.
,
, SOAP - RESTful.

14.
- SOAP
- (),
. , , HTML: ,
. - . URL,
, .
- -
(SOA). - . - , SOAP, , REST (. ).
- SOAP, , , -,
, (,
, , ,
). - SOAP
, - ( ).
(Visual Basic, C#, C, C++, Java ..). -
-
: XML-. SOAP XML , , XML.
- SOAP .
, , , - SOAP
. HTTP ,
.
- SOAP .
business-to-business (B2B), ,
, . SOAP , ( Enterprise
Application Integration, EAI).
.
,
, - SOAP, WSDL SOAP.
, - SOAP, .

546 14. - SOAP

- SOAP
, - SOAP -,
( ) ( ). , EJB, - SOAP XML. - SOAP ,
, , ,
- ( ).
.14.1 SOAP. (UDDI),
.
, .

.14.1.

- SOAP .
, :
(XML) , - SOAP (SOAP, WSDL UDDI);
Web Services Description Language (WSDL, -) , , ;
Simple Object Access Protocol (SOAP, )
, XML, -;
.
(HTTP)
, SMTP JMS ;
Universal Description Discovery and Integration (UDDI)
, . SOAP- (WSDL).

547
- SOAP
- SOAP
. ,
XML.

XML
XML 12, , XML-,
. XML , , - SOAP. , XML , -
(WSDL) (SOAP). XML-
(XSD)
. - SOAP
RPC (Remote Procedure Call, )
XML.

WSDL
WSDL (IDL), - SOAP (.14.2).
- SOAP, , , , , , . ,
. WSDL
Java, XML.

.14.2. WSDL -

-
,
. WSDL. 14.1 ,
- SOAP,
(
). WSDL XML,
, , , - (soap:address location), (operation
name="validate" )
(soap:binding transport).

548 14. - SOAP


14.1. WSDL,

<?xml version="1.0" encoding="UTF-8" ?>


<definitions
xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://chapter14.javaee7.book.agoncal.org/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.xmlsoap.org/wsdl/"
targetNamespace="http://chapter14.javaee7.book.agoncal.org/"
name="CardValidatorService">
<types>
<xsd:schema>
<xsd:import namespace="http://chapter14.javaee7.book.agoncal.org/"
schemaLocation="http://localhost:8080/chapter14/
CardValidatorService?xsd=1"/>
</xsd:schema>
</types>
<message name="validate">
<part name="parameters" element="tns:validate"/>
</message>
<message name="validateResponse">
<part name="parameters" element="tns:validateResponse"/>
</message>
<portType name="CardValidator">
<operation name="validate">
<input message="tns:validate"/>
<output message="tns:validateResponse"/>
</operation>
</portType>
<binding name="CardValidatorPortBinding" type="tns:CardValidator">
<soap:binding transport="http://schemas.xmlsoap.org/soap/
http"style="document"/>
<operation name="validate">
<soap:operation soapAction=""/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
</binding>
<service name="CardValidatorService">
<port name="CardValidatorPort" binding="tns:CardValidatorPortBinding">
<soap:address location="http://localhost:8080/chapter14/
CardValidatorService"/>
</port>
</service>
</definitions>

WSDL XML , ,
. , -

549
- SOAP
(types, message, portType, binding, service). .14.1
WSDL. WSDL ,
, .14.1 W3C.
WSDL, ,
W3C.
14.1. WSDL

definitions

WSDL, ,

types

, .
XML (CardValidatorService?xsd=1) , -

message

, -. ( validate)
(validateResponse)

portType

- ( validate).

binding

( SOAP) ,

service

<port>, ( URL)

port

<xsd:import namespace> XML-,


WSDL. 14.2
, -: CreditCard (,
..), (validate),
( ), (validateResponse).
14.2. WSDL

<xs:schema xmlns:tns="http://chapter14.javaee7.book.agoncal.org/"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://chapter14.javaee7.book.agoncal.org/
"version="1.0">
<xs:element name="validate" type="tns:validate"/>
<xs:element name="validateResponse" type="tns:validateResponse"/>
<xs:complexType name="validate">
<xs:sequence>
<xs:element name="arg0" type="tns:creditCard" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
< xs:complexType name="creditCard">
<xs:sequence/>
<xs:attribute name="number" type="xs:string" use="required"/>
<xs:attribute name="expiry_date" type="xs:string" use="required"/>

550 14. - SOAP


<xs:attribute name="control_number" type="xs:int" use="required"/>
<xs:attribute name="type" type="xs:string" use="required"/>
</xs:complexType>
<xs:complexType name="validateResponse">
<xs:sequence>
<xs:element name="return" type="xs:boolean"/>
</xs:sequence>
</xs:complexType>
</xs:schema>

JAXB, 12, , XSD 14.2 Java .


WSDL
- ( , JAX-WS
, ).

SOAP
WSDL -, SOAP
, XML-,
(.14.3). SOAP -. -, XML- , HTTP. WSDL, SOAP XML,
SOAP XML-
(, , ..). HTTP, - SOAP XML, HTTP, HTTP.

.14.3. , - SOAP

SOAP ,
.
, .
, .14.3. - SOAP ,
( , , ), ,
. 14.3 14.4 SOAP.

551
- SOAP
14.3. SOAP-,

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/
xmlns:cc="http://chapter14.javaee7.book.agoncal.org/">
<soap:Header/>
<soap:Body>
<cc:validate>
<arg0 number="123456789011" expiry_date="10/12" control_number="544"
type="Visa"/>
</cc:validate>
</soap:Body>
</soap:Envelope>
14.4. SOAP-,

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:cc="http://chapter14.javaee7.book.agoncal.org/">
<soap:Body>
<cc:validateResponse>
<return>true</return>
</cc:validateResponse>
</soap:Body>
</soap:Envelope>

SOAP-
(.14.3), validate - . SOAP (.14.4)
( ).
.14.2 SOAP.
WSDL, SOAP W3C.
14.2. SOAP

Envelope

, .

Header

Body

Fault

, .

UDDI
, ,
, .
,
. UDDI - , . WSDL
UDDI, .

552 14. - SOAP


. , - UDDI, .
UDDI XML -,
, . , , ,
..
-. , WSDL.

UDDI , (IBM, Microsoft SAP). 2006 , UDDI. 2007 ,
UDDI OASIS, .


-, . SOAP , . , - , HTTP,
, HTTPS (HTTP Secure),
TCP/IP, SMTP (Simple Mail Transport Protocol, ), FTP (File Transfer Protocol, ) ..

- SOAP
4,
JPA. - , , . , -,
Java Community Process (JCP).

- SOAP
- SOAP . - : Common Object Request Broker
Architecture (CORBA), UNIX-,
Distributed Component Object Model (DCOM),
Microsoft. Remote Procedure Call (RPC)
Java Remote Method Invocation (RMI).
, . HTTP
, . XML ,

553
- SOAP
W3C , XML1.0 .
1998 , HTTP XML, .
SOAP 1.0, Microsoft 1998,
1999.
XML. 2000 IBM SOAP1.1, WSDL W3C 2001. UDDI 2000 (OASIS),
-. SOAP,
WSDL UDDI -, . IT-.
Java - Java API XML RPC1.0 (JAX-RPC1.0) 2002, JAX-RPC1.1
J2EE1.4 2003.
. JavaEE5 Java
Java API XML - 2.0 (JAXWS2.0) - SOAP.
Java EE7 JAX-WS2.2a.

,
- SOAP
-,
, .14.3, W3C, JCP
OASIS.
14.3. , - SOAP

JSR

URL

JAX-WS

2.2a

JCP

224

http://jcp.org/en/jsr/detail?id=224

1.3

JCP

109

http://jcp.org/en/jsr/detail?id=109

2.1

JCP

181

http://jcp.org/en/jsr/detail?id=181

JAXB

2.2

JCP

222

http://jcp.org/en/jsr/detail?id=222

SAAJ

1.3

JCP

67

http://jcp.org/en/jsr/detail?id=67

JAX-RPC

1.1

JCP

101

http://jcp.org/en/jsr/
detail?id=101

JAXR

1.1

JCP

93

http://jcp.org/en/jsr/detail?id=93

SOAP

1.2

W3C

http://www.w3.org/TR/soap/

XML

1.1

W3C

http://www.w3.org/TR/xml

WSDL

1.1

W3C

http://www.w3.org/TR/wsdl

UDDI

1.0

OASIS

http://uddi.org/pubs/uddi_v3.htm

W3C , -,
HTML, XHTML, RDF, CSS .., , -,
XML, XML-, SOAP WSDL.

554 14. - SOAP


OASIS - , UDDI,
WS-Addressing, WS-Security, WS-Reliability ( WS-*).
Java. JCP ,
Java EE7 Java SE7. JAX-WS2.2a (JSR 224), Web Services1.3
(JSR 109), Web Services Metadata 2.3 (JSR 181) JAXB 2.2 (JSR 222).
Java Web Services (JWS Java). SAAJ (SOAP with Attachments API for Java API SOAP Java), JSR67, JavaSE SOAP .
JavaEE
JavaEE. JAX-WS
JAX-RPC (JSR 101), . JAX-RPC
Java EE6, , Java EE7. Java API XML (Java API for XML Registers, JAXR) API
Java, UDDI. UDDI
, JSR (93) Java EE7.
, ,
- SOAP Java , API.
, (XML,
WSDL, SOAP, HTTP ..) JWS
, .

JAX-WS 2.2a
JAX-WS 2.2a API ( .14.4)
, - Java.

- SOAP, . ,
, SOAP, JAX-WS. JAX-WS , Java
XML (JAXB), 12.
14.4. JAX-WS

javax.xml.ws

API JAX-WS

javax.xml.ws.http

API, XML/HTTP

javax.xml.ws.soap

API, SOAP 1.1/ HTTP


SOAP 1.2/HTTP

javax.xml.ws.handler API

Web Services1.3
JSR109
- JavaEE.
- .

555
- SOAP

WS-Metadata 2.3
Web Services Metadata (WS-Metadata, JSR181)
, - (
.14.5). JSR181 -.
WSDL Java , . Java EJB.
14.5. WS-Metadadta

javax.jws

Java WSDL

javax.jws.soap

API, -
SOAP

- SOAP
, JAX-WS WS-Metadata Java EE7.
- SOAP Java EE. , Java EE7 - SOAP , , , .. Bean Validation ,
(.3).


Metro - Java
. JAX-WS JAXB, API JAXRPC. , , ,
SOAP -, - SOAP. Metro
GlassFish, GlassFish, Java SE - (, Tomcat Jetty).
Apache CXF ( XFire) Apache Axis2
JWS. , , - SOAP.

- SOAP
,
HTTP, WSDL, SOAP XML. -
SOAP ? WSDL,
Java.
WSDL ,
Java .
, . (WSDL) ,

556 14. - SOAP


.. , Java . Metro (wsimport), WSDL.
WSDL. Metro (wsgen) WSDL . , ,
WSDL . JAX-WS.
Java WSDL . : , Java
, .
/ , ,
.
, , , -
. - SOAP Java EE7 WSDL SOAP. -
POJO, -.
14.5 -, .
14.5. - CardValidator

@WebService
public class CardValidator {
public boolean validate(CreditCard creditCard) {
Character lastDigit = creditCard.getNumber().charAt(
creditCard.getNumber().length() - 1);
if (Integer.parseInt(lastDigit.toString()) % 2 != 0) {
return true;
} else {
return false;
}
}
}

EJB, - SOAP POJO, .


, - Java, @javax.jws.WebService, .
JAX-WS ,
Java XML, HTTP. -
SOAP CardValidator ,
. , .
, , .

557
- SOAP
CreditCard (14.6) , - SOAP. -
XML-,
Java XML. JAXB,
API. 12,
CreditCard @javax.xml.bind.annotation.XmlRootElement,
(, @XmlAttribute),
. JAXB XML
Java .
14.6. CreditCard JAXB

@XmlRootElement
public class CreditCard {
@XmlAttribute(required = true)
private String number;
@XmlAttribute(name = "expiry_date", required = true)
private String expiryDate;
@XmlAttribute(name = "control_number", required = true)
private Integer controlNumber;
@XmlAttribute(required = true)
private String type;
// ,
}

JAXB
XML, . - Java, .

- SOAP
Java EE7, - SOAP , ,
. ,
POJO - SOAP @WebService. - :
@javax.jws.WebService XML-
(webservices.xml);
( )
( ),
@WebService;
final abstract;
;
finalize();
- SOAP - ,
@javax.ejb.Stateless @javax.ejb.Singleton
(.7);

558 14. - SOAP


, , .
WS-Metadata (JSR 181) , ,
, POJO -,
.
. , ,
-,
EJB ( EJB).

- SOAP
JAX-WS - Java EJB.
(SEI).
POJO (.14.5) - EJB (14.7), , , - EJB
@Stateless ( @Singleton). ,
.
14.7. - CardValidator EJB

@WebService
@Stateless
public class CardValidator {
public boolean validate(CreditCard creditCard) {
Character lastDigit = creditCard.getNumber().charAt(
creditCard.getNumber().length() - 1);
if (Integer.parseInt(lastDigit.toString()) % 2 != 0) {
return true;
} else {
return false;
}
}
}

,
EJB, . EJB,
, ,
, . -
- EJB .
, - SOAP, RMI,
.

WSDL
XML-,
WSDL SOAP. Java
, . -

559
- SOAP
Java WSDL. JAXB ,
, / XML
. , JWS Java
WSDL ,
SOAP SOAP .
JAX-WS (JSR224) WS-Metadata (JSR181)
:
WSDL javax.jws
WSDL/Java. @WebMethod, @WebResult,
@WebParam @OneWay - ;
SOAP javax.jws.soap
SOAP (@SoapBinding @SOAPMessageHandler).
Java EE7, -
XML (webservices.xml).
WSDL.

@WebService
@javax.jws.WebService Java -.
(
), , . :
@WebService
public class CardValidator {...}

,
. ,
endpointInterface:
@WebService
public interface Validator {...}
@WebService (endpointInterface = "org.agoncal.book.javaee7.chapter14.
Validator")
public class CardValidator implements Validator {...}

@WebService (14.8), - WSDL ( <wsdl:portType>


<wsdl:service>) ,
WSDL ( wsdlLocation).
14.8. @WebService API

@Retention(RUNTIME) @Target(TYPE)
public @interface WebService {
String name() default "";
String targetNamespace() default "";
String serviceName() default "";
String portName() default "";

560 14. - SOAP


String wsdlLocation() default "";
String endpointInterface() default "";
}

, WSDL
- SOAP, . :
@WebService(portName = "CreditCardValidator",
serviceName = "ValidatorService")
public class CardValidator {...}

WSDL, 14.1,
:
<service name="ValidatorService">
<port name="CreditCardValidator" binding="tns:CreditCardValidatorBinding">
<soap:address location="http://localhost:8080/chapter14/ValidatorService"/>
</port>
</service>

@WebService, -, ,
@WebMethod.

@WebMethod
- SOAP WSDL
.
, @javax.jws.WebMethod
. API :
WSDL. 14.9 , -
CardValidator .
14.9. ,

@WebService
public class CardValidator {
@WebMethod(operationName = "ValidateCreditCard")
public boolean validate(CreditCard creditCard) {
// -
}
@ WebMethod(operationName = "ValidateCreditCardNumber")
public void validate(String creditCardNumber) {
// -
}
@WebMethod(exclude = true)
public void validate(Long creditCardNumber) {
// -
}
}

561
- SOAP
WSDL, 14.10, : ValidateCreditCard ValidateCreditCardNumber.
WSDL.
14.10. WSDL

<message name="ValidateCreditCard">
<part name="parameters" element="tns:ValidateCreditCard"/>
</message>
<message name="ValidateCreditCardResponse">
<part name="parameters" element="tns:ValidateCreditCardResponse"/>
</message>
<message name="ValidateCreditCardNumber">
<part name="parameters" element="tns:ValidateCreditCardNumber"/>
</message>
<message name="ValidateCreditCardNumberResponse">
<part name="parameters" element="tns:ValidateCreditCardNumberResponse"/>
</message>
<portType name="CardValidator">
<operation name="ValidateCreditCard">
<input message="tns:ValidateCreditCard"/>
<output message="tns:ValidateCreditCardResponse"/>
</operation>
<operation name="ValidateCreditCardNumber">
<input message="tns:ValidateCreditCardNumber"/>
<output message="tns:ValidateCreditCardNumberResponse"/>
</operation>
</portType>

@WebResult
@javax.jws.WebResult ,
WSDL. 14.11 validate() IsValid.
14.11.

@WebService
public class CardValidator {
@WebResult(name = "IsValid")
public boolean validate(CreditCard creditCard) {
// -
}
}

WSDL return.
@WebResult
:
<!-- -->
<xs:element name="return" type="xs:boolean"/>
<!-- IsValid -->
<xs:element name="IsValid" type="xs:boolean"/>

562 14. - SOAP


, WSDL, XML ,
@WebParam, 14.12.
14.12. @WebParam API

@Retention(RUNTIME) @Target(PARAMETER)
public @interface WebParam {
String name() default "";
public enum Mode {IN, OUT, INOUT};
String targetNamespace() default "";
boolean header() default false;
String partName() default "";
};

@WebParam
@javax.jws.WebParam, 14.12,
@WebResult, -. API
WSDL (14.13),
. : IN, OUT INOUT (), ,
( IN).
14.13.

@WebService
public class CardValidator {
public boolean validate(@WebParam(name= "Credit-Card", mode = IN)
CreditCard creditCard) {
// -
}
}

XSD, 14.2, , arg0.


@WebParam Credit-Card:
<!-- -->
<xs:element name="arg0" type="tns:creditCard" minOccurs="0"/>
<!-- Credit-Card -->
<xs:element name="Credit-Card" type="tns:creditCard" minOccurs="0"/>

@OneWay
@OneWay , , void.
,
, ,
(, , ).

@SoapBinding
, - , SOAP.

563
- SOAP
SOAP, WSDL1.1: RPC ( ). , SOAP.
SOAP .
<soap:Body> , . .
RPC SOAP . <soap:Body>
. ,
, .
SOAP ( , )
/.
XML-.
SOAP , , , .
/:
/ ( );
/ ( WS-*);
RPC/ ;
RPC/ .
WSDL, ,
(/ ).
@SoapBinding , 14.14, .
14.14. -, RPC/

@WebService
@SOAPBinding(style = RPC, use = LITERAL)
public class CardValidator {
public boolean validate(CreditCard creditCard) {
// -
}
}

14.14 ,
RPC. WSDL XML-,
- SOAP . 14.15
.
14.15. WSDL RPC

<!-- -->
<message name="validate">
<part name="parameters" element="tns:validate"/>
</message>
<message name="validateResponse">

564 14. - SOAP


<part name="parameters" element="tns:validateResponse"/>
</message>
...
<soap:binding transport="http://schemas.xmlsoap.org/soap/http"
style="document"/>
<!-- RPC-->
<message name="validate">
<part name="arg0" type="tns:creditCard"/>
</message>
<message name="validateResponse">
<part name="return" type="xsd:boolean"/>
</message>
...
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"/>


, - SOAP, . - CardValidator,
14.5, (14.16).
14.16. - CardValidator,

@WebService(portName = "CreditCardValidator",
serviceName = "ValidatorService")
@SOAPBinding(style = RPC, use = LITERAL)
public class CardValidator {
@WebResult(name = "IsValid")
@WebMethod(operationName = "ValidateCreditCard")
public boolean validate(@WebParam(name = "Credit-Card")
CreditCard creditCard) {
// -
}
@WebResult(name = "IsValid")
@WebMethod(operationName = "ValidateCreditCardNumber")
public void validate(@WebParam(name = "Credit-Card-Number")
String creditCardNumber) {
// -
}
@WebMethod(exclude = true)
public void validate(Long creditCardNumber) {
// -
}
}

565

14.16 -, RPC/ ( ,
validate(Long CreditCardNumber) - @WebMethod(exclude=true)).
, WSDL
. 14.17 WSDL, , 14.1
( ).
14.17. WSDL

<?xml version="1.0" encoding="UTF-8" ?>


<definitions
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://chapter14.javaee7.book.agoncal.org/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.xmlsoap.org/wsdl/"
targetNamespace="http://chapter14.javaee7.book.agoncal.org/"
name="ValidatorService">
<types>
<xsd:schema>
<xsd:import namespace="http://chapter14.javaee7.book.agoncal.org/"
schemaLocation="http://localhost:8080/chapter14/
ValidatorService?xsd=1"/>
</xsd:schema>
</types>
<message name="ValidateCreditCard">
<part name="Credit-Card" type="tns:creditCard"/>
</message>
<message name="ValidateCreditCardResponse">
<part name="IsValid" type="xsd:boolean"/>
</message>
<message name="ValidateCreditCardNumber">
<part name="Credit-Card-Number" type="xsd:string"/>
</message>
<message name="ValidateCreditCardNumberResponse"/>
<portType name="CardValidator">
<operation name="ValidateCreditCard">
<input message="tns:ValidateCreditCard"/>
<output message="tns:ValidateCreditCardResponse"/>
</operation>
<operation name="ValidateCreditCardNumber">
<input message="tns:ValidateCreditCardNumber"/>
<output message="tns:ValidateCreditCardNumberResponse"/>
</operation>
</portType>
<binding name="CreditCardValidatorBinding" type="tns:CardValidator">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http"
style="rpc"/>
<operation name="ValidateCreditCard">
<soap:operation soapAction=""/>
<input>

566 14. - SOAP


<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
<operation name="ValidateCreditCardNumber">
<soap:operation soapAction=""/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
</binding>
<service name="ValidatorService">
<port name="CreditCardValidator"
binding="tns:CreditCardValidatorBinding">
<soap:address location="http://localhost:8080/chapter14/
ValidatorService"/>
</port>
</service>
</definitions>

@WebService WSDL <portType name> <port


name>. @WebMethod <operation name>, @WebResult
@WebParam <part name>, <message>.
XML- , ,
<xs:complexType>. (14.18),

XSD, 14.2. , - SOAP


RPC ( /,
creditCard boolean).
14.18. XML-

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://chapter14.javaee7.book.agoncal.org/"
version="1.0">
<xs:complexType name="creditCard">
<xs:sequence/>
<xs:attribute name="number" type="xs:string" use="required"/>
<xs:attribute name="expiry_date" type="xs:string" use="required"/>
<xs:attribute name="control_number" type="xs:int" use="required"/>
<xs:attribute name="type" type="xs:string" use="required"/>
</xs:complexType>
</xs:schema>

WSDL (.14.17) XSD (. 14.18) .

567

SOAP. 14.19 SOAP-,
-. (ValidateCreditCard) ,
(Credit-Card).
14.19. SOAP ValidateCreditCard

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:cc="http://chapter14.javaee7.book.agoncal.org/">
<soap:Header/>
<soap:Body>
<cc:ValidateCreditCard>
<Credit-Card number="123456789011" expiry_date="10/12"
control_number="544" type="Visa"/>
</cc:ValidateCreditCard>
</soap:Body>
</soap:Envelope>

14.20 SOAP, . , , ,
(<IsValid>true</IsValid>).
14.20. SOAP ValidateCreditCard

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:cc="http://chapter14.javaee7.book.agoncal.org/">
<soap:Body>
<cc:ValidateCreditCardResponse>
<IsValid>true</IsValid>
</cc:ValidateCreditCardResponse>
</soap:Body>
</soap:Envelope>


: , - , .
. Java, - ,
JVM . - SOAP
,
. , SOAP Fault SOAP. JAX-WS Java SOAP Fault, . ,
, SOAP Fault.
validate - CardValidator, 14.5, , , CreditCard ,
NullPointerException.
JAX-WS NullPointerException ,
SOAP Fault (14.21) .

568 14. - SOAP


14.21. SOAP Fault SOAP

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<soap:Fault>
<faultcode>soap:Server</faultcode>
<faultstring>java.lang.NullPointerException</faultstring>
</soap:Fault>
</soap:Body>
</soap:Envelope>

14.21, JAX-WS
faultstring,
Java. faultCode. soap:Server,
, ( soap:Client).
SOAP Fault (14.22). - (
), . soap:Fault, SOAP
.
14.22.

@WebService
public class CardValidator throws CardValidatorException {
public boolean validate(CreditCard creditCard) {
Character lastDigit = creditCard.getNumber().charAt(
creditCard.getNumber().length() - 1);
if (Integer.parseInt(lastDigit.toString()) % 2 == 0) {
return true;
} else {
throw new CardValidatorException(" ");
}
}
}

Exception, RuntimeException
- SOAP, javax.xml.ws.WebServiceException
(, javax.xml.ws.soap.SOAPFaultException). @WebFault,
SOAP (14.23).
14.23. WebFault

@WebFault(name = "CardValidationFault")
public class CardValidatorException extends Exception {
public CardValidatorRTException() {
super();
}

569

public CardValidatorRTException(String message) {
super(message);
}
}

- SOAP , 14.23,
JAX-WS SOAP,
14.24.
14.24. SOAP Fault SOAP

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<soap:Fault>
<faultcode>soap:Server</faultcode>
<faultstring>org.agoncal.book.javaee7.chapter14.CardValidatorException</
faultstring>
<detail>
<ns2:CardValidationFault
xmlns:ns2="http://chapter14.javaee7.book.agoncal.org/">
<message> </message>
</ns2:CardValidationFault>
</detail>
</soap:Fault>
</soap:Body>
</soap:Envelope>

SOAP
faultCode .., API javax.xml.soap.SOAPFactory
javax.xml.soap.SOAPFault ( 14.25).
14.25. SOAPFactory SOAPFault

@WebService
public class CardValidator {
public boolean validate(CreditCard creditCard) {
Character lastDigit = creditCard.getNumber().charAt(
creditCard.getNumber().length() - 1);
if (Integer.parseInt(lastDigit.toString()) % 2 == 0) {
return true;
} else {
SOAPFactory soapFactory = SOAPFactory.newInstance();
SOAPFault fault = soapFactory.createFault("
", new QName("ValidationFault"));
throw new CardValidatorException(fault);
}
}
}

14.25 SOAPFault (ValidationFault), SOAP


(14.26).

570 14. - SOAP


14.26. SOAPFault, SOAP

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<soap:Fault>
<faultcode>ValidationFault</faultcode>
<faultstring> </faultstring>
</soap:Fault>
</soap:Body>
</soap:Envelope>


.14.4, - SOAP
, .
, : , . .

.14.4. - SOAP

- EJB ( ) , @PostConstruct
@PreDestroy. @PostConstruct,
, -, @PreDestroy .
, ( 2).

WebServiceContext
- SOAP javax.xml.ws.WebServiceContext @Resource.
- ,

571

, .

JAX-WS WS-Metadata Java EE7, ,
CDI, @Inject,
WebServiceContext: @Resource.

14.27 WebServiceContext, , Admin . .14.6 , javax.xml.ws.WebServiceContext.


14.27. - SOAP, WebServiceContext

@WebService
public class CardValidator {
@Resource
private WebServiceContext context;
public boolean validate(CreditCard creditCard) {
if (!context.isUserInRole("Admin"))
throw new SecurityException(" ");
// -
}
}
14.6. WebServiceContext

getMessageContext

MessageContext ,
.
SOAP: , ..

getUserPrincipal

Principal, ,

isUserInRole

, ,

getEndpointReference EndpointReference,


Java EE7, - SOAP
(, ),
XML. WEB-INF webservices.xml
. Java EE7, webservices.xml ,
,
. , 14.28 ,
WSDL (OverriddenPort) - CardValidator.

572 14. - SOAP


14.28. webservices.xml

<webservices xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/javaee_web_services_1_3.xsd"
version="1.3">
<webservice-description>
<webservice-description-name>CardValidatorWS</webservice-description-name>
<port-component>
<port-component-name>CardValidator</port-component-name>
<wsdl-port>OverriddenPort</wsdl-port>
<service-endpoint-interface>
org.agoncal.book.javaee7.chapter14.Validator
</service-endpoint-interface>
<service-impl-bean>
<servlet-link>CardValidatorServlet</servlet-link>
</service-impl-bean>
</port-component>
</webservice-description>
</webservices>

- SOAP .war .jar (


EJB). , .war , EJB Lite. -, .jar EJB, , , .
, :
;
( );
WSDL , ( ,
, WSDL JAX-WS);
SOAP ( , JAX-WS);
.

- SOAP
- SOAP , Java EE, GlassFish JBoss. , JAX-WS Java EE7 . - SOAP
-, Tomcat Jetty, JAX-WS, Metro, CXF Axis2.

573
- SOAP
, JAX-WS Java SE EJB (,
-). API javax.xml.ws.Endpoint
- SOAP. Endpoint.publish (14.29)
HTTP, Oracle JVM
( com.sun.net.httpserver).
14.29. - SOAP,

@WebService
public class CardValidator {
public boolean validate(CreditCard creditCard) {
// -
}
public static void main(String[] args) {
Endpoint.publish("http://localhost:8080/cardValidator",
new CardValidator());
}
}

14.29 publish - SOAP


CardValidator, http://
localhost:8080/cardValidator. -.
stop,
(
).

- SOAP
, , - SOAP.
, . WSDL Java ( )
-, HTTP SOAP. -
RMI. RMI, JAX-WS
. , -
( ,
, Java, RMI-IIOP).
WSDL . Metro
WSDL Java (wsimport), Java- WSDL. Java - ( EJB).
Java -, HTTP.
(.14.5),
SOAP () . , SOAP

574 14. - SOAP


.
. - SEI, -, .

.14.5. , -

SOAP
WSDL, , CardValidator (SOAP- validate)
(SOAP- validateResponse).

wsimport wsgen JDK1.7, GlassFish Metro.
wsimport WSDL
JAX-WS, SEI; wsgen - WSDL.
Java
SE7 (CLI) GlassFish, Ant
Maven.

SOAP
JAX-WS JavaSE, - SOAP
Java, Main, JVM,
JavaEE, (, EJB
). , , .
-, @javax.xml.ws.WebServiceRef
CDI.


, - SOAP. 14.30, -
CardValidator .

575
- SOAP
CardValidatorService ( WSDL wsimport)
new. - Card
Validator (getCardValidatorPort()) - .
validate(), , ,
-, SOAP, .. , URL
WSDL
.
14.30. Java SE, - SOAP

public class WebServiceConsumer {


public static void main(String[] args) {
CreditCard creditCard = new CreditCard();
creditCard.setNumber("12341234");
creditCard.setExpiryDate("10/12");
creditCard.setType("VISA");
creditCard.setControlNumber(1234);

CardValidator cardValidator =
new CardValidatorService().getCardValidatorPort();
cardValidator.validate(creditCard);

, . WSDL, . , URL,
-, CreditCard XML,
- SOAP SOAP.


, ,
- SOAP . 14.31 Java- main, (ACC) @WebServiceRef. @Resource @EJB, ,
-. ( ), -
.
14.31. Java SE, ACC

public class WebServiceConsumer {


@WebServiceRef
private static CardValidatorService cardValidatorService;
public static void main(String[] args) {
CreditCard creditCard = new CreditCard();

576 14. - SOAP


creditCard.setNumber("12341234");
creditCard.setExpiryDate("10/12");
creditCard.setType("VISA");
creditCard.setControlNumber(1234);
CardValidator cardValidator =
cardValidatorService.getCardValidatorPort();
cardValidator.validate(creditCard);
}
}

, 14.31 , EJB, - JSF.


, , @WebServiceRef .

CDI
JAX-WS Java EE7 , , CDI. ,
- @Inject. , 2,
CDI,
(14.32).
14.32. , -

public class WebServiceProducer {


@Produces
@WebServiceRef
private CardValidatorService cardValidatorService;
}

WebServiceProducer 14.32 EJB CardValidatorService @Inject - (14.33).


CDI, - SOAP,
2.
14.33. EJB, CDI .
-

@Stateless
public class EJBConsumerWithCDI {
@Inject
private CardValidatorService cardValidatorService;
public boolean validate(CreditCard creditCard) {
CardValidator cardValidator = cardValidatorService.getCardValidatorPort();
return cardValidator.validate(creditCard);
}
}

577


, - SOAP,
, GlassFish .
JAXB JAX-WS, Maven wsimport. -,
. , -
CardValidator.
- SOAP CardValidator , .
, CreditCard,
true, , false, . -, ( HTTP-).
- GlassFish, wsimport ,
- .
.14.6, Maven:
- .war (chapter14-service-1.0.war), .jar (chapter14-consumer-1.0.jar).
, ,
(wsimport), ( JAX-WS).

CreditCard
CreditCard, 14.34, POJO,
- validate(). - SOAP XML-, Java. CreditCard JAXB (, @XmlRootElement), XML , SOAP.
CreditCard ,
, ( MM/), (Visa, Master Card, American Express ..),
.
14.34. CreditCard JAXB

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class CreditCard {
@XmlAttribute(required = true)
private String number;
@XmlAttribute(name = "expiry_date", required = true)
private String expiryDate;
@XmlAttribute(name = "control_number", required = true)
private Integer controlNumber;
@XmlAttribute(required = true)
private String type;
// ,
}

.14.6.

578 14. - SOAP

579

- SOAP CardValidator
- CardValidator (14.36) Validator (14.35), JAX-WS- @WebService. CardValidator
POJO, -, EJB ( @Stateless @Singleton).
validate(), CreditCard.
:
, . boolean.
.war (chapter14service-1.0.war).
14.35. -

@WebService
public interface Validator {
public boolean validate(CreditCard creditCard);
}
14.36. - CardValidator

@WebService(endpointInterface = "org.agoncal.book.javaee7.chapter14.
Validator")
public class CardValidator implements Validator {
public boolean validate(CreditCard creditCard) {
Character lastDigit = creditCard.getNumber().charAt(
creditCard.getNumber().length() - 1);
if (Integer.parseInt(lastDigit.toString()) % 2 == 0) {
return true;
} else {
return false;
}
}
}

Java
WSDL, @WebMethod, @WebResult @WebParam,
, -,
.

CardValidatorTest
- SOAP ,
- (
, , ..). POJO
CardValidator .
14.37, POJO CardValidator,
CreditCard , , .
, ,
.

580 14. - SOAP


14.37. CardValidatorTest

public class CardValidatorTest {


@Test
public void shouldCheckCreditCardValidity() {
CardValidator cardValidator = new CardValidator();
CreditCard creditCard = new CreditCard("12341234", "10/10", 1234, "VISA");
assertTrue(" ", cardValidator.
validate(creditCard));
creditCard.setNumber("12341233");
assertFalse(" ", cardValidator.
validate(creditCard));
}
}

, , , - SOAP ? 14.27, ,
WebServiceContext, , Admin. WebServiceContext
null .
(, WebServiceContext), - SOAP
, .

CardValidatorIT
- SOAP
-, WSDL
.. ,
, , . Java SE6
- API javax.xml.ws.Endpoint.
14.38 JUnit, -
CardValidator SOAP URL (http://localhost:8080/cardValidator).
(endpoint.isPublished())
WSDL URL http://localhost:8080/cardValidator?wsdl
(Service.create(wsdlDocumentLocation, serviceQN)). servi
ce.getPort - SOAP,
(cardValidator.validate(creditCard)). ,
- (endpoint.stop()).
14.38. CardValidatorIT

public class CardValidatorIT {


@Test
public void shouldCheckCreditCardValidity() throws MalformedURLException {
// - SOAP
Endpoint endpoint =

581

Endpoint.publish("http://localhost:8080/cardValidator",
new CardValidator());
assertTrue(endpoint.isPublished());
assertEquals("http://schemas.xmlsoap.org/wsdl/soap/http",
endpoint.getBinding().getBindingID());
// -
URL wsdlDocumentLocation =
new URL("http://localhost:8080/cardValidator?wsdl");
String namespaceURI = "http://chapter14.javaee7.book.agoncal.org/";
String servicePart = "CardValidatorService";
String portName = "CardValidatorPort";
QName serviceQN = new QName(namespaceURI, servicePart);
QName portQN = new QName(namespaceURI, portName);
//
Service service = Service.create(wsdlDocumentLocation, serviceQN);
Validator cardValidator = service.getPort(portQN, Validator.class);
// -
CreditCard creditCard = new CreditCard("12341234", "10/10", 1234, "VISA");
assertTrue(" ",
cardValidator.validate(creditCard));
creditCard.setNumber("12341233");
assertFalse(" ",
cardValidator.validate(creditCard));
// - SOAP
endpoint.stop();
assertFalse(endpoint.isPublished());
}
}

, - CardValidator SOAP ,
GlassFish.

,
Maven
- CardValidator ( 14.35 14.36) , .war
(<packaging>war</packaging>). pom.xml (14.39)
glassFish-embedded-all,
Java EE7, JAX-WS -.
glassFish-embedded-all GlassFish4.0
.jar, . 1.7 maven-compiler-plugin , Java
SE7 (<source>1.7</source>).

582 14. - SOAP


14.39. pom.xml , -

<?xml version="1.0" encoding="UTF-8"?>


<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>chapter14</artifactId>
<groupId>org.agoncal.book.javaee7</groupId>
<version>1.0</version>
</parent>
<groupId>org.agoncal.book.javaee7.chapter14</groupId>
<artifactId>chapter14-service</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.glassfish.main.extras</groupId>
<artifactId>glassfish-embedded-all</artifactId>
<version>4.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.2</version>

583

<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.12.4</version>
<executions>
<execution>
<id>integration-test</id>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

Java EE7 ,
web.xml webservices.xml. , Maven
web.xml .war,
failOnMissingWebXml maven-war-plugin false,
Maven .
-
, pom.xml, Maven:
$

mvn package

target, chapter14-service-1.0.war.
, , Validator.class, CardValidator.class Credit
Card.class WEB-INF\classes. .war ,
WSDL ( JAX-WS).
(. 14.37)
(. 14.38) Maven Surefire Failsafe, Maven:
$ mvn integration-test

, SOAP - CardValidator ,
GlassFish.

GlassFish
- .war, GlassFish.
asadmin.
, chapter14-service-1.0.war, ,
GlassFish , :

584 14. - SOAP


$ asadmin deploy chapter14-service-1.0.war
Application deployed with name chapter14-service-1.0.
Command deploy executed successfully.

,
:
$ asadmin list-components
chapter14-service-1.0 <webservices, web>

, GlassFish - ( .war
-, ..) -. GlassFish, .14.7 (http://localhost:4848/),
, chapter14-service-1.0 Applications ().

.14.7. -, GlassFish

, WSDL, ,
URL
WSDL - SOAP CardValidator:
http://localhost:8080/chapter14-service-1.0/CardValidatorService?wsdl

, WSDL
.war. Metro WSDL , - ( SOAP Validate SOAP ValidateResponse,

.14.6). WSDL , -.

WebServiceConsumer
- , GlassFish , ,
URL WSDL. WSDL - wsimport. -, ,
14.40.

585

14.40. WebServiceConsumer, -

public class WebServiceConsumer {


@WebServiceRef
private static CardValidatorService cardValidatorService;
public static void main(String[] args) {
CreditCard creditCard = new CreditCard();
creditCard.setNumber("12341234");
creditCard.setExpiryDate("10/12");
creditCard.setType("VISA");
creditCard.setControlNumber(1234);
CardValidator cardValidator = cardValidatorService.getCardValidatorPort();
System.out.println(cardValidator.validate(creditCard));
}
}

WebServiceConsumer CreditCard, , -,
validate() (true false ,
). ,
. CardValidatorService, CardValidator CreditCard . , .


Maven
WebServiceConsumer
wsimport. , Maven JAX-WS wsimport,
generate-resources. Maven
. generate-resources . , ,
wsimport, WSDL. , - GlassFish
WSDL. :
http://localhost:8080/chapter14-service-1.0/CardValidatorService?wsdl

pom.xml 14.41 , glassfishembedded-all 4.0, JDK (1.7). WebServiceConsumer chapter14-consumer-1.0.jar. .jar,


META-INF/MANIFEST.MF, . Main-Class ,
WebServiceConsumer. .jar (, java -jar).

586 14. - SOAP


14.41. pom.xml

<?xml version="1.0" encoding="UTF-8"?>


<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>chapter14</artifactId>
<groupId>org.agoncal.book.javaee7</groupId>
<version>1.0</version>
</parent>
<groupId>org.agoncal.book.javaee7.chapter14</groupId>
<artifactId>chapter14-consumer</artifactId>
<packaging>jar</packaging>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>org.glassfish.main.extras</groupId>
<artifactId>glassfish-embedded-all</artifactId>
<version>4.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<manifest>
<mainClass>org.agoncal.book.javaee7.chapter14.WebServiceConsumer</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.jvnet.jax-ws-commons</groupId>
<artifactId>jaxws-maven-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<goals>
<goal>wsimport</goal>
</goals>
<configuration>
<wsdlUrls>
<wsdlUrl>

587

http://localhost:8080/chapter14-service-1.0/CardValidatorService?wsdl
</wsdlUrl>
</wsdlUrls>
<keep>true</keep>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

, , , Maven:
$

mvn generate-sources

Maven generate-sources , , wsimport. URL -


WSDL, . Maven:
[INFO] --- jaxws-maven-plugin:2.2:wsimport (default) @ chapter14-consumer --[INFO] Processing: http://localhost:8080/chapter14-service-1.0/
CardValidatorService?wsdl
[INFO] jaxws:wsimport args: [-keep,
chapter14-consumer/target/generated-sources/wsimport,
-encoding, UTF-8, -Xnocompile,
http://localhost:8080/chapter14-service-1.0/CardValidatorService?wsdl]
parsing WSDL...
Generating code...
[INFO] --------------------------------------------------------------------[INFO] BUILD SUCCESS
[INFO] ---------------------------------------------------------------------

, target/generated-sources/wsim
port . , ,
CardValidator, CardValidatorService CreditCard, SOAP
(Validate) (ValidateResponse).
JAXB JAX-WS, CreditCard
-. . .jar
:
$ mvn package

588 14. - SOAP


chapter14-consumer-1.0.jar, WebServiceConsumer, (..14.6,
). -.

WebServiceConsumer
, WebServiceConsumer @WebServiceRef,
-.
, (ACC). , chapter14-consumer-1.0.jar , Main-Class MANIFEST.MF. , , appclient,
GlassFish, .jar :
$ appclient -client chapter14-consumer-1.0.jar

- HTTP , , .

, , .
, CORBA, DCOM, RPC RMI.
HTTP (W3C, OASIS) - SOAP
(XML) .
- SOAP , ()
().
- SOAP (WSDL, SOAP ..). , Java EE, JAX-WS, JAXB, WS-Metadata .. , .
, JAX-WS
Java WSDL.
, -, , ( )
Maven. WSDL
- SOAP.
Amazon, eBay, Google, Yahoo!
- SOAP. -
RESTful ( ), .

15.
- REST
- SOAP (SOAP, WSDL, WS-*), , , . - SOAP, -
B2B-, ,
. Web2.0 -,
- . ,
. HTML5 JavaScript -.
-. - , RESTful. , ,
Amazon, eBay, Google Yahoo!, - SOAP
RESTful-, .
(REST) , . -, ,
. - ,
(HTTP) (URI),
. , , URI
. HTTP GET ( ), DELETE,
POST ( ) PUT ( ).
RESTful- ,
: HTTP. - , REST-,
. - RESTful, , ,
HTTP- -,
, . , ,
(, , WSDL).
,
, REST. ,
- .

590 15. - REST

- RESTful
- SOAP , HTTP.
. , -
RESTful HTTP :
. REST
,
(URI). , -.
. REST
. RESTful ,
.


REST ,
( ). , Java . ?
(www.piter.com).
, ,
Java, .
. Java :
http://www.piter.com/search/index.php?q=Java&s.x=21&s.y=12&s=%CF%EE%E8%F1%
EA&ext=&inSaleOnly=0&searchAs=0&orderBy=r&order=ASC&itemsPerPage=10.

, ( ?).
, . . . Java.
. - (http://www.piter.com/book.phtml?978549600544).
.
. REST
; ,
, , .. .

URI
RESTful- .
, , . ,
, , (, , ). ,
. -

591
- RESTful
; . , ,
?
Java.
Java. .
.
URI, , , . URI: WWW-, , , ,
(URL) (URN). URI .15.1.
15.1. URI

URI

http://books.piter.com/collection/kompyutery-iinternet

Java.

http://static2.insales.ru/images/products/1/3744/
25513632/49600544.jpg

http://books.piter.com/page/sotrudnichestvo

http://pogoda.ru/Sankt-Peterburg/

Flickr
1 2014

http://www.flickr.com/explore/2014/01/01

Flickr

http://www.flickr.com/explore/interesting/7days

http://www.movies.com/categories/adventure

URI , . : URI,
,
. URI :
http://host:port/path?queryString#fragment
http , host DNS- IP-, port . Path , ;
/. ,
( , /,
&).
, #, ,
. URI
1 2014 :
http://www.weather.com:8080/weather/2014/01/01?location=Lisbon,Portugal&time=
morning

592 15. - REST

, , . , URI?
? , : , JSON, XML, PDF,
JPG . , ; .
. , Java Apress :
HTML-, : http://www.apress.com/java;
, (CSV): http://
www.apress.com/resource/csv/bookcategory?cat=32.
?
. URI , . . :
http://www.apress.com/java;
http://www.apress.com/java/csv;
http://www.apress.com/java/xml.
URI , URI
/csv ( : text/csv), /xml, /pdf ..
URI
(, http://www.apress.com/java) ,
. .
, URI .

, RESTful, . - . , URI,
. URI ,
. - ,
, .
, .
- 42 CreditCardValida
tor.java .
,
, . ? : 42 CreditCardValidator,

593
- RESTful
, URI
. REST- : , , , ..
URI ,
, ,
. ,
, .

, . ,
uv vu u, v. REST .
.
- , ,
. ,
. REST , -
, ,
. REST . URI, ,
-,
, , ..
, () CD
(15.1), , ( URI). , .
.
15.1. CD,

<cd>
<title> </title>
<year ref="http://music.com/year/1956">1956</year>
<artist ref="http://music.com/artists/123"> </artist>
<artist ref="http://music.com/artists/456"> </artist>
<link rel="self" type="text/json" href="http://music.com/album/789"/>
<link rel="self" type="text/xml" href="http://music.com/album/789"/>
<link rel="http://music.com/album/comments" type="text/xml"
href="http://music.com/album/789/comments"/>
</cd>

, . , ,
- , .
.

594 15. - REST


XML- , .
, URI http://music.com/album/789/comments.
- , URI, ,
. GET
, PUT ..
, : .


, RESTful, .
, , , . , . ,
( ,
, (Architectural Styles and the Design of Network-based Software Architectures)).
,
.
- - HTTP. , , . HTTP
- . , SOAP, WSDL WS-*, HTTP ,
( SOAP- , JMS). , WSDL,
. -
(HTTP- URI), ,
(URI), HTTP- (GET, POST ..).
, . HTTP , ,
.


REST . , HTTP- ,
, .
:
. -

595
- RESTful
,
. 15.1, :
, ,
. , , , .
. ( ), .
.
, :
, ,
( ), (,
) .. ,
, .

HTTP
HTTP
. URI, HTML, -. HTTP W3C IETF. (RFC),
RFC216, HTTP1.1.


HTTP ,
.
(.15.1). , , .
.

.15.1. HTTP

Apress,
-, HTTP. ,
, , cURL. ,
http://www.apress.com/java?limit=all&mode=list:
$ curl vXGET http://www.apress.com/java?limit=all&mode=list
> GET /java?limit=all&mode=list HTTP/1.1
> User-Agent: curl/7.23.1 (x86_64-apple-darwin11.2.0) libcurl/7.23.1
zlib/1.2.5

596 15. - REST


> Host: www.apress.com
> Accept: */*

, :
HTTP-, GET;
, /java?limit=all&mode=list;
(User-Agent).
: .
GET .
:
< HTTP/1.1200 OK
< Date : Sat, 17 Nov 201217:42:15 GMT
< Server: Apache/2.2.3 (Red Hat)
< X-Powered-By: PHP/5.2.17
< Vary: Accept-Encoding,User-Agent
< Transfer-Encoding: chunked
< Content-Type : text/html; charset=UTF-8
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>
...

:
200-OK;
Date, Server, Content-Type. text/html,
, XML (application/
xml) (image/jpeg);
-
(
HTML-).

cURL (http://curl.haxx.se/) URL- , HTTP, FTP, SFTP, SCP
. HTTP-, HTTP- ..
.

HTTP- ,
.
/, ,
.
IETF

597
- RESTful
, HTTP. .
.15.2 , .
15.2.

Accept

(, text/plain)

Accept-Charset

(, utf-8)

Accept-Encoding

(, gzip, deflate)

Accept-Language

(en-US)

Cookie

HTTP-cookie,

Content-Length

Content-Type

MIME- (, text/xml)

Date

ETag

(,
8af7ad3082f20958)

If-Match

,
,

If-Modified-Since

304 ,

User-Agent

, (,
Mozilla/5.0)

HTTP-
,
HTTP-. HTTP- GET, POST, PUT, DELETE. , . HTTP , , : HEAD, TRACE, OPTIONS, CONNECT.
GET ,
. GET ,
. , GET . , ,
, : , .
.
(, - ), , ,
, .
.
POST, (, XML ..),
, URI, . , POST

598 15. - REST


, , .. , POST ( ),
(
). ,
201 . GET POST.
PUT , URI. URI ,
URI. PUT , ,
. PUT (
), :
PUT, .
DELETE . DELETE ,
, .
DELETE , .
, HTTP, .
yy HEAD GET , . HEAD .
yy TRACE, . TRACE , ( ) , .
yy OPTIONS
, /,
URI.
/ , , .
.
yy CONNECT -, ( HTTP
).


1 , 12 HTTP.
. ,
;
.
1

. . .

599
- RESTful
, ( ), HTTP- Accept, Accept-Charset, Accept-Encoding, AcceptLanguage User-Agent. , Java, ( )
http://books.piter.com/search?q=Java, Accept text/csv. ,
Accept-Language
CSV (, ).


HTTP , (
MIME-). Content-Type Accept .
: text, image, audio, video application.
(text/plain, text/xml, text/xhtml ..).
:
text/plain ,
;
text/html . , - HTML;
image/gif, image/jpeg, image/png , , ( , ) ;
text/xml, application/xml , XML-
;
application/json JavaScript (JSON). , (.12).


HTTP-.
60 . Status-Code
, , .
. :
1xx : , ;
2xx : , ;
3xx :
;
4xx :
;
5xx : ,
.

600 15. - REST


.15.3 , .
15.3. HTTP

100

101

200

. , ,

201

204 - ,

206

;
,

301

URI,
URI

304 ,
307

URI;
- URI

308

,
URI

400

401

403, ,

403

404

- , URI,

405 - ,

406 , Accept,
500

501

503 - ,

; ,

505 HTTP HTTP,

601
- RESTful


.
, .
HTTP . ,
, , .
GET
Last-Modified. .
, If-Modified-Since. - ( -)
. , , , 304 .
.
; , ,
.
ETag. ETag MD5- SHA1- .
, ETag.
.15.2 , ETag. , GET, URI (GET /
book/12345). XML- ,
200 , ETag.
, ETag If-None-Match,
,
. 304 , , .

. 15.2. 304

, HTTP- If-Modified-Since, If-Unmodified-Since,


If-Match, If-None-Match If-Range, .

602 15. - REST


(
, ),
. If-* GET PUT.

-
, . - ? ,
,
, . ; . ,
HTTP-? :
POST ( XML, JSON
) URI http://www.apress.com/book/. URI : http://www.apress.com/book/123456;
GET (
, , , )
http://www.apress.com/book/123456;
PUT http://www.ap
ress.com/book/123456;
DELETE http://www.apress.com/
book/123456.
HTTP-, CRUD.

WADL
SOAP- WADL, -. (WADL)
- REST. ,
. WADL W3C, , . 15.2 .
15.2. WADL, ,

<application xmlns="http://wadl.dev.java.net/2009/02">
<doc xmlns:jersey="http://jersey.java.net/" jersey:generatedBy="Jersey:
2.0"/>
<resources base="http://www.apress.com/">
<resource path="{id}">
<param name="id" style="template" type="xs:long"/>

603
-
<method name="GET">
<response>
<representation element="book" mediaType="application/xml"/>
<representation element="book" mediaType="application/json"/>
</response>
</method>
<method name="DELETE"/>
</resource>
<resource path="book">
<method name="GET">
<response>
<representation element="book" mediaType="application/xml"/>
<representation element="book" mediaType="application/json"/>
</response>
</method>
</resource>
</resources>
</application>

15.2 (http://www.apress.com/),
({id}) (GET) (DELETE)
. (GET) APress
JSON XML.

-

SOAP WS-*, W3C, REST
, . REST :
HTTP;
URI, URL;
XML, JSON, HTML, GIF, JPEG .. ( ).
Java JAX-RS (API Java
- ), REST
: ,
.

REST
REST ,
, 5 (
: http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm).
,

604 15. - REST


. ,
, ,
.
, , ,
.
, REST
. HTTP, , HTTP , .

API Java -

- REST Java , HTTP. HTTP-


XML HTTP. ,
. - JAX-RS. , ,
HTTP- .
JAX-RS ( JSR 311)
2008. API,
REST.
REST. Java EE7 JAX-RS 2.0. API.

JAX-RS2.0
JAX-RS2.0 ( JSR339)
, Java EE7 . JAX-RS2.0 :
API, JAX-RS1.x,

API. JAX-RS2.0 API
;
JAX-RS2.0 ,
SOAP . , ;
,
;
,
- .

605
-
.15.4 ,
JAX-RS.
15.4. JAX-RS

javax.ws.rs

,
-

javax.ws.rs.client

API JAX-RS

javax.ws.rs.container

- API JAX-RS

javax.ws.rs.core

, -

javax.ws.rs.ext

API, ,
JAX-RS API


JAX-RS Jersey. ,
: CDDL GPL. Jersey API Jersey.
JAX-RS, CXF (Apache), RESTEasy
(JBoss) Restlet ( , ,
JAX-RS).

-

(
HTTP), , - REST.
:
HTTP-, HTTP- . JAX-RS
API, - . - REST
POJO, , javax.ws.rs.Path.
15.3 .
15.3. - REST

@Path("/book")
public class BookRestService {
@GET
@Produces("text/plain")
public String getBookTitle() {
return "H2G2";
}
}

606 15. - REST


BookRestService Java, @Path. ,
URI /book. getBookTitle() HTTP- GET ( @GET).
(MIME- text/plain; MediaType.TEXT_PLAIN).
HTTP-, ,
URL http://www.myserver.com/book.
JAX-RS HTTP-
HTTP
URI. , API , JAXB
XML- . JAX-RS
.
GlassFish .

15.3 , REST- ,
- . ,
POJO REST-, @Path. JAX-RS
,
.
REST-:
@javax.ws.rs.Path (JAX-RS2.0
XML- , );
(),
, ;
( @Path) .
;
finalize();
EJB REST- @javax.ejb.Stateless @javax.ejb.Singleton (.7);
, ,
.

CRUD -
REST
15.3 , REST-, .
, .

607
-
REST- , . , @Stateless. ( JPA), 15.4.
15.4. REST- Book, ,

@Path("book")
@Stateless
public class BookRestService {
@Context
private UriInfo uriInfo;
@PersistenceContext(unitName = "chapter15PU")
private EntityManager em;
@GET
@Produces(MediaType.APPLICATION_XML)
public Books getBooks() {
TypedQuery<Book> query = em.createNamedQuery(Book.FIND_ALL, Book.class);
Books books = new Books(query.getResultList());
return books;
}
@POST
@Consumes(MediaType.APPLICATION_XML)
public Response createBook(Book book) {
em.persist(book);
URI bookUri =
uriInfo.getAbsolutePathBuilder().path(book.getId().toString()).build();
return Response.created(bookUri).build();
}
@DELETE
@Path("{id}")
public Response deleteBook(@PathParam("id") Long bookId) {
em.remove(em.find(Book.class, bookId));
return Response.noContent().build();
}
}

15.4 REST-, XML- . getBooks()


XML- (
). GET .
createBook() XML-
. HTTP- POST
(Response) URI (bookUri) , created. deleteBook

.

608 15. - REST


15.4 JAX-RS
. , .

URI URI
@Path URI
. , . 15.5
REST-, http://www.myserver.com/items.
/items .
15.5. Item

@Path("/items")
public class ItemRestService {
@GET
public Items getItems() {
// ...
}
}

. ,
15.6 ( , @GET, @POST @DELETE,
HTTP-).
15.6. ItemRestService

@Path("/items")
public class ItemRestService {
@GET
public Items getItems() {
// URI : /items
}
@GET
@Path("/cds")
public CDs getCDs() {
// URI : /items/cds
}
@GET
@Path("/books")
public Books getBooks() {
// URI: /items/books
}
@POST
@Path("/book")
public Response createBook(Book book) {

609
-
}

// URI: /items/book

15.6 - ,
( ) CD-Bookstore.
/items @Path (getItems()).
, @Path , . , CD : /items/cds. /items/books
getBooks(). ,
/items/book.
@Path("/items") ,
,
. HTTP- (GET,
PUT ..). .


REST URI,
. . - REST ,
. 15.4 ,
@javax.ws.rs.PathParam. JAX-RS
, (@PathParam, @QueryParam, @MatrixParam, @CookieParam, @HeaderParam
@FormParam).
15.7 , @PathParam
URI. , , ,
. searchCustomers
, getCustomerByLogin ([a-zA-Z]*), getCustomerById (\\d+).
15.7.

@Path("/customer")
@Produces(MediaType.APPLICATION_JSON)
public class CustomerRestService {
@Path("search/{text}")
public Customers searchCustomers(@PathParam("text") String textToSearch) {
// URI : /customer/search/smith
}
@GET
@Path("{login: [a-zA-Z]*}")

610 15. - REST


public Customer getCustomerByLogin(@PathParam("login") String login) {
// URI : /customer/foobarsmith
}
@GET
@Path("{customerId : \\d+}")
public Customer getCustomerById(@PathParam("customerId") Long id) {
// URI : /customer/12345
}
}

@QueryParam ,
URI. /, & . : http://www.myserver.com/custo
mer?zip=75012&city=Paris. @MatrixParam @QueryParam,
URI (
;). 15.8 , URI .
15.8.

@Path("/customer")
@Produces(MediaType.APPLICATION_JSON)
public class CustomerRestService {
@GET
public Customers getCustomersByZipCode(@QueryParam("zip") Long zip,
@QueryParam("city") String city) {
// URI : /customer?zip=75012&city=Paris
}
@GET
@Path("search")
public Customers getCustomersByName(@MatrixParam("firstname") String
firstname, @MatrixParam("surname") String surname) {
// URI : /customer/search;firstname=Antonio;surname=Goncalves
}
}

HTTP,
URI. cookie HTTP-.
@CookieParam cookie, @HeaderParam . 15.9 ID cookie HTTP-.
15.9. cookie HTTP-

@Path("/customer")
@Produces(MediaType.TEXT_PLAIN)
public class CustomerRestService {
@GET
public String extractSessionID(@CookieParam("sessionID") String sessionID) {

611
-
// ...
}
@GET
public String extractUserAgent(@HeaderParam("User-Agent") String userAgent) {
// ...
}
}

@FormParam , , .
@FormParam .
, @DefaultValue , . ,
. 15.10 , . , getCustomersByAge age, 50.
15.10. ,

@Path("/customer")
public class CustomerRestService {
@GET
public Customers getCustomersByAge(@DefaultValue("50") @QueryParam("age")
int age) {
// ...
}
@GET
public Customers getCustomersByCity(@DefaultValue("Paris")
@MatrixParam("city") String city) {
// ...
}
}



REST . , -, PDF- , . JAX-RS
Java, , String, InputStream JAXB. @javax.ws.rs.Consumes @javax.ws.rs.Produces , .
,
. JAX-RS javax.ws.rs.core.MediaType,
MIME-. , .15.5.

612 15. - REST


15.5. MIME-, MediaType

MIME-

APPLICATION_ATOM_XML

"application/atom+xml"

APPLICATION_FORM_URLENCODED

"application/x-www-form-urlencoded"

APPLICATION_JSON

"application/json"

APPLICATION_OCTET_STREAM

"application/octet-stream"

APPLICATION_SVG_XML

"application/svg+xml"

APPLICATION_XHTML_XML

"application/xhtml+xml"

APPLICATION_XML

"application/xml"

MULTIPART_FORM_DATA

"multipart/form-data"

TEXT_HTML

"text/html"

TEXT_PLAIN

"text/plain"

TEXT_XML

"text/xml"

WILDCARD

"*/*"

@Consumes @Produces, , .
(*/*). CustomerRestService
, (15.11). : getAsJsonAndXML
(XML JSON).
15.11. Customer

@Path("/customer")
@Produces(MediaType.TEXT_PLAIN)
public class CustomerRestService {
@GET
public Response getAsPlainText() {
// ...
}
@GET
@Produces(MediaType.TEXT_HTML)
public Response getAsHtml() {
// ...
}
@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response getAsJsonAndXML() {
// ...
}
@PUT
@Consumes(MediaType.TEXT_PLAIN)

613
-
public void putName(String customer) {
// ...
}
}

- REST ,

, Accept HTTP-. ,
Accept :
Accept: text/plain

URI /customer, getAsPlainText().


HTTP-:
Accept: text/plain; q=0.8, text/html

, text/plain text/html,
.
( ), 0,8 ( text/html,
text/plain, 80%-
). URI /customer
getAsHtml().


, ( , , HTTP-), .
- REST? Java,
Java, JAXB
, , HTTP. MIME-
(Entity
Provider, . ) . , HTTP
(, 204 ,
void null; 200 , ).
:
, , HTTP , , / cookie .
Reponse. ja
vax.ws.rs.core.Response, . 15.12 .
15.12. Customer, , JAXB

@Path("/customer")
public class CustomerRestService {
@GET
public String getAsPlainText() {
return new Customer("", "", "jsmith@gmail.com",

614 15. - REST


"1234565").toString();
}
@GET
@Path("maxbonus")
public Long getMaximumBonusAllowed() {
return 1234L;
}
@GET
@Produces(MediaType.APPLICATION_XML)
public Customer getAsXML() {
return new Customer("", "", "jsmith@gmail.com", "1234565");
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getAsJson() {
return Response.ok(new Customer("", "", "jsmith@gmail.com",
"1234565"), MediaType.APPLICATION_JSON).build();
}
}

getAsPlainText ,
getMaximumBonusAllowed . , ,
200 , . getAsXML Customer JAXB POJO. ,
XML-.
getAsJson HTML-, javax.ws.rs.core.Response.
Response HTML-, ,
ResponseBuilder, . - JAXB- (Customer)
200 ( ok()), JSON MIME-.
ResponseBuilder.build() Response.
Response ,
HTML- (
). .15.6 Response API.
15.6. Response API

accepted()

ResponseBuilder 202

created()

ResponseBuilder
( URI)

noContent()

ResponseBuilder

notModified()

ResponseBuilder 304

615
-

ok()

ResponseBuilder 200

serverError()

ResponseBuilder 500

status()

ResponseBuilder

temporaryRedirect() ResponseBuilder
getCookies()

cookie

getHeaders()

getLinks()

getStatus()

readEntity()

Java.
MessageBodyReader,

Response ResponseBuilder . , ,
. .
, API:
Response.ok().build();
Response.ok().cookie(new NewCookie("SessionID", "5G79GDIFY09")).build();
Response.ok("Plain Text").expires(new Date()).build();
Response.ok(new Customer ("", ""), MediaType.APPLICATION_JSON).
build();
Response.noContent().build();
Response.accepted(new Customer("", "", "jsmith@gmail.com",
"1234565")).build();
Response.notModified().header("", "Mozilla").build();

HTTP-
, , HTTP , (GET, POST, PUT ..) JAX-RS
HTTP- @GET, @POST, @PUT, @DELETE, @HEAD @OPTIONS.
. 15.13 - REST, CRUD: @GET , @POST
, @PUT @DELETE
.
15.13. Customer, CRUD-

@Path("/customer")
@Produces(MediaType.APPLICATION_XML)
@Consumes(MediaType.APPLICATION_XML)

616 15. - REST


public class CustomerRestService {
@GET
public Response getCustomers() {
// ..
return Response.ok(customers).build();
}
@GET
@Path("{customerId}")
public Response getCustomer(@PathParam("customerId") String customerId) {
// ..
return Response.ok(customer).build();
}
@POST
public Response createCustomer(Customer customer) {
// ..
return Response.created(createdCustomerURI).build();
}
@PUT
public Response updateCustomer(Customer customer) {
// ..
return Response.ok(customer).build();
}
@DELETE
@Path("{customerId}")
public Response deleteCustomer(@PathParam("customerId") String customerId) {
// ..
return Response.noContent().build();
}
}

HTTP , HTTP
. , JAX-RS .
GET ( ) , URI. GET 200 .
PUT , . ,
: 200 204 .
.
POST , URI
. 201 URI
204 , ,
URI.
DELETE , , URI.

617
-
200 ( ), 202 (
) 204 , ,

.
URI. REST-.
, REST
URI. JAX-RS javax.ws.rs.core.UriBuilder,
java.net.URI URI. UriBuilder
, URI
URI. 15.14 UriBuilder URI ,
, .
15.14. UriBuilder

public class URIBuilderTest {


@Test
public void shouldBuildURIs() {
URI uri =
UriBuilder.fromUri("http://www.myserver.com").path("book").path("1234").
build();
assertEquals("http://www.myserver.com/book/1234", uri.toString());
uri = UriBuilder.fromUri("http://www.myserver.com").path("book ")
.queryParam("author", "Goncalves").build();
assertEquals("http://www.myserver.com/book?author=Goncalves",
uri.toString());
uri = UriBuilder.fromUri("http://www.myserver.com").path("book")
.matrixParam("author", "Goncalves").build();
assertEquals("http://www.myserver.com/book;author=Goncalves", uri.toString());
uri = UriBuilder.fromUri("http://www.myserver.com").path("{path} ")
.queryParam("author", "{value}").build("book", "Goncalves");
assertEquals("http://www.myserver.com/book?author=Goncalves",
uri.toString());
uri = UriBuilder.fromResource(BookRestService.class).path("1234").build();
assertEquals("/book/1234", uri.toString());
uri = UriBuilder.fromUri("http://www.myserver.com").fragment("book").build ();
assertEquals("http://www.myserver.com/#book", uri.toString());
}
}


, . @javax.ws.rs.core.
Context
: HttpHeaders , UriInfo , Request , SecurityContext Providers . ,

618 15. - REST


15.15 , UriInfo ,
URI, HttpHeaders .
15.15. Customer, HttpHeaders UriInfo

@Path("/customer")
public class CustomerRestService {
@Context
UriInfo uriInfo;
@Inject
private CustomerEJB customerEJB;
@GET
@Path("media")
public String getDefaultMediaType(@Context HttpHeaders headers) {
List<MediaType> mediaTypes = headers.getAcceptableMediaTypes();
return mediaTypes.get(0).toString();
}
@GET
@Path("language")
public String getDefaultLanguage(@Context HttpHeaders headers) {
List<String> mediaTypes =
headers.getRequestHeader(HttpHeaders.ACCEPT_LANGUAGE);
return mediaTypes.get(0);
}
@POST
@Consumes(MediaType.APPLICATION_XML)
public Response createCustomer(Customer cust) {
Customer customer = customerEJB.persist(cust);
URI bookUri =
uriInfo.getAbsolutePathBuilder().path(customer.getId()).build();
return Response.created(bookUri).build();
}
}

HTTP,
, (Date, Server,
Content-Type ..). HTTP- , - REST .
HTTP-.
javax.ws.rs.core.HttpHeaders. HttpHeaders
@Context,
HttpHeaders
. 15.15
Accept-Language MediaType.

619
-

JAX-RS2.0 @Context . , @Inject ,
CDI . ,
JAX-RS CDI
: @Inject.


, JAX-RS
Java . , Java.
JAXB, XML- .
XML JSON , .
. JAX-RS / , . : MessageBodyReader MessageBodyWriter.
, Customer custom/format,
1234/John/Smith. ,
/, ,
, . (
), Customer . 15.16 CustomCustomerWriter ,
javax.ws.rs.ext.MessageBodyWriter
@Provider. @Produces
("custom/format"). , writeTo Customer
, .
15.16. , Customer

@Provider
@Produces("custom/format")
public class CustomCustomerWriter implements MessageBodyWriter<Customer> {
@Override
public boolean isWriteable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return Customer.class.isAssignableFrom(type);
}
@Override
public void writeTo(Customer customer, Class<?> type, Type gType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
OutputStream outputStream) throws IOException, WebApplicationException {
outputStream.write(customer.getId().getBytes());
outputStream.write('/');

620 15. - REST


outputStream.write(customer.getFirstName().getBytes());
outputStream.write('/');
outputStream.write(customer.getLastName().getBytes());
}
@Override
public long getSize(Customer customer, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return customer.getId().length() + 1 + customer.getFirstName().length()
+ 1 + customer.getLastName().length();
}
}

, Java javax.ws.rs.ext.MessageBodyReader @Provider. ,


(*/*). @Consumes 15.17 . readFrom
, /
Customer. MessageBodyReader MessageBodyWriter WebApplicationException, .
15.17. ,
Customer

@Provider
@Consumes("custom/format")
public class CustomCustomerReader implements MessageBodyReader<Customer> {
@Override
public boolean isReadable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return Customer.class.isAssignableFrom(type);
}
@Override
public Customer readFrom(Class<Customer> type, Type gType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> httpHeaders, InputStream inputStream)
throws IOException, WebApplicationException {
String str = convertStreamToString(inputStream);
StringTokenizer s= new StringTokenizer(str, "/");
Customer customer = new Customer();
customer.setId(s.nextToken());
customer.setFirstName(s.nextToken());
customer.setLastName(s.nextToken());
return customer;
}
}

621
-
CustomCustomerWriter CustomCustomerReader, , . . - REST
, JAX-RS
:
@GET
@Produces("custom/format")
public Customer getCustomCustomer () {
return new Customer("1234", "", "");
}

, JAX-RS
(.15.7).
.
15.7. , JAX-RS

byte[]

(*/*)

java.lang.String

(*/*)

java.io.InputStream

(*/*)

java.io.Reader

(*/*)

java.io.File

(*/*)

javax.activation.DataSource

(*/*)

javax.xml.transform.Source

XML- (text/xml, application/xml)

javax.xml.bind.JAXBElement

XML,
JAXB (text/xml, application/xml)

MultivaluedMap<String,String>

(application/x-wwwform-urlencoded)

javax.ws.rs.core StreamingOutput

(*/*),
MessageBodyWriter


,
. ,
,
- , - .
. , . , ,
(ServletException, WebServiceException WebApplicationException).
javax.ws.rs.WebApplicationException
(BadRequestException, ForbiddenException, NotAcceptableException, NotAllowedException,

622 15. - REST


NotAuthorizedException , NotFoundException , NotSupportedException ).

JAX-RS HTTP-.
500 .
javax.ws.rs.WebApplicationException , ( jav ax.ws.rs.cor e.Resp onse.Status ) . 15.18
getCustomer (IllegalArgumentException ),
1000, 404 ,
, ,
. NotFoundException.
15.18. ,

@Path("/customer")
public class CustomerRestService {
@Inject
private CustomerEJB customerEJB;
@Path("{customerId}")
public Customer getCustomer(@PathParam("customerId") Long customerId) {
if (customerId < 1000)
throw new IllegalArgumentException("Id must be greater than 1000!");
Customer customer = customerEJB.find(customerId);
if (customer == null)
throw new WebApplicationException(Response.Status.NOT_FOUND);
return customer;
}
}

1, .
Response. , JAX-RS . ExceptionMapper<Eextends
java.lang.Throwable>, @Provider. 15.19 javax.persistence.EntityNotFoundException
404 .
15.19. JPA, 404

@Provider
public class EntityNotFoundMapper implements ExceptionMapper<EntityNotFound
Exception> {
public Response toResponse(javax.persistence.EntityNotFoundException ex) {
return Response.status(404).entity(ex.getMessage()).type(MediaType.TEXT_
PLAIN).build();
}
}
1

DRY, , Don'tRe
peat Yourself . . .

623
-



REST-,
, . , ;
, ,
.
Java EE ( EJB) JAX-RS JSR250 : @PostConstruct,
@PreDestroy, @RunAs, @RolesAllowed, @PermitAll, @DenyAll @DeclareRoles.
@PostConstruct @PreDestroy - .
.15.3 ,
Java EE.

. 15.3.

- REST WAR- EJB


JAR- , -
Java EE7. , -
REST @Stateless @Singleton . SOAP , REST
. ,
@Path ( ). :
JAX-RS2.0 .

624 15. - REST

- REST
, - ,
,
CRUD, .. ?
.15.1, HTTP- URI. , ,
REST.
. ,
URI . , HTTP- GET POST.
, . PUT DELETE
( Postman Chrome). , , cUrl.
HTTP- , ,
- REST.
JAX-RS2.0 Java - REST.
API java.net.HttpURLConnection, API
(, Jersey, Resteasy Restlet). JAX-RS
, API .

API
JAX-RS 2.0 API, HTTP- REST- (
HTTP). API ( ),
(
javax.ws.rs.client .15.8, API Response
.15.6). : Client, WebTarget Response. Client ( ClientBuilder) WebTarget. WebTarget
URI,
Response. HTTP-,
cookie. , .
Entity.
15.8. javax.ws.rs.client

Client

API,

ClientBuilder

API,
Client

625
- REST
/
Configurable
Entity
Invocation
Invocation.Builder
WebTarget

Client, WebTarget Invocation


,

,

, URI

, ,
API. -
REST.


API Client. HTTP- . , WebTargets,

. Client
ClientBuilder:
Client client = ClientBuilder.newClient();

Client
.
Client , . ,
CustomCustomerReader (.15.17)
:
Client client = ClientBuilder.newClient();
client.configuration().register(CustomCustomerReader.class).
setProperty("MyProperty", 1234);


Client, URI -
REST HTTP-.
WebTarget Invocation. Client.target()
-, URI. WebTarget. WebTarget
URI:
WebTarget target = client.target("http://www.myserver.com/book");

WebTarget java.net.URI, javax.ws.rs.core.UriBuilder


javax.ws.rs.core.Link:
URI uri = new URI("http://www.myserver.com/book");
WebTarget target = client.target(uri);

URI, .
HTTP-. WebTarget Invocation.Builder.
HTTP- GET URI, :
Invocation invocation = target.request().buildGet()

626 15. - REST


Invocation.Builder GET, POST, PUT DELETE.
, MIME-
, . PUT POST Entity,
- REST:
target.request().buildDelete();
target.queryParam("author", "Eloise").request().buildGet();
target.path(bookId).request().buildGet();
target.request(MediaType.APPLICATION_XML).buildGet();
target.request(MediaType.APPLICATION_XML).acceptLanguage("pt").buildGet();
target.request().buildPost(Entity.entity(new Book()));

Invocation. invoke()
- REST
Response, () . Response :
Response response = invocation.invoke();

, , GET REST-, http://www.my


server.com/book. text/plain:
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://www.myserver.com/book");
Invocation invocation = target.request(MediaType.TEXT_PLAIN).buildGet();
Response response = invocation.invoke();

API
:
Response response =
ClientBuilder.newClient().target("http://www.myserver.com/book")
.request(MediaType.TEXT_PLAIN).get();

, Response .


Response HTTP, - REST. API
HTTP, , cookie , , ( , ). , ,

HTTP , , , HTTP-:
assertTrue(response.getStatusInfo() == Response.Status.OK);
assertTrue(response.getLength() == 4);
assertTrue(response.getDate() != null);
assertTrue(response.getHeaderString("Content-type").equals("text/plain"));

627
- REST
Response , - REST. readEntity
, Java.
MessageBodyReader,
. , ,
(String), JAX-RS :
String body = response.readEntity(String.class);

readEntity() POJO,
JAX-RS MessageBodyReader, . , Book JAXB, XML, JAX-RS
JAXB XML POJO Book:
Book book = response.readEntity(Book.class);

, REST :
Response response =
ClientBuilder.newClient().target("http://www.myserver.com/book")
.request().get();
String body = response.readEntity(String.class);

GET ,
( Response ):
String body =
ClientBuilder.newClient().target("http://www.myserver.com/book")
.request().get(String.class);

REST
JAX-WS, Java SE
- SOAP JDK, JAX-RS
API. .
SOAP . - REST Java,
JVM ( , , ),
Java EE, (, EJB, ).
, - REST . , , (, ),
- (, JavaScript).

628 15. - REST


, , -
REST , GlassFish.
, cURL
( API). JAXB- Books,
JPA- Book, .
BookRestService CRUD- . - ,

( ). , , , HTTP-
cURL API JAX-RS. JAXB Jersey
XML JSON.
, Maven.
WAR (chapter15-service-1.0.war). , .15.4, :
src/main/java Books, Book BookRestService,
,
( ApplicationConfig );
src/main/resources persistence.xml, ,
Book Derby;
src/test/java BookRestServiceIT;
pom.xml Maven (POM),
.

. 15.4.

Book
Book,
: JAXB @XmlRootElement

629

(15.20). XML-
.
15.20. Book JAXB

@Entity
@XmlRootElement
@NamedQuery(name = Book.FIND_ALL, query = "SELECT bFROM Book b")
public class Book {
public static final String FIND_ALL = "Book.findAll";
@Id
@GeneratedValue
private String id;
@Column(nullable = false)
private String title;
private Float price;
@Column(length = 2000)
private String description;
private String isbn;
private Integer nbOfPage;
private Boolean illustrations;
// , ,
}

persistence.xml (
).

JAXB- Books
, - REST,
. List<Book>, JAXB-. XML- ,
POJO, JAXB. 15.21,
Books ArrayList<Book> @XmlRootElement.
15.21. JAXB- Books, Book

@XmlRootElement
@XmlSeeAlso(Book.class)
public class Books extends ArrayList<Book> {
public Books() {
super();
}
public Books(Collection<? extends Book> c) {
super(c);
}
@XmlElement(name = "book")

630 15. - REST


public List<Book> getBooks() {
return this;
}
public void setBooks(List<Book> books) {
this.addAll(books);
}
}

BookRestService
BookRestService - REST,

. ,
, .
.

BookRestService (15.22) , . JAX-RS ,


URI. @Path("/book") (URL,
).
: http://localhost:8080/book.
15.22. BookRestService

@Path("/book")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Stateless
public class BookRestService {
@PersistenceContext(unitName = "chapter15PU")
private EntityManager em;
@Context
private UriInfo uriInfo;
// ...

@Produces @Consumes
, :
XML JSON. , @Stateless, 7. , -
REST EJB .
, UriInfo.


REST, HTTP- POST
XML JSON ( ,
@Consumes). XML JSON,
createBook(). 15.23,
Book ; , Book

631

JAXB XML Book
. book , BadRequestException ( 400 ).
15.23. createBook BookRestService

// ...
@POST
public Response createBook(Book book) {
if (book == null)
throw new BadRequestException();
em.persist(book);
URI bookUri = uriInfo.getAbsolutePathBuilder().path(book.getId()).build();
return Response.created(bookUri).build();

}
// ...

Response, URI
. 200 (Response.ok()), , . REST 201 ( 204), ,
(Response.created()). URI, (bookUri).
, 15.23, XML JSON. JSON .
cURL POST JSON. JSON/XML, Jersey ( , XML,
, Book JAXB):
$ curl -XPOST --data-binary "{\"description\":\"-
\",
\"illustrations\":false,\"isbn\":\"1-84023-742-2\",\"nbOfPage\":354,
\"price\":12.5,\"title\":\" \"}"
-H"Content-Type: application/json"
http://localhost:8080/chapter15-service-1.0/rs/book -v

cURL ( -v) HTTP-


(. ). URI ,
601:
>
>
>
>
>
>
>
<
<

POST /chapter15-service-1.0/rs/book HTTP/1.1


User-Agent: curl/7.23.1 (x86_64-apple-darwin11.2.0) libcurl/7.23.1
Host: localhost:8080
Accept: */*
Content-Type: application/json
Content-Length: 165
HTTP/1.1201 Created
Server: GlassFish Server Open Source Edition 4.0

632 15. - REST


< Location: http://localhost:8080/chapter15-service-1.0/rs/book/601
< Date: Thu, 29 Nov 201221:49:44 GMT
< Content-Length: 0

ID
, URL
/book/{id }. id
. 15.24 ,
NotFoundException (404). MIME- getBook() XML JSON.
15.24. getBook BookRestService

// ...
@GET
@Path("{id}")
public Response getBook(@PathParam("id") String id) {
Book book = em.find(Book.class, id);
if (book == null)
throw new NotFoundException();
return Response.ok(book).build();
}
// ...

@Path . {id} URL-


. cURL 601 JSON-:
$ curl -XGET -H"Accept: application/json"
http://localhost:8080/chapter15-service-1.0/rs/book/601
{"description":"- ","id":"1",
"illustrations":false,"isbn":"1-84023-742-2","nbOfPage":354,
"price":12.5,"title":"H2G2"}

Accept, XML 601:


$ curl -XGET -H"Accept: application/xml"
http://localhost:8080/chapter15-service-1.0/rs/book/601
<?xml version="1.0" encoding="UTF-8"
standalone="yes"?><book><description>-
</description><id>601</id><illustrations>false</illustrations>
<isbn>1-84023-742-2</isbn><nbOfPage>354</nbOfPage><price>12.5</price>
<title>H2G2</title></book>


15.25
TypedQuery, Books. ,

633

ArrayList<Book> XML-
JAXB. 200 ,
.
15.25. getBooks BookRestService

// ...
@GET
public Response getBooks() {
TypedQuery<Book> query = em.createNamedQuery(Book.FIND_ALL, Book.class);
Books books = new Books(query.getResultList());
return Response.ok(books).build();
}
// ...

, cUrl, ,
XML, JSON:
$ curl -XGET -H"Accept: application/json"
http://localhost:8080/chapter15-service-1.0/rs/book
$ curl -XGET -H"Accept: application/xml"
http://localhost:8080/chapter15-service-1.0/rs/book


deleteBook() 15.26 getBook(),
ID .
getBook() , HTTP-
DELETE ( GET). ,
NotFoundException, 204 .
15.26. deleteBook BookRestService

// ...
@DELETE
@Path("{id}")
public Response deleteBook(@PathParam("id") String id) {
Book book = em.find(Book.class, id);
if (book == null)
throw new NotFoundException();
em.remove(book);
return Response.noContent().build();
}
// ...

cURL ( -v), DELETE. 204 . , :


$ curl -XDELETE http://localhost:8080/chapter15-service-1.0/rs/book/601 -v>
DELETE /chapter15-service-1.0/rs/book/601 HTTP/1.1

634 15. - REST


>
>
>
>
<
<

User-Agent: curl/7.23.1 (x86_64-apple-darwin11.2.0) libcurl/7.23.1


Host: localhost:8080
Accept: */*
HTTP/1.1204 NoContent
Server: GlassFish Server Open Source Edition 4.0

JAX-RS
BookRestService Book Jersey url; HTTP-,
. , , /rs, Jersey. url Jersey web.xml, @ApplicationPath ( 15.27).
ApplicationConfig javax.ws.rs.core.Application
- REST ( c.add(BookRestService.class)),
(c.add(MOXyJsonProvider.class)).
15.27. ApplicationConfig, URL- /rs

@ApplicationPath("rs")
public class ApplicationConfig extends Application {
private final Set<Class<?>> classes;
public ApplicationConfig() {
HashSet<Class<?>> c= new HashSet<>();
c.add(BookRestService.class);
c.add(MOXyJsonProvider.class);
classes = Collections.unmodifiableSet(c);
}
@Override
public Set<Class<?>> getClasses() {
return classes;
}
}

- (
), @ApplicationPath URL- /rs/*. , , URL
/rs/, Jersey . ,
, cURL, URL /rs:
$ curl -XGET -H"Accept: application/json"
http://localhost:8080/chapter15-service-1.0/rs/book

12 , XML JSON.
: (JAXP JSON-P)
(JAXB). JAX-RS
XML MessageBodyReader MessageBodyWriter,

635

JAXB. , JSON (,
JSON-B).
JSON. ApplicationConfig Jersey (MOXyJsonProvider). JSON-
MessageBodyReader MessageBodyWriter.
JAX-RS.

Maven
WAR-
(<packaging>war</packaging>). pom.xml, 15.28,
, (
glassfish-embedded-all). , JAXB Java SE, . , pom.xml
Failsafe, ( BookRestServiceIT,
).
15.28. pom.xml , -

<?xml version="1.0" encoding="UTF-8"?>


<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>chapter15</artifactId>
<groupId>org.agoncal.book.javaee7</groupId>
<version>1.0</version>
</parent>
<groupId>org.agoncal.book.javaee7.chapter15</groupId>
<artifactId>chapter15-service</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.glassfish.main.extras</groupId>
<artifactId>glassfish-embedded-all</artifactId>
<version>4.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>

636 15. - REST


<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.2</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.12.4</version>
<executions>
<execution>
<id>integration-test</id>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>


, pom.xml, Maven:
$ mvn package

, chapter15-service-1.0.war . : Book.class, Books.class, ApplicationConfig.class


BookRestService.class WEB-INF\classes. WAR persistence.xml.

637

GlassFish
, , GlassFish Derby,
WAR-,
asadmin . , target,
chapter15-service-1.0.war, :
$ asadmin deploy chapter15-service-1.0.war

,
:
$ asadmin list-components
chapter15-service-1.0 <ejb, web>

, ,
cURL , POST, ( )
GET. DELETE .

WADL
WADL ( -)
, REST. ,
REST- BookRestService, URL: http://local
host/8080/chapter15-service-1.0/rs/application.wadl. 15.29 WADL-.
15.29. WADL, GlassFish
- BookRestService REST

<application xmlns="http://wadl.dev.java.net/2009/02">
<resources base="http://localhost:8080/chapter15-service-1.0/rs/">
<resource path="/book">
<method id="POST" name="POST">
<request>
<representation element="book" mediaType="application/xml"/>
<representation element="book" mediaType="application/json"/>
</request>
</method>
<resource path="{id}">
<param name="id" style="template" type="xs:string"/>
<method id="GET{id}" name="GET">
<response>
<representation mediaType="application/xml"/>
<representation mediaType="application/json"/>
</response>
</method>
<method id="DELETE{id}" name="DELETE"/>
</resource>
</resource>
...

638 15. - REST


</resources>
</application>

WADL 15.29 (http://localhost:8080/


chapter15-service-1.0/rs/) , REST- (/book {id}).
, HTTP-, ( POST,
GET, DELETE...).


BookRestServiceIT
, GlassFish, , HTTP- -
REST. API JAX-RS 2.0 Client.
, . . ,
GlassFish Derby , 15.30
.
. shouldNotCreateANullBook , Book. ,
400 . shouldNotFindTheBookID ID ,
404 .
shouldCreateAndDeleteABook ,
. -, XML Book ,
201 . bookURI URI
. URI .
, Book (book = response.
readEntity(Book.class)) ,
. DELETE, , 204 .
GET, , , 404 .
15.30. ApplicationConfig, URL- /rs

public class BookRestServiceIT {


private static URI uri = UriBuilder.
fromUri("http://localhost/chapter15-service-1.0/rs/book").port(8080).build ();
private static Client client = ClientBuilder.newClient();
@Test
public void shouldNotCreateANullBook() throws JAXBException {
// POST
Response response = client.target(uri).request().post(Entity.entity(null,
MediaType.APPLICATION_XML));

639

assertEquals(Response.Status.BAD_REQUEST, response.getStatusInfo());
}
@Test
public void shouldNotFindTheBookID() throws JAXBException {
// ID GET
Response response = client.target(uri).path("unknownID").request(). get ();
assertEquals(Response.Status.NOT_FOUND, response.getStatusInfo());
}
@Test
public void shouldCreateAndDeleteABook() throws JAXBException {
Book book = new Book("H2G2", 12.5F, "Science book", "1-84023-742-2", 354,
false);
// POST
Response response = client.target(uri).request().post(Entity.entity(book,
MediaType.APPLICATION_XML));
assertEquals(Response.Status.CREATED, response.getStatusInfo());
URI bookURI = response.getLocation();
// , GET
response = client.target(bookURI).request().get();
book = response.readEntity(Book.class);
assertEquals(Response.Status.OK, response.getStatusInfo());
assertEquals("H2G2", book.getTitle());
// id DELETE
String bookId = bookURI.toString().split("/")[6];
response = client.target(uri).path(bookId).request().delete();
assertEquals(Response.Status.NO_CONTENT, response.getStatusInfo());
// GET Book ,
response = client.target(bookURI).request().get();
assertEquals(Response.Status.NOT_FOUND, response.getStatusInfo());
}
}

, GlassFish Derby , Maven Failsafe.


Maven:
$ mvn failsafe:integration-test

- SOAP.
-, JAX-RS JAX-WS.
REST HTTP,

640 15. - REST


, , , , . ,
HTTP- (GET, POST, PUT .) , .
HTTP,
. HTTP ,
, cookie . HTTP-
- REST
URI . ,
( ETag). REST- HTTP, .
API JAX-RS2.0
- REST.
JAX-RS API Java, Java EE7 - .
, ,
HTTP- (@GET, @POST
..). - REST
, ,
HTTP.
,
.