This self-study exam preparation guide for the SCEA certification exam contains everything you need to test yourself and pass the Exam. All Exam topics are covered and insider secrets, complete explanations of all SCEA subjects, test tricks and tips, numerous highly realistic sample questions, and exercises designed to strengthen understanding of SCEA concepts and prepare you for exam success on the first attempt are provided. Put your knowledge and experience to the test. Achieve SCEA certification and accelerate your career. Can you imagine valuing a book so much that you send the author a "Thank You" letter? Tens of thousands of people understand why this is a worldwide best-seller. Is it the authors years of experience? The endless hours of ongoing research? The interviews with those who failed the exam, to identify gaps in their knowledge? Or is it the razor-sharp focus on making sure you don't waste a single minute of your time studying any more than you absolutely have to? Actually, it's all of the above. This book includes new exercises and sample questions never before in print. Offering numerous sample questions, critical time-saving tips plus information available nowhere else, this book will help you pass the SCEA exam on your FIRST try. Up to speed with the theory? Buy this. Read it. And Pass the SCEA Exam.
ISBN 978-1-74244-657-8
90000
9 781742 446578
SCEA: Sun Certified Enterprise Architect CX 310-052 Exam Certification Exam Preparation Course in a Book for Passing the SCEA Exam - The How To Pass on Your First Try Certification Study Guide
Sun Certified Enterprise Architect for the Java EE Platform (SCEA) certification certifies the skills of a software architect in the Java Enterprise Edition technology (formerly J2EE).
Foreword This Exam Preparation book is intended for those preparing for the Sun Certified Enterprise Architect certification. This book is not a replacement for completing the course. This is a study aid to assist those who have completed an accredited course and preparing for the exam. Do not underestimate the value of your own notes and study aids. The more you have, the more prepared you will be. While it is not possible to pre-empt every question and content that may be asked in the SCEA exam, this book covers the main concepts covered within the Enterprise Architect discipline. Due to licensing rights, we are unable to provide actual SCEA Exam. However, the study notes and sample exam questions in this book will allow you to more easily prepare for the SCEA exam. Ivanka Menken Executive Director The Art of Service
Write a review to receive any free eBook from our Catalog - $99 Value! If you recently bought this book we would love to hear from you! Benefit from receiving a free eBook from our catalog at http://www.emereo.org/ if you write a review on Amazon (or the online store where you purchased this book) about your last purchase! How does it work? To post a review on Amazon, just log in to your account and click on the Create your own review button (under Customer Reviews) of the relevant product page. You can find examples of product reviews in Amazon. If you purchased from another online store, simply follow their procedures. What happens when I submit my review? Once you have submitted your review, send us an email at
[email protected] with the link to your review, and the eBook you would like as our thank you from http://www.emereo.org/. Pick any book you like from the catalog, up to $99 RRP. You will receive an email with your eBook as download link. It is that simple!
2
Copyright The Art of Service │Brisbane, Australia│Email:
[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Notice of Rights All rights reserved. No part of this book may be reproduced or transmitted in any form by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the publisher. Notice of Liability The information in this book is distributed on an “As Is” basis without warranty. While every precaution has been taken in the preparation of the book, neither the author nor the publisher shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the instructions contained in this book or by the products described in it. Trademarks Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations appear as requested by the owner of the trademark. All other product names and services identified throughout this book are used in editorial fashion only and for the benefit of such companies with no intention of infringement of the trademark. No such use, or the use of any trade name, is intended to convey endorsement or other affiliation with this book.
3
Copyright The Art of Service │Brisbane, Australia│Email:
[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Table of Contents Foreword ......................................................................................... 1 Table of Contents ............................................................................. 4 1
Sun Certified Enterprise Architect ............................................ 10
2
Exam Specifics ......................................................................... 11 2.1.
3
Exam Prerequisites ................................................................... 11
General Java Concepts ............................................................ 12 3.1.
Philosophy Behind Java ............................................................ 12 3.1.1. Object‐Oriented Language .............................................................. 12 3.1.2. Language Elements ......................................................................... 13
3.2.
Source Files .............................................................................. 14
3.3.
Primitives and Constructs ......................................................... 15 Data Types ....................................................................................... 15 Integral (int) ..................................................................................... 16 Floating Point .................................................................................. 16 Boolean ........................................................................................... 17 Character ......................................................................................... 17 Enumeration .................................................................................... 18 Objects ............................................................................................ 19 Arrays .............................................................................................. 19 Classes ............................................................................................. 20
3.3.1. 3.3.2. 3.3.3. 3.3.4. 3.3.5. 3.3.6. 3.3.7. 3.3.8. 3.3.9.
3.4.
Class Fundamentals ................................................................. 21 Inheritance ...................................................................................... 22 Types of Classes ............................................................................... 23 Abstract Classes ............................................................................... 24 Interfaces......................................................................................... 24
3.4.1. 3.4.2. 3.4.3. 3.4.4.
3.5.
Class Declaration ...................................................................... 26 Class Modifiers ................................................................................ 27 Modifiers ......................................................................................... 28
3.5.1. 3.5.2.
3.6.
Functionality ............................................................................ 33 Importing......................................................................................... 33 Argument Passing ............................................................................ 35 Encapsulation .................................................................................. 35 Inheritance ...................................................................................... 36
3.6.1. 3.6.2. 3.6.3. 3.6.4.
4
Copyright The Art of Service │Brisbane, Australia│Email:
[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
3.6.5. 3.6.6. 3.6.7. 3.6.8.
3.7.
Polymorphism ................................................................................. 37 Garbage Collection .......................................................................... 37 Converting and Casting ................................................................... 38 Object Reference Conversion and Casting ...................................... 41
Algorithm Design ..................................................................... 43 Assignment ...................................................................................... 44 Condition ......................................................................................... 44 Iteration ........................................................................................... 45 Operators ........................................................................................ 46
3.7.1. 3.7.2. 3.7.3. 3.7.4.
3.8.
Algorithms ............................................................................... 48 Variables .......................................................................................... 48 Instance Variable ............................................................................. 48 Local Variable .................................................................................. 49 Methods .......................................................................................... 50
3.8.1. 3.8.2. 3.8.3. 3.8.4.
3.9.
Operators ................................................................................. 50 Unary Operators .............................................................................. 51 Assignment Operators ..................................................................... 53 Arithmetic Operators ...................................................................... 53 Comparison Operators .................................................................... 56 Bitwise Operators ............................................................................ 57 Short‐Circuit Logical Operators ....................................................... 59 Conditional Operators ..................................................................... 59
3.9.1. 3.9.2. 3.9.3. 3.9.4. 3.9.5. 3.9.6. 3.9.7.
3.10.
Exceptions ............................................................................ 60
3.11.
Assertions ............................................................................ 65 Overloading and Overriding ............................................................ 66 Constructors .................................................................................... 69 Inner Classes ................................................................................... 70 Contracts and Conventions ............................................................. 73 Threads ............................................................................................ 74
3.11.1. 3.11.2. 3.11.3. 3.11.4. 3.11.5.
3.12. 3.12.1.
3.13. 3.13.1. 3.13.2. 3.13.3. 3.13.4. 3.13.5.
3.14.
Methods from String Class.................................................... 79 Key Methods ................................................................................... 80 Java Development Fundamentals ......................................... 81 Packages .......................................................................................... 81 Importing Packages ......................................................................... 82 “javac” Command............................................................................ 83 Classpaths ....................................................................................... 84 “java” Command ............................................................................. 85 Class Library ......................................................................... 86 5
Copyright The Art of Service │Brisbane, Australia│Email:
[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
3.14.1. 3.14.2. 3.14.3. 3.14.4. 3.14.5. 3.14.6.
4
java.lang .......................................................................................... 86 java.util ............................................................................................ 89 java.io .............................................................................................. 90 java.net ............................................................................................ 92 java.awt ........................................................................................... 92 java.swing ........................................................................................ 93
Enterprise JavaBeans .............................................................. 94 4.1.
Overview ................................................................................. 94 Uses of Enterprise JavaBeans .......................................................... 94 Benefits of Enterprise JavaBeans .................................................... 95 Characteristics of Enterprise JavaBeans .......................................... 95 Building a Bean ................................................................................ 97 EJB Roles .......................................................................................... 99 Remote Method Invocation (RMI) ................................................ 101
4.1.1. 4.1.2. 4.1.3. 4.1.4. 4.1.5. 4.1.6.
4.2.
Client View ............................................................................ 104 4.2.1. Java Naming and Directory Interface (JNDI) .................................. 104 4.2.2. Remote Client API ......................................................................... 105 4.2.3. Remote Home Interface ................................................................ 108 4.2.4. Remote Interface ........................................................................... 110 4.2.5. Local Client API .............................................................................. 112
4.3.
Session Bean Components ..................................................... 113 Stateful and Stateless Session Beans............................................. 113 Session Bean Lifecycle ................................................................... 114 Creating Beans .............................................................................. 118 Bean Classes .................................................................................. 119
4.3.1. 4.3.2. 4.3.3. 4.3.4.
4.4.
Java Persistence API Entities ................................................... 122 Characteristics of Entities .............................................................. 122 Entity Bean Code ........................................................................... 125 Component Interfaces ................................................................... 126 Home Interfaces ............................................................................ 128 Entity Bean Instances .................................................................... 130 Synchronization ............................................................................. 132 Container Callbacks ....................................................................... 134 Entity Classes ................................................................................. 135 Entity Identity and Primary Keys ................................................... 136 Multiplicity .................................................................................... 137
4.4.1. 4.4.2. 4.4.3. 4.4.4. 4.4.5. 4.4.6. 4.4.7. 4.4.8. 4.4.9. 4.4.10.
4.5.
Java Persistence Query Language ........................................... 139 WHERE Clause ............................................................................... 139 SELECT Clause ................................................................................ 140
4.5.1. 4.5.2.
6
Copyright The Art of Service │Brisbane, Australia│Email:
[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
4.6.
Message‐Driven Bean Component ......................................... 141 Message‐Driven Bean Class ........................................................... 141 Message‐Driven Bean Methods .................................................... 144 Behavior of a Message‐Driven Bean ............................................. 145
4.6.1. 4.6.2. 4.6.3.
4.7.
Transactions ........................................................................... 146 Bean‐Managed Transaction........................................................... 148 Container‐Managed Transaction ................................................... 149
4.7.1. 4.7.2.
5
Java Web Services ................................................................. 151 5.1.
J2EE Web Services .................................................................. 151 5.1.1. Java EE Services and APIs .............................................................. 152 5.1.2. JAXP ............................................................................................... 152 5.1.3. StAX ............................................................................................... 153 5.1.4. JAXR ............................................................................................... 153 5.1.5. JAXB ............................................................................................... 154 5.1.6. SAAJ ............................................................................................... 156 5.1.7. WS‐I Basic Profile .......................................................................... 156 5.1.8. Universal Description Discovery and Integration (UDDI) .............. 157
5.2.
XML Web Service ................................................................... 157 XML Terminology ........................................................................... 158 Document Type Definition ............................................................ 159
5.2.1. 5.2.2.
5.3.
SOAP Web Service .................................................................. 160 Structure of SOAP .......................................................................... 160 UDDI .............................................................................................. 161 Handler Framework....................................................................... 162 MessageContext ............................................................................ 163 Processing and Extensibility Model ............................................... 163
5.3.1. 5.3.2. 5.3.3. 5.3.4. 5.3.5.
5.4.
REST Web Services ................................................................. 164 HTTP Methods ............................................................................... 165 Provider and Dispatch ................................................................... 168
5.4.1. 5.4.2.
5.5.
JSON Web Services ................................................................. 169 JSON Schema ................................................................................. 170
5.5.1.
5.6.
WSDL ..................................................................................... 170 Basic Elements .............................................................................. 170 Binding Mechanisms ..................................................................... 171 Document and RPC Styles ............................................................. 173 Benefits and Disadvantages .......................................................... 175 The wsgen Utility ........................................................................... 176
5.6.1. 5.6.2. 5.6.3. 5.6.4. 5.6.5.
7
Copyright The Art of Service │Brisbane, Australia│Email:
[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
5.7.
JAX‐WS .................................................................................. 177 JAXB ............................................................................................... 177 Creating a Web Service ................................................................. 178
5.7.1. 5.7.2.
5.8.
JAXR ...................................................................................... 180 Web Service Architecture Model Using JAXR ................................ 180 JAXR Clients ................................................................................... 181
5.8.1. 5.8.2.
5.9.
Security .................................................................................. 182 Basic Security Mechanisms ........................................................... 182 HTTPS ............................................................................................ 183 SAML ............................................................................................. 185 XACML ........................................................................................... 187 WS‐Security ................................................................................... 188
5.9.1. 5.9.2. 5.9.3. 5.9.4. 5.9.5.
5.10. 5.10.1. 5.10.2. 5.10.3. 5.10.4.
6
Web Services Interoperability Technologies ........................ 189 Client Creation ............................................................................... 191 Message Optimization ................................................................... 192 Reliable Messaging ........................................................................ 193 Service Security ............................................................................. 194
Java Enterprise Applications ................................................. 196 6.1.
Application Design Concepts .................................................. 196 Decomposition .............................................................................. 196 Tiers ............................................................................................... 199 Layers ............................................................................................ 201 Service‐Level Requirements .......................................................... 202
6.1.1. 6.1.2. 6.1.3. 6.1.4.
6.2.
Application Architectures ....................................................... 205 Client/Server Systems ................................................................... 205 Three‐Tier Systems ........................................................................ 206
6.2.1. 6.2.2.
6.3.
Integration ............................................................................. 207 Integration with Java Components ................................................ 208 Integration with Non‐Java Components ........................................ 208
6.3.1. 6.3.2.
6.4.
Business Tier Technologies ..................................................... 209 Using Enterprise Java Bean ........................................................... 209 Web Services and EJBs .................................................................. 210
6.4.1. 6.4.2.
6.5.
Web Tier Technologies ........................................................... 211 Servlets .......................................................................................... 211 JavaServer Pages ........................................................................... 212 JavaServer Faces ............................................................................ 212 Web Frameworks .......................................................................... 213
6.5.1. 6.5.2. 6.5.3. 6.5.4.
8
Copyright The Art of Service │Brisbane, Australia│Email:
[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
6.6.
Patterns ................................................................................. 213 GoF Patterns .................................................................................. 214 Java EE Patterns ............................................................................. 222
6.6.1. 6.6.2.
6.7.
Security .................................................................................. 227 Java Security Definitions ............................................................... 227 Security for Web Services .............................................................. 229 Security Models ............................................................................. 229 Security Behavior .......................................................................... 230
6.7.1. 6.7.2. 6.7.3. 6.7.4.
7
Practice Exam ....................................................................... 231
8
Answer Guide ....................................................................... 245
9
References ............................................................................ 254
10
Index ................................................................................. 256
9
Copyright The Art of Service │Brisbane, Australia│Email:
[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
1 Sun Certified Enterprise Architect Sun Certified Enterprise Architect (SCEA) is designed for enterprise architects who are responsible for designing and creating Java Enterprise Edition technology-compliant applications which are scalable, flexible, and secure. Certifications in Java including specialties: Sun Certified Java Programmer (SCJP) Sun Certified Java Developer (SCJD) Sun Certified Web Component Developer (SCWCD) Sun Certified Business Component Developer (SCBCD) Sun Certified Developer for Java Web Services (SCDJWS) Sun Certified Mobile Application Developer (SCMAD) Sun Certified Enterprise Architect (SCEA) The certification process requires the candidate to complete three steps: pass a multiple-choice exam, complete an assignment, and pass an essay exam. This guide supports the first exam which covers:
Application Design Concepts and Principles
Common Architectures
Integration and Messaging
Business Tier Technologies
Web tier Technologies
Applicability of Java EE Technology
Patterns
Security 10
Copyright The Art of Service │Brisbane, Australia│Email:
[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
2 Exam Specifics Sun Exams are managed by Oracle University and proctored by Pearson VUE. Scheduling and location of test sites can be obtained at www.pearsonvue.com. Tests are conducted at a testing center. Two valid forms of ID are required when arriving at the center. In addition, many Oracle University locations offer exams in addition to training. Exams are delivered in a secure environment, proctored, and timed. The Sun Certification Java Associate exam is:
CX-310-052
Multiple-choice and drag and drop exam
120 minutes in length
64 questions randomly selected
Pass mark is 57%
2.1. Exam Prerequisites
The Sun Certified Java Programmer or Oracle Certified Profession, Java Programmer certification is required to be a candidate for the SCBCD.
11
Copyright The Art of Service │Brisbane, Australia│Email:
[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
3 General Java Concepts
3.1. Philosophy Behind Java
Java programming is an object-oriented construction with many similarities to C and C++. Applications written in Java are typically compiled to bytecode that can run on any Java Virtual Machine (JVM). The driving force behind Java is the idea of portability. The catchphrase “Write Once, Run Anywhere” shows the commitment of being able to run any Java Application on any platform in any language. The goals of the programming language support the concept:
Java should be “simple, object oriented, and familiar”`
Java should be “robust and secure”.
Java should be “architecture neutral and portable”.
Java should be “high performance”.
Java should be “interpreted, threaded, and dynamic”.
3.1.1. Object-Oriented Language
Java is just one of several object-oriented languages used in programming applications. The structure of the Java languages begins with a class. A class is a category of objects. The creation of objects is set by the structure of the class when it is created. Class 12
Copyright The Art of Service │Brisbane, Australia│Email:
[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
models are used to define the properties and behaviors of an object. An object in turn will represent the properties and behaviors of the class it belongs to. The properties of an object are called attributes and these attributes are defined by fields. A field is considered a variable storing a value, which in turn represents a particular property of an object. How an object behaves is called its operations and is defined by methods. Both fields and methods are collectively known as members within a class declaration.
3.1.2. Language Elements
Like any language, the construction of the language follows precise rules, or grammar. How the language is constructed will provide a semantic definition, meaning or interpretation of the language. Like words, lexical tokens are the lowest level of the language elements in Java. Combinations of tokens are used to create complex constructs of the language, such as expressions, statements, methods, and classes. Examples of tokens are:
Identifiers – a case-sensitive sequence of characters used to name a program, class, method, variable, or label. The first character of the identifier must be a letter.
Keywords – words which are predefined in the language and cannot be used to identify other entities. All keywords are lowercase.
Literals – identifies a constant value, either as a numerical, character, Boolean, or string value. Integer data types 13
Copyright The Art of Service │Brisbane, Australia│Email:
[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
identify the type of literals used. String literals are a sequence of characters enclosed within double quotes and occurring on a single line of code.
White Spaces – a sequence of spaces, tabs, form feeds, and line terminator characters used to help distinguish between tokens.
Operators – used to identify specific relationships between tokens.
3.2. Source Files
Source files end in .java extension and contain only one top-level public class definition and an unlimited number of non-public class definitions. The unextended filename match the public class name. Compilation Units are not required, but ordered if present. They include:
Package declaration
Import statements
Class, interface, and enum definitions
Package Declaration is simply formatted and starts with a keyword package, followed by package name. The package name is a series of elements separated by periods. Only alphanumerical characters are allowed in package names. Packages are placed in a directory hierarchy. 14
Copyright The Art of Service │Brisbane, Australia│Email:
[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Import Statements have a similar format to packages and allow individual classes from a package or the entire package to be imported into a Java program. The formatting is as follows:
Format to import individual classes: import keyword + fully qualified class name + ';'
Format to import entire class: package name + '*'
3.3. Primitives and Constructs
3.3.1. Data Types
Data types are a simple non-object type representing a single value. The primitive data types found in Java include:
boolean
char
byte
short
int
long
float
double
Signed data types are numeric types whose value can be positive, zero, or negative. Include byte, short, int, and long. Unsigned data types are numeric types whose value can be positive or zero. 15
Copyright The Art of Service │Brisbane, Australia│Email:
[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Primitive types are precisely defined, making Java highly portable.
3.3.2. Integral (int)
Integer can be assigned to any numeric primitive data types and are expressed in decimal, octal, or hexadecimal with decimal as the default. Octal numbers (base 8) is expressed with a 0 prefix, distinguishing them from decimal numbers (base 10) which can begin with any number between 1 and 9. Hexadecimal (base 16) is expressed with a 0x or 0X prefix with hex digits in upper or lower case characters.
Default integral literals are 32-bit value. 64-bit literals are expressed with an L suffix (should be uppercase to eliminate confusion with the numeral 1). Types can be of various sizes. When a numeric type is used with a type with a greater range, it can be promoted to the bigger type. For instance, a byte is 8 bits and an int is 32 bits: when used in the same assignment, the byte can be promoted to an int first. A numeric value can never be demoted to a smaller type.
3.3.3. Floating Point
Floating points conform to the IEEE 754 international specification and therefore are relatively the same on all Java platforms. The 16
Copyright The Art of Service │Brisbane, Australia│Email:
[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
exception to this standard is the ability for extended precisions. The differences are often overlooked by applications, but the keyword “strictfp” as a class modifier on the class containing the floating-point operation will ensure the compiler will prohibit any optimization on a platform that does not support the precision. A floating point operation can be identified with the “float” or “double” keyword: values are double unless suffixed with an F or f identifying that the value should be produced as a float value. The value can be specified in decimal or scientific notation: an e or E will denote the scientific notation. A floating-point literal must contain a decimal point. Floating point values can describe non-numeric situations by taking on bit patterns representing non-numeric values. Non-numeric bit patterns are referenced using NaN (Not a Number).
3.3.4. Boolean
Boolean literals are either true or false.
3.3.5. Character
Characters are unsigned integrals supporting Unicode and ASCII. Character literals represent a single Unicode character, usually expressed by enclosing a character in single quotes. Character literals can be expressed as Unicode value using four hexadecimal 17
Copyright The Art of Service │Brisbane, Australia│Email:
[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
digits, preceded by \u with the entire expression in single quotes. Special characters supported by Java include:
'\n' = new line
'\r' = return
'\t' = tab
'\b' = backspace
'\f' = formfree
'\'' = single quote
'\”' = double quote
'\\' = backslash
3.3.6. Enumeration
Enumerations are an object type limited to an explicit set of values. An order exists with the value which is declared in the code. The declared name of the enumeration in the source code will correspond with the string name. The string name of the value can be obtained using the name() method. An ordered list of enumeration (enum) values can be achieved using the static values( ) method. The compareTo() method will compare an enumeration value to another value with the same enumeration type. With this method, an integer is returned to describe the first values relationship with the compared value in the form of less than zero (less than), zero (equal), or greater than zero (greater than).
18
Copyright The Art of Service │Brisbane, Australia│Email:
[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
3.3.7. Objects
Objects are application components which are self-contained and reusable. Different objects work together to compose the complete application. The internals of an object should never be exposed: public variables should be avoided, using accessor methods to set and return values. When an object is used in its existing form as a piece of a new object, the objects are being composed. When the behavior of the object is changed or refined, inheritance is in use. Composition is the best option when reusing objects, since inheritance involves breaking down the object. Relationships between objects should be minimal. Related objects should be organized into packages, including classes.
3.3.8. Arrays
Arrays are an ordered collection of primitives, object references, or other arrays. They are usually homogeneous, except when allowed by polymorphism (all elements of an array of the same type). Created arrays must have a specified element type and contain elements that are instances of that class of subclass in that class. To create and use an array, the following three steps must be taken: 19
Copyright The Art of Service │Brisbane, Australia│Email:
[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Declaration
Construction
Initialization
Declaration tells the compiler the array's name and the element types contained within the array. Square brackets are used to identify arrays and come before or after the array name. The declaration does not specify the size of an array, which is done at runtime when the array is allocated. The size of the array can be specified using a variable rather than a literal. Construction can be performed on the same line as the declaration. Elements in constructed elements automatically initialize to default values.
Numeric elements initialize to 0
Non-numeric elements initialize to 0-like values
To avoid non-default values, declaration, construction, initialization should be combined in a single step. Array size is inferred from the number of elements within the curly braces. A value can be explicitly assigned to each element.
3.3.9. Classes
A class can contain:
Methods 20
Copyright The Art of Service │Brisbane, Australia│Email:
[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Variable
Initialization code
Classes
A class can be declared using the class keyword. The variables and the methods of the class will appear within the braces of the class declaration. Once the class is defined, an object based on the class can be created; where the object represents an instance of the class. Within a class, two kinds of variables can be defined:
Instance variable – the values of the variables within an instance of an object differs from other instances of the object.
Static variables – the variables within an instance of an object is the same as all other instances of the same object.
3.4. Class Fundamentals
Class Paths are used by Java compiler or Virtual Machine when a class file is needed. They are formed by merging the CLASSPATH environment variable and any locations specified in -classpath or -cp command line arguments. Members of a classpath include directories or jar files. The main() Method is the entry point for standalone Java applications. 21
Copyright The Art of Service │Brisbane, Australia│Email:
[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
The method must be public to be called by the JVM. It is static and does not require a construction of an application class instance. Three different variables supported within a class and method:
Member – created when an instance is created and destroyed when the object is destroyed.
Automatic (or method local) – created on entry to a method and is sustained when the method is being executed.
Class (or static) – created when the class is loaded and destroyed when a class is unloaded.
3.4.1. Inheritance
Classes in Java can be declared as a subclass of another class. This declaration is performed using the extends keyword. By subclassing, the classes within Java become a hierarchy. The higher level of a class is called a superclass. A subclass will inherit the variables and methods from its superclass and used if declared within the subclass. All members not designed as private in the superclass is inherited by the subclass. Only one class can be extended from a class: that is, a class can only inherit from another single class. A subclass can be further extended into more subclasses and is typically found when a class is refined by adding more variables and methods. 22
Copyright The Art of Service │Brisbane, Australia│Email:
[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
3.4.2. Types of Classes
A nested class is a class which is declared within the body of another class of interface. The top level class is not a nested class. Named classes fall into three types:
Abstract class
Final class
Public class
If a class is implemented incompletely, it must be declared as an abstract class, where it cannot be instantiated, but can be extended by subclasses. A class which is declared final cannot have subclasses. All public declared classes are referenced from other packages. All classes, except the Object class, are an extension of an existing class. Classes are considered generic if the type variables declared have bindings which are different across different instances of the class. The body of a class will declare members of the class, instance and static initializers, and constructors. The entire body of the class declaration is the scope of the member within the class. Access modifiers can be used on all field, method, member class, member interface, and constructor declarations. Members within a class can consist of declared and inherited members.
23
Copyright The Art of Service │Brisbane, Australia│Email:
[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
3.4.3. Abstract Classes
A class which is incomplete or considered incomplete is an abstract class. Abstract classes can have abstract methods: methods which are declared but not implemented at the time. If a normal class contains an abstract method but is not an abstract class, a compiletime error will occur. A class can have an abstract method under the following conditions:
An abstract method is explicitly declared.
A superclass of the class has an abstract method which is not declared or inherited by the class.
The class does not declare nor inherit a method that implements a method which is declared or inherited by a direct superinterface of the class.
If the intent is to have subclasses complete the implementation of a method, argument, or the like, the class type should be declared abstract to prevent compile errors. When nonabstract methods are placed into an abstract class, the functionality of the class is inherited, but the methods that define the behavior are restricted to the subclass. The result is a concrete subclass.
3.4.4. Interfaces
Normally, Java will only allow a class to inherit from a single class: interfaces allow multiple inheritances to occur. An interface defines a set of methods that a class must implement. A class can declare that 24
Copyright The Art of Service │Brisbane, Australia│Email:
[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
an interface is implemented if the required methods are implemented. No part of the inheritance hierarchy has to be inherited nor a particular implementation used. The methods listed by the interface will define the behavior for the object. Interface types and class types act the same way. An interface looks like an abstract class. It is defined using the interface keyword. The purpose of the interface is to define what a class must do, without defining how a class does it. They can be implemented by any class, from any inheritance tree. An interface can be considered a 100% abstract class, where the following rules must apply:
Interfaces must be declared with the keyword interface.
All methods are implicitly public and abstract.
All variables defined in the interface must be public, static, and final.
Methods must not be static, or marked final, strictfp, or native.
Only interfaces can be extended by the interface.
One or more other interfaces can be extended within the interface.
Another interface or class cannot be implemented by the interface.
Interface types can be polymorphically used.
25
Copyright The Art of Service │Brisbane, Australia│Email:
[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
3.5. Class Declaration
When declaring a class, two kinds of class declarations exist: normal class declarations and enum declarations. The name of the class in the declaration is specified by the identifier. If a class has the same name as any enclosing class of interface, a compile-time error will occur. Following the identifier is the body of the class. The syntax of a class is as follows:
class<extends clause> { <method declarations> } The first part of the syntax is the class header. The class header must contain the keyword class and the class name, or identifier. The body of the class is found within the braces. All other constructs are optional.
26
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
3.5.1. Class Modifiers
Class modifiers are added before the class declarations. They fall into two categories:
Access modifiers: public, protected, private
Non-access modifiers: strictfp, final, and abstract
Access modifiers are used to restrict or allow access to a created class. Java has four access controls. The default or package access control level is obtained when none of the specified access modifiers are used. Only the default access or public access will work for classes. Protected and private access is often seen in method and variable declarations. The access of a class provides visibility to create an instance of the class, extend the class, and access certain methods and variables found within the class. This visibility is available to another class. The different access modifiers work as such:
Default access – called package-level access because a class can only be seen by classes within the same package.
Public access – a class can be accessed by all classes within all packages without any restriction.
A class can only have one access modifier attributed to it. Non-access modifiers can be added to the access modifiers in any combination. Multiple non-access modifiers can be used under strict conditions. For example, the modifiers strictfp and final can be used simultaneously; 27
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
but the combination final and abstract can never exist. Remember that final classes cannot be subclassed, while abstract classes can.
3.5.2. Modifiers
Modifiers control the behavior of a class, variable, or method and are Java keywords that give the compiler information about the nature of code, data, or classes. They specify a particular feature (class, variable, or method) which is static, final, or transient. Access modifiers dictate which classes are allowed to use a feature. Access modifiers are: public, private, and protected. Other modifiers are used in combination to describe attributes of a feature and include:
final
abstract
static
native
transient
synchronized
volatile
Access Modifiers control which classes may use a feature, including:
the class
its variable
its methods and constructors 28
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
its nested classes
The rules for using access modifiers include:
Class-level variables are the only variables that can be controlled by an access modifier.
The only access modifier permitted to non-nested classes is public.
A feature can only have one access modifier.
If no access modifier is assigned, the access is default.
The public modifier allows use of any class, variable, or method by any Java program without restriction and can be overridden by any subclass. The private restricts use of any class, variable, or method by any Java program and may only be used by an instance of the class declaring the variable or method that is private. The default is used when no access modifier is specified. Default features are accessible to any class in the same package as the original class. Features outside of the original class package are not accessible and classes outside of the package cannot access the features within the package. The protected modifier allows less accessibility than public, but more public than default. Only variables and methods can be declared protected. A protected feature of a class is available to:
All classes in the same package.
All subclasses of the class owning the protected feature, 29
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
even if in another package. Privileges of different-package subclasses include:
Ability to override protected methods of the superclass.
An instance can read and write protected fields inherited from its superclass, but not from inherited fields of other instances.
An instance may call protected methods inherited by its superclass, but not from other instances.
Java specifications do not allow methods to be overridden to be more private. Rules for overriding access:
A private method may be overridden by private, default, protected, or public method.
A default method may be overridden by default, protected, or public method.
A protected method may be overridden by protected or public method.
A public method may be overridden by a public method.
The final modifier can be applied to classes, variables, and methods. The principles governing modifier final:
Final features may not be changed.
Final classes cannot be subclassed.
Final variables cannot be modified once a value has been assigned.
A final object reference variable cannot change. 30
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
The data owned by an object that is referred to by a final object reference variable can be changed.
A final method cannot be overridden.
The abstract modifier can be applied to classes and methods. An abstracted class may not be instantiated, forcing deference of implementation to subclasses. A class must be declared abstract under the following conditions:
One or more abstract methods are contained in a class.
One or more abstract methods is inherited by the class when the method does not provide implementation.
When a class declares the implementation of an interface but does not provide the implementation of every method of that interface.
The static modifier can be applied to variables, and methods. Static features belong to a class, not to individual instances of a class. They allow variables to be static: x will always be x no matter how many instances of x occur. Static variables are referenced through a reference to any instance of the class or though the class name. Static methods are not allowed to use nonstatic features of their class and are not concerned with individual instances of a class. They can be invoked before a class instance is constructed. Instance methods have an implicit variable named this, which references the object executing the method. With nonstatic code, a variable or method can be referenced without specifying which object's variable or method 31
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
intended. The compiler assumes the intent is 'this'. With static methods, no 'this' exists. Attempting to access an instance variable or call an instance method within a static method, an error message occurs. If a static method must access a nonstatic variable or method, it must specify which instance of its class owns the variable or executes the method. Static Initializers are static code contained in a class but does not exist within a method body. They are a block of initializer code surrounded by curly braces and labeled static. The code is executed exactly once when the class is loaded and that execution happens in order of appearance. The native modifier only applies to methods and indicates that the body of a method can be found elsewhere, specifically in a library outside of the Java Virtual Machine. Native code is written in nonJava language and compiled for a single target machine type. It is used to port Java to new platforms to support GUI components, network communication, and platform-specific functionality. Native code should be loaded and available to JVM or a delay will happen. To avoid delay, the library holding the native code should be called as early as possible. The transient modifier applies only to variables and are not stored as part of the object's persistent state. They allow many objects to be written to a destination outside of the JVM. Once written to an outside destination, all Java security mechanisms have no effect. 32
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
The volatile modifier only applies to variables and identifies the variables so the compiler can take special precautions, as well as when variables may be modified asynchronously. The volatile modifier is typically found in multiprocessor environments. The synchronized modifier used to control access to critical code within multithreaded programs.
3.6. Functionality
3.6.1. Importing
Import commonly means to bring something from an external space into an internal space. In Java, importing refers to bringing the import class name into the source file's namespace. A namespace is an abstract entity such as a directory or a source file containing items with unique names. Items can have short names and long names. Short names are used within the namespace and long names outside the namespace. A source file namespace contains the names of all classes and interfaces in the source file's package. Short names allow the statement: java.util.Vector vec = new java.util.Vector(); to be stated as: Vector vec = new Vector(); 33
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
The static import facility allows static data and methods to be imported as well as classes, so myColor = Color.BLUE; can be stated as myColor = BLUE; Static imports eliminate the problems associated with constant interfaces and provide access to static data and static methods. The result is a slight compile-time cost and zero runtime cost. Many packages or applications define constants needed by more than one source file. Constant interfacing is used to eliminate prefixing when associating constants to multiple classes. Constants are put into interfaces. Any class implementing the interface does not require a prefix to the constant. Unfortunately, constant interfaces will have some drawbacks:
Interfaces are for defining types, but constant interfaces only contain data.
Code creation by multiple programmers can create undisclosed dependencies.
With static imports, constants are associated with the proper classes, using the keywords import static. The static import facility is aware of packages and access modes. To static import a class from a different package, the class name must be prefixed with the package path. Only public data can be imported from classes in external packages. Data imported from other classes in the same package may be public, 34
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
protected, default, but not private. The star notation can allow importing all accessible constants from a class.
3.6.2. Argument Passing
When arguments are passed into a method call, a copy of the argument is actually passed, allowing changes to the argument value by the method to not affect the original data. As a result, objects are not dealt directly by Java programs. During the construction of an object, the constructor creates a bit pattern (value) that uniquely identifies the object. This bit pattern becomes a reference to the object. The reference can be the address of the object. In most JVMs, the reference is actually the address of an address, which refers to the real data (double indirection).
3.6.3. Encapsulation
The benefit of object-oriented programming is the ability to use another programmer’s code. Unfortunately because of the inheritance concerns, when the original code is improved, those improvements may prove to be damaging to the new code. Encapsulation allows changes to be made to implementation code without breaking any dependent code. Encapsulation provides:
Maintainability
Flexibility
Extensibility 35
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
These properties are possible by forcing the use of public accessed methods instead of direct access to instance variables and protection of instance variables. Through encapsulation, the programmer has the ability to define which methods and variables can be publicly accessed and which are hidden. This is done through the use of public and private access modifiers. The easiest way to adopt encapsulation is to mark all instance variables as private and control access using public statements to set and get values. In addition, anywhere a particular value can be used, a method call should be used which will return the required type of value.
3.6.4. Inheritance
Inheritance is a standard feature of Java, where one code will inherit the methods and variables set by another code. Each time these methods are inherited outside of it creates an instance of the code. Inheritance can be seen as either an IS-A or HAS-A relationships. In an IS-A relationship, the programmer is saying that ‘this object is a type of that object’. The IS-A relationship is expressed using the ‘extends’ or ‘implements’ keywords. With HAS-A relationships, the focus is on usage rather than inheritance. Therefore, the programmer is saying that ‘this object is referenced by that object’. This is often seen when creating specialized classes which perform a specific operation. This encourages the creation of primary code which is not performing too 36
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
many operations without making calls to other classes, as well as, reuse of smaller, distinct classes.
3.6.5. Polymorphism
If a Java object passes more than one test for IS-A relationship, the object is considered polymorphic. All Java objects, except objects of the type Object, are polymorphic because they can pass an IS-A test for their own type and for the class Object. The advantage of polymorphism is the ability to write reference variables which are assigned to any object assigned and extending the declared reference value. In other words, a subclass which passes a IS-A test with its superclass can have either the subclass or superclass referenced. If A extends B and B extends C, A and B can be referenced instead of C because C has an IS-A relationship with both A and B.
3.6.6. Garbage Collection
Garbage collection is a mechanism in Java for managing data storage and allocation of space. In Java, allocated memory is not explicitly freed. Method locals and arguments are allocated space when initiated and discarded when the method exits. Objects are allocated space on the heap and limited by the amount of memory available on the host. Recovery of space allocated on the heap is managed by 37
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
garbage recovery. It solves two dilemmas:
Releasing storage too soon resulting in corrupted data.
Not releasing storage causing a memory shortage.
Memory is tracked through the runtime system which also determines if memory is still usable. The runtime system does this with a lowpriority thread referred to as a garbage collector. Storage is recovered when the garbage collector determines that it is definitely no longer required.
3.6.7. Converting and Casting
Every Java variable has a type. Data values can change type either explicitly or implicitly. Those changes happen upon request or at the initiative of the system. Converting and Casting are two styles of type changes. Casting is explicitly performed and allows widening and narrowing conversions: casting must be done to conduct narrowing conversions. Narrowing runs the risk of losing information. Casting provides an explicit type change of a value. To cast into a new type, the expression is prefixed with the new type name in parentheses. Compile-time and runtime rules must be observed. Conversion is an automatic, non-explicit type change. Converting is done implicitly and will only allow widening conversions. Broad 38
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
categories of Java data types: primitives and objects. Primitive data types include ints, floats, Booleans, while object data types include hundreds of classes and interfaces provided by the Java Developer Kit, plus classes and interfaces developed by independent programmers. Conversion of a primitive occurs during:
Assignment
Method call
Arithmetic promotion
Assignment occurs when a value assigned to a variable has a different type from the original value. The general rules for primitive assignment conversion are:
A boolean cannot be converted to any other type.
Widening conversions allow a non-boolean to be converted to another non-boolean type.
Narrowing conversion would not allow a non-boolean to convert to another non-boolean type.
Widening conversions change a value to a type accompanying a wider range of values without losing information about the value's magnitude. Widening accommodates:
From byte to a short, int, long, float or double.
From short to an int, long, float or double.
From char to an int, long, float or double.
From int to a long, float or double.
From long to a float or double.
From float to a double. 39
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Any conversion not represented above is considered a narrowing conversion. Literal values can cause compiler errors using widening conversion, but not narrowing conversion. The assignment conversion rule is relaxed when assigning to a narrower primitive type. Method Call happens when a value of one type is passed as an argument to a method that expects another type. Rules that govern method-call conversions are the same as assignment conversions. Widening conversions are permitted, but narrowing conversions are forbidden. Arithmetic Promotion happens while the compiler is interpreting the different kinds of operand in the expression. This type of conversion is done by the system within the arithmetic statements. All conversions of this type are widening. Rules governing arithmetic promotion are separated between unary and binary operators. The rules for unary operators are:
If the operand is a byte, short, or char, it is converted to an int; unless ++ or - - are used, and no conversion happens.
No conversion is done in all other cases.
The rules for binary operators are:
If one operand is a double, the other operand is converted to a double.
Else if one operand is a float, the other operand is 40
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
converted to a float.
Else if one operand is a long, the other operand is converted to a long.
Else both operand are converted to int.
Casting explicitly requests a conversion and allows the widening and narrowing an argument. Casting a value to a wider value is always permitted and never required. Only casting will allow a narrowing conversion. The rules governing casting of primitive types are:
Any non-boolean type can be cast to another non-boolean type.
Booleans cannot be cast into another type, nor another type cast into a boolean.
3.6.8. Object Reference Conversion and Casting
Object Reference Conversion uses assignment conversions, methodcall conversions and casting. It is more complicated because more possible combinations of old and new types exist. Three general kinds of object reference type exist:
Class type
Interface type
Array type
A code example of object reference assignment conversion is: Oldtype = new Oldtype(); 41
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Newtype y = x; Oldtype can be a class, interface, or an array Newtype can be a class, interface, or an essay Below are rules for specific conversions Oldtype is a class Oldtype is an
Newtype is Oldtype must be a a class
subclass of
Oldtype is an
interface
array
Newtype must be
Newtype must be
an Object
an Object
Oldtype must be a
Newtype must be
Newtype Newtype is Oldtype must an
implement
subinterface of
Cloneable or
interface
interface Newtype
Newtype
Serializable
Compiler error
Oldtype must be an
Newtype is Compiler error
array of some
an array
object reference type
The rules for method-call conversion are the same as assignment conversions. The general rule is that converting to a superclass is permitted, while converting to a subclass is not.
Object Reference Casting is much like primitive casting, with general rules for testing:
When Oldtype and Newtype are both classes, one class must be a subclass of the other.
When Oldtype and Newtype are both arrays, both arrays 42
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
must contain reference types and the conversion must be legal.
Casting can always be done between an interface and a nonfinal object.
In reference value casting, an important distinction is made between compile-time knowledge and runtime knowledge: the type of reference variable is known at compile time, while the class of an object reference by the variable is known at runtime. Some rules for casting are enforced at compiler time, others during execution. Common runtime rules include:
If Newtype is a class, the class of the expression being converted must be or inherited from Newtype.
If Newtype is an interface, the class of the converted expression must implement Newtype.
3.7. Algorithm Design
Statements are found within methods and classes to describe the activities of the program. Expressions are evaluated to produce a value, or result; and are used in statements. There are three basic forms of statements:
Assignment
Condition
Iteration
Statements and expressions can be viewed within a code block and 43
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
are grouped syntactically between curly braces.
3.7.1. Assignment
Assignment statements are the simplest form of statement. They “assign” a value to a variable or set parameters to an object. The code below identifies an assignment statement: { X = Y; } In the statement above, the value Y is assigned to X, making the two expressions equal.
3.7.2. Condition
Conditional statements are in the form of if/else clauses. The syntax of a conditional statement would be: if (condition) statement; [ else statement; ] In this example, if the condition is met, the first statement is used; but if the condition is not met, the second statement. For this reason, a condition is considered a Boolean expression where a true or false 44
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
value is the result. A conditional statement does not require the else clause; and it allows multiple statements to be used when a condition is met.
3.7.3. Iteration
Statements using ‘do-while’ loops have a conditional attribute but are considered iterative statements. The syntax of the code is: do statement; while (condition); In this loop, the statement will always be executed at least once; and continual execution is dependent on the declare condition remaining in place. When the statement should not be executed but the condition still monitored, a ‘while’ statement may be used by itself. The ‘for’ statement is similar to the ‘do-while’ loop except the condition is evaluated before executing the activity. This statement is used to declare or initialize variables which are limited to the scope of the condition. The syntax of the ‘for’ statement is: for (initialization; condition; incrementor ) statement; A simpler, or enhanced form of the ‘for’ statement, allows the iteration over an array or collection of values. The syntax of the statement is: for ( varDeclaration : iterative ) 45
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
statement; When a number of alternative integer-type results are possible, a switch statement can be used within the argument to identify which alternative to use. In this situation, each branch of the statement is evaluated to a different constant integer value as a condition. If none of the conditions are matched, an optional default case is used. The syntax of a switch statement is: switch (int expression) { case int constantExpression : statement; [ case int constantExpression : statement; ] … [ default : statement; ] } The break statement is used to break out of a conditional statement loop by stopping the current block statement. The continue statement is used in conjunction with ‘for’ and ‘while’ loops to return the statements to the point where they were checking their conditions.
3.7.4. Operators
Operators are a key aspect of any programming language. However, 46
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Java operators behave differently than operators in other languages. Operators perform traditional arithmetic and logical operations. Java operators are also used to perform object-oriented cast and instance of operations. Operators usually carry precedence; that is, some operators will be handled before others as they have greater precedence.
Category
Type
Operators
Unary
Increment and decrement
++ --
Unary plus and minus
+-
Bitwise inversion
Arithmetic
Boolean complement
!
Cast
()
Multiplication
*
Division
/
Modulo
%
Addition
+
Subtraction
-
Shift
<< >> >>>
Comparison
Ordinal
< <= > >=
Object-type
instanceof
Equality
== !=
Bitwise
&^|
Short-Circuit
&& ||
Conditional
?:
Assignment
= op=
47
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
3.8. Algorithms
3.8.1. Variables
Within Java, a value is assigned to a variable. The designated type of the variable acts as a place-holder for bits. A variable has bits representing a numerical value. A reference variable is a variable which refers to an object and the bits represent the path for getting to the object. The scope of a variable refers to the life of a variable: that is, how long the variable is good for in the program. There are four basic scopes:
Static variables – created when a class is loaded and lasts as long as the class remains loaded in the Java Virtual Machine.
Instance variables – created when a new instance is created and lasts as long as the instance lasts.
Local variables – Tied to a method and remains as long as the method remains within the stack.
Block variables – exists as long as the code block is executing.
3.8.2. Instance Variable
Instance variables are defined at the class level and initiated to a 48
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
default value when a new instance is created. Instance variables can be primitive, reference an object, or reference an array. An instance variable will be within the initial curly braces of the class but not within the curly braces of the method, such as: public class X { int var; public static method(Y) { } }
3.8.3. Local Variable
Local variables are defined within a method and include the parameters of a method. They can be called automatic variables which must be assigned a value in the code. The local variable will be found within the curly braces of both the class and the method. public class X { public static method(Y) { int var; } } All local variables must be explicitly initialized before they are used because they do not have default values. A local variable and an instance variable can have the same name. If this occurs, the local variable will hide the name of the instance variable within the scope of the method is in process called shadowing. Shadowing is often 49
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
recognized when the special reference ‘this’ is used within the method; which allows explicit reference to the current object. The this reference allows the reference of the enclosed object to be passed to some other method.
3.8.4. Methods
Methods are found within the body of a class and are executed when the method is invoked or called. Methods will take arguments which are supplied by the caller and return a value based on those arguments. They will always specify a return type. The return types they may specify are a primitive type, a reference type, or the type void. The type void will return no value. Static methods belong to a class and not to the instances of that class. As a result, they can be called by name through the call name and without any objects around. They can be accessed directly by other static members of the class; but cannot directly see or call those members within an instance. Instances can call a static method.
3.9. Operators
One goal of programming is to keep expressions simple; therefore when creating arguments or using operators, particular attention is used to ensure evaluation of the argument is performed correctly. Redundant brackets are used to drive how particular expressions 50
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
should be evaluated. The order of evaluation of operands in an expression is fixed. Evaluation is done from left to right requiring the leftmost expression to be evaluated first. When operands have been evaluated, the operations are performed. The order of execution is specified by precedence and associativity; however, the order of evaluation is not specified by precedence or associativity. Associativity is dealt with by going right to left.
3.9.1. Unary Operators
Most operators take two operands, such as division which uses two numbers. Unary operators use only a single operand. Increment and Decrement Operators are used to modify the value of an expression by adding or subtracting 1. if x = 10, then ++x = 11 if x = 10, then -- x = 9 Operators can be positioned before and after the expression to affect operation. pre-increment and pre-decrement: ++x and - - x post-increment and post-decrement: x++ and x- -
51
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Initial Value of x Expression
Final Value of y
Final Value of x
10
y = x++
10
11
10
y = ++x
11
11
10
y=x--
10
9
10
y=--x
9
9
Unary Plus and Minus Operators differ from binary + and – operators which perform traditional addition and subtraction because they emphasize the positive or negative nature of a numeric literal. The determination of binary or unary use of operators is automatic depending on context. Within Java, each primitive type uses a virtual representation that is platform independent allowing bit patterns representing a particular value in a particular variable type are always the same. Bitwise inversion operators invert binary values: 1 to 0 and 0 to 1 So 10101010 becomes 01010101 This inversion is used in conjunction with shift operators to perform any form of bit manipulation, such as driving I/O ports. The Boolean Complement Operator inverts the value of a boolean expression: true is false and false is true. They are typically used in the test part of if() statements, but can be used to allow the body of 52
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
the if() statement and the else statement to be swapped leading to cleaner and shorter code. Cast Operators are used for explicit conversions of the type of expression and must follow specific rules which are checked by the compiler and the runtime system.
3.9.2. Assignment Operators
Assignment operators set the value of a variable or expression to a new value. Simple assignments use the equal sign (=). The operators, + and * can be used with the equal sign to combine calculations and assign functions, as in: x += y or x = x + y x *= y or x = x * y When using assignment operators, there are two conditions in place:
Assignment operators include an implicit cast.
Side effects of x are evaluated exactly once, not twice.
3.9.3. Arithmetic Operators
Multiplication and division operators are all primitive numeric types and characters. Two situations can occur when using these types of operators: overflow and underflow.
53
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Overflow refers to are larger numerical result than can be represented by the maximum number that can be represented: 64 * 4 = 256 or 100000000 in binary code. However stored as a byte variable, 64 * 4 = 0 since only the low-order eight bits of data can be represented. Typically happens more when multiplying then dividing. Underflow refers to the forced condition where a fractional part of an integer is lost: 3.85 will become 3. Typically happens more when dividing then multiplying.
A Modulo Operator will provide a value that is related to the remainder of a division. Traditionally, a division of integrals such as 9 divided by 5 would result in an answer of 1 remainder 4. Using Modulo operators, the statement would read x = 9 ÷ 5; with a result value of 4. Generally applied to integers, but can be applied to floating-point numbers with the following procedure: 1. Subtract the magnitude of the right operand by the magnitude of the left one. 2. Repeat until the magnitude of the result is less than the magnitude of the right operand. Modulo example: 13 ÷ 5
6.4 ÷ 2.8
13 – 5 = 8
6.4 – 2.8 = 3.6
8–5=3
3.6 – 2.8 = 0.8
3 < 5 so 13 ÷ 5 = 3
0.8 < 2.8 so 6.4 ÷ 2.8 = 0.8
The sign of the result is determined by the sign of the left operand. 54
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
When applied to floating-point types, the result might have a fractional part. When applied to negative numbers, absolute values are used to obtain a result which is negative. Addition and subtraction are applied to operand of numeric type, though the + operator can be uniquely applied when one operand is a string object. Concatenation is the process of joining string objects. Overloading applies when the same name is used for more than one piece of code. Operator overloading is when an operator can take different operand types. A + expression with two operands of primitive numeric types; the result is:
A primitive numeric type.
At least int, due to normal promotions.
Of a type as wide as the wider of the two operand.
Calculates value by promoting operands to the result type then performs addition.
A + expression with any operand of primitive non-numeric type:
At least one operand must be a string object or literal.
Any remaining non-string operands are converted to string and the result is a concatenation of all operands.
Converting an operand to a String requires the toString() method Object type to object method, primitive type using Integer.toString(). 55
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Arithmetic errors can occur when:
Overflow and underflow can occur when operands are too large or too small.
Integer division by zero results in an ArithmeticException.
All other arithmetic will provide a result, even if it is arithmetically incorrect.
Floating-point calculations represent out-of-range values using IEEE 754 infinity, minus infinity, and NaN values.
Integer calculations that cause overflow will provide a result, typically a truncated bit pattern.
NaN values are issued to identify calculations that have no value in ordinary arithmetic. Calculations involving infinity or square root of negative numbers can result in a NaN value. Floating-point calculations can return a NaN. Java defines two NaN values: Float.NaN and Double.NaN. Considered non-ordinal, or any value of x including NaN will return false when using comparisons.
3.9.4. Comparison Operators
All comparison operators, or relational operators, will return a boolean result of true or false. Ordinal Comparison is used to test the relative value of numeric operands, such as with dissimilar numeric types, including char. 56
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Ordinal comparison cannot handle boolean or class-type operands. Object-type Comparison uses the instanceof statement which determines whether or not a given object is an instance of a particular class. The left side of the argument can be any object reference expression, while the right side of the argument must be a class, interface, or array type. A compiler error occurs when the left operand cannot be cast to the right operand. Equality Comparison tests whether two values are the same and can be applied to non-numeric types:
== tests equality
!= tests inequality
For object types, the value is seen as the reference to the object; therefore comparisons of two objects will look at the references to the same objects, rather than the objects themselves. Object comparisons compare the data of two objects. Reference comparisons compare the memory locations of two objects. The equals() method should be used instead of the == or != operators when comparing content or semantics.
3.9.5. Bitwise Operators
Bitwise operators provide operations for bitwise AND, eXclusive-OR (XOR), and OR. These operators apply to integral types. They follow three rules: 57
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
AND statements will produce a positive result if both sides of the argument are the same: 1 AND 1 produces 1, any other combination produces 0.
XOR statements will produce a positive result if one but not both sides of the argument is positive: 1 XOR 0 and 0 XOR 1 produces 1, any other combination produces 0.
OR statements will produce a positive result if either side of the argument is positive: 0 OR 0 produces 0, any other combination produces 1.
Operand 1
Operand 2
AND result
XOR result
OR result
0
0
0
0
0
0
1
0
1
1
1
0
0
1
1
1
1
1
0
1
Using Boolean expressions with bitwise operators, the results are:
Operand 1
Operand 2
AND result
XOR result
OR result
false
false
false
false
false
false
true
false
true
true
true
false
false
true
true
true
true
true
false
true
58
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
3.9.6. Short-Circuit Logical Operators
Short-Circuit logical operations are used to provide logical AND and OR operations on boolean types. They are similar to & and | operators with the ability to “short circuit” a calculation to improve efficiency. They are central to null-reference-handling and follow two basic rules:
For AND operations, if the left operand is false, the result is false without regard to the right side.
For OR operations, if the left operand is true, the result is true without regard to the right side.
These rules allow evaluation to stop at the left side of the argument.
3.9.7. Conditional Operators
Also known as ternary operator, the conditional operator consists of three operands and acts like if/then statements. Expressed as a = x ? b : c; a = x is evaluated:
if true, a = b
if false, a = c
The rules to follow using conditional operators include:
Expression types for band c should be compatible.
Expression type for x should be boolean.
Expression types for b and c should be assignment 59
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
compatible with the type of a.
Value assigned to a will be b if x is true, and c if x is false.
Condition Operators are sometimes prohibited by company style guides.
3.10. Exceptions
Programs have a specific goal in mind. Exceptions are occasions where an abnormal execution of the program happens. The circumstances of abnormal behavior are called exception conditions and represented as objects. Exceptions are either caught or declared. All exceptions come from the java.lang.Throwable superclass. When exception objects are constructed:
A text message is stored inside the exception describing the circumstances that caused the exception.
A visual display of the JVM’s call stack at the moment the exception is created is available with the method, printStackTrace().
To retrieve the text message, getMessage() is used. A stack trace tells:
What line of the source file the exception was created.
The location of the method containing the previously called line. 60
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Keeps identifying deeper locations until a line in main().
Who called the code already described.
Creating try and catch blocks is one way to call a method that throws an exception. The format of try and catch blocks is: try { //Exception- throwing code } catch (Exception_type name) { //Exception-handling code } The try block contains code that throws exceptions and different exception types. When multiple exception types are thrown, multiple catch blocks must be used. The catch block handles the exceptions. The catch block starts with a declaration within parentheses and consists of a type and a name. The type in the declaration must match the type thrown by the try code. The name does not have to be defined, as its scope is within the braces. If no exception exists, the try block runs to completion and execution continues after the last catch block. If an exception does exist, the appropriate catch block executes and then execution continues after the last catch block. The last catch block associated with a try block is the finally block and is guaranteed to execute, except when the block throws its own exception, usually from: 61
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
The death of a the current thread
Execution of System.exit()
Turning off the computer
The finally block is used to ensure that execution of the first line after the try/catch/finally code begins. A try block is not always needed. Declaring a method exception can be done by ending a line with the throws keyword and an exception type. Multiple exception types may be declared using commas to separate the exceptions. A throws declaration can be combined without restriction from other modifiers. When an exception happens, the JVM processes it. Processing starts with checking if the exception came from a try block. If from a try block, each catch block is checked in the order of appearance for compatibility with the exception. Compatibility refers to the exception being an instance of the class declared at the beginning of the catch block. If the exception is not compatible or not thrown by a try block, the JVM checks the declared exception types. If compatibility is found with a declared exception, the JVM focuses on the method that called the current method and continues until the exception is handled. If there is no compatible catch block, the JVM prints out the exception's stack trace and terminates. 62
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Two types of exceptions can occur: checked and runtime. Rules for runtime exceptions are:
Can always be avoided.
Must be handled during design, development and debugging of code.
Should not be handled using catch blocks.
Any exception not a runtime exception is a checked exception. Rules for checked exceptions are:
Must be handled by catching or declaring the exception.
The compiler ensures that every checked exception has a handler somewhere.
Methods can be written to throw exceptions. The process for throwing exceptions is: 1. Decide if the exception should be checked at runtime. 2. Choose the exception type. 3. Check API pages. 4. Use the class related to the situation you want to signal. 5. Or create an exception class. 6. Construct an instance of the exception type. 7. Use the throw keyword. All exception classes in the core packages have two constructors: noargs and a descriptive string. The use of a no-args constructor should be avoided. Descriptive strings are the test that is returned when the exception is caught. Exceptions should be thrown immediately after 63
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
construction to accurately represent the thread's status at the time it was thrown. All checked exception types must be represented in the method's “throw” list. The process for creating exception classes is:
Decide on a checked or runtime exception.
Checked exceptions should extend java.lang.Exception or subclass.
Runtime exceptions should extend java.lang.RuntimeException or subclass.
Choose a descriptive name ending in exception.
Each exception class should have three constructors:
Message
Cause
Message and cause
A message is a string that is retrieved by the getMessage() call. A cause is another exception and they happen when a method handles an exception by throwing a different exception type. Use the getCause() method to retrieve an exception's cause. The return type of getCause() is Throwable allowing causes to have causes. The structure of cause on cause is called exception chaining. The message and cause is passed to the superclass constructor. To override a method, the Java compiler insists that all exception classes thrown by the new method must be the same as the 64
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
exception class thrown by the original method.
3.11. Assertions
Assertions provide a mechanism for verifying that a class's methods are called correctly. The mechanism can be enabled or disabled at runtime. Assertions are typically enabled during development and disabled in production. The format for assertions is:
assert Expression1;
assert Expression1:Expression2; Expression1 must have a boolean type Expression2 can have any type.
When disabled, the assert statement does nothing. If enabled, Expression1 is evaluated. If true, nothing happens: if is false, than an AssertionError is thrown. If Expression2 exists, it is passed to the constructor of the AssertionError and converted to a string used as the error's message. Using assertions require:
Knowing how to compile.
Knowing how to enable at runtime.
Knowledge who to use appropriately.
Assertions were introduced as a keyword in 1.4 release of Java. Before 1.4, assert was used as an identifier. A compiler flag controls 65
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
whether assert should be treated as an identifier or as a keyword. Release 5.0 of Java automatically treats assert as a keyword. Assertions are disabled by default and are enabled at runtime: -enableassertions on the Java command line -ea flag on the Java command line A common use for assertions is to check preconditions, postconditions, and class invariants. Preconditions are constraints that must be met to enter a method. If not met, the method should terminate immediately. Constraints are typically functions of its arguments and the state of its object. Common form of precondition testing is argument range checking. Postconditions are constraints that must be met before returning from a method. If not met, the method does not return. Constraints are typically functions of its return value and the state of its object. Identify a failure within the method. Class variants are constraints on a class's state that must be met before and after execution of any non-private method of a class.
3.11.1. Overloading and Overriding
In Java, a method is uniquely identified by the combination of its fully qualified class name, method name, and the exact sequence of its argument types. To re-use the same name for a method, use: 66
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Overloading – re-using with different arguments and different return type.
Overriding – re-using with identical arguments and return type.
To re-use method names, certain conditions must be met:
In an unrelated class, no special conditions apply and the two methods are not related.
In the class of subclass defining the original method, the argument list differs in terms of the type of at least one argument.
In a strict subclass of the class defining the original method, identical arguments types and order must exists and the same return type must be achieved.
The distinctions between overloading and overriding are:
Overloaded methods support each other; an overriding method replaces the overridden method.
Any number of overloaded methods can exist in the same class while each method in a parent class can be overridden only once in any other subclass.
Overloaded methods must have different argument lists; overridden methods must have argument lists of identical type and order.
Overloaded methods may freely choose a return type; The overriding method must have the identical return type as the overridden method. 67
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Overloading allows multiple implementations of the same functions to have the same name; overriding modifies an implementation of a particular piece of behavior for a subclass.
Method Overloading is the re-use of a method name within a class or subclass for a different method and is used when several methods perform closely related functions under different conditions. The technique improves program readability. The methods that perform different functions should have different names. Overloaded methods can have different return types, accessibility, and exception lists. Overloaded methods can call each other for support. Method Overriding defines a method with exactly the same name and argument types as a method in the parent type. Overriding methods must use the same return type as the method it overrides, as well as follow the same accessibility and exception list rules. The requirements for overriding are:
Method name, type, and order of arguments must be identical to those of the method in a parent class.
The return type must be the same as superclass's return type or a subclass of the return type.
Methods marked final cannot be overridden.
Accessibility cannot be more restrictive than the accessibility of the original method.
Checked exception types that are the same as those thrown by the original method can be thrown by the 68
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
overriding methods. Covariant return types describe an overridden method which is a subclass of the return type of the superclass version. The extends keyword requires a subclass to be an extension of the parent class. Late binding refers to a delay in making a decision to invoke the proper code for execution until runtime. Overriding methods inherit the exact behavior of the methods overridden; however, additional behavior can be added to the overriding method. Method declaration in release 5 allows an argument list which includes a variable number of args of a particular type.
3.11.2. Constructors
In a general sense, inheritance allows the code and data which is defined in a parent class to be available for use in a subclass. Constructors are not inherited normally and must be defined for each class within the class. Constructors are defined with arguments to control the construction of the parent part of the object. A constructor is invoked with a call for the new AnyClass(argument1, argument 2,..). If there are no arguments, the constructor is called a no-argument constructor. If no constructors are explicitly coded for a class, a default constructor is automatically created by the compiler and the constructor is called a default constructor. Default constructors have public access if the class is public and default for any other access. 69
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
One constructor can call another constructor using this(arguments). Control of the constructor can be passed to the parent class using the keyword super. The superclass constructor must be called before any reference is made to any part of the object. The super(arguments) must be the first statement of the constructor. There are no special considerations related to overloading constructors. Overloaded constructor versions are invoked using this(arguments) and must be the first statement of the constructor.
3.11.3. Inner Classes
Inner classes, or nested classes, are used to provide additional clarity and make programs more concise. They are fundamentally the same as any other class but are declared within some class. They can be declared in any block, including methods with some differences. Member classes refer to classes defined within a class, not a method. Scope and access define the complexity of inner classes. Typically, the fully qualified name of the inner class retains as part of its name the name of the class enclosing it. Normally, when an inner class is created a preexisting instance of the outer class must act as context. The accessibility of members of the enclosing class is crucial because the inner class has a hidden reference to the outer class instance that was the context when the inner class object was created. Sometimes, an instance of an inner class from a static method or other situation may be created when a 70
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
this object is not available, such as an unrelated class. This situation is available using the new operator and if it was a member method of the outer class. A new operation to construct an instance of an inner class can imply the prefix this. Members of a class (variables, methods, or nested classes) can be marked with private, public, protected, or default access. Access modifiers carry the same meaning for member classes as for other members of the class. A member class may be marked static and carries a meaning similar to applying static to a variable associated with a class. A static inner class does not have any reference to an enclosing instance:
Methods of a static inner class cannot use the keyword this to access instance variables of the enclosing class.
Methods of a static inner class can access static variables of the enclosing class.
To define a class within a method, there are three considerations:
Anything declared inside a method is not a member of the class but is local to the method; therefore they are private to the method and cannot be marked with a modifier or static.
An object created from an inner class within a method can have some access to the variables of the enclosing method.
Anonymous classes are possible, that is a class with no specified name. 71
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Any variable can be accessed by methods within an inner class provided that variable is marked final. A final variable is treated as a constant. Anonymous classes do not need a name and are used to extend another class or implement a single interface. The definition, construction, and first use of an anonymous class all occur in the same place. Anonymous classes provide a convenient approach to avoid trivial naming of classes. Anonymous classes should remain small. Anonymous classes are unique to method scopes. Specific constructors cannot be defined for an anonymous inner class. To construct an inner class with arguments, some conditions do exist. The structure to declare and construct an anonymous inner class: new ClassName() [/* class body. */] The structure to assign an object reference into a variable: ClassName anClassName = new ClassName() [/* class body. */]; The structure to assign an object reference as an argument to a method: aMethod(new ClassName() [/* class body */]); When an anonymous inner class extends another class and the parent class has constructors that take arguments, a constructor from the parent class can be invoked by specifying the argument list to the construction of the anonymous inner class. 72
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Though a constructor cannot be created within an anonymous inner class, the initializer feature from JDK 1.1 can be used and will be invoked as part of the construction process.
3.11.4. Contracts and Conventions
A contract is an agreement about the behavior of some of the class' methods. Contracts are used to ensure that a class can interact predictably with other classes. The most common contracts in Java are: equals and hash code. Parts of an equals() method description are: x=x If x = y, then y = x If x = y = z, then x = z The version of equals() inherited from Object used the == operator to test for equality. If the behavior is overridden, the compiler cannot determine adherence to the contract. Violation of the contract while attempting to benefit from the contract will result in elusive bugs in the programming. A hash code is an int that represents the uniqueness of an object and are used by classes needing to determine whether two objects contain different values. If two objects are equal based on their equals() methods, they must have equal hash codes. Though not part of a contract, two unequal objects can also have equal hash codes. Programming hash codes should balance between detecting 73
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
uniqueness and running efficiently. Naming conventions are contracts that specify how a method's name relates to its behavior. A naming convention concerns properties of objects. Properties are qualities that are represented by one of more of an object's variables. Rules for naming conventions are:
A property name begins with a lowercase letter. All subsequent letters are lowercase except for the first letter of a new word
Underscores are not allowed
A method that returns a value of a property is named getXxx(), where xxx is the property name
A method that modifies the value of a property is named setXxx(), where xxx is the property name
3.11.5. Threads
Threads create the illusion that a single Java Virtual Machine looks like multiple machines running simultaneously. A single-threaded Java program has one entry point (the main() method) and one exit point. A multithreaded program has a first entry point (the main() method) followed by multiple entry and exit points for other methods. Thread support resides in three places: 74
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
java.lang.Thread class
java.lang.Object class
Java language and JVM
Threads execute with calling its start() method which doesn't cause the thread to run, but makes it eligible to run. The start() method registers the thread with system code called the thread scheduler. The scheduler determines which thread is running on each available CPU at any given time. A thread can be executing or in several nonexecuting states. When threads execute, they are executing a method called run(): either its own run() method or the run() method of some other object. To execute its own run() method, the Thread class must be subclassed and implement the run() method. To execute the execute the run() method of some object other than itself, an instance of the Thread class must be constructed. Then the Thread constructor is called, the object owning the run() method you want must be specified. Therefore, construction of threads can be done by extending Thread and implementing Runnable. When the run() method return, the thread is finished and considered dead. Once dead, the thread cannot be started again. The data and methods of a thread are still available even though a thread is dead. Thread methods include a stop() method, which forcibly terminates a thread but this is not a recommended practice. Thread methods can be forcibly terminated using interrupt(). 75
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Thread states include:
Running – the thread get the full attention of the JVM's processor to execute the run() method.
Suspended – allows any arbitrary thread to make another thread unready for an indefinite period of time.
Sleeping – passes time without doing anything and without using the CPU.
Blocked - waiting for some occurrence outside of the thread to proceed performing input and output.
Ready – the thread is ready to move to a running state as soon as the JVM processor is available.
Dead – the thread has completed execution of the run() method.
Monitor states – can block and revive threads.
Every thread has a priority, from 1 to 10. Threads with high priority take precedence over threads with lower priority. The thread scheduler considers priority when deciding which thread to execute. The default priority is 5. Call the set Priority() method to set priority. Call the getPriority() method to return a thread's priority. Daemon Threads are infrastructure threads which are created automatically by the JVM. When an application begins, only one nondaemon thread is in existence: the main thread. Threads created by daemon threads are initially daemon threads while threads created by non-daemon threads are initially non-daemon threads.
76
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
The status of daemon threads can be changed before execution by calling set Daemon() method. The JVM runs until the only live threads are daemon. Controlling threads refers to moving threads from one state to another state. A thread offering to move out of running state to ready state if the scheduler is willing to run another thread is called a yielding thread. A yielded thread goes into Ready state. If other threads are in a Ready state, the thread may have to wait before executing again. If no other threads are in a Ready state, the yielding thread can continue executing immediately. The format is yield() and the method is a static method of the Thread class. Yielding allows a timeconsuming thread to permit other threads to execute. When suspending, one thread can make another thread unready for an indefinite period of time. The suspended thread becomes ready when some other thread resumes it. Threads have no control over when it is suspended. The format of the thread is suspend() and the resume() method is used to move the thread out of suspension. When sleeping, the sleep() method to request that the current executing thread cease execution for a specified amount of time. The method can be called in two ways dependent on desire to specify sleep period in milliseconds or nanoseconds. Sleep is a static method. When sleep is finished, the thread does not move to a running state, but to a ready state until the scheduler moves it to running. Sleep can be interrupted, whereupon it moves to a ready state. 77
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Blocking, waiting, and other monitor states are used when a method must wait for the availability of data, value, functionality, or such. The method is blocked from continuing until the desired item is available. read() is a blocking method. Threads can be blocked if a wait() call is issued or a lock for a monitor fails to be acquired. Every object has a lock which is controlled by only one thread. Locks control access to the object's synchronized code. To execute synchronized code, a thread must acquire the object's lock. If the lock is under another thread's control, the attempting thread goes into the state, Seeking Lock, and becomes ready when the lock becomes available. When a thread owning a lock moves out of the synchronized code, the thread automatically gives up the lock Only explicit programming required is to declare synchronization of the code by:
Put the synchronized modifier in the method's declaration.
Surround the desired code with curly brackets {} and inserting the expression synchronized(an Object) before the first curly.
To synchronize part of a code (not recommended):
Synchronize on the lock of a different object.
The wait() method puts an executing thread into a waiting state and allows a shared object to pause a thread when the object becomes unavailable to that thread and allow it to continue when appropriate. The notify() and notifyall() methods move waiting threads out of a waiting state. These methods are implemented in the Object class, 78
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
not the Thread. The wait() method can only be called in synchronized code. Additional points about the wait() method includes:
The calling thread gives up the CPU and the lock.
The calling thread goes into the monitor's waiting pool.
Points about notify() method include:
One arbitrary thread gets moved from the waiting pool into a Seeking Lock statement.
The moved thread must reacquire the lock before proceeding.
notifyAll() moves all threads in the waiting pool into a Seeking Lock state.
As all objects have a lock, all classes have a lock. A class lock will control access to all synchronized static code in the class. Deadlocking describes a class of situations that prevent a thread from executing, such as a thread is waiting for a condition but something in the program prevents the condition from arising.
3.12.
Methods from String Class
The Java String class, or java.lang.String, is fundamental to using Java. A string object will encapsulate a sequence of Unicode characters. The characters are stored within a regular array, but the String object will only allow access to this array from its own API. As a result Strings are immutable: That is, once a string object is created, it cannot be changed. A number of operations on the object can appear to change the characters or length of the string, but in reality, they 79
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
simply return a new String object. Strings can be identified by double quotes. The string itself will be found within the quotes and assigned to a String variable. String concatenation can be used to combine different strings.
3.12.1. Key Methods
The charAt() method allows the characters of a String to be accessed like an array, or one at a time. The substring() method will return a portion of the string. The startswith() and endsWith() methods can be used find substrings within a string, specifically the beginning and end of the String. The indexOf() will search for the first occurrence of a character or substring and return the position of the starting character or -1 if the substring is not found. Strings can be edited: more specifically, a new string can be created which is based on the original string. The trim() methods is used to remove the leading and trailing whitespace from the string. The replace() method will allow a substitution of a portion of the string with another string.
80
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
3.13.
Java Development Fundamentals
3.13.1. Packages
Packages are organized to create programs. A program may have several packages contained within it. Each package will have its own set of names or types within it, namely class and interface types. A type can be accessible outside a package if it is a top level type and is declared public. The naming structure for packages is hierarchical. A package will consist of a number of compilation units which have automatic access to all types declared within the package. The compilation will automatically import all public types declared within the predefined package java.lang. Packages are stored in a file system or database. Within the compilation units of the package are the declared members of the package, including subpackages and top level class types and top level interface types. A package cannot contain two members of the same name. A naming convention for a fully qualified name of a subpackage is packagename.subpackagename. The predefined package java has subpackages called awt, applet, io, lang, net, and util. A package declaration is created within a compilation unit to associate the compilation unit with the package. The syntax of the compilation unit is: 81
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
CompilationUnit: PackageDeclaration(opt) ImportDeclarations(opt) TypeDeclarations(opt) The syntax of a package declaration is: PackageDeclaration: Annotations(opt) package PackageName ; The annotations on a package declaration are restricted to one per package, but are optional. The package name must be the fully qualified name or the name. If a package declaration does not exist, the compilation unit is considered part of an unnamed package. This unnamed package cannot contain subpackages. Though Java can support than one unnamed package, it is required to support only one unnamed packaged. Unnamed directories are typically stored within each directory, since only one unnamed package is observable at a time based on the current directory.
3.13.2. Importing Packages
The import declaration enables a static member or named type to be referenced by a simple name. If the import declaration is not used, the fully qualified name must be used. There are four types of import declarations:
Single-type-import – uses the canonical name of a single 82
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
named type.
Type-import-on-demand – will import all accessible types of a named type or package when required.
Single-static-import – uses the canonical name to import all accessible static members with a given name from a type.
Static-import-on-demand – will import all accessible static members of a named type when required.
3.13.3. “javac” Command
The compiler used in JAVA is invoked using the javac command. The syntax of the javac command is: javac [options] [source files] The ‘options’ and ‘source files’ are optional to the command and allow multiple entries with spaces in between. The ‘javac – help’ command can be used to obtain a summary of valid options. The compiler will, by default, place a .class file into the same directory as the .java source file. When working larger projects, it is reasonable to separate the .class and .java files. To do this, the –d (destination) option with the javac command will instruct the compiler on which directory to place the .class files. To complete the command, the .class file to be stored and the directory which to store the file must be specified: the syntax being: javac – d directory source/file 83
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
3.13.4. Classpaths
Classpaths are lists of directories where classes are found. A classpath can be declared in two ways:
As an operating system environment variable which is used by default whenever the java or javac commands are used.
As a command-line option for javac and java commands which overrides the environment variable.
The classpath option allows the programmer to define which directories should be searched for classes. Any number of directories can be listed in the option command. The construction of an individual directory location requires forward slashes to define the different branches in the path. To distinguish between multiple paths, the colon (:) symbol is used as a delimiter between paths. By default, the java and javac commands will not search the current directory; therefore, must be told to search the current directory by using a period (.) to define the current directory. When classpaths are searched, it is done from left to right of the listed directory. Therefore if classes with duplicate names are found in the multiple directories, the order of the directories in the command will provide different results. The java command will allow the classpath command to be abbreviated to –cp. The consistency of the shortened command with the javac command prevents its use in every situation.
84
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
When searching for classes, the java and javac commands must work in the same way:
Both must have the same list of directories to search.
The list of directories must be in the same order.
Once the desired class is found, the search is completed.
If multiple classes have the same name, the first .class file found is used.
Directories containing classes standard with J2SE are searched first followed by directories defined by classpaths.
3.13.5. “java” Command
The java command is used to invoke the Java virtual machine to run programs which have been compiled. The structure of the java command is: java [options] class [args] The ‘options’ and ‘args’ part of the command are optional and allow multiple values. Exactly one class must be specified for execution. The .class extension for the class file is not required because the java command assumes that a specified file is a .class file.
85
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
3.14.
Class Library
The Java Application Programming Interface provides a collection of numerous classes that create the standard Java packages. These classes can be used by programmers to use within their own programs without having to recreate the code. Some of the most important packages found in the API are:
java.lang – defines the basic language classes.
java.util – defines utilities and collections classes.
java.io – defines input and output classes.
java.net – defines networking and remote method invocation classes.
java.awt – defines the classes for the GUI interface, abstract Window Toolkit.
javax.swing – defines the classes for a Swing GUI.
3.14.1. java.lang
The java.lang contains the fundamental classes required by the Java language and is imported automatically. The following classes are found in java.lang:
Boolean – the value of the primitive type Boolean wrapped into an object.
Byte – the value of the primitive type byte wrapped into an object.
Character – the value of the primitive type char wrapped 86
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
into an object.
Character.Subset – represents particular subsets of the Unicode character set.
Character.UnicodeBlock – represents a family of character blocks in the Unicode specification.
Class - instances of the class Class which represents the classes and interfaces running in a Java application.
ClassLoader – responsible for loading classes.
Compiler – supports Java-to-native-code compilers and related services.
Double - the value of the primitive type double wrapped into an object.
Enum<E extends Enum<E>> - the common base class of all Java enumeration types.
Float - the value of the primitive type float wrapped into an object.
InheritableThreadLocal - extends ThreadLocal to provide inheritance of values from a parent thread to a child thread.
Integer - the value of the primitive type int wrapped into an object.
Long - the value of the primitive type long wrapped into an object.
Math – contains methods for performing basic numeric operations.
Number – an abstract superclass for the classes BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, 87
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
and Short.
Object – the root of the class hierarchy.
Package – contains version information about a Java package’s implementation and specification.
Process – represents the operating system processes.
ProcessBuilder – used to create operating system processes.
Runtime – allows the application to interface with the environment.
RuntimePermission – used for runtime permissions.
SecurityManager – allows a security policy to be implemented by applications.
Short - the value of the primitive type short wrapped into an object.
StackTraceElement – an element in a stack trace.
StrictMath – contains methods for performing basic numeric operations.
String – represents character strings.
StringBuffer – a thread-safe, mutable sequence of characters.
StringBuilder – a mutable sequence of characters.
System – contains several class fields and methods which are useful.
Thread – a program’s thread of execution.
ThreadGroup – represents a set of threads.
ThreadLocal - provides thread local variables.
Throwable – a superclass of all errors and exceptions in 88
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
the Java language.
3.14.2. java.util
The java.util contains a framework for collections, legacy collection classes, event model, data and time facilities, tools for international programming, and miscellaneous utilities. A collection is an object which represents a group of objects. The collections framework is a unified architecture for representing and using collections. The framework allows a collection to be manipulated outside of its representation. As a result of the collections framework, useful data structures and algorithms are available to programs and will reduce their programming effort. Since the structures and algorithms are streamlined for high performance, their use will increase performance of the application. The framework also provides a common language for ensuring interoperability between unrelated APIs, while reducing any need to learn multiple related APIs. The collection framework contains:
Collection interfaces
General-purpose implementations
Legacy implementations
Special-purpose implementation
Concurrent implementations
Wrapper implementation 89
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Convenience implementations
Abstract implementations
Algorithms
Infrastructure
Array Utilities
3.14.3. java.io
The java.io package is responsible for information on system input and output through data streams, serialization, and the file system. Streams are the most fundamental i/o in Java and represent a flow of data. This flow of data, or communication channel, has a writer at one end and a reader that the other. The java.nio package uses a similar concept called channel, rather than stream. There are several stream types available to Java from the java.io package:
InputStream and OutputStream – basic function for reading and writing unstructured sequences of bytes and used to build all other byte streams.
Reader and Writer – basic function for reading and writing a sequence of character data and used to build all other character streams.
InputStreamReader and OutputStreamWriter – used to convert bytes to characters or characters to bytes.
DataInputStream and DataOutputStream – enables the reading and writing of simple data types such as numeric primitives and String objects. 90
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
ObjectInputStream and ObjectOutputStream – enables the reading and writing of whole serialized JAVA objects.
BufferedInputStream, BufferedOutputStream, BufferedReader, and BufferedWriter – uses buffers to increase efficiency.
PrintStream and PrintWriter – simplifies text printing.
PipedInputStream, PipedOutputStream, PipedReader, and PipedWriter – used in pairs to move database within an application.
FileInputStream, FileOutStream, FileReader, and FileWriter – allows reading and writing of files located in the local filesystems.
Streams allow one-way communication in Java. The classes in the java.io represent the end of a simple stream. To create a bidirectional communication, two streams are required: one of each type of stream. The java.io.File class is used to encapsulate access to information about a file or directory, or metadata. Using streams to read and write file data, the file class will store the information about those files appropriately. Object serialization is another function of java.io which automatically saves and loads the state of an object. An instance of a class implementing the Serialized interfaces will be able to save and restore from a stream.
91
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
3.14.4. java.net
Network applications are implemented using classes found within the java.net package. The package has two parts for dealing with low level and high level abstractions:
Low Level API handles: o
Addresses – network identifiers such as IP addresses
o
Sockets – basic bidirectional data communication mechanisms
o
Interfaces – network interfaces
High Level API handles: o
Universal Resource Identifiers
o
Universal Resource Locators
o
Connections
3.14.5. java.awt
The java.awt package contains classes for creating user interfaces and using graphics and images. Objects within the user interface, such as a button, are called components. The Component class is the basis for all AWT components. A container is a component that contains other components. It can have a layout manager to control the visual placement of the components within the container.
92
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
3.14.6. java.swing
The javax.swing package contains the classes used for Java’s graphical user interface toolkit, Swing. The classes found within the package represent the windows, buttons, combo boxes, trees, tables, and menus required to build rich client-side applications. Swing is a part of the Java Foundation Classes (JFC), which also includes:
Abstract Window Toolkit (AWT)
Accessibility
2D API
Drag and Drop
93
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
4 Enterprise JavaBeans
4.1. Overview
4.1.1. Uses of Enterprise JavaBeans
Enterprise JavaBeans, or EJB, is application development through building blocks, or EJB components. These components can be mixed and matched in various ways to provide different applications for the business. Also called a bean, these components can be developed, sold and used across the business worlds. The idea builds on the concept of reusing Java classes to include the reuse of application functionality. In most cases, the behavior of the bean can be modified without making changes to the underlying Java code. This allows the business developer to focus on the business logic of the application while allow the Java services to be handled through an EJB server vendor. The services handled by the EJB server include:
Transaction Management
Security
Concurrency
Networking
Resource Management
Persistence 94
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Messaging
Deploy-time Customization
4.1.2. Benefits of Enterprise JavaBeans
The greatest benefit of Java programming is its portability. With EJB, the benefit remains the same. Beans can be written once and deployed anywhere. (The benefit is sometimes referred in the acronym WODA). In the early days of application development, a business was at the mercy of the application server vendor; that is, if a new feature was required, the business had to wait until the application server vendor developed it. With JavaBeans, the business no longer has to wait: either they can add the functionality themselves or they can go to another application server vendor.
4.1.3. Characteristics of Enterprise JavaBeans
Enterprise JavaBeans is a specification for a server and is a subset of J2EE. This means that the J2EE server must include an EJB container in order to run EJB. Components for EJB cannot run outside of the EJB container. JavaBeans, or beans, is an expression meaning reusable component. Regular, or non-enterprise, beans follow a naming convention used by development tools. The most common javabeans are GUI components and run in a Java Virtual Machine. Though enterprise 95
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
javabeans are reusable components too, they are used at development time to improve efficiency in connecting different beans together. An enterprise bean will implement at runtime and must be run within an EJB container. To understand the mechanics of EJB, one must look first at the client/server architecture. Clients can be any computer on the network, a servlet, a stand-alone Java app, an enterprise bean, or mobile device. The term client encompasses any client object which is calling the particular enterprise bean on the server in question. On the server, the EJB Container and the database are located: the EJB Container contains the business logic and the database holds the data used by the logic. Within the EJB container lays the business interface, the EJB object, the services, and the Enterprise Bean. The Client will never communicate directly with the bean, but is intercepted by the EJB object. It will pass all requests to the container which will authenticate clients, instantiate beans, and initiate garbage collection. The container will call the appropriate bean to fulfill the client’s request. There are three types of beans:
Entity – represents an item in persistent store, particularly a row in the table found in the database.
Message-Driven – used only when listening for messages from a JMS messaging services: messages are sent from the client to the messaging service which forwards on to the server.
Session – used for all other requests and typically 96
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
represents a process.
4.1.4. Building a Bean
The process for building a bean covers five general actions: 1. Coding the bean class 2. Coding the appropriate interfaces: home and component 3. Creating an XML deployment descriptor 4. Loading the ejb-jar file 5. Deploying the bean on the server The bean class contains all the business methods that the client will call. The bean types contained within the bean class are of all three types of beans: Session, Entity, and Message-driven. The client sees two interfaces. The component interface contains all the declared business methods. Each business method must correspond to a method in the bean class. Additionally, all methods on the interface must declare a RemoteException. As a result, the java.rmi.RemoteException statement must be imported: along with the javax.ejb.*. To complete the coding of the component interface, either the EJBObject interface or the EJBLocalObject must be extended. Though the bean class can implement the component interface, the specification does not recommend this approach. Rather, the class must be created separate and before the interface. The home interface is used by the client to request a reference to the 97
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
component interface and, from a client perspective, will create and distribute bean references to the client. The syntax for the home interface is similar to the component interface, with a few exceptions. The EJBHome interface or EJBLocalHome interface must be extended. A create() method is used to return the component interface type and two exceptions must be called: CreateException and RemoteException. The structure of the bean is determined by the deployment descriptor (DD). The relationship between the bean class, component interface, and the home interface is defined by the DD. A single DD can be implemented for multiple beans within the EJB container. The DD will tell the server the classes within the bean and how they are connected. The name of the DD file must be ejb-jar.xml. Every bean must be placed into a JAR file. The ejb-jar file is defined by the specification to house all items the bean is dependent on to perform properly, including classes, interfaces, and the deployment descriptor. The DD must be located in the META-INF directory. The ejb-jar file can have any name assigned to it. The bean class, home interface class, and component interface class must be in a directory within the JAR file which matches the defined package they are a part of. Classes and interfaces which are generated by the container are not placed in the ejb-jar file. The final step in the process is to deploy the bean on the server. This is performed in two steps: application assembly and deployment. Tools provided by the server vendor are required to perform each 98
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
step. Application assembly focuses on making a bean are usable part of an application. A single bean may be used as the entire application or multiple beans may be combined into a single application. When combining multiple beans, each bean which has its own ejb-jar and DD will be placed into a new ejb-jar with a different DD which communicates how the beans are related to each other. Additional information may be added to the DD during the application assembly. Environmental entries are properties written in the code by the developer but does not have a value attributed to the property until the application is assembled. Deployment involves naming the bean and putting the bean into the control of the server’s container.
4.1.5. EJB Roles
Four basic roles are found in bean development:
Bean Provider
Application Assembler
Deployer
Container and Server Provider
The Bean Provider is responsible for writing the bean code: designing and programming enterprise javabeans. To the process, they provide the ejb-jar files which contain one or more beans and a single deployment descriptor. The bean provider is an expert in the business 99
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
logic for a particular component within a particular domain. The Application Assembler will compile multiple enterprise javabeans provided by multiple bean providers. The deliverable for the application assembler is a single ejb-jar file containing one or more beans, a single deployment descriptor and information on application assembly. The application assembler may also create clients and define the interactions between other components. The purpose of the application assembler is to combine multiple enterprise beans into a single application and defining the behavior of the application, particularly in the areas of security and transactions. They are well knowledgeable in a particular domain. Deployers are customized enterprise beans for a specific operating environment, taking the deliverable from the application assembler and resolve any external dependencies that may be present. If a particular resource is required, the deployer will map the logical name from the bean provider to the actual name of the resource on the server. The deployer is well knowledgeable about the specific operational domain the enterprise bean is located. He knows the security users and roles for the system, how the server is configured, and how the deployment descriptor should be interpreted for the environment. The container and server provider is responsible for implementing the specification; particularly in the area of distributed objects, transactions, and other low-level system services. They provide an EJB compliant server, deployment tools, and the runtime environment 100
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
for enterprise beans.
4.1.6. Remote Method Invocation (RMI)
Enterprise JavaBeans use Remote Method Invocation (RMI). Method invocation provides the fundamentals for communication in Java. Remote Method Invocation allows communication between virtual machines on different hosts. Its basic function is to obtain a reference to an object on a remote host and use that object on the existing virtual machine. Similar to remote procedure calls (RPC) in C programming, the difference with RMI is its data structure which handles both the data and the methods for using the data. RMI also uses object serialization to send objects and all the connected objects that they reference through graphs. The object must be serializable before it can be used remotely. When a method invocation is initiated on a remote object, it happens on the remote host where the object resides. The results of the method are seen on the referencing virtual machine. This is different from a non-remote object, or data transfer object (DTO), which is copied over the network to the requesting virtual machine. When a method is invoked on a remote object, what is being called is some local code acting as a proxy for the object. This local code is code that is called a stub. With the object on the original host is another proxy, called the skeleton. The skeleton receives the remote method invocations from the stub and passes them on to the object. 101
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
For Java 5.0 clients and servers, the generation of stubs and skeleton classes are done dynamically: For earlier versions, the stub and skeleton classes must be generated explicitly and deployed with the application. This must be done to enable interoperability with older Java clients. A remote interface is implemented by remote objects which identify which methods can be invoked remotely. It is created when the java.rmi.Remote interface is extended for the application. For the client-side code, the remote object should be an instance of the remote interface, not an instance of its implementation class. All methods in the remote interface must declare they can throw the java.rmi.RemoteException. The exception is required in case a networking error happens. Remote objects are made available by using the java.rmi.server.UnicastRemoteObject class. This can be done by having the remote object extend UnicastRemoteObject. The RMI runtime system will automatically export the class in order to begin listening for network connections. The RMI has a registry used to identify a reference to a registered remote object on another host. The client is able to find the initial object through the registry, which initiates the process to allow remote methods calls to pass remote references. The registry is implemented using the Naming calls and the rmiregistry application. The application must be running on the local host before the Java program using the registry is started. Once completed, instances of remote objects can 102
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
be created and bound to particular names in the registry. When a client object finds an object in the registry, a special URL with the rmi: protocol, hostname, and object name is constructed. The RMI Naming class on the client talks to the registry and returns a remote object reference. In EJB, the EJBObject acts as the remote object which communicates with the Enterprise Bean. The EJB container is considered the whole of the RMI heap. A business interface exists between the client and the stub and another exists between the stub and the remote object. Essentially, the business interface for both is the same and is implemented by the receiving entity (stub and EJBObject, respectively). The business interface is called the component interface in EJB. The difference between an RMI interface and a component interface is the extension of the javax.ijb.EJBObject rather than the java.rmi.Remote. As calls reach the remote object, the services provided by the server are invoked, including security, transactions, and persistence. The EJBObject will implement the remote business interface to handle remote calls from the stub.
103
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
4.2. Client View
4.2.1. Java Naming and Directory Interface (JNDI)
Java Naming and Directory Interface (JNDI) is an API used in Java to access a directory service to allow Java software clients to identify data and objects using a name. JNDI operates independently from the underlying implementation and will specify a service provider interface (SPI) to allow a directory service to be connected to the framework. Implementations of JNDI can use either a server, flat file, or a database. The JNDI API provides:
A method for binding an object to a name
A lookup interface to allow general queries to the directory
An event interface to allow determination of modified directory entries
LDAP extensions to support LDAP service capabilities
The SPI provides support for:
LDAP
DNS
NIS
RMI
CORBA
File Systems 104
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Names are organized in JNDI in a hierarchy. A name can be any string or an object supporting the Name interface. A name is bound to an object within the directory. This binding is the result of storing either the object or a reference to the object in the directory service. The JNDI API will define the context which specifies where an object is searched. Directories have attributes associated to them which enable object searching. JNDI drivers reserved for directory service types are loaded at runtime. These drivers map to a specific directory service and are automatically loaded when a link to the directory service is chosen. This process allows clients to navigate through directory services without knowing what services are present. JNDI enables the client to perceive the EJB server as a set of directories. The client uses JNDI to locate and obtain a remote reference to the EJB home, which in turn provides an EJB object reference to an enterprise bean. The process begins with a JNDI InitialContext object. This initial context is the start of any JNDI lookup and the written code begins with defining a properties table of the type Properties to allow the addition of various values to define the context. The coding will change based on the implementation of JNDI by the EJB vendor.
4.2.2. Remote Client API
A primary key is required for entity beans. In addition, a bean class and component interfaces are provided by enterprise bean 105
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
developers. While the component interfaces and primary key are visible to the client, the bean class is not visible. The client-side API in EJB is supported by the component interfaces and primary key. Clients use the Remote Client API, specifically the remote interface, remote home interface, and the Java RMI. In EJB 1.1, all clients will use the Remote Client API while only remote clients use the API in EJB 2.0. If the enterprise beans are located in the same EJB container in EJB 2.0, the Local Client API can be used. The Local Client API provides local component interfaces. The restrictions and overhead normally attributed to the Remote Client API are not present. Remote interfaces are defined using Java RMI-IIOP and enforces compliance with CORBA. The underlying protocol used to access enterprise beans by remote clients must be able to support the interface types and arguments compatible with Java RMI-IIOP. Compliance with Java RMI-IIOP types require EJB vendors to restrict interface and argument definitions to types that map to IIOP 1.2. The remote home interface and remote interface contain the supertypes of javax.ejb.EJBHome and javax.ejb.EJBObject, which are extensions of java.rmi.Remote. These interface subtypes must adhere to Java RMI specifications. The remote component interfaces follow several guidelines, mostly affecting the allowable return types and parameters. Two types of return and parameter types exist:
Declared – checked by the compiler
Actual – checked at runtime. 106
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Java RMI allows actual types to be used, but they must be primitives, String types, java.rmi.Remote types, or serialized types. There are no special rules by Java RMI related to declared return types or parameter types. If a type is not a java.rmi.Remote type during runtime, it is assumed to be serialized: if this type is not serialized, an exception will be thrown. Actual types are checked at runtime and cannot be checked by the compiler. Serialized objects are copied, not referred, which means that changes in a serialized object on one tier are not automatically reflected on the other tiers. Objects implementing Remote are passed as remote references, which is a Remote interface implemented by a distributed object stub. The stub is serialized and passed by value when a remote reference is passed. Arguments are remote references passed into the create() method and the EJB object stub pointing to the same EJB object is passed by copy. Every method defined in the remote interface is required by the Java RMI specification to throw the java.rmi.RemoteException to identify problems with the communication of distributed objects. Remote interface type scan throw exceptions specific to the application. Some restrictions are placed on remote interface and value types by Java RMI-IIOP. Method overloading is restricted: namely, a remote interface cannot directly extend two or more interfaces with methods of the same name. A remote interface can overload its own methods and extend the remote interface with overloaded method names. The 107
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
other major restriction is serialized types cannot not implement the java.rmi.Remote interface either directly or indirectly.
4.2.3. Remote Home Interface
Life-cycle operations and metadata for the enterprise bean are provided by the remote home interface. When using JNDI to access a bean, a remote reference, or stub, to the bean’s EJB home is obtained to implement the remote home interface. Each bean type may have one home interface. This interface will extend the javax.ejb.EJBHome interface. To delete an enterprise bean, use the EJBHome.remote() methods. The arguments for this action will either be the javax.ejb.Handle of the bean or the primary key for entity beans. The javax.ejb.Handle is a serializable pointer to a specific bean. When the remove methods are invoked, the remote reference of the enterprise bean on the client will become invalid because the stub of the bean no longer works. The impact of the remove methods is dependent on the bean reference removed. Removal of session bean reference will end the conversational state maintained by the session bean. Removal of the entity bean reference will delete any data referenced from the database. The EJBHome.getEJBMetaData() will return an instance of the javax.ejb.EJBMetaData. This will describe the remote home interface, the remote interface, and primary key classes. It will also define the 108
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
enterprise bean as a session or entity bean. The metadata allow enterprise beans from a client perspective to be interpreted. The EJBMetaData is used rarely by application developers, but knowledge of its existence is helpful when creating automatic code generators or other automatic facilities. The EJBHome.getHomeHandle() method is used to call the HomeHandle by returning a javax.ejb.HomeHandle object. This object provides a serializable reference to the remote home of an enterprise bean. It allows a remote home reference to be stored and used at a later time. Create and find methods can be included in the remote home interfaces. Create methods will throw a CreateException if the create process cannot be completed; while a FinderException is thrown by the find methods for any errors. The methods used are specific to each enterprise bean. Session beans will not have find methods: only entity beans will have find methods. This is true for entity beans because they represent uniquely identifiable data within the database. Create methods in EJB 2.0 can be expanded using a method name as a suffix, in the form of create<SUFFIX>(). This expansion is not required and it is not supported in EJB 1.1. The same is possible for find methods in the home instance for bean-managed entities. Every find<SUFFIX>() method in the home interface must correspond to an ejbFind<SUFFIX>() method in the bean. Home methods can be defined in the home interface and consist of any methods which are not create or find methods. Home methods 109
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
are business methods invoked on the home interface and are not specific to one bean instance. They should have a corresponding ejgHome() method in the bean class. Home methods are available only to entity beans.
4.2.4. Remote Interface
The remote interface will define the business methods of an enterprise bean. The base class for all remote interfaces is the javax.ejb.EJBObject interface, which is an extension of the java.rmi.Remote interface. Remote interfaces are not used for system-level operations, such as persistence, security, concurrency, or transactions. They focus on the business problem, while the system-level operations are handled by the EJB server. All remote interface methods for bean are required to throw a java.rmi.RemoteException at the very least. Custom exceptions can be included in the remote interface to identify abnormal conditions or errors in the business methods. The javax.ejb.EJBObject interface is extended by all remote interfaces. This interface provides utility methods and return types which can be used to manage the interactions between the bean and clients. When a reference to the remote interface is obtained by the client, the reference is actually pointing to an EJB object. The remote interface is implemented by the EJB object by delegating business method calls 110
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
to the bean class. The methods return information about the corresponding bean instance on the server. The EJBObject.getEJBHome() method returns a remote reference to the EJB home as a javax.ejb.EJBHome object. It can be used to control the scope of the remote EJB home for the EJB object. The primary key for an entity bean can be returned by the EJBObject.getPrimaryKey() method. The method can only be used by EJB objects representing entity beans. Specific data represented by entity beans are identified using the primary key. Since session beans represent tasks or processes, primary keys are not helpful. Remote references to entity beans can be obtained using the findByPrimaryKey() method. The primary key is required for the correct bean in the correct container. It must also implement the java.io.Serializable interface to ensure it can be obtained from an EJB object regardless of its form. Remote references for EJB objects can be compared using the EJBObject.isIdentity() method. The method returns a true value is the two object references represent the same bean, even when the object stubs are attached to different object instances. Entity and session beans can be removed using the EJBObject.remove() method. It has the same impact as the EJBHome.remove() method. In session beans, the remove() method will release the session and the remote EJB object reference becomes invalid. In entity beans, the entity data is deleted from the database and the remote reference becomes invalid. 111
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
The EJBObject.getHandle() method returns a javax.ejb.Handle object. Using the Handle which is a serialized reference, the Handle object can be saved in the same way that the primary key can be used. As a result, a remote EJB object reference can be recreated to point to the same type of session bean or the entity bean where the Handle originates. The Handle interface will specify only one method, the getEJBObject(). The method will return the remote EJB object. The Handle object will also encapsulate the details of a JNDI lookup on the container. Similar in purpose to the javax.ejb.Handle is the javax.ejb.HomeHandle, which will store and retrieve references to remote EJB homes.
4.2.5. Local Client API
Local component interfaces are introduced in EJB 2.0 to provide different semantics and execution contexts for enterprise beans in the same container system. Co-located beans identify when two or more enterprise beans interact, as in deployed in the same container system and executed within the same JVM. They do not use the network for communication: though they do not incur the overhead of Java RMI-IIOP, they are required by the EJB 1.1 specification to use the Java RMI-IIOP semantics for communication. Session and entity beans can implement remote or local interfaces, or both. Any bean type can be a co-located client of a session or entity bean. The Local Client API is similar to the Remote Client API: it is composed of two interfaces, a local and a local home interface. The 112
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
local interface defines the business methods of the enterprise bean that are invoked by co-located beans. The business methods will match the signatures of business methods defined in the bean class. Local interfaces will extend the javax.ejb.EJBLocalObject interface and remote interfaces will extend the javax.ejb.EJBObject interface. The EJBLocalObject interface defines several methods, including:
getEJBLocalHome()
getPrimaryKey()
isIdentity()
remove()
The local home interface is similar to the remote home interface in its defining of life-cycle methods for enterprise beans. Unlike a remote home interface, the local home interface is invoked by other colocated beans. The life-cycle methods include find, create, and remove methods.
4.3. Session Bean Components
4.3.1. Stateful and Stateless Session Beans
Session beans are either stateful or stateless. This attribute is attached to the bean at the time of deployment. A stateful bean retains the conversation state between method calls, while a stateful bean does not. In other words, the stateful bean remembers the state of the 113
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
client as long as the session is alive. Though the client can still perform method calls to stateless beans, this type of bean is not expected to remember anything about previous method calls. While stateless beans will not remember the client-specific state, it can be found within a state itself. That is, they can have instance variables like other objects. In this case, an instance variable cannot maintain values which are specific to an individual client.
4.3.2. Session Bean Lifecycle
The high level action of a session bean consists of creating and using the bean. These two steps can be broken down into smaller parts, specifically: Creating a Bean 1. The create() method is called by client on the home stub. 2. The home object receives the create() call. 3. The EJBObject (component interface) for the bean is created by the Container. 4. The bean is made by the Container. 5. The EJBObject stub to the client to the Home. Using a Bean 6. The client calls a business method on the component interface stub using a getAdvice() method. 7. The getAdvice() call is received by the EJBObject. 114
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
8. The Container handles the action and the getAdvice() is called on the bean. Removing a Bean The lifecycle of the session bean is dependent on whether the bean is considered stateful or stateless. Both conditions will involve bean creation, use, and removal. A stateful session beans has two additional events between use and removal: passivation and activation. Bean passivation is the act of putting a bean to sleep to conserve resources. Bean activation will wake the bean up from sleep condition for the purpose of servicing a business method from the client. These events are not known until a container callback method is called for the bean. Container callbacks are contained in the home interface for the bean and within the SessionBean interface of the session bean class. For session beans, the container callbacks which are home-related will match each create() method declared in the home interface. These matching method using the ejbCreate() method. Four container callback methods are declared within the SessionBean interface: providing bean context, activating the bean, passivating the bean, and removing the bean. Every session bean will have at least five container callbacks: exactly five for stateless session beans. In addition to the four declared within the session bean class, the fifth is the ejbCreate() to match the create() method declared within the home interface. For stateful beans, there may be more create() methods. 115
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
There are three transitions for stateful session beans:
Does not exist to method ready
Method ready to does not exist
Method ready to passivated
Passivated to method ready
Passivated to does not exist
A bean does not exist before it is created, sitting within a state of nonexistence. When a session bean move out of this state, the constructor for the bean runs, then the setSessioncontext(), and then the ejbCreate() method. The state is returned when the bean times out, an system exception is thrown, or a remote() method is called by the client. The method ready state identifies when a bean is either executing a method for the client or waiting for the client to make another business method call. An active transaction may not be present while in this state. If the bean is in a transaction, if cannot be passivated. A passivated bean is stored in a temporary hold to conserve resources between calls. A passivated bean remains an inactive object on the heap until is it reactivated by the Container using an ejbActivate method. When moving from a does not exist state to a method ready state, the following methods are present in the code:
constructor – should be empty with all code being placed in the ejbCreate() 116
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
setSessionContext() – must be saved for context
ejbCreate() – should contain initialization code
When moving from a method ready state to a passivated state or from a passivated state to a method ready state, the following methods are used respectively:
ejbPassivate()
ejbActivate()
When ejbPassivate() completes, every non-transient instance variable must be a reference to:
A Serializable object
A null value
A remote component or home interface
A local component or home interface
A SessionContext object
A bean’s JNI context
The UserTransaction interface
A resource manager connection factory
When moving from a passivated or method ready state to a ‘does not exist’ state, the following are present:
Timeout – after the bean is passivated, the client doesn’t call any methods on the component interface; the container will decide to kill the bean, but does not call ejbRemove(). The bean and EJB object are killed and the client receives an exception when the stub is used again. 117
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
System exception – an unchecked exception is thrown during method execution; the container will decide to kill the bean, but does not call ejbRemove(). The bean and EJB object are killed and the client receives an exception when the stub is used again.
ejbRemove() – all resources should be released before ending the remove state. In most cases, resources are acquired and released with each business method; but in some cases resources are released within the remove() method. The use of a cleanup() method called from the ejbPassivate() and ejbRemove() will ensure resources are released properly.
4.3.3. Creating Beans
An object must be granted “beanness” in order to become a bean. The point when an object becomes a bean is critical to the developer. “Beanness” to an object provides a context for the bean, a JNDI context, and access to beans and resources. A context for the bean is sometimes called the EJBContext. It is the only connection to the Container and allows the bean to obtain security information, force a transaction, and more. A JNDI context is provided to every bean to enable the bean to find resource manage connection factories, other beans, and deploy-time constant values. The type of bean created, the transaction status, and the methods used will determine how much capability is available to individual 118
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
beans.
4.3.4. Bean Classes
Several sets of rules must be followed when creating bean classes. The rules related to the home interface are:
The local component interface must be returned by the local home interface, while the remote component interface must be returned by the remote home interface.
A CreateException must be declared by every create method in the home interface, regardless of local or remote connection.
The EJBLocalHome must be extended by the local home interface and RemoteExceptions must not be declared.
The EJBHome must be extended by the remote home interface and RemoteExceptions must be declared on every method.
Stateless beans will have only one empty create() method (no arguments).
Stateful beans will have one or more create() methods and can have arguments. The create() methods must start with the ‘create’ string and can be overloaded.
Legal RMI-IIOP types must be used for all arguments and return types for Remote home interface methods.
The rules regarding home methods within the bean class are:
Every create method in the home must have a matching 119
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
ejbCreate method in the bean class and the ejbCreate method must have a void return type.
The ejbCreate methods must be public and cannot be final or static.
Exceptions declared in the home interface do not need to be declared in the bean class.
RemoteExceptions should never be declared in the bean class.
Application exceptions not declared in the home interface must not be declared for the matching create method.
Stateless beans can have only one ejbCreate() method and must have no arguments.
Stateful beans must have one or more ejbCreate methods and must start with the string ‘ejbCreate’.
Business methods in the component interface must following the rules below:
Business method names never start with the string ‘ejb’.
Legal RMI-IIOP types must be used for all arguments and return types for Remote component methods.
The EJBLocalObject must be extended by local component interfaces and RemoteExceptions must never be declared.
The EJBObject must be extended by remote component interfaces and every method must declare RemoteExceptions.
Neither the local home nor component interface of a bean 120
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
should be exposed through a remote component method. Business methods in the bean class must following the rules below:
Business methods must be declared public and not final or static.
Business method names must not begin with the string ‘ejb’.
The ‘this’ must never be passed as an argument or return value.
Legal RMI-IIOP types must be used for all arguments and return types for remote component interface methods.
Exceptions declared in the component interface do not have to be declared in the bean class.
RemoteExceptions must not be declared in the bean class.
Application exceptions must not be declared if they were not declared in the component interface for a matching business method.
Some additional rules for bean classes include:
The javax.ejb.Session must be implemented by the class, either directly or indirectly.
The class must be public and not declared as final or abstract.
A public, no-arg constructor must be in the class.
A finalize() method must never exist in the class.
The bean’s component interface is not required to be implemented by the class. 121
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
The matching home and component interface methods must be implemented by the class.
If a stateful bean, the SessionSynchronization interface can be optionally implemented.
A bean class can have a superclass.
4.4. Java Persistence API Entities
4.4.1. Characteristics of Entities
Entity beans represent data which exist in an underlying persistent store. A persistent store could be a relational database, an object database, or stored serialized objects in files. The entity bean provides an object-oriented perspective to that store. Entity beans are data objects. In EJB application, entity beans are combined with session beans, where the session beans provides a process and the entity bean provides the data that the process is acted upon. Entities are the things which are represented by entity beans. If the entity is deleted, the entity bean disintegrates. However when the entity bean is killed, the entity still exists. This is because the entity is real, while the entity bean is simply a representation of something that is real. In most applications, entities are not realized as entity beans until a particular entity is required in the application logic. From a client’s perspective, entity beans allow the database to be 122
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
manipulated, specifically:
Making a new entity
Deleting an entity
Updating an entity state
Searching or querying entities
The client interface for entity bean works different than interfaces for session beans. With a session bean, the business methods of the bean are called after creating the bean and having the Container allocate a new EJB object. With entity beans, the entity already exists and a new reference to the entity must be created. This requires one or more finder methods. The following process for existing entities is performed: 1. A JNDI lookup on the entity bean home is performed and a home interface reference obtained, a findByPrimaryKey() method on the home stub is called. 2. The findByPrimaryKey() method invocation is sent to the home object. 3. The Container initiates a bean from the bean pool to confirm the existence of the entity in the database. 4. The bean checks for the entity using the primary key. 5. The bean communicates the entity’s existence to the home object. 6. The container makes or finds an EJB object for the entity. 7. A stub for the entity is returned by the Container. When a new entity is created, the process is as follows: 123
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
1. A JNDI lookup on the entity bean home is performed and a home interface reference obtained, a create() method on the home stub is called. 2. The create() method invocation is sent to the home object. 3. The Container pulls a bean from the pool. 4. The Container or bean inserts a new row in the database and a new primary key is generated by the bean. 5. The bean is linked to an EJB object and the new primary key is obtained by the context and EJB object. 6. A stub is returned by the Container for the new entity. Entity beans can undergo passivation and activation. Unlike session beans though, passivated entity beans remain live objects on the heap. Stateful session beans will go to sleep in a pool. Entity beans, stateless beans, and message-driven beans will use pools but do not go to sleep there: the pools are used for living, RAM-using objects on the heap. Entity bean pool is called when the bean is finished with a business method. When a bean is passivated, it has no identity = it does not represent any entity from the database. The passivation method is used to release resources not used while the bean is sitting in the pool, not running a business method. The ejbActivate() method is used by the Container when a bean is required to service a business method.
124
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
4.4.2. Entity Bean Code
A simple entity bean is coded as follows
// package and imports declared public class BeanName implements EntityBean {
private String columnName1;
private String columnName2;
private String uniqueID;
private entityContext context;
private String ejbCreate(String first, String second) {
columnName1 = first;
columnName2 = second;
uniqueID = this.getPK() ;
// DB INSERT
return uniqueID;
}
public String getColumnName1 () {
}
public void setColumnName1 (String variablename) {
}
return columnName1;
columnName1 = variablename;
125
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
public String getColumnName2 () {
}
public void setColumnName2 (String variablename) {
}
return columnName2;
columnName2 = variablename;
public void ejbActivate() { }
public void ejbPassivate() { }
public void ejbRemove() {// DELETE}
public void setEntityContext(EntityContext ctx) {
}
context = ctx;
public void unsetEntityContext() { }
public void ejbLoad() {// DELECT}
public void ejbStore() {// UPDATE}
private String getPK() {
}
return “”+ (int) (primary key algorithm);
4.4.3. Component Interfaces
126
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
A component interface of an entity bean is exactly like a session bean’s with business methods and an extension of the javax.ejbObject. The business methods for an entity bean represent a single entity: multiple entities require multiple entity beans. The interface is developed using the methods: getcolumnName1()
setcolumnName1(String variablename)
getcolumnName2()
setcolumnName2(String variablename)
What the client sees as part of the interface is:
getcolumnName1()
setcolumnName1(String variablename)
getcolumnName2()
setcolumnName2(String variablename)
getPrimaryKey()
getEJBHome()
getHandle()
remove()
isIdentical()
Remote component interfaces must:
Import javax.ejb.* and java.rmi.RemoteException.
Extend the javax.ejb.EJBObject. 127
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Declare one or more business methods.
All arguments and return types must be RMI-IIOP compatible.
Every method must declare a RemoteException.
Application exceptions can be declare but must not be runtime exceptions.
Methods can have arbitrary names, without beginning with ‘ejb’.
Methods can be overloaded.
4.4.4. Home Interfaces
The difference between home interfaces for session beans compared to entity beans is the basic: there is a greater possibility for finding an existing entity than creating a new one and queries can be performed on more than one entity. For the home interface, the following code is written:
create(String col String first, String second)
findByPrimaryKey(String key)
findByCity(String city)
What the client sees on the other side of the interface is:
create(String col String first, String second)
findByPrimaryKey(String key)
findByCity(String city) 128
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
getEJBMetaData()
getHomeHandle()
remove(Handle h)
remove(Object key)
The final four methods above, which are seen by the entity bean client, are the same four seen by the session bean client. Both entity and session beans must extend the javax.ejb.EJBHome. While entity beans can use both remove() methods, session beans will only use the remote() method that takes a Handle. The create and finder methods in an entity bean home will always return the component interface for the bean. A reference to one EJB object is required for the methods, create() and findByPrimaryKey(). With a remote interface, remote stubs are returned by create and finder methods. The problem is that multiple stubs may be returned when performing on multiple items. Business methods can be used within the home interface to return anything, not just component interfaces. This allows queries to return the actual entity data and not simply the references to the entities. The rules of the remote home interface are:
The javax.ejb.* and java.rmi.RemoteException must be imported.
The javax.ejb.EJBHome must be extended.
One or more create() methods can be declared. These 129
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
methods must return the Remote component interface and declare a RemoteException and CreateException.
All create() methods must begin with the prefix string “create”.
The findByPrimaryKey() method can be declared and must return the Remote component interface and declare a RemoteException and CreateException.
One of more finger methods can be declared. These methods must return the Remote component interface or java.util.Collection and declare both a RemoteException and a Finder Exception.
One or more home business methods can be declared with the following guides: o
All arguments and return types must be RMI-IIOP compatible.
o
Every method must declare a RemoteException.
o
Application exceptions can be declare but must not be runtime exceptions.
o
Methods can have arbitrary names, without beginning with ‘create’, ‘find’, or ‘remove’.
Methods can be overloaded.
4.4.5. Entity Bean Instances
An entity is a real thing within the underlying persistence store and an entity bean is a representation of that real thing. When the real thing is entity is removed from the store, it representation disintegrates. 130
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Removal of the entity can be done by deleting the entity from the database or by calling the remove() method on the home or component interface. During the development and deployment of the entity bean, it consists of the home and component interface, the deployment descriptor, and the bean class. Sometimes, the term ‘entity bean’ is used to represent the possibility of an entity. If an entity exists for a particular bean type, the entity bean for that entity exists. Therefore, if the entity is deleted, the entity bean dies; but the entity bean instance returns to the pool. An instance of the bean class on the heap is affected by the Container or a server. While the death of the bean can be tied to an event on the database, the death of a bean instance can only come from the Container or server crash. The instance lifecycle for entity beans moves between three states:
does not exist
pooled
method ready
There are four transitions between these states
From does not exist to pooled
From pooled to method ready
From method ready to pooled
From pooled to does not exist
131
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
The first transition is performed by the constructer with a setEntityContext() method to move the bean into a pooled state. To transition further into a method ready state, either an ejbCreate() or ejbPostCreate() method must be used on new entity beans or an ejbActivate() method for existing entity beans. The ejbPassivate() and ejbRemove() are used for the third transition from method ready to pooled, but never both at the same time. The last transition into a does not exist state occurs when the unsetEntityContext() method is used or an instance throws a system exception.
4.4.6. Synchronization
Since the bean is not an entity but a representation of the entity, the bean and the actual entity must remain synchronized. Synchronization is the effort of the Container. A client with a reference to the bean may change the state of the bean by using a set() method. If the method affects a persistent field of the bean, the bean and the database will be out of sync temporarily until the database is updated by the bean. The same temporary loss of synchronization is possible when the data within the database is updated. In this case, the bean must be updated with the change. The Container is responsible to ensure a negative impact is prevented when the bean and database are out of sync. This is done by:
Preventing anyone from working with the entity in the database when someone is already working with the bean
Updating the database with the entity bean’s state once it 132
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
has been updated, before the entity can be accessed by anyone else
Refreshing the bean with the entity’s current state before running any business method on a particular entity
The synchronization process takes the following steps: 1. A business method is called by a client. 2. The call is intercepted by the Container and a transaction is started before obtaining the bean. 3. The database is told by the Container to lock the row and granted access only to the Container. 4. The Bean is loaded by the Container with the entity state from the database. 5. Multiple business methods are run by the bean in the same transaction. 6. The database is updated by the database with the new state of the bean before the transaction is ended. 7. The Container tells the database to remove the lock on the entity. The Container knows when the bean and the database entity need to be synchronized based on the transactions. Database access is controlled based on the database access code. Container-Managed Persistence (CMP) will have the container take care of all the database access code, including adding and deleting entities. BeanManaged Persistence (BMP) has database access code created by the developer using JDBC statements in callback methods, including looking up a DataSource, obtaining a Connection, and sending JDBC 133
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
statements to the database. Container-managed persistence (CMP) is enhanced EJB 2.0. The design of the entity bean class is made by the Bean Provider. The bean’s field which are part of the bean’s persistent state must be chosen and relate to columns in one of more database tables. Changes to the entity and the entity bean are tracked by the Container and will determine how to synchronize the two based on the state of the transactions. EJB-QL is written by the Bean Provider to instruct the Container on how to perform selections. Information found within the Deployment Descriptor provides guidance to the Container on the actual implementation of the CMP bean.
4.4.7. Container Callbacks
In addition to the ejbPassivate, ejbActivate, and ejbRemove methods, entity bean interfaces have another three container callbacks. They are:
unsetEntityContext() – called by the container to reduce the pool size
ejbLoad() – called to refresh the bean with data from the underlying persistent store
ejbStore() – called by the Container to update the database to reflect the state of the bean
The other difference from session beans, entity beans set the EntityContext rather than the SessionContext. The 134
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
setEntityContext(EntityContext ec) method allows the Container to give the bean a reference to its context. The entity bean has new home container callbacks. Every create() method found in the home must have two methods in the entity bean: ejbCreate() and ejbPostCreate(). Every home business method must have a matching ejbHome<methodName>. Finder methods are part of the bean class but not defined in the bean. Every entity bean using CMP will have at least seven container callbacks.
4.4.8. Entity Classes
Entity bean classes consist of items from the home interface, the component interface, the EntityBean interface, and virtual persistent fields. For every create() method in the home, the bean class must have a matching ejbCreate() and ejbPostCreate() method. Every business method in the home must have a matching ejbHome<method> in the bean class. Finder methods do not need to be written into the bean class: they will be written by the Container based on information from the deployment descriptor. Each method found in the component interface must have a corresponding concrete implementation in the bean class. The EntityBean interface can be implemented either directly or indirectly. For each persistent field, an abstract getter and setter must be provided. In the bean class code, virtual persistent fields will exist only as abstract getters and setters. These fields represent values that 135
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
map to columns in the database. They are not instance variables.
4.4.9. Entity Identity and Primary Keys
The initialization code for the entity is coded into the ejbCreate() method. With entity beans, the method is not used to construct the bean but to associate the bean to the new entity it represents. The most important code required within the ejbCreate() method is the primary key. Every entity must have a unique identity. Containers will never allow entities to share the same primary key. Determining the primary key is the developer. The simplest form of primary key is a direct mapping between a single field and a single column in the database. Compound keys use two or more container-managed persistent fields. The use of the ejbCreate() method must follow the rules:
Each ejbCreate<method> must match a corresponding create<method> in the home interface.
Method names must begin with the prefix “ejbCreate”.
Methods must be declared public and must not be declared static or final.
Declared return types must be the entity bean’s primary key type.
Method arguments must be the same as the arguments of the matching create<method>. 136
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
A throws clause must be declared with CreateException, or any arbitrary application exception which is also declared in the home interface.
RemoteExceptions must not be declared.
The use of the ejbPostCreate() method follows rules similarly to the ejbCreate() method, except for the following:
Method names must begin with the prefix “ejbPostCreate”.
Declared return types must be void.
The rules for using primary keys are:
A primary key class must be Serializable and public.
A single persistent field from the bean class can be used as a primary key by identifying the field name and the class type in the DD.
Two or more persistent fields can be used to uniquely identify the entity by making a custom compound primary key class.
A compound key class must be comprised of fields defined as persistent fields in the bean class and those fields must have public accessor methods.
4.4.10. Multiplicity
When dealing with entities within an application, relationships can be set between different entities. These relationships can take on many 137
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
forms, including:
One-to-One – each entity has a corresponding relationship to another single entity.
One-to-Many – an entity has a corresponding relationship to multiple secondary entities. Each secondary entity is associated to only one primary entity.
Many-to-Many – entities, whether primary or secondary, correspond to multiple entities in the database.
Multiplicity will affect the return type. A multiplicity of one identifies objects with only one entity bean. A multiplicity of many means the object holds a collection of entity beans. Container-managed fields exist because the fields have a getter and setter. Like container-managed relationship (CMR) fields, a pair of abstract getters and setters is defined. The different is that instead of setting and returning a value, a reference to another entity bean or collection is set and returned. Relationships always contain two beans. The ejb-relation is used to establish relationships between two beans. Each bean is defined with an ejb-relationship-role which establishes the multiplicity, source, cmrfield, and cascade-delete for the bean.
138
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
4.5. Java Persistence Query Language
EJB-QL is a portable query language. It allows SQL-like statements to be written into the deployment descriptor. Select methods are developed by letting the Container build the database access code from queries. The process follows as such: 1. Write a home business method. 2. Implement the home business method to call the ejbSelect method. 3. Declare the abstract select method in the bean class. 4. Write the EJB-QL for the select query.
4.5.1. WHERE Clause
The WHERE clause is optional. A collection of entities may be returned in the bean class. The coding uses information from the deployment descriptor. A basic code for a SELECT using WHERE is: SELECT OBJECT (x) FROM Schema x WHERE x.field =?1 In this code, the first part is SELECT OBJECT (x) where it identifies all bean types of the value x. The second part defines the representation of the bean type as x. The final part, WHERE x.field =?1, restricts the returned bean to those beans where the CMP field matches the first parameter of the select method. Navigating to another related bean referenced in a CMR field. Using the dot operator will simplify the navigation. Using an AND clause will 139
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
allow a value to be selected rather than a whole bean. The WHERE clause can use:
Literals
Input parameters
Comparisons
4.5.2. SELECT Clause
The SELECT clause identifies what the query will return, either:
An abstract schema type – a range variable
A single value type – a single-valued path expression
The statements SELECT and FROM are mandatory. The FROM clause declares the identification variable and defines the domain of the query. The statement OBJECT (m) is used to return a bean’s abstract schema type, but never a . Identifiers used must be valid Java identifiers. They must not have the same name as an or ejb-name> in the DD. They also may not be a reserved work in EJB-QL which are:
SELECT
FROM
WHERE
DISTINCT 140
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
OBJECT
NULL
TRUE
FALSE
NOT
AND
OR
BETWEEN
LIKE
IN AS
UNKNOWN
EMPTY
MEMBER
OF
IS
4.6. Message-Driven Bean Component
4.6.1. Message-Driven Bean Class
Message-driven beans provide asynchronous communications between the client and the server: entity and session beans provide synchronous communications. The client sends the message and is referred to as the message Producer, while the server receives the message and is referred to as the message Consumer. The Producer 141
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
will send the message and moves on. The Container receives the message and acknowledges it to the service. When the Consumer receives the message, it is processed without needing a connection to the client. The processing involves the Container obtaining a bean from the pool, invoking the onMessage() method. The bean’s transaction is committed and the Container sends the bean back to the pool. Multiple message beans of the same time can be processed concurrently. The Container makes sure that each bean is threadsafe. The lifecycle of the message-driven bean is similar to the stateless session bean, with the following states:
does not exist
method ready
A typical message-driven bean class is coded as: package headfirst; import javax.ejb.*; import.javax.jma.*; public class className implements MessageDrivenBean, MessageListener {
private MessageDrivenContext conext;
public void ejbCreate() { }
public void ejbRemove()
{ }
public void setMessageDrivenContext (MessageDrivenContext 142
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
ctx) {
context = ctx;
}
Public void onMessage(Message msg) {
try {
// process the message
if (msg instanceof textMessage) {
System.out.printIn(message.getText() };
}
} catch (JMSException ex) {
}
TextMessage message = (TextMessage) msg;
} The rules for developing a message-driven bean class are:
The javax.ejb.MessageDrivenBean and javax.jms.MessageListener must be implemented.
The class must be public, and never be abstract or final.
A public constructor must be present with no arguments.
A no-arg ejbCreate() method must be present and the method must be public, not final or static, with a void return type.
The onMessage() method must be defined from the MessageListener interface. The method must be public, not final or static, with a void return type. A single 143
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
argument of type javax.jms.Message is required.
The ejbRemote() and setMessageDrivenContext() methods must be in the MessageDrivenBean interface, exactly as they are declared in the interface.
No methods should be allowed to throw application exceptions.
4.6.2. Message-Driven Bean Methods
Three kinds of methods are found in the bean class of a messagedriven bean:
ejbCreate()
onMessage()
container callbacks
The Deployment Descriptor must be told what type of messages should be listened for. At deployment, the DD will bind the bean to a specific topic or queue configured as a resource in the EJB server. The code found in the DD is: <enterprise‐beans> <message‐driven>
<ejb‐name>MessageName
<ejb‐class>ClassName
TransType
<message‐driven‐destination>
<destination‐type>javax.jms.Topic 144
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
4.6.3. Behavior of a Message-Driven Bean
Message types are either topics or queues. Topics can be subdivided into durable and non-durable subscriptions. A producer will send a message and a listening consumer for the message will get a copy of the message. A durable subscription ensures that the consumer receives all messages, including messages gathered when the consumer is offline. Non-durable subscriptions require the consumer to be online in order to receive the message. The Container will choose one bean from the bean pool to get the message: if multiple bean types subscribe to the topic, one bean from each bean pool will get the message. Queues are similar to lists. A message is intended for a single user. Once the message is processed, all other transactions are complete. The initiation of another transaction requires the sending of another message. A queue message is a point to point message. For a queue messages, only one bean from the pool associated with the queue will get the bean. Message-driven beans are made virtually the same way stateless session beans are made:
Call the bean’s constructor 145
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Call the bean’s context setter
Call the bean’s ejbCreate() method
Message-driven beans do not have clients; therefore, no home interface is present. With no client, there is no client security information. Acknowledgement ensures that messages are never lost. When delivered successfully, the Container will tell the messaging service that the message was delivered. If the consumer is processing the message and an error occurs, the Container can tell the messaging service to put the message back in the queue. The Container knows that an error occurred by one of two methods determined by the Bean Provider. The transaction status can provide message acknowledgement by identifying the transaction commits or roll backs. If a transaction rolls back, the message returns to the queue. This is used for container-managed transaction demarcation. The second method is method completion, where message acknowledgement is tied to successful completion of the method. If a runtime exception is thrown, the message goes back to the queue. This method is used for bean-managed transaction demarcation.
4.7. Transactions
An EJB transaction is a single unit of work which is compiled to where everything succeeds or everything reverts to its previous state. The unit of work is either committed or rolled back in its entirety. The 146
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
characteristics of a good transaction are:
Atomic – either all of the transaction works or it all fails.
Consistent – the data remains consistent whether the transaction fails or succeeds.
Isolated – transaction processing is not impacted by other transactions which are processing at the same time.
Durable – after a transaction is committed, changes made by the transaction becomes permanent even when the server goes down and comes back up.
Distributed transactions are supported by EJB containers through a two-phase commit protocol. In phase one, the transaction manager ensures that all transaction participants ready to move into the second phase. In phase two, the transaction manager tells all transaction participants to commit or rollback. Transactions are propagated through method calls. Three separate scenarios are possible:
A called method runs in the caller’s transactions – the transaction is propagated to all other methods in the call stack and all called methods are run in the same transaction.
A called method runs without a transaction – the first transaction is not propagated and suspended, and the second method runs without a transaction.
A called method runs within its own transaction – the first transaction is not propagated and suspended, and the 147
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
second method runs in a new transaction. Transactions are managed by the container, but it needs to be instructed on how to manage. The transaction code can be written into the bean class or transaction declarations put into the Deployment Descriptor. Methods related to transactions are located in two interfaces: javax.transaction.UserTransaction and javax.ejb.EJBContext. The UserTransaction interface is for beans using bean-managed transactions (BMT). The EJBContext has methods for both Containermanaged transactions (CMT) and BMT.
4.7.1. Bean-Managed Transaction
To make a BMT transaction:
From the EJBContext, get a UserTransaction reference.
Start the transaction.
End the transaction (commit or rollback)
The call stack of the checkout() method proceeds as follows:
The ut.begin() is called and the transaction started.
The ut.begin() completes and the checkOut() method runs in a transaction.
The validateCredit() is called and runs in the same transaction as checkOut().
The validateCredit() completes and the checkout() method remains running. 148
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
The checkInventory() is called and runs in the same transaction.
The checkInventory() completes. The transaction remains open.
The commit() is called: ending the transaction.
The commit() completes and the checkout() runs without a transaction.
The doNotTxStuff() is called without a transaction.
A BMT bean must not start a transaction before the current transaction ends. A stateless session or message-driven bean must not complete a transactional method without ending the transaction. A BMT transaction is one way: they can propagate out to a CMT bean, but cannot be propagated. If propagation into a BMT bean is initiated or a transaction is in progress when a method on a BMT bean is called, the transaction will be suspended. The transaction waits for the BMT bean to complete its work.
4.7.2. Container-Managed Transaction
With CMT, the container starts and completes transactions based on the DD. There are six attributes which are marked in the DD:
Required
RequiresNew
Mandatory
Supports 149
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
NotSupported
Never
Attributes work by marking a method with one of the attributes listed above. When the method is called, the container will use the attribute to do one of the following:
Run the method in the caller’s transaction.
Suspend the caller’s transaction and start a new transaction.
Suspend the caller’s transaction and run the method without a transaction.
Throw an exception because the caller does not have a transaction.
Throw an exception because the caller does have a transaction.
150
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
5 Java Web Services
5.1. J2EE Web Services
A web service is a distributed application typically delivered over HyperText Transport Protocol. The components of the service can be deployed and executed on distinct devices. Web services can be divided into two groups: SOAP-based and REST-style. A SOAP-based service is a special case of a REST-style service. SOAP stands for Service Oriented Architecture Protocol, but used to be called Simple Object Access Protocol. Essentially, it is an Extensible Markup Language (XML) dialect where documents are messages. SOAP is largely unseen by the client, usually as in a request/response message exchange pattern (MEP) using the infrastructure. REpresentational State Transfer (REST) has no official standard. Web services are successful because of language transparency: the client and the service do not need to be written in the same language. This allows interoperability between services and requesters which may be different in programming languages, support libraries, and platforms. Soap-based web services written in Java will have an intermediary to translate differences in data types and service and the requester languages are not Java-based. In additional to language transparency, web services are also distinguishable from other 151
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
distributed software services by:
Open infrastructure – uses industry-standard, vendorindependent protocols and built on top of existing infrastructures already present, specifically security, networking, and data formatting.
Modular design – new services can be generated by integrating and layering existing services.
5.1.1. Java EE Services and APIs
Web services in Java can be compiled and deployed using the core Java programming language without additional software: minimum version must be Java SE 6. All libraries required to compile, execute, and consume services are within the core language. The primary API is JAX-WS which is the Java API for XML-Web Services. JAX-WS supports SOAP-based and REST-style services and its name commonly shortened to Java Web Services (JWS).
5.1.2. JAXP
When parsing a request XML document, interfaces and classes from the javax.xml.transform package are often used. This package is part of the Java API for XML-Processing, or JAX-P. The tools found in JAX-P are designed to allow XML processing and address the needs of a RESTful service. A SAX parser is one such tool and is streambased. Its purpose is to invoke callbacks provided by the programmer 152
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
to process parsing events. SAX pushes information to the application. A Document Object Model (DOM) parser is tree-based and will construct a tree representation of a well-formed XML document.
5.1.3. StAX
StAX is short for Streaming API for XML. It is an application programming interface used to read and write XML documents. Generally XML APIs are either tree-based or event-based. A treebased API will read the entire document into memory in a tree structure and make it ready for random access by the calling application. Event-based APIs will register to receive events as entities which are encountered within the source document. StAX acts as a median between both approaches. A programmatic entry point is a cursor representing a point within the documents. The cursor is moved ahead by the application, pulling information from the parser as it is required.
5.1.4. JAXR
The Java API for XML Registries (JAXR) is a standard API for accessing and interacting with different types of metadata registries. The current standard implementation supports ebXML Registry 2.0 and UDDI version 2.0. The JAXR provides an API for clients and XML registries to interact and a service provider interface (SPI) for registry 153
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
providers to add their registry implementations. The API insulates application code from the registry mechanism; allowing the registry to change without the application code needing to change.
5.1.5. JAXB
The JAXB (Java Architecture for XML Binding) provides Java developers a method to map Java classes to XML representations. It has two features: the ability to marshal Java objects into XML and the ability to unmarshall XML back into a Java object. This allows the storing and retrieving of data in any XML format without needing to utilize a specific set of XML loading and saving routings for the application’s class structure. The JAXB provides the xjc tool to convert XML Schema and other schema file types into class representations. The classes are marked using annotations from javax.xml.bind.annotation.* namespace. An instance of JAXBContext is required to create Marshallers and Unmarshallers. The following list is a mapping of Java data types and XML Schema types:
java.lang.String
xsd:string xsd:anySimpleType
java.math.BigInteger
xsd:positiveInteger
int
xsd.int xsd:unsignedShort 154
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
long
xsd:long xsd:unsignedInt
short
xsd:short xsd:unsignedByte
java.math.BigDecimal
xsd:decimal xsd:unsignedLong
float
xsd:float
double
xsd:double
boolean
xsd:boolean
byte
xsd:short
javax.xml.namespace.QName xsd:QName xsd:NOTATION
javax.xml.datatype.XMLGregorianCalendar xsd:dateTime xsd:time xsd:date xsd:g
byte[]
xsd:base64Binary xsd:hexBinary
java.lang.Object
javax.xml.datatype.Duration
xsd:anySimpleType xsd:duration
155
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
5.1.6. SAAJ
SOAP with Attachments API for Java (SAAJ) is a standard method for sending XML documents over the Internet from a Java platform. The API allows developers to produce and consume messages which conform to the SOAP 1.1 specification and SOAP with Attachments note. SOAP messages require considerable processing power and memory when used as an XML-based messaging protocol. All parts of a SOAP message must conform to XML rules regarding allowed characters and character sequences. The entire SOAP message is usually parse before processing the contents. For these reasons additional mechanisms were required by SOAP for carrying large payloads and binary data as an attachment rather than in the message envelope itself. A SOAPMessage object within a SAAJ toolkit contains a complete SOAP message.
5.1.7. WS-I Basic Profile
The WS-I Basic Profile is a specification from the Web Services Interoperability industry consortium. It provides interoperability guidance for core specifications for Web Services, such as SOAP, WSDL, and UDDI. WSDL is used to describe services as sets of endpoints operating on messages. 156
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
5.1.8. Universal Description Discovery and Integration (UDDI)
UDDI is a platform-independent registry for businesses on the Internet. If is based on XML and is an open industry initiative sponsored by the Organization for the Advancement of Structured Information Standards (OASIS). The service allows business to publish service listings and identify each other as well as define who services and application interaction over the Internet. The business registration is comprised of three components:
White Page – basic information about the business, including identifiers and contacts.
Yellow Pages – industrial categorizations using standard taxonomies.
Green Pages – technical information about services published by the business.
5.2. XML Web Service
Extensible Markup Language, or XML, is a further set of rules for electronically encoding documents with greater flexibility, usability, and scalability than HTML. It is supported by Unicode to allow use with different languages across the world. XML maintains a textual format designed for documents but is used widely to represent arbitrary data structures. XML data can be accessed through several programming interfaces.
157
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
5.2.1. XML Terminology
The most common terms used in XML are:
Characters (Unicode) – the content of an XML document.
Processor – analyzes the markup and passes structured information to the application.
Application – uses the structured information to deliver results; the interface.
Markup – the characters that comprise the “code” of the XML document and identifiable with “<…..>” or “&….;”.
Content – the characters of the XML document that is not considered code and found between tags.
Tag – markup constructs beginning with “<” and ending with “>”: there are start-tags <section>, end-tags , and empty-element tags .
Element – A logical component of a document that either begins with a start-tag and matching end-tag or uses an empty-element tag.
Child Elements – additional markups contained within an element.
Attribute – a markup construct identifying a name/value pair.
XML Declaration – defined information about the document.
158
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
5.2.2. Document Type Definition
Document Type Definition is a type of XML schema for defining a document type for SGML markup languages. It uses a terse formal syntax which declares the elements and references that appear in the document, as well as the entities used in an instance document. There are two types of declarations used by DTD:
Internal subset – consists of the DTD within the boundaries of the document.
External subset – consists of the DTD located in a separate text file and referenced by a public identifier and/or system identifier.
DTDs use element and attribute-list declarations to describe a class of documents. Markup documents declare element types, attribute lists, entities, and notations. An element type declaration defines the element and its possible content. An attribute list defines the name, data type, and default value of each attribute associated to an element type. Entity declarations define the variables used as abbreviations and are of two types: internal (defines entity references used to replace certain strings) and external (defines external storage objects). Notation declarations are used to read the file format of unparsed external documents.
159
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
5.3. SOAP Web Service
A SOAP-based web service can be implemented as a single Java class; but best practices call for two parts – the interface to declare the methods for web service operations and the implementation which defines the methods within the interface. The interface is commonly called the Service Endpoint Interface (SEI) and the implementation is the Service Implementation Bean (SIB). The SJB may be either a POJO (instances of regular Java classes) or a Stateless Session Enterprise Java Bean (EJB).
5.3.1. Structure of SOAP
A SOAP message is a one-way transmission from sender to receiver. Applications based on SOAP can set up conversational patterns which combine one-way messaging. The fundamental message exchange pattern (MEP) for a SOAP-based web services is a brief conversation started with a request initiating and a response ending the conversation. The structure of a SOAP message comes in three parts. The only required portion of the message is the SOAP body and this body can be empty. Combine this body with an optional SOAP header and a SOAP envelope is created. Optional SOAP attachments can be added to complete a message. Messages can be manipulated using programmer-written classes called handlers. These handlers can contain methods, called callbacks, which are invoked during runtime 160
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
for web service to allow access to the underlying SOAP. At the application level, SOAP is hidden; but at the handler level, the underlying SOAP is exposed. Fundamentally, SOAP messages allow for communication between the sender and receiver. However, the architecture for SOAP allows for intermediaries. The intermediaries are nonterminal recipients or nodes found on the route from the sender to receiver. They inspect and can manipulate any incoming SOAP message between sending on to the final receiver. Specifically, intermediaries should inspect elements in the header; processing the meta-information which is appropriate for the receiver or other intermediaries. For SOAP, XML elements in the header are called header blocks.
5.3.2. UDDI
The UDDI is a tag of the header block within the SOAP message. It identifies the header block as containing a Universally Unique Identifier (UUID) value. This value is a 128-bit number formatted as a string of hexadecimal numerals. It is a statistically unique identifier. Every request for a web service must have its own UUID. The header block with the uddi tag has an additional attribute, called SOAP-ENV:actor. The value of the actor attribute is next which identifies the next recipient, or intermediary, on the path from the message sender to the ultimate receiver. The identified intermediary must inspect the header block and will throw a fault if it cannot. 161
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
5.3.3. Handler Framework
A handler framework is provided by the JWS to allow inspection and manipulation of incoming and outgoing messages. Two steps are required to inject a handler into the framework: 1. Create a handler class to implement the handler interface in the javax.xml.ws.handler package. Two Handler subinterfaces are also provided, including LogicalHandler and SOAPHandler. The first subinterface has access to the message payload in the SOAP body, while the second interface has access to the entire SOAP message including headers and attachments. Despite the subinterfaces, the implementing class must define three methods: handleMessage, handleFault, and close. A fourth method, getHeaders, is required for the SOAPHandler interface. 2. The handler should be placed within a handler chain, usually through a configuration file, but sometimes as managed by code. The handler framework is designed to support a chain of responsibility pattern, similar to a filtering solution. Once a written handler is injected into the framework, it acts as a message interceptor with access to every incoming and outgoing message. If a method for a service is called with a negative argument, a SOAP fault can be thrown. A LogicalHandler on the client side will intercept 162
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
outgoing requests and check the argument to the method. If the argument is negative, it can be changed.
5.3.4. MessageContext
A context provides an object access to its underlying container. From a programming perspective, a context is a key/value collection where the keys are strings and the value is a set of arbitrary objects. The MessageContext is normally accessed in handlers and is used to allow a service to interact with the transport level. It has two primary parameter types, or subtypes, SOAPMessageContext and LogicalMessageContext.
5.3.5. Processing and Extensibility Model
The SOAP processing model defines the model, participants, SOAP nodes, and the process for processing a SOAP message by the SOAP receiver. The SOAP nodes are:
SOAP sender – a SOAP node which sends a message.
Initial SOAP sender – the starting node of a SOAP message within a SOAP message path.
SOAP message path – The set of SOAP nodes which a single SOAP message passes.
SOAP intermediary – acts as a SOAP receiver and sender and targetable from within a SOAP message.
SOAP receiver – a SOAP node which receives a message. 163
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Ultimate SOAP receiver – the final destination of a SOAP message responsible for processing the contents of the SOAP body and any SOAP header blocks.
5.4. REST Web Services
Representation State Transfer is a software architecture style for distributed hypermedia systems. These systems allow text, graphics, audio, and other media to be stored across a network and interconnected through hyperlinks. Resources in a RESTful state are any object with an URI. Uniform Resource Identifiers (URIs) are uniform because they conform to formatting requirements. Resources are linked using hyperlinks. The linking is performed through URIs. Web-based informational items must have at least one representation. The most common resource representation is text/html, but most resources need multiple representation. Since resources have state, a useful representation must capture a resource’s state. In a RESTful request targeted at a resource, the resource stays on the service machine. A representation of the resource is provided to the requester if the request succeeds. The representation transfers to the requester machine. RESTful web services require resources to represent and client-invoked operations on those resources. HyperText Transport Protocol (HTTP) is a transport protocol and a 164
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
messaging system. Payloads in HTTP messages are types using the MIME type system. Response status codes are provided to inform the requester about the success of a request and, if fails, the reason why. The RESTful approach treats HTTP as an API, using its methods to perform REST-based functions.
5.4.1. HTTP Methods
HTTP is a protocol running on top of TCP/IP and has a basic request/response structure to it. Within this structure, the browser makes the requests and the server responds to the request. HTML is contained within the HTTP response where HTTP will add header information to the top of the HTML content. The header is used to process the HTML page by the browser. Three types of requests in HTTP dominate the traffic between browser and server. These requests have corresponding features within the servlet. The HTTP requests are:
GET – appends data to the URL before sending to server
POST – sends data to server separate from the URL
PUT
The corresponding features for Java servlets are driven by the service methods, which calls the doXXX() methods. The corresponding features are:
doGet(request,response)
doPost(request,response) 165
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
doPut(request,response)
Submissions using the GET method have a length limit of 1KB, and the results from this submission can be bookmarked. Its normal use is for simple HTML page requests, and is the method use to start writing a servlet. The GET request is the most common type of browser request. Based on the HTTP standard, the method is used to “retrieve whatever information (in the form of an entity) is identified by the Request-URI.” POST submissions can be large and the results cannot be bookmarked. It is most commonly used with HTML forms and is more sophisticated than the GET request. The general purpose of the POST method is to request something while sending form data to the server. The method is designed to post long messages, providing a block of data, and submitting long data fields to the database. The action performed by the POST method may not provide a standard HTML page in return. There are a number of differences between the GET and POST request including: GET
POST
Data is appended to URL as
Name-value pairs are sent in
name-value pairs
body of request, not URL
Query length is limited (~1KB)
Query length is unlimited
Data is seen in address bar
Data is hidden from users
166
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Used to retrieve data only ASCII based Easy to bookmark Used more often
Used to make changes on the server ASCII and Binary based Will not bookmark Used less often
The purpose of the PUT method is to upload files to the server, but is generally done using the POST method. Another method of interest is the HEAD method. In some cases, a request to a server is made simply to obtain status or get basic information from the server. Using the GET method will return a header and content. With the HEAD method, the same header will be returned without any body or content. This is done by calling the doGet() but setting the headers but no output. The benefit of the HEAD method is the message size which is very small and therefore very quick and lightweight. Other HTTP Methods include:
TRACE – requests a loopback of the request message to determine what is being presented in the response.
OPTIONS – requests a list of HTTP methods.
DELETE – requests the resource to be deleted at the requested URL.
CONNECT – requests a connection when tunneling.
167
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
A URI acts as an identifying noun in RESTful services while HTTP methods act as verbs to specify operations on the resource identified by the URI. In the syntax, the HTTP verb comes before the URI, with the requester’s version of HTTP ending the sentence. HTTP/URI pairs are terse, precise, and uniform.
5.4.2. Provider and Dispatch
In RESTful services, the client will send request information using the HTTP start line and optionally through the inserted HTTP header. The GET and DELETE requests will result in HTTP messages with no body, while PUT and POST requests result in HTTP messages with bodies. HTTP bodies are not used by clients of RESTful services, so information in the request must be contained in the header. The HTTP body can be used to introduce the Dispatch interface: the client side version of the server-side Provider interface. A Provider interface can be used without the client-side Dispatch interface. A Dispatch interface can be used no matter how the RESTful service is implemented. The Provider implements the following method on the server: public Source invoke(Source request) A Dispatch object will implement the same method on the client side. This object is sometimes called a dynamic service proxy. The relationship between Provider and Dispatch supports the natural exchange of XML documents. Some steps of the exchange include: 168
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
The invocation of the Dispatch method invoke by the client with an XML document as a Source argument. If no XML document is required, the Source argument can be null.
The service-side runtime will dispatch the request to the Provider method invoke. The Source argument for this method corresponds to the client-side Source.
The Source is transformed by the service into an appropriate Result. This Result is processed in a way which is appropriate for the application and returns an XML document to the client. If no response is required, null is returned.
The Dispatch method invoke returns a Source, which is sent from the service, and transformed into an appropriate Result and processed by the client.
5.5. JSON Web Services
JavaScript Object Notation (JSON) is a lightweight text-based open standard used to exchange human-readable data. It is built on JavaScript programming language for the purpose of representing simple data structures and associative arrays. The format is often used to serialize and transmit structured data over a network connection, and acts as an alternative to XML. Similar to JavaScript, JSON is language independent. The basic types found in JSON are:
Number (integer or real) 169
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
String
Boolean
Array
Object
null
5.5.1. JSON Schema
Like the XML Schema, structures and data types can be verified within a container. For JSON, this container is the JSON object. The JSON Schema is a specification for JSON-based formats for defining the structure of JSON data. It provides a contract for the required JSON data in a given application and how that data can be modified. The JSON Schema is intended to provide guidance on validation, documentation, and interaction control of JSON data. It is based on the concepts from XML Schema, RelaxNG, and Kwalify.
5.6. WSDL
5.6.1. Basic Elements
WSDLs are the service contracts for SOAP-based web services and its consumers. It provides critical information, such as the service endpoint, the service operations, and the data types required for the operations. Also found in the service contract are the descriptions for 170
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
the messages exchanged in the service and the underlying service patterns. The outermost element of the WSDL is named definitions and groups a number of definitions into sections:
types – an optional section which keeps, directs, or imports an XML Schema Definition (XSD) which describes data types.
message – defines the messages used to implement the service. The messages are constructed using defaults if no type section exists, or as defined by the type section. Service patterns are defined by the order of the messages in this section.
portType – represents the named operations of the service, with each operation consisting of one or more messages.
binding – moves WSDL definitions from an abstract state to concrete state by providing the details about the service. The binding section must provide the transport protocol used to send and receive underlying SOAP messages, the style of the service, and the data format of the SOAP messages.
service – identifies one or more endpoints providing the service’s functionality and the sum or its operations.
5.6.2. Binding Mechanisms
Within the binding section, the possible values for the style attribute are rpc and document. The document value is the default. The 171
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
possible values for the use attribute are literal and encoded. That means there are four possible combinations of style and use:
document and literal
document and encoded
rpc and literal
rpc and encoded
Only two of the combinations above occur regularly in contemporary SOAP-based web services: document/literal and rpc/literal. The use of encoded does not comply with the Web Services-Interoperability (WS-I) guidelines. WS-I assists software architects and developers to produce web services which interoperate seamlessly despite different platforms and programming languages. The document style identifies that the underlying messages for the web service contain full XML documents. Messages written in the document style are explicitly typed. The rpc style identifies the underlying SOAP messages contain parameters in the request messages and return values in the response messages. The rpc style will name the messages but they are not explicitly typed. Either style can be used to provide the request/response pattern of the web service, though the rpc style underscores this pattern. The document style can provide services with rich explicitly defined data types through the XSD document. Any service pattern can be supported. For architects, the use of the document style is simpler because the body of a SOAP message is self-contained and precisely 172
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
defined. For developers, the rpc style is simpler because the generation of Java types which correspond to XML Schema types does not require wsgen utility. The rpc style requires messages with the names of associated operations which have parameters as subelements. The use attribute defines how data types for the services are encoded and decoded. Data types used in the implementation language are serialized to WSDL-compliant types; which in turn, on the client side are deserialized into client-language types. How this serialization/deserialization is specified by the WSDL service contract. A literal attribute ensures the type definitions literally follow the WSDL document’s XML Schema. An encoded attribute identifies that service type definitions come from encoding rules.
5.6.3. Document and RPC Styles
The WS-I basic profile for web services interoperability defines the document style as the default style. Through the XSD, an explicit definition of data types is provided by the XSD for the service’s SOAP messages. As such, the service client can determine which data types are involved in the service and how the document in the SOAP message body should be structured. The rpc style is appealing because web service operations have names linked to underlying implementations, making it programmingfriendly. Document-style service can use a wrapped convention to 173
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
make it look and feel like an rpc-style service. Two elements of the body of the unwrapped SOAP request envelope are num1 and num2. The body does not contain the name of the service operation to add the numbers together and send the sum as a response. The body of a wrapped request envelope has a single element called addNums, the name of the request service operation, and two subelements holding the numbers to be added. Because of the wrapping, the service operation is explicit, while the arguments of the operation are nested intuitively. The following guidelines pertain to the wrapped document convention:
The body of the SOAP envelope should contain a single XML element with any number of required XML subelements.
The relationship between the single XML element in the SOAP body and the XSD is well defined.
XML elements in the XSD act as wrappers for the SOAP message body.
The request wrapper and the service operation have the same name.
The response wrapper is the request wrapper’s name with an appended Response.
The portType section has named operations with ‘typed’ messages.
A java SOAP-based web service is, by default, wrapped document 174
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
type with literal encoding.
5.6.4. Benefits and Disadvantages
The benefits of the document style are:
The SOAP message body can be validated against the XSD.
Any service in this style can arbitrarily use rich data types.
As long as the structure of a SOAP message is clearly defined in an XSD, the body of the message can have great flexibility.
The wrapped convention allows the benefits of the rpc style to be acquired in this style.
The disadvantages to the document style are:
The name of the service operation is not in the SOAP message when using the unwrapped variant.
The writing of the wrapped variant has a high level of complexity.
Overloaded service operations are not supported by the wrapped variant because the XML wrapper element in the SOAP message body and the service operation has the same name.
The benefits of the rpc style are:
With no types section, the WSDL is relatively short and simple. 175
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
The names of the underlying web service operations are carried in the WSDL messages.
Message throughput is improved because messages do not carry any type-encoding information.
The disadvantages of the rpc style are:
No XSD is provided from which the body of the SOAP message can be validated.
Rich data types cannot be arbitrarily used by the service since no XSD exists to define such types.
Tight coupling is encouraged between service and client.
Java services written in this style may not be recognized in other framework.
5.6.5. The wsgen Utility
The wsgen utility provides the artifacts required for any documentstyle service, whether it is wrapped or unwrapped. The utility will generate a Java class (Java data type) for each message. The types generates here are used by the publisher to generate the WSDL for a document-style service. The utility is commonly introduced to translate a web service from rpc-style to document-style, to generate Java types which can be bound to XML Schema types. To do this, packages associated with JAX-B are used.
176
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
5.7. JAX-WS
5.7.1. JAXB
The Java Architecture for XML Binding (JAXB) provides a method for binding XML schemas and Java representations. JAXB provides methods for unmarshalling XML instance documents into Java content trees, then reversing the process to marshall Java content trees into XML instance documents. A JAXB implementation contains the following architectural components:
Schema compiler – binds a source schema to a set of schema derived program elements as defined by an XMLbased binding language.
Schema generator – maps a set of existing program elements to a derived schema as defined by program annotations.
Binding runtime framework – provides marshaling and unmarshalling operations for accessing, manipulating, and validating XML content.
Using the architectural components above the general process for JAXB binding is: 1. An XML schema is used as input to the JAXB binding compiler to generated JAXB classes. 2. All generated classes, source files, and application code is 177
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
compiled. 3. XML documents written to the constraints in the source schema are unmarshalled by the JAXB binding framework. 4. A content tree is generated which is instantiated from the generated JAXB classes and represents the structure and content of the source XML document. The source XML documents are optionally validated before generating the content tree. 5. The XML data representation of the Java content tree is modified by the client application using interfaces generated by the binding compiler. 6. The processed content tree is marshaled to one or more XML output documents.
5.7.2. Creating a Web Service
A JAX-WS web service can be developed starting with a Java class annotation with the javax.jws.WebService annotation which defines the class as a web service endpoint. A service endpoint interface (SEI) declares the methods invoked by the client on a service. Though not required to build a JAX-WS endpoint, a SEI is implicitly defined in the web service implementation class. A SEI can be explicitly specified by adding the endpointInterface element to the WebService annotation of the implementation class. If defined, the SEI must define the public methods available to the endpoint implementation class. The endpoint implementation class and wsgen tool can be used to generate the web service artifacts and stubs used 178
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
to connect a web service client to the JAX-WS runtime. The steps used to create the web service and client is: 1. Coding the implementation class 2. Compiling the implementation class 3. Generating the artifacts required for service deployment using the wsgen 4. Packaging files into a WAR file 5. Deploying a WAR file 6. Coding the client class 7. Generating and compiling the stub files using wsimport 8. Compiling the client class 9. Running the client A JAX-WS endpoint requires:
An implementing class must be annotated with either the javax.jws.WebService or javax.jws.WebServiceProvider annotation.
The implementing class may explicitly refer to an SEI using the endpointInterface element of the @WebService annotation or implicitly defined for the implementing class.
The business methods of the implementing class must be public and not declared static or final.
All business methods exposed to the web service clients must be annotations with javax.jws.WebMethod.
All business methods exposed to web service clients must have JAX-B-compatible parameters and return types. 179
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
An implementing class cannot be declared final or abstract.
An implementing class must have a default public constructor.
An implementing class must use the javax.annotation.PostConstruct or javax.annotation.PreDestroy annotations on methods in its lifecycle event callbacks.
5.8. JAXR
5.8.1. Web Service Architecture Model Using JAXR
The architecture of the Java API for XML Registries includes a client and provider. A JAXR client program uses the JAXR API to access a business registry through a JAXR provider. A JAXR provider grants access to a registry or class of registry based on a common specification. The provider implements the javax.xml.registry which consists of the API interfaces and classes defining the registry access interface and the javax.xml.registry.infomodel which consists of interfaces defining the information model for JAXR. The interfaces for the information model define the object types residing in a registry and their relationship to each other. The basic interface in the package is the RegistryObject interface. The basic interfaces in the javax.xml.registry package include the 180
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Connection and RegistryService. The Connection interface is a client session with a registry provider. The RegistryService object is obtained by the client from its connection and enables the client to obtain the interfaces required to access the registry. The primary interfaces of the package include the BusinessQueryManager and the BusinessLifeCycleManager. The Business Query Manager allows the client to search a registry for information in accordance with the javax.xml.registry.infomodel. SQLsyntax can be used for these queries using an optional DeclarativeQueryManager interface. The BusienssLifecycleManager allows the client to modify the information in a registry by either saving or deleting the information.
5.8.2. JAXR Clients
A JAXR client is a program accessing registries using the JAXR API. Clients must establish a connection to the registry. This is done by:
Getting access to a registry
Creating or looking up a connection factory
Creating a connection
Setting connection properties
Obtaining and querying a RegistryService object
To use the Java WSDP Registry Service, Java WSDP 1.5 must be downloaded and installed along with the Registry Service in the Application Server. JAXR providers can provide one or more preconfigured connection 181
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
factories. Resource injection is used by clients to obtain these factories. They are used by the client to create a connection. The creation process begins by creating a set of properties that specify the URLs of the registries being accessed. The standard connection properties are:
javax.xml.registry.querymanagerURL
javax.xml.registry.lifeCycleManagerURL
javax.xml.registry.semanticEquivalences
javax.xml.registry.security.authenticationMethod
javax.xml.registry.uddi.maxRows
javax.sml.registry.postalAddressScheme
Connections are used to obtain a RegistryService object and the required interfaces.
5.9. Security
5.9.1. Basic Security Mechanisms
Wire-level security occurs at the transport level of a network, specifically focusing on the basic protocols which control communication between a web service and the client. Three services are typically involved at this level. The first service ensures that the service and client are who they say they are through some form of authentication. The second service encrypts the data to ensure that it is not intercepted. The third service ensures the integrity of the 182
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
message, that is, the message received is the same as the message sent. User authentication and authorization is that portion of web services which enables clients to access the resources required by them. Secured resources require the client to have the proper credentials. These credentials are presented and verified in two steps. The first step is the presentation of user-specific information, such as username and password. Access is denied if this user information is incorrect. This step is user authentication. The second step is determining what access or what level of access the client has. Known as role authorization, this optional step depends on dividing clients into categories with varied degrees of access. Web service security (WSS or WS Security) is a set of protocols specifying the how security is enforced on messaging in SOAP-based web services. WSS provides comprehensive end-to-end security.
5.9.2. HTTPS
HTTPS is a secure version of HTTP and provides three critical security services on top of the services provided by HTTP. They include:
Peer Authentication
Confidentiality
Integrity 183
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Peer authentication involves ensuring that both ends of a connection prove their identity to each other. It is handled through the exchange of digital certificates. This is usually initiated as a client challenges the web server. Here is the process:
The client browser challenges the web server to authenticate itself with the server responding with one or more digital certificates.
The digital certificates are checked by the browser against its truststore – a database of digital certificates trusted by the browser.
The browser is typically not checked by the web server.
Confidentiality is performed as a process of encryption and decryption. Two different approaches are used in encryption: symmetric and asymmetric. Both approaches will encrypt the data bits as an input into an encryption engine and the provision of an encryption key as another input. Encrypted bits become cipher bits: the input bits are considered plaintext if represented text, while the output of the encryption is ciphertext. All encrypted data must be decrypted to be read. The cipher bits are inputted into the decryption engine along with a decryption key. In the symmetric approach, the encryption key and the decryption key is the same. While the fastest approach, symmetric methods are problematic during distribution of the keys. In a symmetric approach a key pair is introduced consisting of a private key and a public key. A private key is not distributed, while the public key can be. When message bits are encrypted with the public 184
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
key, they can only be encrypted with the private key. The opposite process is true. The asymmetric approach resolves the distribution problems of the symmetric approach but is much slower. Ensuring integrity is the most straightforward of the HTTPS services. Each message sent over HTTPS contains a digest which is recomputed by the receiver. If the computed digest differs from the sent digest, the message is considered to be altered during transmission.
5.9.3. SAML
Security Assertion Markup Language (SAML) is based on XML principles and is a standard for exchanging authentication and authorization data between security domains. It is a product of the OASIS Security Services Technical Committee. SAML uses an OpenID standard. It assumes the principal is enrolled within at least one identity provider (a producer of assertions). The identity provider provides local authentication services to the principal, typically a user. A service provider, or consumer of assertions, will rely on the identity provider to identify the user. Upon request the identity provider will pass a SAML assertion to the service provider who will use it to make an access control decision. SAML is based on:
XML – as a standard language
XML Schema – provides structure for SAML assertion and 185
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
protocols
XML Signature – a digital signature for authentication and message integrity
XML Encryption – provides elements for encrypted name identifiers, encrypted attributes, and encrypted assertions
HTTP – provides a transport protocol
SOAP – required use
The semantics and syntax for assertions is defined by the SAML Core. A SAML protocol references what is transmitted, not how. A SAML binding will determine how requests and responses for SAML map onto standard messaging or communications protocols. A SAML profile is a concrete manifestation of a defined use case using assertions, protocols, and bindings. A SAML protocol define several SAML elements and how they are packaged. A SAML protocol is a simple request/response protocol. A SAML assertion contains a packet of security information. They are transferred from identity providers to service providers and contain statements used to make control decisions. Three types of statements are provided:
Authentication – declares the principal did authentication with the identity provider at a particular time using a particular method of authentication.
Attribute – declares a name-value pair associated with a subject. 186
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Authorization – declares what actions are permitted to be performed on what resources for a particular subject.
5.9.4. XACML
XACML is short for eXtensible Access control Markup Language. It is a declarative access control policy language implemented in XML. It is also a processing model used to interpret the policies. Policies are a collection of rules, which like requests, use subjects, resources and actions. A subject element is the entity requesting access. Subjects have one or more attributes. A resource element is a data, service or system component and has a single attribute. An action element defines the level of access requested on a resource and can have one or more attributes. Environment elements can optionally provide additional information. They are managed by the Policy Administration Point (PAP). XAMCL utilizes obligations. An obligation is a directive from the Policy Decision Point (PDP) to the Policy Enforcement Point (PEP). This directive explains what must be carried out before and after granting access. The PDP evaluates and issues authorization decision. The PEP intercepts a user’s access request to a resource and enforces the PDP’s decision. The Policy Information Point (PIP) will provide external information to the PDP.
187
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
5.9.5. WS-Security
WS Security is a set of specifications for augmenting wire-level security through a unified, transport-neutral, end-to-end framework. It runs on top of the SOAP protocol. A number of layered blocks are part of the architecture. The first layer of the architecture is comprised of the WS-Policy, WS-Trust, and WS-Privacy. The second layer consists of WS-SecureConversation, WS-Federation, and WS-Authorization and builds on the components of the first layer. Brief descriptions of each component are below:
WS-Policy – defines the general security capabilities, constraints, and policies.
WS-Trust – handles how security tokens are issued, renewed, and validated.
WS-Privacy – defines how services state and enforce privacy policies, as well as how a service can determine whether a requester will follow those privacies.
WS-SecureConversation – provides secure web service conversations across different sites, security contexts, and trust domains.
WS-Federation – addresses the management of security identities across different platforms and organizations.
WS-Authorization – covers the management of authorization data and the policies for granting access to secured resources.
188
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
5.10.
Web Services Interoperability Technologies
WSIT is a product of Sun and Microsoft to ensure interoperability of web services enterprise technologies. It is an implementation of several open web services specifications supporting enterprises. The WSIT features include five primary categories:
Core XML – includes the services of XML, XML Namespace, XML Infoset, and XML Schema.
Core Web Services – including SOAP, MTOM, and WSAddressing.
Bootstrapping – including WSDL, WS-Policy, and WSMetadataExchange.
Reliability – includes WS-ReliableMessaging, WSCoordination, and WS-AtomicTransactions.
Security – including the services of WS-Security Policy, WS-Security, WS-Trust, and WS-SecureConversation.
Bootstrapping is the use of a URL to access a web service, retrieving its WDSL file, and using the file to create a web service client. The general process involves:
The URL for the desired web services is obtained by the client.
The URL and wsimport tools are used to send a MetadataExchangeRequest to access the web service and obtain the WSDL file for the client.
The WSDL is used by the client to create the web service 189
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
client.
The web service client accesses and uses the web service.
Message Optimization Technology ensures that web services messages are transmitted in the most efficient manner over the Internet. This is done by encoding binary objects into XML format in such a way to balance the SOAP application processing time and the bandwidth needed to transmit the SOAP message over the network. Reliable Messaging Technology is a Quality of Service (QoS) technology. Reliability is a measurement of a system’s ability to deliver messages from point-to-point without error. This requires messages in a given message sequence to be delivered once and optionally in the correct order. If a message is lost in transit or delivered out of order, systems with this technology can recover. WSIT also contains security technology using WS-Security to provide interoperable message content integrity and confidentiality. The WS Security Policy enables web services to use security assertions to represent preferences and requirements for web service endpoints. WS-Trust enables web service applications to use SOAP messages to request security tokens to establish trusted communications between client and service.
190
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
5.10.1. Client Creation
A web service client is used to access and consume a web service provider. To create a web service client, the interoperability requirements of the web service provider must be obtained. These requirements are made available through the WSDL files as found in the service registries and/or published on the Internet site through a URL. Either a web browser or the NetBeans IDE can be used to obtain the WSDL files. WSDL files contain information on:
Network service – the name of the service, its location, and ways to communicate with the service
Web services policies – expresses the capabilities, requirements, and general characteristics of a web service. The providers use these policies to standardize policy information, specifically conveying the conditions for which two web service endpoints interact.
WSDL files are requested and transferred from the provider to the client using the Web Services Metadata Exchange (WS-MEX). The protocol is a bootstrap mechanism. If the type of metadata desired is known, the type can be specifically asked for in the client request.
191
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
5.10.2. Message Optimization
Web services which use WSIT technologies can be developed starting with a Java class file annotated with the javax.jws.WebService annotation. This annotation defines the class as a web serviced endpoint. To use the IDE to create a web service: 1. Click on the Runtime tab in the left pane and verify the listing for GlassFish; if not, register it. 2. Choose File > New Project, then Web Application from within the Web category. Click Next. 3. Assign a project name for the service provided and set the project location to the application server. Click Finish. 4. Right-click the CalculatorApplication node and choose New > Web Service. 5. Enter the web service name in the Web Service Name and the Package fields. 6. Select Create an Empty Web Service. 7. Click Finish. 8. Right-click the class body and choose Web Service > Add Operation. 9. Type ‘add’ in Name and choose int from the Return Type drop-down list in the upper portion of the Add Operation dialog box. 10. Click Add and create a parameter of type int named ‘1’ in the lower portion of the Add Operation dialog box. Click OK. Do this step again with another parameter named ‘j’. Close the Enter Method Parameter dialog box. 192
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
11. Click OK. An add method will be added to the Source Editor. 12. Change the add method to return ‘k’ which is ‘int k = 1+j’. To deploy and test the web service: 1. Right-click the project node and select Properties, then Run. 2. Type /CalculatorWSService?wsdl in the Relative URL field and click OK. 3. Right-click the project node and choose Run Project. The steps above will cause the IDE to start the web container, build the application, and display the WSDL file page in the browser.
5.10.3. Reliable Messaging
Several configuration options are available for endpoint reliable messaging:
Reliable Messaging – defines whether reliable messaging is enabled.
Ordered Delivery – ensures application messages for a given message sequence is delivered to the endpoint application in the correct order.
Flow Control – defines whether the Flow Control feature is enabled which works in conjunction with the Max Buffer Size to determine the maximum number of messages for sequence stored at the endpoint waiting for delivery to the 193
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
application.
Max Buffer Size – If Flow Control is enabled then defines the number of messages buffered for a message sequence. The default setting is 32.
Inactivity Timeout – defines the time interval either the source or destination may terminate any message sequence due to inactivity. The default setting is 10 minutes, or 600,000 milliseconds.
A Security Context Token (SCT) for each application message sequence is acquired by the web service. The token is used to sign all messages exchanged for the sequence between the source and destination. As part of the Secure Conversation feature, the entire feature ensures that sequence messages are secure while in transit and prevents users from seeing data not intended for them.
5.10.4. Service Security
Security for a web service or web service operation can be configured using the IDE: 1. Create or open the web service. 2. Expand the Web Services node in the Projects window. 3. Right-click the node for the desired web service. 4. Select Edit Web Service Attributes. 5. Select Secure Service to enable WSIT for all web service operations. 6. Select a Security Mechanism. 194
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
7. Define the Keystore, Truststore, STS, SSL, and user information required for the selected security mechanism. 8. Click OK to save. 9. Right-click the project node and select Run Project. To secure the client: 1. Create a web service client. 2. Expand the client node in the Projects window. 3. Expand the Web Service References node. 4. Right-click the node to pick a web service reference. 5. Select Edit Web Service Attributes. 6. Choose the appropriate options which are dependent on the security mechanism define on the server. 7. Click Ok to save.
195
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
6 Java Enterprise Applications
6.1. Application Design Concepts
6.1.1. Decomposition
Architecture design will usually decompose the larger systems into smaller components which can be constructed in relative isolation from each other. Components are typically related to requirements which are relevant to service level agreements. Those components include:
Scalability
Maintainability
Reliability
Availability
Extensibility
Performance
Manageability
Security
Basic strategies are used in decomposition. Not all strategies are applied to any architecture, and some strategies are groups together. There are ten recognized strategies groups into five sets:
Layering or Distribution
Exposure, Functionality, or Generality 196
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Coupling and Cohesion, or Volatility
Configuration
Planning and Tracking or Work Assignment
Decomposition typically will start with a strategy from the first group process. If the architecture is sufficiently decomposed to allow it to be built, the process stops. If not, the process moves to the next group of strategies and continues until the system can be broken down into components small enough to begin building the system. Layering involves ordering principles in some way, typically in an abstraction. One layer uses the services of another layer and provides services to a higher level layer. Architectures are typically divided into layers or tiers through layering decomposition. Distribution is a method for building scalable systems and is often used instead of layering. The method is seen typically when:
Multiple clients are supported.
Process boundaries can isolate faults.
Dedicated tasks have their own thread of control.
Exposure focuses on the components, how they are exposed and consumed by other components. All components can be seen in three aspects: services, logic, and integration. Services look at the accessibility of the component by other components. How a component applies the work required to finish a given task is handled by the logic of the component. Integration will explore how a 197
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
component accesses the services of another component. Functionality will group the architecture within a given problem area and is useful for situations where operational processes are the focus. Generality focuses on reusable components which can be used within several functional areas of the same system or several different systems. It isolates and defines the different components to determine the extent and scope of reusability in an environment. Coupling and Cohesion will group or separate component. High cohesion refers to the grouping of components that work together. Low coupling refers to separating components that may work together but do so infrequently. Volatility will isolate those components which are more likely to change. Application components which support business rules are less likely to change than user interface components. Requirements are a clear indicator of how different components are volatile. A single system must be able to support different configurations. Decomposition using configurations provide flexibility requirements to an application; that is, an application can have a shared core but be used for different purposes based on its configuration. Some major configuration concerns focus on security, performance, or usability of an application. Planning and Tracking will develop a detailed project plan supporting 198
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
ordered dependencies and size. Ordering will explore the dependencies between component packages to determine the required completion order of components. Work is sized, or broken down into smaller parts so a project can be developed in an iterative fashion. Decomposition based on work assignments will create a distribution for functions based on physical location, skill-set-matching, and security areas of the individuals working the application.
6.1.2. Tiers
Components can be organized into ordered chain of service providers and consumers. Within a tier approach, components of one tier will provide services to an adjacent tier while consuming services of another adjacent tier. A traditional architecture will have the following tiers:
Client
Web/presentation
Business
Integration
Resource
The client tier deals with devices and systems that manage the display and interaction locally. The client tier should be transient and disposable because the technologies available at this tier may not be controllable by enterprises. This is the physical tier of an application. 199
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Services which provide content and services to channel-specific user interfaces are found on Web tiers. The focus of the tier is to present information to end users and external systems, requiring attention to content assembly, formatting, conversions, and content transformation. The services found on the Web tier manage user sessions and translate inbound application requests to business service language. This tier is often considered the presentation tier. Above the presentation tier is the business tier where transactions are managed and business logic is executed. The level or range of services can be low-level such as authentication to line-of-business functionality. Integration tier services work to obtain and provide access to external resources. Queuing, communications through publish/subscribe functions, and point-to-point messaging are examples of services at this tier. The components in the upper layers of this tier are usually called “middleware”. Legacy systems, data feeds, databases, and specialized hardware and software systems make up the resource tier by providing information sources, sinks and stores. The resource tier, or data tier, is accessed and abstracted by the integration tier.
200
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
6.1.3. Layers
The hardware and software stack used to host services within a particular tier is called a layer. They provide an ordered relationship across boundaries mediated by interfaces. The relationships represented by a layer focus on the implementation and deployment of components. The typical layers include:
Application
Virtual platform
Application infrastructure
Enterprise services
Compute and storage services
Networking infrastructure
The application layer is a combination of user and business system functionality on the middleware substrate. It is the defining entity that makes a specific system unique from other systems. The virtual platform layer provides interfaces to the middleware modules found within the application infrastructure later. Enterprise JavaBeans, servlets, and other Java EE APIs identify some of these interfaces. These component APIs of the virtual platform provide the foundation for the application layer but are contained within a container at the application infrastructure layer. Middleware products are contained within the application infrastructure layer to provide the operational and developmental 201
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
infrastructure. Glassfish is a container within this layer. The enterprise service layer is comprised of the operating system and virtualization solutions. Its purpose is to provide interfaces between the application infrastructure layer and the operating system functions. This layer run on top of the compute and storage layer and provides the physical hardware in the architecture. The networking infrastructure layer is the physical networking solution, including network interfaces, routers, switches, load balancers, and connectivity hardware.
6.1.4. Service-Level Requirements
Service level requirements are also known as QoS or non-functional requirements and are developed from stakeholder involvement in defining:
Scalability
Maintainability
Reliability
Availability
Extensibility
Performance
Manageability
Security
From a service-level perspective, trade-offs may have to be accepted 202
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
to reach a minimal expectation of service quality for all stakeholders. Scalability refers to the support of required quality of service expectations as the system load increases and the system is unchanged. If the load increases and the system respond within acceptable limits, the system is considered scalable. Every system has a capacity defined as the maximum number of processes or users which can be handled by the system without diminishing the quality of service. Maximum scalability refers to a system which is running at maximum capacity while maintaining quality of service expectation. To move beyond maximum capacity, additional hardware must be added either vertically or horizontally. Horizontal scaling will add more machines while vertical scaling will add more processors, memory, or disks to the current machine. Scalability is not the only issue when the load increases on a system. Reliability is an issue as well; that is, does the system process requests and transactions with the same level of reliability before and after the load increase. In other words, is the integrity and consistency of the application compromised with larger loads? Reliability and scalability are corresponding issues. If reliability of a system is lost, so is scalability. Therefore, a reliable system is a scalable system. Reliability can also affect availability, or the accessibility to services or resources. Redundant components and failover solutions can allow availability expectations to be met even when individual components fail. In this respect, individual components may be unreliable, but the entire service can still be available. As more components are deemed 203
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
unreliable, availability becomes a greater concern. Extensibility refers to the ability to add, delete, and modify existing system functionality without impacting the system. Extensibility is not measurable on a deployed system but is a concern during development of the system. Some concerns during development related to extensibility are low coupling, encapsulation, and interfaces. The ability to correct flaws within the existing system without impacting the other components of the system is commonly understood as maintainability. Like extensibility, the maintainability of a deployed system cannot be measured, but is a concern during the development of the system. Performance is typically measured in terms of response time for a given transaction per user or the number of transactions in a given time period. Manageability refers to the management of a system’s health in respect to scalability, reliability, availability, security, and performance. The system focus in manageability is on monitoring quality of service requirements and changing system configurations to dynamically improve the system based on these requirements. Security ensures the system is not compromised. Confidentiality, integrity, and availability are major concerns of security. When creating architecture components, six dimensions are often 204
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
used to consult a well-rounded architecture:
Capacity
Redundancy
Modularity
Tolerance
Workload
Heterogeneity
6.2. Application Architectures
6.2.1. Client/Server Systems
Systems built for client/server communication are traditionally called two-tier systems. They typically include a thick client with both presentation and business logic and a server with a database. Browser-based two-tier systems could have the business logic and database on the same server. Two-tier systems have their greatest advantage in ensuring security of the system. This is usually the result of the systems being located behind a firewall. Security breakdowns are the result of flaws in physical security or the use of unsecured computers. The disadvantage to two-tier systems is availability because of the reliance on all components by the system. Therefore, if one component fails, the entire system will fail. The only component that 205
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
can be increased is the database, making scalability a concern. Extensibility and maintainability have the same concern, since added functionality will impact other components. As more clients are added to the system, the harder it is to monitor the growing number; making manageability is growing concern.
6.2.2. Three-Tier Systems
Three-tier systems consist of tiers for web, business, and resources. The presentation logic is typically moved from the client computer to a server which is clustered. As a result, scalability is greatly improved over traditional client/server systems. Availability is improved because of the clustering capabilities and the ability to provide failover services. Functionality is separated into different tiers to improve extensibility and maintainability. All tiers are deployed on the servers, making monitoring of components easier and improving manageability. Performance can be improved through load balancing mechanism but can diminish when large amounts of data are transferred from server to server. Multi-tiered systems have an additional tier for integration but share the same advantages and disadvantages as three-tier systems.
206
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
6.3. Integration
Every Java EE application is expected to send and receive data between systems or applications. A few of the topics related to data transfers are:
SOAP as a messaging protocol
SOAP with Attachments API for Java (SAAJ)
RESTful Web services
Web Services for Java EE 1.2 requirements
Java API for XML Web Services (JAX-WS)
Java Architecture for XML Binding
SOAP with Attachments API for Java
Java API for XML-based RPC (JAX-RPC)
Java API for XML Registries (JAXR)
Java Messaging Service (JMS)
Java Connector Architecture (JCA).
Integration is defined as a process which passes information between two or more software entities. This communication can be distinguished further by how information is transferred:
Synchronous or asynchronous
Transfer acknowledgement
Transfer transactional
Multiple messages batched or single message sent
Message-level or transport-level encryption
Technology differences in systems
Messaging and transport protocols. 207
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
6.3.1. Integration with Java Components
When integrating two systems on the Java platform, the primary component to enable the integration is the Java Messaging Service (JMS). JMS functions asynchronously and supports:
Publish/subscribe messaging models
Point-to-point messaging models
Message delivery acknowledgements
Message-level encryption
Distributed transactions through Java Transaction API (JTA) using XAConnectionFactory, XAConnection, and XASession objects and interfaces.
6.3.2. Integration with Non-Java Components
To integrate with a system on a non-Java platform, JMS is inappropriate and web services are required. In this situation, two options are available to the software architect: SOAP or RESTful semantics and the Java Connector Architecture. The advantages over JMS that Web services have are:
The integration of heterogeneous systems are enabled by the Web service design.
As long as the WSDL is maintained, the underlying implementation of systems will not be impacted.
Enables technological independence allowing non-Java solutions to be both producers and consumers of 208
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
messages. The Java Connector Architecture (JCA) provides standardized access to an enterprise information system, typically mainframe, from a Java EE platform. A JCA system has three primary components:
Enterprise Information System
Resource Adaptor
Java EE-compliant application server
6.4. Business Tier Technologies
6.4.1. Using Enterprise Java Bean
Enterprise Java Bean (EJB) is used in J2EE architectures as a server-side component to encapsulate business logic. Common characteristics of all implemented EJBs are:
Components are distributed, representing a logically related work accessible even locally or remotely.
EJBs and their clients have a common contract enforced by well-defined interfaces.
EJBs are implemented as Java classes.
EJBs are managed by the EJB container at runtime.
Neither inbound nor outbound data is explicitly managed.
Metadata annotations, deployment descriptors, and variable from the container are used to configure EJBs.
When using only services defined by the EJB specification, 209
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
EJBs are easily ported to other EJB containers. The EJB component model can support different types of EJBs. High level characteristics of the component model allow:
A stateless service
A stateful service
Asynchronous invoked service by a different component
An entity object
Using EJBs is a decision based on scalability and security. EJB containers manage a pool of EJBs to provide scalable solutions. The management considers the number, frequency, and duration of client requests. Stateless session beans provide greater scalable advantages than stateful beans. Security is a core service of the EJB container,
6.4.2. Web Services and EJBs
EJBs may consume Web services or serve as Web service endpoints. To create an EJB as a web service, a @WebService annotation can be attached to a class definition. This will cause public methods to be automatically published as web service operations. The JAX-WS API is used by any Java class to access web services. Web services are software designed to allow system to system communication over a network. Most Web services use either SOAP protocols or XML over HTTP/HTTPS protocols, though multiple 210
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
transport and data protocols can be used. The use of EJBs as Web services or to consume Web services has distinct advantages:
Increased developer productivity.
Web services can be rapidly consumed to meet business requirements.
Business logic can be quickly exposed as web services for external applications.
The disadvantages of EJBs as related to web services is the potential for a disorderly application architecture, accessibility to data and information to external and application, and validation of data being broken or skipped.
6.5. Web Tier Technologies
6.5.1. Servlets
Servlets are designed to handle inbound requests to the server from remote clients, using the protocols using a request/response model. The HTTP/HTTPS protocol is most commonly used, though other protocols can be supported by the servlet. Servlets implement the javax.servlet.Servlet interface: or the javax.servlet.HttpServlet interface for HTTP-based servlets.
211
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
When servlets are running, the routing logic is contained in the core service methods to allow the inbound request to be sent to the appropriate handler. A container will host the servlet. The system is scalable by enabling multiple threads to use the servlet.
6.5.2. JavaServer Pages
JavaServer Pages are special HTML pages which are dynamically created. These pages are embedded with markup which is evaluated during runtime by the web container to create the page before sending to the client for rendering. JSPs are fulfilled as servlets; therefore must be compiled to the servlet models before requests can be handled. They handle the presentation of data to the user and contain no business logic. Current practices in JSP development will replace all Java code with EL, JSTL, or custom tags.
6.5.3. JavaServer Faces
JavaServer Faces is based on the JEE platform and provides a user interface framework for web applications. It is designed to develop from the perspective of user and system-generated events, instead of HTTP requests and responses. JSF components are reusable and intended to improve the productivity during development, software quality, and system maintainability. JSF can work closely with other 212
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
technologies such as ASP.NET and Ruby on Rails. JavaServer Faces are used in the same manner as JSPs and can be used in the same situation to create a hybrid solution. .
6.5.4. Web Frameworks
Each of the specifications written on the subjects above can have gaps when creating an application. Web frameworks can fill these gaps.
6.6. Patterns
Patterns are used when the same solution is applied continuously over similar problems. They are helpful in software development to identify and develop reusable code. An industry standard set of patterns were introduced in the book, Design Patterns: Elements of Reusable Object-Oriented Software, written by Erich Gamma, Richard Helm, John Vlissides, and Ralph Johnson. These patterns are commonly known as the Gang or Four (GoF) design patterns. The book, Core J2EE Patterns: Best Practices and Design Strategies, document the correct patterns to successfully architect a J2EE solution.
213
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
6.6.1. GoF Patterns
The GoF patterns are categorized into:
Creational patterns
Structural patterns
Behavioral patterns
Creational patterns allow objects in a system to be created without identifying a specific class type. The creation process is given to the subclass of the class. The Creational patterns are:
Abstract Factory – an interface for creating related or dependent objects are provided. Given a set of abstract classes, the instances are created from a matched set of concrete subclasses. The client interacts with the product interfaces and the Abstract Factory class. This pattern isolates concrete classes from the client, allows exchanges of product families to be performed easily, and promote consistency. The pattern should be used when the system and its products should be independent from each other, the system should be configured with a family of products, the family of product objects is designed to be used together, or the architect’s desire is to provide a class library of products.
Builder – the construction of a complex object is differentiated from its representation to allow the creation of different objects. An object can be constructed by specifying a type and content, while shielding the client. 214
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
The creation of complex objects is defined by a class that builds instances of another class. The pattern allows a product’s internal representation to be varied, the construction and representation of the object’s code to be isolated, and provides greater control over the construction process. The pattern is best used when the object creation algorithm should be independent of both the object and its components or the different representations of the constructed object are required.
Factory Method – an interface for creating objects is defined, but the decision for determining which classes to instantiate is given to the subclass. This allows new classes to be introduced without modification to the code. The pattern eliminates the need to bind application classes to the code and enables subclasses to provide an extension of the object. The pattern should be used when a class cannot anticipate the class of objects to create, a subclass is given authority to specific objects it creates, or the knowledge of the delegated subclass is localized.
Prototype – allows the creation of customized objects without explicit knowledge of their classes or details for creating them. The pattern allows products to be added or removed at runtime. New objects can be specified by using different values or structures. As a result, the number of subclasses created is reduced and allows applications to be configured dynamically. The pattern is best used when dynamic loading of classes is desirable, when a separate class hierarchies of factories and products should 215
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
be avoided, or when class instances can have only one of a few different combinations of state.
Singleton – ensures only one instance of the class is present and a global point of access to that class is provided. As a result, all objects using an instance of the class uses the same instance. The pattern allows controlled access to this single instance, reduces the name space required, permits refinement of operations and representation, as well as a variable number of instances, and is more flexible than class operations. The pattern should be used when only one instance of a class can exist.
Structural patterns are applied to large parts of the application to define their relationships with each other. This allows systems to be created without rewriting the code or having a great deal of customization required. The structural patterns are:
Adapter – provides an intermediary between two classes. An interface of one class is converted to be used by another class. The interface is known to clients and provides access to a class instance of a class not known to the client. The pattern allows two or more incompatible objects to interact and improve reusability of older functional code. The best times to use the pattern is when a class needs to be used, but the required interface does not match, a reusable class need to be created which will work with unrelated or unforeseen classes, an object’s interface is different from what is expected in the 216
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
environment, or translation of interfaces between multiple sources is required.
Bridge – distinguishes between the functional abstraction and internal implementation of a complex component to allow independent modification. The pattern improves extensibility because different abstractions and implementations can be combined. The patterns are best used when a permanent binding between an abstraction and implementation should be avoided, subclasses should be used to provide extensibility, or changes in the implementation should not require the client to recompile code.
Composite – allows the creation of a hierarchical tree structure with different complexities while every element in the structure can operate in a uniform interface. The pattern defines the class hierarchies of primitive objects and composite objects. New types of components can be added easier, maintaining a flexible structure and manageable interface. The best times to use the pattern is when a whole or partial hierarchy of objects must be represented; when the differences between object compositions and individual objects should be ignored; and when the structure should be dynamic and support varied levels of complexity.
Decorator – allows object functionality to be added or removed without the external appearance of function of the object being changed. An instance of a subclass of the original class will delegate operations to the original object. 217
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
The pattern has greater flexibility than static inheritance and simplifies code by writing a set of classes. Classes loaded with features do not have to be at the top of the hierarchy. The extensibility of the object is enhanced as new classes are written. The best uses of the pattern is when responsibility to individual objects should be added dynamically and transparently in the future are static subclassing is impractical.
Façade –defines a high-level interface to a set of interfaces in a subsystem. The interface is unified and enables objects to access the subsystem. It is most appropriate when a simple interface is required to access a complex system and protects the clients from the subsystem components. Coupling is reduced between subsystems and weak coupling is encouraged between the client and subsystem. The pattern is best used when multiple dependencies between the client and implementation classes are present. The pattern allows subsystems to be layered.
Flyweight – enables shared objects, which in turn, reduces the number of low-level-detailed objects, the memory and storage they use. The best times to use the pattern occurs when a large number of objects are used by an application, storage costs are high because of this large number and the application does not depend on object identity.
Proxy – access to an object is controlled through a surrogate or placeholder object. The most common 218
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
implementations of this pattern are Remote and Virtual proxies. A remote proxy will mask an object residing in a different address space; while a virtual proxy will allow optimizations to be performed. The best use of the pattern to provide a versatile or sophisticated reference to an object is required. Behavioral patterns are used to control the state and behavior of a system. The behavioral patterns recognized are:
Chain of Responsibility – provides a chain in the system, allowing messages to be handled at the level it is received or directed to an appropriate level. The pattern reduces coupling and adds flexibility when assigning object responsibilities. Set of classes can behave as a combined whole. The pattern is best used when more than one object can handle a request, the handler object is not known, or the receiver is not explicitly specified.
Command – enables a command to be stored, passed to a method, and returned like an object because the request is encapsulated in an object. The pattern allows new commands to be added without changing classes. The object making the request is distinguished from the object fulfilling the request. The pattern should be used when objects need to be parameterized by an action, particularly undo, logging, or transaction, or when requests should be specified, queued, and executed at different times.
Interpreter – defines a representation for a language’s grammar and an interpreter which uses the representation. 219
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
With this pattern, a language’s grammar is easy to change and extend, as well as its implementation. The patterns should be used when the grammar is simple and efficiency is not a major concern.
Iterator – allows items in a collection to be sequentially accessed when the items are independent from an underlying collection. The pattern supports variations in the traversal of the collection and provides a simplified interface. The best time to use the pattern is when the items of a collection should be accessed without exposing the collections internal representation. It supports multiple traversals of the objects within the collection. A uniform interface is provided for traversing different structures.
Mediator – communication between objects is simplified by the introduction of a single object to manage message distribution. Loose coupling is promoted by preventing objects from referring to each other explicitly. Their interactions can be varied independently. Because central control is maintained, individual components of the application are simpler and easier to handle and can be more generic. The pattern should be used when the communication between a set of objects is complex, but well defined, and the behavior between several objects needs to be customized without requiring subclasses.
Memento – provides and stores a “snapshot” of an object’s state to allow for the object’s return to the same state. The best times to use the pattern is when the probability that an object needs to return to a specific state is required and 220
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
the direct interface to that state would expose implementation details and break the encapsulation of an object.
Observer – allows a component to broadcast messages to receivers flexibly and defines a one-to-many dependency between objects. When one object changes its state, all dependencies are notified and updated automatically. The pattern supports broadcast communication and allows coupling between subject and observer. The pattern is best used when objects need to change based on a dependency from other objects, or objects need to notify other objects with very little knowledge or assumptions about the objects.
State – an object can alter its behavior when its internal state changes. The pattern localizes the state-specific behavior and partitions behavior for difference states and enables explicit changes to state. The pattern is best used when the behavior of the object depends on its state, as well as contains operations with large conditional statements depending on the state.
Strategy – defines a set of classes representing possible behaviors to change the functionality of an application. This pattern provides an alternative to subclassing: each behavior is defined by its own class which eliminates conditional statements. A model can utilize new behaviors without rewriting the application code. The pattern should be used when related classes differ only in their behaviors and different variants of an algorithm are required. 221
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Template Method – provides a method for overriding parts of a method without rewriting it through the use of subclasses. The pattern will define the structural component of an algorithm in an operation. This is a fundamental technique for reusing any code and is best used when implementing invariant parts of an algorithm. The common behavior among subclasses is localized to avoid code duplication.
Visitor – allows a representation of an operation to be performed on elements of an object structure to be maintained. A new operation can be defined without changing the classes of the elements. The best use of the pattern is when many object classes with different interfaces are contained in an object structure and operations on these objects is dependent on their concrete classes. Best performance occurs when the classes defining the object structure will change rarely.
6.6.2. Java EE Patterns
The core patterns of J2EE are represented in several tiers:
Presentation Tier – organizes components to improve code re-use.
Business Tier – creates a loose coupling between business logic, presentation, and resources.
Integration Tier – isolates the core logic of a system from the external systems or data stores. 222
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
The presentation tier provides the following patterns:
Intercepting Filter – can manipulate a request before processing or response after sending the results. The pattern centralizes the preprocessing of requests and postprocessing of responses. The pattern is used when this pre- or post-processing of requests or responses is required.
Context Object – encapsulates the specifics of protocol implementation to allow code to be portable across operating systems. The pattern improves reusability and maintainability of the code. The pattern is used whenever system components require access to system information and will decouple the application from underlining protocols and system interfaces.
Front Controller – creates central control logic for presentation request handling. The processing performed by the front controller is based on the request information. Reusability is improved by the pattern, as well as the separation of concerns. The pattern is used when common logic needs to be applied to multiple requests while hiding the processing logic from view.
Application Controller – used to centralize invocation and retrieval of request-processing components. The pattern improves extensibility and separation of concerns. The best times to use the pattern would be when common control logic must be applied or central management of the application is required. 223
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
View Helper – separates the processing logic and view. The pattern is used when view-processing logic should be encapsulated.
Composite View – combines simple views into a complex view without impacting the content or layout. Common headers, footers, and other components will reduce code duplication. Views can be modified based on authorization of access. The pattern is used when common view components should be used or view component changes based on authorization.
Dispatcher View – handles requests and generates responses using limited business processing. The processing logic is differentiated from the view to improve reusability. The pattern is best used when static views are present and limited business processing is available.
Service to Worker – performs request handling functions and invokes business logic before passing control to the view. The pattern centralizes business logic for requests.
Patterns found on the business tier include:
Business Delegate – masks the complexity of communication with business component from a remote client. This is done by minimizing coupling between clients to business services. As a result, the remoteness of the client and service is hidden and performance improves. The pattern is best used when access to business services from multiple client types should be encapsulated, 224
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
exceptions should be translated into application exceptions, and service creation details should be hidden.
Service Locator – establishes a consistent approach for locating business components regardless of type. The pattern establishes a standard for retrieving business components within an application and is used best when business services are located in different places and in different ways.
Session Façade – provides remote clients an interface to a service, rather than of code like the Façade pattern. The pattern reduces the number of calls to business components. Coupling between tiers is reduced and a cleaner API is provided to the client. The pattern is best used when a series of calls must be made to business components by the client.
Application Service – business components are centralized and aggregated. The reusability of business logic is centralized and improved. The pattern is used best when duplicated business logic is seen in the Session Façade pattern.
Business Object – business data is separated from logic. The pattern is best used to increase reusability of business logic.
Composite Entity – business entities are aggregated into a single coarse-grained entity to increase maintainability and improve network performance. The pattern is best used to avoid remote entity beans and leverage Bean Managed 225
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Persistence (BMP). POJO business objects can be encapsulated within this pattern.
Transfer Object – an object is used to carry data across tiers to reduce network traffic and code duplication. The pattern is used when objects need to be sent between system tiers.
Transfer Object Assembler – builds a composite transfer object and returns that object to the client. The pattern is used when several transfer objects need to be sent between tiers.
Value List Handler – results are cached and presented to the client to traverse and select. The pattern improves network performance and separation of concerns. The best time to use the pattern is to iterate through a set of objects and implement read-only lists without the need for transactions.
The integration tier provides the following patterns:
Data Access Object – access to persistent stores are encapsulated by managing the connections to the store. Code reused is improved and code complexity is reduced. Migration to new data stores is easier. The best times to use the pattern are when data access from a separate layer is provided and that data access is decoupled from the business logic.
Service Activator – asynchronous requests to business components are handled. The pattern integrates the JMS 226
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
into the application and allows clients to continue processing. The proper time to use the pattern is when a business service should be invoked asynchronously.
Domain Store – the persistence of an object is separated from the object model. The pattern is used with object relational model frameworks and products. The pattern should be used when object model uses are complex and entity beans should not be used.
Web Service Broker – services are exposed and brokered using XML and other web protocols.
6.7. Security
A primary concern of any Java EE system is security, specifically methods to maintain confidentiality, integrity, authentication, authorization, and non-repudiation. Several Java technologies are relevant to security concerns:
Java Language Specification (JLS)
JAAS API
WS-Security
Java Runtime Environment (JRE)
6.7.1. Java Security Definitions
Below are several terms related to Java Security:
Credential – a container with structured information used 227
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
to authenticate a principal.
Principal – a person or system which can be uniquely identified and authenticated by a Java security module.
Authentication – a process where the credential of a named principal is verified as a user to the system, specifically supporting HTTP basic authentication, SSL mutual authentication, and form-based login.
Authorization – a process where the verified principal is allowed or disallowed access to a named resource based on permissions explicitly naming the principal or implicitly named because of groups the principal belongs to.
Client-side security applies to applications which are installed directly on a machine or run through a browser using a Java plug-in or deployed using Java Web Start. Web-based applications and applets run in a sandbox environment allowing clients to control the requests that the code can access or not access. The end-user will be prompted whenever client side-resources are access. Server-side security refers to the security features of EJB and Web containers. Within an ELB container, a user’s permissions can be checked using with the isCallerInRole or getCallerPrincipal methods. Declarations can be used within the container’s code to allow users and roles to access specific EJB methods. The web container uses similar methods, isUserInRole and getUSerPrincipal. A web container acts as the external interface of the application. An EJB and web container can be used together. In this situation, the EJB container will use the credential associated with the application to authorize the 228
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
requests. Once the request is authorized, the web container will pass control of the request to the EJB container for processing. The request of the processed operation will return to the web container and eventually return to the end user after further processing.
6.7.2. Security for Web Services
The security features for web services are defined in the WS-Security standards and addresses:
Authentication and authorization
Message-level integrity
Message-level and transport confidentiality
6.7.3. Security Models
Security models are used by application architects to determine the potential threats and the appropriate countermeasures. A model considers:
System infrastructure
User authentication
User authorization
Auditing
Data encryption
System hardening
229
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
6.7.4. Security Behavior
The behavior of security is defined as declarative or programmatic. In the declarative model, the security configuration is contained within the deployment descriptor and can be modified at deployment time while recompiling the source code. Annotations can be used within the source code directly. In a programmatic security model, specific methods are called to determine who a business request is serviced by. The model can be used in lieu of declarative security methods or in conjunction with them. The key methods used to support this model are:
isCallerInRole (EJBContext)
getCallerPrincipal (EJBContext)
isUserInRole (HttpServletRequest)
getUserPrincipal (HttpServletRequest)
230
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
7 Practice Exam Question 1 Which decomposition method focuses on the service, logic, and integration aspects of application components? A. Distribution B. Exposure C. Generality D. Functionality
Question 2 What is the leading advantage of client/server systems over multitiered systems? A. Security B. Availability C. Extensibility D. Manageability
231
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Question 3 Which of the following patterns is found in the GoF Structure pattern? A. Prototype B. Interpreter C. Business Delegate D. Bridge Question 4 Which Java EE pattern in the presentation tier is responsible for separating the processing logic and view? A. Intercepting Filter B. Dispatcher View C. View Helper D. Application Controller
Question 5 What role in JavaBean development is responsible for writing the code contained in the Java Bean? A. Application Assembler B. Bean Provider C. Deployer D. Container and Server Provider 232
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Question 6 What characteristic of a good EJB transaction ensures that transaction processing is not impacted by other transactions currently processing? A. Consistent B. Atomic C. Durable D. Isolated
Question 7 What HHTP method is used to remove a resource from a requested URL? A. DELETE B. GET C. TRACE D. POST
Question 8 Which WS-Security component defines how security tokens are handled? A. WS-Policy B. WS-Trust C. WS-Federation D. WS-Authorization 233
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Question 9 Which of the following steps is not part of the process to create and use an array? A. Initialization B. Construction C. Verification D. Declaration
Question 10 When a class obtains methods and variables from another class, what is the Java feature being used? A. Inheritance B. Polymorphism C. Encapsulation D. Conversion
Question 11 What is required to use assertions in Java? A. Knowledge of compilation process B. Knowledge of enablement process C. Knowledge of authorized individuals D. All of the above
234
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Question 12 Which of the following represents a “lexical token” in Java? A. Attribute B. Identifier C. Method D. Bean
Question 13 Peer Authentication, confidentiality, and integrity are security services provided by what protocol? A. HTTP B. SOAP C. RESTful D. HTTPS
Question 14 What SOAP node type represents the final destination of a SOAP message? A. SOAP message path B. SOAP sender C. Ultimate SOAP receiver D. SOAP Intermediary
235
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Question 15 Which of the following methods is not found in the class of a message-driven bean? A. onMessage() B. unsetEntityContext() C. ejbCreate() D. ejbRemove()
Question 16 Which Java EE pattern is introduced in the Integration Tier category? A. Domain Store B. Front Controller C. Service Locator D. Composite Entity
Question 17 Which of the following categories list patterns introduced in the Design Patterns: Elements of Reusable Object-Oriented Software? A. Integration B. Presentation C. Structural D. Business
236
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Question 18 Which of the following is not a dimension of creating architecture components within application development? A. Redundancy B. Tolerance C. Capacity D. Authentication
Question 19 Which of the following quality of service concerns is not measurable in a deployed application? A. Scalability B. Extensibility C. Performance D. Security
Question 20 Which of the following is not a recognized component of architecture design? A. Extensibility B. Availability C. Authentication D. Performance
237
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Question 21 Which application architecture tier represents the middleware aspects of the application, such as queuing and messaging? A. Integration B. Business C. Resource D. Presentation
Question 22 What product allows java components to be integrated with other Java components? A. Java Connector Architecture B. RESTful services C. Java Messaging Service D. SOAP protocol
Question 23 Which creational pattern allows dynamic configuration of application? A. Factory Method B. Prototype C. Abstract Factory D. Singleton
238
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Question 24 What is the function of the Application Service pattern in the business tier of Java EE patterns? A. Hides the complex nature of the communication between remote client and business components B. Separates the business data and logic C. Creates an object to carry data across tiers D. Centralizes and aggregates business components
Question 25 What type of Enterprise JavaBean is used to represent an item found in persistent store? A. Session B. Entity C. Message D. All of the above
Question 26 Which transition of states for stateful session beans is initiated by a ejbActivate() method? A. Passivated to method ready B. Does not exist to method ready C. Method ready to passivated D. Passivated to does not exist 239
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Question 27 What scenario is present when the original EJB transaction is not propagated or suspended and the second method runs in a new transaction? A. A called method run s without a transaction B. A called method runs in the caller’s transaction C. A called method runs within its own transaction D. None of the above
Question 28 What section of the WSDL is responsible for defining the named operations of a web service? A. types B. portType C. binding D. service
Question 29 Which WSIT feature is not a Core Web Service? A. SOAP B. MTOM C. WS-Addressing D. WSDL
240
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Question 30 Which of the following is not contained in a class? A. Methods B. Initialization code C. Containers D. Variables
Question 31 Which Java modifier ensures the class or method it is attached is not instantiated? A. abstract B. final C. private D. static
Question 32 Which configuration option for reliable messaging ensures messages are delivered in the proper sequence? A. Flow Control B. Ordered Delivery C. Reliable Messaging D. Inactivity Timeout
241
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Question 33 Which JAXB-based architecture component will map existing program elements to a defined schema? A. Schema compiler B. Binding runtime framework C. Schema generator D. None of the above Question 34 In XML, what is a markup construct used to identify a name/value pair? A. Tag B. Declaration C. Element D. Attribute
Question 35 Which of the following actions cannot be performed by an entity bean? A. Modifying an entity B. Creating a new entity C. Deleting an entity D. Querying an entity
242
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Question 36 Which Java technology is not commonly associated with Java security features? A. WS-Security B. Java Messaging Service C. Java Language Specification D. Java Runtime Environment
Question 37 What is the function of the behavior pattern, Interpreter? A. Allows sequential access of items in a collection B. Introduces an object to manage message distribution C. Allows messages to be handled at an appropriate level D. Represents the grammar of a language
Question 38 Which of the following components is not part of the Java connector Architecture (JCA)? A. Enterprise Information System B. Application Server C. Java Messaging Service D. Enterprise Information System
243
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Question 39 Which QoS measurement area covers the response time of transactions in an enterprise solution? A. Reliability B. Performance C. Scalability D. Availability
Question 40 Which layer of application architecture contains the operating system? A. Enterprise services B. Application infrastructure C. Compute and storage services D. Virtual platform
244
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
8 Answer Guide Question 1 Answer: B Reasoning: The Exposure, Functionality, and Generality methods are performed in the second tier of decomposition. While functionality will group components into problem areas and generality will focus on the reusability of the components, exposure defines individual components, how they are exposed and consumed by other components. The definitions of the components are rooted in aspects of service, logic, and integration. Service speaks to the accessibility. Logic focuses on who a given task to the component is handled. Integration defines how a component will access the services of another component. Question 2 Answer: A Reasoning: Two-tiered systems are secure because they exist behind a firewall. Because of the systems reliance on all components of the system, availability, extensibility, maintainability, and manageability are disadvantages because adding or removing components will impact the functionality of the other components. Question 3 Answer: D Reasoning: The structural patterns include adapter, bridge, composite, decorator, façade, flyweight, and proxy. 245
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Question 4 Answer: C Reasoning: The View Helper pattern is used to encapsulate viewprocessing logic. The pattern separates the processing logic from the view. Question 5 Answer: B Reasoning: Bean Providers write the code of the bean, which is combined with other beans by the Application Assembler. The Deployer is responsible for customizing the bean for deployment into an enterprise. A Container and Server Provider is implement specifications. Question 6 Answer: D Reasoning: The characteristic, isolated, ensures that processing transactions are not impacted by other processing transactions. Question 7 Answer: A Reasoning: The DELETE method is used to remove a web resource. Question 8 Answer: B Reasoning: The WS-Trust component defines the handling of security tokens in respect to issuance, renewal, and validation. 246
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Question 9 Answer: C Reasoning: The steps used to create and use an array are declaration, construction, and initialization. Verification is not a step in the process. Question 10 Answer: D Reasoning: Assertions require all three items mentioned before they can be used. Question 11 Answer: A Reasoning: Inheritance is the Java feature which creates IS-A or HAS-A relationships between elements of code, particular classes. As a result, methods and variables are inherited from one class. Question 12 Answer: B Reasoning: Lexical tokens are the lowest form of language element in Java and represent identifiers, keywords, literals, white spaces, and operators. Question 13 Answer: D Reasoning: HTTPS is a secure version of HTTP, which provides additional services of authentication, confidentiality, and integrity. 247
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Question 14 Answer: C Reasoning: Within the path of the SOAP message, there are several nodes for sending and receiving the SOAP message. The final destination is typically called the ultimate SOAP receiver. Question 15 Answer: B Reasoning: The methods found in a message-driven bean class are onMessage(), ejbCreate() and container callbacks. The unsetEntityContext() method is associated to entity beans not message-driven beans. Question 16 Answer: A Reasoning: The patterns found in the Integration Tier of the Java EE patterns are data access object, service activator, domain store, and web service broker. Question 17 Answer: C Reasoning: The book, Design Patterns: Elements of Reusable ObjectOriented Software, introduced the GoF design patterns which are categorized into creational, structural, and behavioral patterns. Integration, presentation, and business tiers patterns were introduced by the book, Core J2EE Patterns: Best Practices and Design Strategies. 248
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Question 18 Answer: D Reasoning: A well-developed architecture will work within six dimensions when creating architecture components: capacity, redundancy, modularity, tolerance, workload, and heterogeneity. Question 19 Answer: B Reasoning: The relevant QoS requirements are related to scalability, maintainability, reliability, availability, extensibility, performance, manageability, and security. Maintainability and extensibility is not measurability in a deployed state. Question 20 Answer: C Reasoning: The components of application design include scalability, maintainability, reliability, availability, extensibility, performance, manageability, and security. Security includes topics of confidentiality, integrity, authorization, and authentication. Question 21 Answer: A Reasoning: Five architecture tiers are recognized: client, web/presentation, business, integration, and resource. The integration tier provides services to obtain and offer access to external resources. Queuing and communications are examples of these services and often considered middleware. 249
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Question 22 Answer: C Reasoning: The Java Message Service (JMS) is the primary component of the Java platforms for enabling integration between multiple Java components. Question 23 Answer: B Reasoning: The prototype pattern does allow dynamic configuration of applications. This is because customizable objects are support which has no explicit knowledge of the classes or details related to their own creation. Question 24 Answer: D Reasoning: The application Service pattern is used to centralize and aggregate business components. Question 25 Answer: B Reasoning: Entity beans represent items in persistent stores, message beans will listen for messages from a JMS messaging service, and session beans typically represent a process. Question 26 Answer: A Reasoning: The transition from passivated to method ready is initiated by the elbActivate() method. 250
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Question 27 Answer: C Reasoning: When a called method runs within its own transaction, the original transaction is not propagated or suspended and the second method is run in a new transaction. Question 28 Answer: B Reasoning: The portType section of the WSDL represents named operations of the services using one or more messages. Question 29 Answer: D Reasoning: WSIT features are divided into five categories: Core XML, Core Web Services, Bootstrapping, Reliability, and Security. The WSDL is categorized as a Bootstrapping feature. Question 30 Answer: C Reasoning: Containers contain classes and classes may call or construct containers. There is a Container class which can be placed into another class. Classes are constructed using methods, variables, initialization code, and other classes. Question 31 Answer: A Reasoning: The abstract modifier will prevent a class or method from being instantiated. 251
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Question 32 Answer: B Reasoning: The proper delivery of messages in a sequence is configurable through the Ordered Delivery option. Question 33 Answer: C Reasoning: The schema generator is used to map existing program elements of a schema derived and defined by the annotations in the program. Question 34 Answer: D Reasoning: An attribute uses a name/value pair to define further define XML markup code. Question 35 Answer: A Reasoning: Entity beans are used to create, delete, query entities, as well as updating the state of an entity. They will not modify an existing entity. This type of modification is performed by session beans, which provides the process, while entity beans provide the data. Question 36 Answer: B Reasoning: Java Messaging Service is associated with integration of component, not security. JAAS API is another Java technology which is relevant to security discussions. 252
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
Question 37 Answer: D Reasoning: The interpreter patter defines a representation of a language’s grammar and an interpreter for that grammar. Question 38 Answer: C Reasoning: JCA is used to integrate Java components with non-Java components. JMS is used to integrate multiple Java components. Java Messaging Service (JMS) is not a component of JCA. Question 39 Answer: B Reasoning: Of the mentioned QoS points, scalability handles the expandability of a system, reliability covers the trust in the system to be active, and availability covers the accessibility of the system to its users. Only performance deals with the response time for transaction: though it also covers the number of transactions at a given time. Question 40 Answer: A Reasoning: Layers are the hardware and software stack used to host services within a specific tier. The typical layers include application, virtual platform, application infrastructure, enterprise services, enterprise services, computer and storage services and networking infrastructure. The enterprise services layer is comprised of operating systems and virtualization solutions to provide an interface between the application infrastructure and the operating system. 253
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
9 References Heller, Philip and Roberts, Simon. Complete Java 2 Certification Study Guide. Sybex: San Francisco, 2005. Knudsen, Jonathan and Niemeyer, Patrick. Learning Java, 3rd Edition. O’Reilly Media Inc.: 2005. Sierra, Kathy and Bates, Bert. Head First Java, 2nd Edition. O’Reilly Media Inc.: 2005. Kalin, Martin. Java Web Services: Up and Running. O’Reilly Media Inc.: 2006. Sierra, Kathy and Bates, Bert. SCJP Sun Certified Programmer for Java 6 Study Guide Exam. McGraw-Hill Osborne Media: 2008 Mughal, Khalid A. and Rasmussen, Rolf W. A Programmer’s Guide to Java SCJP Certification: A Comprehensive Primer, Third Edition. Addison-Wesley Professional: 2008. Hall, Marty and Brown, Larry. Core Servlets and JavaServer Pages: Volume 1: Core Technologies, 2nd Edition. Prentice Hall: Santa Clara, 2006. Trottier, Alain. Sun Certification Training Guide: Java 2 Enterprise Edition Web Component Developer Exam. Pearson Certification: 2003. Sierra, Kathy and Bates, Bert. Head First EJB. O’Reilly Media Inc.: 2003. Cade, Mark and Sheil, Humphrey. Sun Certified Enterprise Architect for Java EE Study Guide, Second Edition. Prentice Hall: 2010
254
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
General Certification Information: www.sun.com Java.net Wiki: http://wiki.java.net/bin/view/Main/WebHome Java Programming: http://en.wikibooks.org/wiki/Java_Programming Java Language Specification, Third Edition: http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html
Websites Web: http://store.theartofservice.com eLearning: http://theartofservice.org
255
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
10 Index A ability 17, 35-7, 59, 154, 204, 206 abstract classes 4, 23-5, 28, 214 access 27, 29-30, 32, 34, 69-71, 79, 104, 108, 161-2, 180-1, 183, 187-9, 216, 218, 223-4, 228 algorithms 5, 48, 89, 221-2 annotations 82, 154, 179, 192, 230, 252 APIs 79, 86, 89, 93, 104, 106, 153, 156, 165 application 10, 12, 88-9, 94, 99-100, 102, 153, 169-70, 193-4, 198-9, 21516, 218, 220-1, 223, 227-8, 238 architecture 12, 161, 180, 188, 196-8, 202, 209 arguments 24, 35, 37, 40-1, 46, 50, 57-9, 66-70, 72, 106-8, 119-21, 128, 130, 136, 143-4, 163 arrays 4, 19-20, 42, 45, 49, 79-80, 234, 247 assertions 5, 65-6, 185-6, 247 attributes 13, 28, 105, 113, 149-50, 159, 161, 187, 235, 242 authentication 182, 186, 200, 227, 237, 247, 249 authorization 183, 224, 227, 249 availability 78, 203-6, 231, 237, 244-5, 249, 253 B bean 6-7, 94-100, 108-11, 113-20, 123-4, 129, 131-6, 138-42, 144-6, 1489, 235-6, 246, 248 bean class 6-7, 97-8, 105-6, 110-11, 113, 119-22, 131, 135, 137, 139, 1414, 148, 248 behavior 7, 13, 19, 24-5, 28, 68-9, 73-4, 94, 100, 145, 219-21 benefits 2-3, 7, 35, 73, 95, 167, 175 block 32, 61-2, 70, 76, 166 BMP (Bean-Managed Persistence) 133, 226 boolean 4, 13, 17, 39, 41, 57, 59, 155 browser 165, 184, 193, 228 business 94-5, 99, 157, 206, 236, 238, 249 business methods 97, 110, 113-15, 118, 120-1, 123-4, 127-9, 133, 135, 179 bytes 15-16, 39-40, 87, 90 C calculations 53, 56, 59 candidate 10-11 cast 38, 41, 57 256
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
casting 5, 38, 41, 43 characters 4, 13-14, 17, 53, 79-80, 90, 156, 158 class declarations 4, 13, 21, 23, 26-7 Class Modifiers 4, 17, 26-7 class type 24-5, 137, 214 classes 4, 12-13, 15, 19-35, 39, 42-3, 48-50, 66-73, 79, 83-7, 91-3, 97-8, 121-2, 214-19, 221-2, 250-1 classpaths 5, 21, 84-5 client 96-8, 102-3, 105-6, 110, 114-18, 127-8, 132-3, 141-2, 146, 151, 1689, 178-83, 189-91, 214, 216-18, 224-8 CMP (Container-Managed Persistence) 133-5 CMT (Container-managed transactions) 148-9 code 14, 18, 28, 32, 35-6, 44-5, 49, 53, 61-3, 69, 78, 158, 215-16, 222-3, 225-6, 246-7 coding 97, 105, 179 collection 45, 86, 89, 138-9, 187, 220, 243 command 5, 83-5, 219 communication 101, 107, 112, 161, 200, 207, 220, 224, 239, 249 compilation units 14, 81-2 component interface 6, 97-8, 103, 105-6, 114, 117, 120-1, 126-7, 129, 131, 135 components 92, 94-5, 97, 100, 151, 157, 188, 196-201, 203-6, 215, 217, 220-2, 224, 243, 245, 252-3 concatenation 55 conditional statements 44-5, 221 conditions 5, 24, 31, 44-6, 53, 67-8, 72, 79, 115, 191 confidentiality 184, 190, 204, 227, 235, 247, 249 connection 92, 118, 133, 142, 167, 181-2, 184, 226 construction 13, 20, 22, 35, 64, 69, 72, 75, 84, 214-15, 234, 247 constructors 5, 23, 28, 35, 63-5, 69-70, 72-3, 116 container 92, 96, 98, 100, 112, 114-18, 123-4, 131-6, 139, 142, 145-6, 14850, 163, 170, 201-2, 251 Container-Managed Persistence (CMP) 133-5 control 69-70, 77, 92, 99, 111, 197, 215, 219-20, 228 conversion 38-43, 200, 234 coupling 176, 198, 218-22, 225 CreateException 98, 109, 119, 130, 137 creation 12, 36, 214-15, 217, 250 credentials 183, 228 curly braces 20, 32, 44, 49 D data types 4, 15, 90, 151, 159, 170-1, 173, 175-6 database 81, 91, 96, 104, 108-9, 111, 122-4, 131-4, 136, 138, 166, 184, 257
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
200, 205-6 DD (deployment descriptor) 98-100, 131, 134-5, 137, 139-40, 144, 148-9, 209, 230 declaration 20, 22, 26, 61-2, 159, 228, 234, 242, 247 decryption key 184 default access 27, 71 dependencies 199, 221 deployer 100, 232, 246 deployment 98-9, 113, 131, 144, 201, 246 Design Patterns 213, 236, 248 destination 32, 83, 194 developers 99, 106, 118, 133, 136, 156, 172-3 directories 21, 33, 82-5, 91, 98, 105 distribution 184, 196-7, 199, 231 documents 151, 153, 157-9, 171, 173, 213 E EJB container 95-6, 98, 103, 147, 209-10, 228-9 ejbCreate 115-16, 120, 132, 135-7, 236, 248 ejbPassivate 117-18, 132, 134 EJBs (Enterprise Java Bean) 8, 94-6, 103, 106, 109, 112, 160, 209-11, 228 encapsulation 4, 35-6, 204, 221, 234 enterprise bean 96, 100-1, 103, 105-6, 108-10, 112-13 Enterprise JavaBeans 6, 94-5, 201, 239 entities 3, 6, 13, 97, 103, 111, 122-4, 128-34, 136-9, 141, 153, 159, 166, 187, 242, 252 entity beans 105, 108-12, 122-5, 127-32, 134-6, 138, 227, 242, 248, 250, 252 errors 24, 88, 109-10, 146, 190 exception types 61-4 exceptions 5, 17, 60-4, 88, 98, 102, 107, 117-18, 150, 225 execution 32, 43, 51, 61-2, 66, 69, 77, 85, 88 expression 13, 18, 38, 40, 43-4, 46, 50-3, 55, 65, 78 extensibility 204, 206, 217-18, 223, 231, 237, 245, 249 extension 23, 69, 103, 106, 110, 127, 215 F fields 13, 23, 135, 137-8 files 83, 85, 91, 122, 189, 192 float 17, 39-41, 87, 155 Flow Control 193-4, 241 functionality 4, 24, 32-3, 78, 95, 196, 198, 206, 221, 231, 245 functions 66, 68, 91, 199, 217, 239, 243 258
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
H handlers 63, 160, 162-3, 212 header 161-2, 165, 167-8 home interface 6, 97-8, 108-10, 115, 119-20, 128-9, 135-7, 146 host 37, 101-2, 212 I identifiers 13, 26, 65-6, 140, 157, 235, 247 implementation 24-5, 31, 68, 104-5, 134, 160, 173, 189, 201, 208, 217, 219-20 import 15, 33, 81, 83, 125, 171 information 3, 88, 90-1, 99-100, 134-5, 139, 153, 166, 168, 181, 183, 187, 191, 200, 207, 211 inheritance 4, 19, 22, 35-6, 69, 87, 234, 247 inner classes 5, 70-2 instance variables 5, 32, 36, 48-9, 114, 136 instances 16, 19, 21-3, 27, 29-32, 36, 47-50, 57, 62-3, 70-1, 75, 87, 91, 102, 131-2, 214-17 integrity 182-3, 185, 203-4, 227, 235, 247, 249 interfaces 4, 23-6, 31, 33-4, 39, 42-3, 87-8, 97-8, 106-8, 112, 127-8, 160, 168, 180-1, 201-2, 214-18 J Java 4, 10, 12-13, 15-16, 18, 22, 24, 27, 33, 36-7, 48, 65-6, 90-1, 101-2, 151-2, 234-5 JAX-WS 8, 152, 177, 207 JAXB (Java Architecture for XML Binding) 7-8, 154, 177 JAXR (Java API for XML Registries) 7-8, 153, 180, 207 JMS (Java Messaging Service) 207-8, 226, 238, 243, 250, 252-3 JVM (Java Virtual Machine) 12, 22, 32, 35, 48, 62, 75-7, 95, 112 L language 12-13, 47, 151, 157, 169, 243 layers 8, 188, 197, 201-2, 226, 244, 253 level 22, 182-3, 187, 200, 203, 217, 219, 243 liability 3 local variables 5, 48-9, 88 M 259
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
maintainability 204, 206, 223, 225, 245, 249 manageability 204, 206, 231, 245, 249 memory 37-8, 153, 156, 203, 218 MEP (message exchange pattern) 151, 160 message exchange pattern (MEP) 151, 160 model 13, 163, 221, 229-30 modifiers 4, 28, 30, 62, 71 monitor 78-9, 206 N nodes 161, 163, 194-5, 248 O OASIS (Organization for the Advancement of Structured Information Standards) 157 object references 19, 43, 72, 111 objects 12-13, 19, 21-2, 31-2, 35-7, 48-50, 57, 69-71, 73-5, 78-9, 86-9, 101, 103-5, 118, 214-22, 226-7 operands 40-1, 51, 55-6, 58-9 operations 13, 36-7, 47, 51, 57, 59, 71, 79, 168, 170-1, 174, 216, 221-2, 240, 251 operators 5, 46-7, 50-3, 55, 57, 59, 71, 73, 247 overridden 29-31, 67-8, 73 P packages 5, 14-15, 19, 23, 27, 29-30, 34, 81-3, 86, 92-3, 125, 152, 176, 180-1 path 48, 84, 161, 248 pattern 9, 172, 213-27, 232, 246, 248 performance 89, 198, 204, 206, 224, 237, 244, 249, 253 persistence 103, 110, 130, 226-7 policies 187-8, 191 polymorphism 5, 19, 37, 234 pool 79, 124, 131, 142, 145, 210 precedence 47, 51, 76 primary key 6, 105-6, 108, 111-12, 123-4, 136-7 primitive type 16, 40-1, 50, 55, 87-8 process 49, 55, 63-4, 97-9, 102, 105, 109, 111, 122-3, 139, 143, 163, 165, 177, 184, 228 processing 62, 142, 146-7, 156, 161, 163-4, 223, 227, 229, 233 products 3, 185, 189, 214-15, 227, 238 programmer 36, 84, 86, 152 260
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
programs 13, 43, 48, 60, 70, 79, 81, 85-6, 89, 252 protocols 103, 106, 147, 165, 183, 186, 191, 211, 223, 235 provider 7, 154, 168, 180, 191 Q Quality of Service (QoS) 190, 202-4, 237, 253 queries 104, 128-9, 139-40, 181 R ready state 77, 116-17, 132 receiver 160-1, 185, 219, 221 reference 31, 35, 49-50, 57, 70-1, 97, 101-2, 105, 110, 117, 123, 129, 132, 135, 138, 159 registry 102-3, 153-4, 180-1 relationships 14, 19, 36-7, 98, 137-8, 168, 174, 180, 201, 216, 247 reliability 190, 203-4, 244, 249, 251, 253 Remote Client 6, 105-6, 112, 224, 239 remote interface 6, 102, 106-8, 110, 113, 129 remote references 102, 105, 107-8, 111 RemoteExceptions 97-8, 119-20, 128, 130 representation 89, 122, 130, 132, 139, 164, 214-16, 219, 222, 253 requests 38, 41, 77, 96-7, 160-1, 164-9, 185-7, 212, 219, 223-4, 228-9 resources 100, 118, 144, 164, 167-8, 183, 187, 203, 206, 222, 228, 233, 238, 249 result 24, 34-5, 43, 45, 50, 54-6, 58-9, 73, 84, 89, 97, 166, 168-9, 205-6, 215-16, 223-4 return types 50, 64, 67-9, 106-7, 110, 119-21, 128, 130, 136-8, 179, 192 rules 13, 25, 29-30, 39-43, 53, 57, 59, 63, 74, 119-21, 129, 136-7, 143, 157, 187 runtime 20, 43, 63, 65-6, 69, 96, 105-7, 160, 209, 212, 215 S SAAJ (SOAP with Attachments API for Java) 7, 156, 207 SAML (Security Assertion Markup Language) 8, 185 scalability 157, 203-4, 206, 210, 237, 244, 249, 253 SCBCD (Sun Certified Business Component Developer) 10-11 scope 23, 45, 48-9, 61, 70, 111, 198 security 8-9, 100, 103, 110, 152, 182-3, 194, 198, 204-5, 210, 227, 230-1, 237, 249, 251-2 sequence 14, 79, 90, 193-4, 241, 252 server 95-8, 100, 102-4, 111, 131, 141, 147, 165-8, 184, 195, 205-6, 211 Server Provider 99-100, 232, 246 261
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
services 3, 87, 151-2, 156-7, 162-3, 169, 171-3, 175-6, 182-3, 187-92, 197200, 203, 209-10, 224-5, 245, 249 servlets 8, 96, 165-6, 201, 211-12 session 97, 109, 111-12, 114, 239 session beans 108-9, 111-16, 122-4, 128-9, 134, 141, 239, 250, 252 SIB (Service Implementation Bean) 160 SOAP 7, 151, 156, 160-1, 189, 208, 235, 240 SOAP message 156, 160-4, 171-2, 175-6, 190, 235, 248 source files 4, 14, 33-4, 60, 83, 177 specification 88, 95, 97-8, 100, 112, 156, 170, 188, 213, 246 SPI (service provider interface) 104, 153 state 66, 77-8, 91, 113-14, 116, 118, 131-4, 142, 146, 164, 216, 219-21, 239, 252 statements 13, 33, 43-6, 52-4, 58, 65, 70, 134, 186 static methods 31-2, 34, 50, 70, 77 Static variables 21, 31, 48, 71 StAX 7, 153 storage services 244, 253 string 55, 64-5, 79-80, 105, 120-1, 125, 128, 159, 161, 163 string object 55, 79-80, 90 structure 12, 64, 72, 85, 89, 98, 160, 165, 170, 175, 178, 185, 215, 217, 220 stub 101-3, 107-8, 117-18, 123-4, 178 subclasses 19, 22-4, 29, 31, 37, 42, 64, 67-9, 214-15, 217, 220, 222 subpackages 81-2 superclass 22, 24, 30, 37, 42, 88, 122 syntax 26, 44-6, 81-3, 98, 168, 186 system 38, 40, 100, 164, 190, 196-9, 201, 203-8, 210, 212, 214, 216, 219, 222, 228, 253 T technologies 190, 199, 213 threads 5, 74-9, 88, 197 tiers 8, 107, 197, 199-201, 206, 222, 225-6, 239, 245, 253 topics 144-5, 207, 249 transactions 7, 100, 103, 110, 116, 118, 133-4, 145-50, 200, 203-4, 219, 226, 233, 240, 251, 253 transitions 116, 131-2, 239, 250 types 4, 16, 23, 36-41, 50, 53, 60-1, 67-9, 81-3, 96-7, 106-7, 159, 165, 1756, 191-3, 239-40 U UDDI (Universal Description Discovery and Integration) 7, 153, 156-7, 161 262
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055
unary 40, 47, 52 underflow 53-4, 56 Unicode 17, 157-8 URL 165-6, 182, 189, 191 users 166, 185, 194, 200-1, 203-4, 212, 228-9, 253 V value 2, 13, 15, 17-18, 20-1, 30, 35-6, 38-41, 43-5, 48-54, 56-7, 73-4, 86-8, 138-40, 161, 171-2 variablename 125-6 variables 5, 13, 20-2, 25, 27-33, 36, 39, 43-4, 48, 53, 71-2, 159, 209, 234, 241, 247 view 223-4, 232, 246 virtual machine 21, 85, 101 W web services 7-9, 151, 156, 161, 172, 176, 178-9, 182-3, 189-94, 208, 21011, 229, 240 work 2, 27, 85, 146, 149, 197-9, 209, 212, 216, 249 WS-Security 8, 188-90, 243 WSDL 7, 156, 170-1, 175-6, 189, 208, 240, 251 X XML 151, 154, 157-8, 169, 187, 189, 210, 227, 242 XML documents 153, 158, 168-9, 172, 178 XML Web Services 7, 157, 207 XSD (XML Schema Definition) 171, 173-6
263
Copyright The Art of Service │Brisbane, Australia│Email:[email protected] Web: http://store.theartofservice.com │eLearning: http://theartofservice.org │Phone: +61 (0)7 3252 2055