P. 1
GIAC Secure Software Programmer - Java certification Exam Certification Exam Preparation Course in a Book for Passing the GSSP - Java Exam - The How To Pass on Your First Try Certification Study Guide

GIAC Secure Software Programmer - Java certification Exam Certification Exam Preparation Course in a Book for Passing the GSSP - Java Exam - The How To Pass on Your First Try Certification Study Guide

|Views: 113|Likes:
Published by Emereo Publishing
The GIAC Secure Software Programmer (GSSP) Certification Exam was developed in a joint effort involving the SANS Institute, CERT/CC, several US government agencies, and leading companies in the US, Japan, India, and Germany. These exams are an essential response to the rapidly increasing number of targeted attacks that are focusing on application vulnerabilities.Programmers can demonstrate that they know the common security flaws found in Java and C programming, and how to avoid the problems, by passing the GSSP exams.This self-study exam preparation guide for the GSSP - Java 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 GSSP - Java subjects, test tricks and tips, numerous highly realistic sample questions, and exercises designed to strengthen understanding of GSSP - Java concepts and prepare you for exam success on the first attempt are provided.Put your knowledge and experience to the test. Achieve GSSP - Java 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 GSSP - Java exam on your FIRST try. Up to speed with the theory? Buy this. Read it. And Pass the GSSP - Java Exam.
The GIAC Secure Software Programmer (GSSP) Certification Exam was developed in a joint effort involving the SANS Institute, CERT/CC, several US government agencies, and leading companies in the US, Japan, India, and Germany. These exams are an essential response to the rapidly increasing number of targeted attacks that are focusing on application vulnerabilities.Programmers can demonstrate that they know the common security flaws found in Java and C programming, and how to avoid the problems, by passing the GSSP exams.This self-study exam preparation guide for the GSSP - Java 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 GSSP - Java subjects, test tricks and tips, numerous highly realistic sample questions, and exercises designed to strengthen understanding of GSSP - Java concepts and prepare you for exam success on the first attempt are provided.Put your knowledge and experience to the test. Achieve GSSP - Java 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 GSSP - Java exam on your FIRST try. Up to speed with the theory? Buy this. Read it. And Pass the GSSP - Java Exam.

More info:

Published by: Emereo Publishing on Nov 02, 2012
Copyright:Traditional Copyright: All rights reservedISBN:9781743040829
List Price: $23.96

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
This book can be read on up to 6 mobile devices.
Full version available to members
See more
See less

02/05/2016

215

9781743040829

Sections

  • 1 Foreword
  • 2 GIAC Secure Software Programmer - Java
  • 3 Exam Specifcs
  • 4.1.1. Object-Oriented Language
  • 4.1.2. Language Elements
  • 4.2. Source Files
  • 4.3.1. Data Types
  • 4.3.2. Integral (int)
  • 4.3.3. Floating Point
  • 4.3.4. Boolean
  • 4.3.5. Character
  • 4.3.6. Enumeration
  • 4.3.7. Objects
  • 4.3.8. Arrays
  • 4.3.9. Classes
  • 4.4.1. Inheritance
  • 4.4.2. Types of Classes
  • 4.4.3. Abstract Classes
  • 4.4.4. Interfaces
  • 4.5.1. Class Modifers
  • 4.5.2. Modifers
  • 4.6.1. Importing
  • 4.6.2. Argument Passing
  • 4.6.3. Encapsulation
  • 4.6.4. Inheritance
  • 4.6.5. Polymorphism
  • 4.6.6. Garbage Collection
  • 4.6.7. Converting and Casting
  • 4.6.8. Object Reference Conversion and Casting
  • 4.7.1. Assignment
  • 4.7.2. Condition
  • 4.7.3. Iteration
  • 4.7.4. Operators
  • 4.8.1. Variables
  • 4.8.2. Instance Variable
  • 4.8.3. Local Variable
  • 4.8.4. Methods
  • 4.9.1. Unary Operators
  • 4.9.2. Assignment Operators
  • 4.9.3. Arithmetic Operators
  • 4.9.4. Comparison Operators
  • 4.9.5. Bitwise Operators
  • 4.9.6. Short-Circuit Logical Operators
  • 4.9.7. Conditional Operators
  • 4.10. Exceptions
  • 4.11.1. Overloading and Overriding
  • 4.11.2. Constructors
  • 4.11.3. Inner Classes
  • 4.11.4. Contracts and Conventions
  • 4.11.5. Threads
  • 4.12.1. Key Methods
  • 4.13.1. Packages
  • 4.13.2. Importing Packages
  • 4.13.3. “javac” Command
  • 4.13.4. Classpaths
  • 4.13.5. “java” Command
  • 4.14.1. java.lang
  • 4.14.2. java.util
  • 4.14.3. java.io
  • 4.14.4. java.net
  • 4.14.5. java.awt
  • 4.14.6. java.swing
  • 5.1.1. Uses of Enterprise JavaBeans
  • 5.1.2. Benefts of Enterprise JavaBeans
  • 5.1.3. Characteristics of Enterprise JavaBeans
  • 5.1.4. Building a Bean
  • 5.1.5. EJB Roles
  • 5.1.6. Remote Method Invocation (RMI)
  • 5.2.1. Java Naming and Directory Interface (JNDI)
  • 5.2.2. Remote Client API
  • 5.2.3. Remote Home Interface
  • 5.2.4. Remote Interface
  • 5.2.5. Local Client API
  • 5.3.1. Stateful and Stateless Session Beans
  • 5.3.2. Session Bean Lifecycle
  • 5.3.3. Creating Beans
  • 5.3.4. Bean Classes
  • 5.4.1. Characteristics of Entities
  • 5.4.2. Entity Bean Code
  • 5.4.3. Component Interfaces
  • 5.4.4. Home Interfaces
  • 5.4.5. Entity Bean Instances
  • 5.4.6. Synchronization
  • 5.4.7. Container Callbacks
  • 5.4.8. Entity Classes
  • 5.4.9. Entity Identity and Primary Keys
  • 5.4.10. Multiplicity
  • 5.5.1. WHERE Clause
  • 5.5.2. SELECT Clause
  • 5.6.1. Message-Driven Bean Class
  • 5.6.2. Message-Driven Bean Methods
  • 5.6.3. Behavior of a Message-Driven Bean
  • 5.7.1. Bean-Managed Transaction
  • 5.7.2. Container-Managed Transaction
  • 6.1.1. Basic Security Mechanisms
  • 6.1.2. HTTPS
  • 6.1.3. SAML
  • 6.1.4. XACML
  • 6.1.5. WS-Security
  • 6.2.1. Types of Security
  • 6.2.2. Security Behaviors
  • 6.2.3. Functions of Security
  • 6.2.4. Security Characteristics
  • 6.2.5. Security Implementation Mechanisms
  • 6.2.6. Container Security
  • 6.2.7. Securing the Application Server
  • 6.2.8. Realms, Uses, Groups, and Roles
  • 6.2.9. SSL Secure Connections
  • 6.2.10. Digital Certifcates
  • 6.3.1. Security for Enterprise Beans
  • 6.3.2. Security View
  • 6.3.3. IOR Security
  • 6.3.4. Deployment of Secure Enterprise Beans
  • 6.3.5. Application Client Security
  • 6.3.6. EIS Applications
  • 6.4.1. Fundamentals of Web Application Security
  • 6.4.2. Caller Identity Checks
  • 6.4.3. Role References
  • 6.4.4. Security Requirements
  • 6.4.5. Secure Connections
  • 6.4.6. Authentication Mechanisms
  • 7.1. Refresher “Warm up Questions”
  • 8.1. Answers to Questions
  • 9 References

1

Foreword

This Exam Preparation book is intended for those preparing for the GIAC Secure Software Programmer - Java 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 those 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 that MAY be asked in the GSSP-JAVA Exam, this book encompasses the main concepts covered within the Java Security discipline. Each process contains a summarized overview of key knowledge. These overviews are designed to help you to reference the knowledge gained through the course. Due to licensing rights, we are unable to provide actual GSSP-JAVA Exam. However, the study notes and sample exam questions in this book will allow you to more easily prepare for a GSSP-JAVA exam. Ivanka Menken Executive Director The Art of Service

1

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 review@ emereo.org 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

Contents
1 2 3 4 4.1.

Foreword

1 11

GIAC Secure Software Programmer - Java Exam Specifics 12 General Java Concepts 13 Philosophy Behind Java 13 13 14 16

4.1.1. Object-Oriented Language 4.1.2. Language Elements 4.2. 4.3. Source Files 15 16 16 18 18 18

Primitives and Constructs

4.3.1. Data Types 4.3.2. Integral (int) 4.3.4. Boolean 4.3.5. Character 4.3.6. Enumeration 4.3.7. Objects 20 4.3.8. Arrays 20 4.3.9. Classes 22 4.4.

4.3.3. Floating Point 17

Class Fundamentals 23

22 23 24 26

4.4.1. Inheritance

4.4.2. Types of Classes 4.4.3. Abstract Classes 4.4.4. Interfaces 4.5. 26 Class Declaration

4.5.1. Class Modifiers 28
3

1.2.6.8.6. Encapsulation 35 4.2. Argument Passing 4. Modifiers 4.6. Garbage Collection 37 41 4. Condition 4.4.9. Inheritance 36 4.6.9.7.4. Operators 4. Iteration 4.1.5.3. Algorithms 4.4.4.8. Polymorphism 37 4.6. Comparison Operators 58 .8. Operators 51 52 4.8. Variables 4.5.1.7. Object Reference Conversion and Casting 4. Converting and Casting 38 4.8. Local Variable 50 4.7. Assignment Operators 54 4.5.6. 4.1.7.6.9. Unary Operators 4. Bitwise Operators 4 52 55 59 4. Arithmetic Operators 4.3.2. Algorithm Design 44 44 46 47 49 49 50 43 4. Methods 4. Instance Variable 4.9.4.3. Assignment 4.7.2.6.9.9.6. Importing 29 33 35 Functionality 33 4.3.8.6.2.7.

13. java.awt 4.4.11.11. java.9.12.swing 5 5.14.14.5. Exceptions Assertions 61 66 67 4.10.2. Short-Circuit Logical Operators 60 4. java.5. Contracts and Conventions 4. java.1. Packages 4.14.2.13.11. java.6.11.3.7.3. Methods from String Class 73 79 80 4.11. Key Methods 80 Java Development Fundamentals 80 82 82 85 4.io 88 4. 83 4. java.1.14.11. “java” Command Class Library 85 85 87 90 90 90 91 4. Threads 75 4.4. Classpaths 4.2. 4. Overloading and Overriding 4. Inner Classes 70 4. Constructors 69 4.4.4. 4.12.util 4. Overview Enterprise JavaBeans 91 5 .14. Conditional Operators 61 4.13.14.13.lang 4.13.5.net 4.1. “javac” Command 4.13.3.1.14.9.1. Importing Packages 4.6.

Synchronization 5.7.5. Bean Classes 114 5. Home Interfaces 5.4.2. Entity Bean Instances 124 .2.2.4.1.4.6.4.5. Characteristics of Entities 5. Benefits of Enterprise JavaBeans 5.5.3.4.4. Remote Interface 5.4.1. Uses of Enterprise JavaBeans 91 5. Characteristics of Enterprise JavaBeans 92 5.3.3.6.2. Container Callbacks 5.4. Entity Classes 129 6 5.3. Java Persistence API Entities 118 122 126 128 116 116 5. Remote Client API 5. Creating Beans 113 5. Building a Bean 3 9 5. 5.1.3.2.4.3.3.2. Java Naming and Directory Interface (JNDI) 5. EJB Roles 5.4.2.3.4. Remote Home Interface 103 Session Bean Components 5. Client View 96 97 100 100 101 105 107 108 108 5.1.1.4. Session Bean Lifecycle 109 5.3. Remote Method Invocation (RMI) 92 5. Entity Bean Code 5.1. Stateful and Stateless Session Beans 5.5.2.2. Local Client API 5. Component Interfaces 121 5.1.1.2.8.1.1.4.

SELECT Clause 5.2.7.6.5.3.1.1. Functions of Security 152 6. Security Characteristics 153 6. Message-Driven Bean Methods 137 5.2. Multiplicity 5. Security Behaviors 6. Types of Security 6.2. Bean-Managed Transaction 6 6.2. Message-Driven Bean Component 135 138 135 5.2. 131 Java Persistence Query Language 133 130 132 5.3.7.2.5. 148 149 150 151 Java EE Security Fundamentals 150 6. SAML 147 6. HTTPS 145 6.5.4.3.9.5.1. Container-Managed Transaction 143 6.6.1.6.1. Basic Security Mechanisms 6.1. XACML 6. Entity Identity and Primary Keys 5.2.6.1.1.2.5. Java Security 144 Security 144 144 5.6.7. Transactions 140 142 5.2.4. Container Security 158 7 . WS-Security 6.1. Behavior of a Message-Driven Bean 5.10.2.4.1. Message-Driven Bean Class 5.1.2. WHERE Clause 33 1 5.4. Security Implementation Mechanisms 154 6.2.5.

IOR Security 170 6. Deployment of Secure Enterprise Beans 170 6. and Roles 6.5.2. SSL Secure Connections 6.3. 164 165 165 Java EE Application Security 163 160 6. Authentication Mechanisms 8 . Security View 167 6.1.7. Securing the Application Server 160 6. Caller Identity Checks 176 6.2. Uses.9. Realms. EIS Applications 6.4. Role References 6.8.2.4.1. Security Requirements 177 6.4.1.4.2.1.6.6.4.6.3.3. Application Client Security 6. Secure Connections 7 7. Security for Enterprise Beans 6. Fundamentals of Web Application Security 6.3.10. 9 Practice Exam 183 Refresher “Warm up Questions” Answer Guide 202 Answers to Questions 202 References 214 183 176 178 180 6.3.3.3. 8 8.4.2.3.5. 172 175 175 Web Application Security 171 6.4.4. Groups. Digital Certificates 6.3.4.2.

9 .

or otherwise.Notice of Rights All rights reserved. without the prior written permission of the publisher. and the publisher was aware of a trademark claim. mechanical. photocopying. 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. No part of this book may be reproduced or transmitted in any form by any means. recording. electronic. No such use. or the use of any trade name. is intended to convey endorsement or other affiliation with this book. 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. Where those designations appear in this book. Notice of Liability The information in this book is distributed on an “As Is” basis without warranty. Trademarks Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. 10 . the designations appear as requested by the owner of the trademark.

NET. assisting in growing the security knowledge of programmers.2 GIAC Secure Software Programmer - Java The Global Information Assurance Certification (GIAC) Secure Software Programmer Exam is available for both Java and . ensuring that software development incorporates the necessary security skills to code secure applications and to provide advanced secure programming skills. The exam covers: • • • • • • • • Input handling Authentication and Session Management Access Control Java Types and JVM Management Application Faults and Logging Encryption Services Concurrency and Threading Connection Patterns 11 . The certification is for individuals responsible for coding secure applications. The certification allows candidates to demonstrate those skills.

proctored and timed. Otherwise. Exams are delivered in a secure environment.3 Exam Specifics GIAC exams are delivered online using a standard web browser. Specifics about the exam are: • Exam Number : • Time Limit: • # of Questions: • Question Type: • Passing Score: GSSP-Java 4 hours 100 Multiple Choice 73% 12 . When purchased with SANS training. the exam is available for 7 to 10 days after the conference ending. the exams are issued within 24 hours after receipt of payment and will remain available for 120 days. Exams are proctored.

The goals of the programming language support the concept: • • • • • Java should be “simple. The catch-phrase “Write Once.1. Applications written in Java are typically compiled to bytecode that can run on any Java Virtual Machine (JVM).1.4 General Java Concepts 4. An object in turn will represent the properties and behaviors of the class it belongs to. The creation of objects is set by the structure of the class when it is created. Java should be “architecture neutral and portable”.1. Java should be “high performance”. Class models are used to define the properties and behaviors of an object. threaded and dynamic”. 4. The driving force behind Java is the idea of portability. which in 13 . object oriented and familiar”. A class is a category of objects. Run Anywhere” shows the commitment of being able to run any Java Application on any platform in any language. A field is considered a variable storing a value. Java should be “interpreted. Philosophy Behind Java Java programming is an object-oriented construction with many similarities to C and C++. The properties of an object are called attributes and these attributes are defined by fields. The structure of the Java languages begins with a class. Object-Oriented Language Java is just one of several object-oriented languages used in programming applications. Java should be “robust and secure”.

Like words. form feeds. lexical tokens are the lowest level of the language elements in Java. The first character of the identifier must be a letter. of the language. String literals are a sequence of characters enclosed within double quotes and occurring on a single line of code. • Operators – used to identify specific relationships between tokens. 4. • White Spaces – a sequence of spaces. and line terminator characters used to help distinguish between tokens. Boolean or string value. character.turn represents a particular property of an object. • Literals – identifies a constant value. How an object behaves is called its operations and is defined by methods. such as expressions. • Keywords – words which are predefined in the language and cannot be used to identify other entities. How the language is constructed will provide a semantic definition. Language Elements Like any language. All keywords are lowercase. Combinations of tokens are used to create complex constructs of the language. meaning or interpretation. the construction of the language follows precise rules or grammar. either as a numerical.1. Both fields and methods are collectively known as members within a class declaration. Integer data types identify the type of literals used. class. tabs. statements. variable or label. Examples of tokens are: • Identifiers – a case-sensitive sequence of characters used to name a program.2. method. methods and classes. 14 .

Packages are placed in a directory hierarchy. Only alphanumerical characters are allowed in package names.4. The formatting is as follows • Format to import individual classes: import keyword + fully qualified class name + ‘. The unextended filename matches the public class name. but ordered if present.2. Source Files Source files end in .’ • Format to import entire class: package name + ‘*’ 15 . followed by package name. They include: • Package declaration • Import statements • Class. 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. interface and enum definitions Package Declaration is simply formatted and starts with a keyword package. The package name is a series of elements separated by periods. Compilation Units are not required.java extension and contain only one top-level public class definition and an unlimited number of non-public class definitions.

3.2. Integral (int) Integer can be assigned to any numeric primitive data types and are expressed in decimal. zero. Include byte.1.4. Hexadecimal (base 16) is expressed with a 0x or 0X prefix with hex digits in upper or lower case characters. 4. short. Unsigned data types are numeric types whose value can be positive or zero. octal. or hexadecimal with decimal as the default. Octal numbers (base 8) is expressed with a 0 prefix. and long.3. 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. Primitives and Constructs 4. distinguishing them from decimal numbers (base 10) which can begin with any number between 1 and 9. 16 . int. Primitive types are precisely defined. Data Types Data types are a simple non-object type representing a single value. making Java highly portable. or negative.3.

A floating-point literal must contain a decimal point. Non-numeric bit patterns are referenced using NaN (Not a Number). The value can be specified in decimal or scientific notation: an e or E will denote the scientific notation. A numeric value can never be demoted to a smaller type.3. Floating point values can describe non-numeric situations by taking on bit patterns representing non-numeric values. 4. The differences are often overlooked by applications. For instance. it can be promoted to the bigger type. When a numeric type is used with a type with a greater range. 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 exception to this standard is the ability for extended precisions. 64-bit literals are expressed with an L suffix (should be uppercase to eliminate confusion with the numeral 1). Floating Point Floating points conform to the IEEE 754 international specification and therefore are relatively the same on all Java platforms.3.Default integral literals are 32-bit value. 17 . 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 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. Types can be of various sizes.

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. Character literals can be expressed as Unicode value using four hexadecimal digits. Character literals represent a single Unicode character.3. 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 4. The string name of the value can be obtained using the name() method.3.4. Character Characters are unsigned integrals supporting Unicode and ASCII.4.5.3. The declared name of the enumeration in the source code will correspond with the string name. 18 . usually expressed by enclosing character in single quotes. Boolean Boolean literals are either true or false 4.

an integer is returned to describe the first values relationship with the compared value in the form of less than zero (less than). The compareTo() method will compare an enumeration value to another value with the same enumeration type. 19 .An ordered list of enumeration (enum) values can be achieved using the static values( ) method. With this method. zero (equal). or greater than zero (greater than).

They are usually homogeneous.4. or other arrays. Different objects work together to compose the complete application.8. The internals of an object should never be exposed: public variables should be avoided. Composition is the best option when reusing objects.7. When an object is used in its existing form as a piece of a new object. since inheritance involves breaking down the object. the objects are being composed. 20 .3. using accessor methods to set and return values. When the behavior of the object is changed or refined. 4. Objects Objects are application components which are self-contained and reusable. Arrays Arrays are an ordered collection of primitives. Created arrays must have a specified element type and contain elements that are instances of that class of subclass in that class. except when allowed by polymorphism (all elements of an array of the same type). object references. inheritance is in use. including classes.3. Related objects should be organized into packages. Relationships between objects should be minimal.

construction. Construction can be performed on the same line as the declaration. A value can be explicitly assigned to each element. the following three steps must be taken: • Declaration • Construction • Initialization Declaration tells the compiler the array’s name and the element types contained within the array. The size of the array can be specified using a variable rather than a literal.To create and use an array. 21 . initialization should be combined in a single step. • Numeric elements initialize to 0 • Non-numeric elements initialize to 0-like values To avoid non-default values. The declaration does not specify the size of an array. declaration. which is done at runtime when the array is allocated. Elements in constructed elements automatically initialize to default values. Array size is inferred from the number of elements within the curly braces. Square brackets are used to identify arrays and come before or after the array name.

Members of a classpath include directories or jar files. Class Fundamentals Class Paths are used by Java compiler or Virtual Machine when a class file is needed.9. They are formed by merging the CLASSPATH environment variable and any locations specified in -classpath or -cp command line arguments.4. • Static variables – the variables within an instance of an object is the same as all other instances of the same object.4. Classes A class can contain: • • • • Methods Variable Initialization code Classes A class can be declared using the class keyword. 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. Once the class is defined. 4. where the object represents an instance of the class. The variables and the methods of the class will appear within the braces of the class declaration.3. Within a class. an object based on the class can be created. 22 .

The main() Method is the entry point for standalone Java applications. A subclass will inherit the variables and methods from its superclass and use if declared within the subclass. The method must be public to be called by the JVM.4.2. A subclass can be further extended into more subclasses and are typically found when a class is refined by adding more variables and methods. a class can only inherit from another single class. Java becomes a hierarchy. This declaration is performed using the extends keyword. Inheritance Classes in Java can be declared as a subclass of another class.1. • Automatic (or method local) – created on entry to a method and is sustained when the method is being executed. It is static and does not require a construction of an application class instance. Only one class can be extended from a class: that is. All members not designed as private in the superclass are inherited by the subclass. • Class (or static) – created when the class is loaded and destroyed when a class is unloaded 4. By subclassing. Types of Classes 23 . the classes within. The higher level of a class is called a superclass. Three different variables supported within a class and method: • Member – created when an instance is created and destroyed when the object is destroyed.4. 4.

Members within a class can consist of declared and inherited members.3. Classes are considered generic if the type variables declared have bindings which are different across different instances of the class. All classes. it must be declared as an abstract class. Abstract classes can have abstract methods: methods which are declared but not implemented at the time. Access modifiers can be used on all field. 4. All public declared classes are referenced from other packages. method. member interface. except the Object class. where it cannot be instantiated. If a normal class contains 24 . but can be extended by subclasses. Abstract Classes A class which is incomplete or considered incomplete is an abstract class. Named classes fall into three types: • Abstract class • Final class • Public class If a class is implemented incompletely.4. The top level class is not a nested class. The entire body of the class declaration is the scope of the member within the class. are an extension of an existing class. instance and static initializers and constructors. member class. A class which is declared final cannot have subclasses.A nested class is a class which is declared within the body of another class of interface. and constructor declarations. The body of a class will declare members of the class.

a compile-time error will occur. argument or the like. • 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. the class type should be declared abstract to prevent compile errors. When nonabstract methods are placed into an abstract class. 25 . A class can have an abstract method under the following conditions: • An abstract method is explicitly declared. If the intent is to have subclasses complete the implementation of a method. The result is a concrete subclass. the functionality of the class is inherited but the methods that define the behavior are restricted to the subclass. • A superclass of the class has an abstract method which is not declared or inherited by the class.an abstract method but is not an abstract class.

A class can declare that an interface is implemented if the required methods are implemented. It is defined using the interface keyword. Interfaces Normally. The methods listed by the interface will define the behavior for the object. static. The purpose of the interface is to define what a class must do. An interface defines a set of methods that a class must implement. Class Declaration 26 . nor a particular implementation used. and final. strictfp. from any inheritance tree. No part of the inheritance hierarchy has to be inherited. They can be implemented by any class.4.4. Methods must not be static.4. Interface types can be polymorphically used. All methods are implicitly public and abstract. without defining how a class does it. An interface looks like an abstract class. Another interface or class cannot be implemented by the interface. 4. All variables defined in the interface must be public. Java will only allow a class to inherit from a single class: interfaces allow multiple inheritances to occur.5. where the following rules must apply: • • • • • • • • Interfaces must be declared with the keyword interface. Only interfaces can be extended by the interface. One or more other interfaces can be extended within the interface. An interface can be considered a 100 per cent abstract class. Interface types and class types act the same way. or marked final. or native.

The body of the class is found within the braces. All other constructs are optional.When declaring a class. two kinds of class declarations exist: normal class declarations and enum declarations. a compile-time error will occur. or identifier. 27 . If a class has the same name as any enclosing class of interface. The name of the class in the declaration is specified by the identifier. The syntax of a class is as follows: <class modifier> class<class name><formal type parameter list><extends clause><implements clause> { <field declarations> <method declarations> <nested class declarations> <nested class declarations> <nested interface declarations> <nested enum declarations> <constructor declarations> <initializer blocks> } The first part of the syntax is the class header. Following the identifier is the body of the class. The class header must contain the keyword class and the class name.

extend the class. final. but the combination final and abstract can never exist. A class can only have one access modifier attributed to it. Protected and private access is often seen in method and variable declarations.1. the modifiers strictfp and final can be used simultaneously. They fall into two categories: • Access modifiers: public. Multiple non-access modifiers can be used under strict conditions. protected. Java has four access controls. The default or package access control level is obtained when none of the specified access modifiers are used. and abstract Access modifiers are used to restrict or allow access to a created class. Only the default access or public access will work for classes. private • Non-access modifiers: strictfp. and access certain methods and variables found within the class. Class Modifiers Class modifiers are added before the class declarations.5. Remember that final classes cannot be subclassed. while abstract classes can.4. For example. 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. The access of a class provides visibility to create an instance of the class. 28 . Non-access modifiers can be added to the access modifiers in any combination. • Public access – a class can be accessed by all classes within all packages without any restriction. This visibility is available to another class.

They specify a particular feature (class. • The only access modifier permitted to non-nested classes is public. including: • • • • the class its variable its methods and constructors 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. 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. variable or method) which is static.2. • A feature can only have one access modifier. final or transient.5. private and protected. 29 . data or classes. Access modifiers are: public. variable or method and are Java keywords that give the compiler information about the nature of code. Modifiers Modifiers control the behavior of a class. Access modifiers dictate which classes are allowed to use a feature.4.

variable.• If no access modifier is assigned. 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. the access is default. The protected modifier allows less accessibility than public. Default features are accessible to any class in the same package as the original class. or method by any Java program without restriction and can be overridden by any subclass. The public modifier allows use of any class. A protected feature of a class is available to: • All classes in the same package • All subclasses of the class owning the protected feature. but more public than default. Features outside of the original class package are not accessible and classes outside of the package cannot access the features within the package. but not from inherited fields of other instances • An instance may call protected methods inherited by its superclass. The private restricts use of any class. Rules for overriding access: 30 . 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. but not from other instances Java specifications do not allow methods to be overridden to be more private. The default is used when no access modifier is specified. Only variables and methods can be declared protected.

or public method. forcing deference of implementation to subclasses. or public method. variables. An abstracted class may not be instantiated. • A protected method may be overridden by protected. not to individual instances of a class. The final modifier can be applied to classes. • A default method may be overridden by default. Static features belong to a class. protected. 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. or public method. • • • • • The abstract modifier can be applied to classes and methods. The data owned by an object that is referred to by a final object reference variable can be changed. A final object reference variable cannot change. protected. Final classes cannot be subclassed. The principles governing modifier final: Final features may not be changed. default. and methods. They allow variables to be static: x will always be x no matter how many 31 . and methods. • A public method may be overridden by a public method. Final variables cannot be modified once a value has been assigned.• A private method may be overridden by private. • A final method cannot be overridden.

network communication and platform-specific functionality. Instance methods have an implicit variable named this. which references the object executing the method. Native code is written in non-Java language and compiled for a single target machine type. 32 . it must specify which instance of its class owns the variable or executes the method. no ‘this’ exists. Attempting to access an instance variable or call an instance method within a static method. The native modifier only applies to methods and indicates that the body of a method can be found elsewhere. If a static method must access a nonstatic variable or method. the library holding the native code should be called as early as possible. It is used to port Java to new platforms to support GUI components. To avoid delay. They can be invoked before a class instance is constructed. Static variables are referenced through a reference to any instance of the class or though the class name. With nonstatic code. Static methods are not allowed to use nonstatic features of their class and are not concerned with individual instances of a class. The compiler assumes the intent is ‘this’. an error message occurs. With static methods. specifically in a library outside of the Java Virtual Machine.instances of x occur. a variable or method can be referenced without specifying which object’s variable or method intended. Static Initializers are static code contained in a class but does not exist within a method body. The code is executed exactly once when the class is loaded and that execution happens in order of appearance. They are a block of initializer code surrounded by curly braces and labeled static. Native code should be loaded and available to JVM or a delay will happen.

They allow many objects to be written to a destination outside of the JVM. A source file namespace contains the names of all classes and interfaces in the source file’s package. all Java security mechanisms have no effect. The synchronized modifier is used to control access to critical code within multithreaded programs.6. Once written to an outside destination.The transient modifier applies only to variables and are not stored as part of the object’s persistent state. Items can have short names and long names. 4. Importing Import commonly means to bring something from an external space into an internal space. Short names allow the statement: 33 . importing refers to bringing the import class name into the source file’s namespace. The volatile modifier is typically found in multiprocessor environments. A namespace is an abstract entity such as a directory or a source file containing items with unique names. Functionality 4. Short names are used within the namespace and long names outside the namespace.1. In Java.6. as well as when variables may be modified asynchronously. The volatile modifier only applies to variables and identifies the variables so the compiler can take special precautions.

With static imports. Can be stated as myColor = BLUE.Vector vec = new java. • Code creation by multiple programmers can create undisclosed dependencies. Static imports eliminate the problems associated with constant interfaces and provide access to static data and static methods.java.BLUE.Vector(). constant interfaces will have some drawbacks: • Interfaces are for defining types.util. but constant interfaces only contain data. 34 . Any class implementing the interface does not require a prefix to the constant. To be stated as: Vector vec = new Vector().util. Many packages or applications define constants needed by more than one source file. so myColor = Color. constants are associated with the proper classes. Constants are put into interfaces. Constant interfacing is used to eliminate prefixing when associating constants to multiple classes. Unfortunately. The result is a slight compile-time cost and zero runtime cost. The static import facility allows static data and methods to be imported as well as classes.

3. The reference can be the address of the object. those improvements may prove to be damaging to the new code. The static import facility is aware of packages and access modes.6. objects are not dealt directly by Java programs. Encapsulation The benefit of object-oriented programming is the ability to use another programmer’s code. Unfortunately because of the inheritance concerns. which refers to the real data (double indirection). allowing changes to the argument value by the method to not affect the original data. To static import a class from a different package. 4.2. default. the class name must be prefixed with the package path. the constructor creates a bit pattern (value) that uniquely identifies the object.6. but not private. Encapsulation allows changes to be made to implementation code without breaking any dependent code. protected. During the construction of an object.using the keywords import static. 4. This bit pattern becomes a reference to the object. Only public data can be imported from classes in external packages. As a result. the reference is actually the address of an address. Encapsulation provides: • Maintainability • Flexibility • Extensibility 35 . In most JVMs. Data imported from other classes in the same package may be public. The star notation can allow importing all accessible constants from a class. Argument Passing When arguments are passed into a method call. when the original code is improved. a copy of the argument is actually passed.

6. the programmer is saying that ‘this object is a type of that object’. Through encapsulation.4. the programmer is saying that ‘this object is referenced by that object’. This is done through the use of public and private access modifiers. Inheritance Inheritance is a standard feature of Java. reuse of smaller. 4. anywhere a particular value can be used. as well as. distinct classes. This is often seen when creating specialized classes which perform a specific operation. 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. 36 .• These properties are possible by forcing the use of public accessed methods instead of direct access to instance variables and protection of instance variables. Inheritance can be seen as either an IS-A or HAS-A relationships. a method call should be used which will return the required type of value. where one code will inherit the methods and variables set by another code. Therefore. The IS-A relationship is expressed using the ‘extends’ or ‘implements’ keywords. the programmer has the ability to define which methods and variables can be publicly accessed and which are hidden. Each time these methods are inherited outside of it creates an instance of the code. the focus is on usage rather than inheritance. With HAS-A relationships. This encourages the creation of primary code which is not performing too many operations without making calls to other classes. In an IS-A relationship. In addition.

are polymorphic because they can pass an IS-A test for their own type and for the class Object.6. In Java. Method locals and arguments are allocated space when initiated and discarded when the method exits. Polymorphism If a Java object passes more than one test for IS-A relationship.4.6. All Java objects.6. the object is considered polymorphic. Garbage Collection Garbage collection is a mechanism in Java for managing data storage and allocation of space. Recovery of space allocated on the heap is managed by garbage recovery. 4. If A extends B and B extends C. a subclass which passes a IS-A test with its superclass can have either the subclass or superclass referenced. Objects are allocated space on the heap and limited by the amount of memory available on the host. 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. A and B can be referenced instead of C because C has an IS-A relationship with both A and B. allocated memory is not explicitly freed. The advantage of polymorphism is the ability to write reference variables which are assigned to any object assigned and extending the declared reference value.5. The runtime system does this with a low-priority 37 . except objects of the type Object. In other words.

Converting is done implicitly and will only allow widening conversions. Conversion is an automatic. non-explicit type change. Primitive data types include ints. Conversion of a primitive occurs during: • Assignment • Method call • Arithmetic promotion 38 . Data values can change type either explicitly or implicitly. Casting is explicitly performed and allows widening and narrowing conversions: casting must be done to conduct narrowing conversions. Storage is recovered when the garbage collector determines that it is definitely no longer required 4. Compile-time and runtime rules must be observed. while object data types include hundreds of classes and interfaces provided by the Java Developer Kit. Converting and Casting are two styles of type changes. the expression is prefixed with the new type name in parentheses. floats.7. Casting provides an explicit type change of a value. plus classes and interfaces developed by independent programmers. Those changes happen upon request or at the initiative of the system. Booleans. To cast into a new type. Narrowing runs the risk of losing information. Broad categories of Java data types: primitives and objects. Converting and Casting Every Java variable has a type.6.thread referred to as a garbage collector.

Widening conversions are permitted. float or double From char to an int. float or double From long to a float or double From float to a double Any conversion not represented above is considered a narrowing conversion. Method Call happens when a value of one type is passed as an argument to a method that expects another type. long. Rules that govern method-call conversions are the same as assignment conversions. but narrowing conversions are forbidden. Literal values can cause compiler errors using widening conversion. 39 . The assignment conversion rule is relaxed when assigning to a narrower primitive type. int. • Widening conversions allow a non-boolean to be converted to another non-boolean type. Widening accommodates: • • • • • • From byte to a short. float or double From int to a long. The general rules for primitive assignment conversion are: • A Boolean cannot be converted to any other type. Widening conversions change a value to a type accompanying a wider range of values without losing information about the value’s magnitude. but not narrowing conversion.Assignment occurs when a value assigned to a variable has a different type from the original value. long. long. • Narrowing conversion will not allow a non-boolean to convert to another non-boolean type. float or double From short to an int.

or char. unless ++ or . All conversions of this type are widening. • Else if one operand is a float.Arithmetic Promotion happens while the compiler is interpreting the different kinds of operand in the expression. Rules governing arithmetic promotion are separated between unary and binary operators. Only casting will allow a narrowing conversion. the other operand is converted to a long. • Else both operand are converted to int. 40 . Casting explicitly requests a conversion and allows the widening and narrowing an argument. • Else if one operand is a long. the other operand is converted to a float. it is converted to an int.. The rules for binary operators are: • If one operand is a double. • Booleans cannot be cast into another type. nor another type cast into a Boolean. and no conversion happens. The rules governing casting of primitive types are: • Any non-boolean type can be cast to another non-boolean type. The rules for unary operators are: • If the operand is a byte. • No conversion is done in all other cases. the other operand is converted to a double. Casting a value to a wider value is always permitted and never required.are used. short. This type of conversion is done by the system within the arithmetic statements.

interface. method-call conversions and casting. or an array Newtype can be a class. Object Reference Conversion and Casting Object Reference Conversion uses assignment conversions. Oldtype can be a class. Newtype y = x. interface.4. 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().8.6. or an essay 41 . It is more complicated because more possible combinations of old and new types exist.

Object Reference Casting is much like primitive casting. with general rules for testing: • When Oldtype and Newtype are both classes. 42 . both arrays must contain reference types and the conversion must be legal. • Casting can always be done between an interface and a nonfinal object. one class must be a subclass of the other. • When Oldtype and Newtype are both arrays.Below are rules for specific conversions Oldtype is a class Oldtype is an Oldtype is an array interface Oldtype must Newtype must be an Newtype must be an be a subclass of Object Object Newtype Oldtype must Oldtype must be Newtype must implement interface a subinterface of be Cloneable or Newtype Newtype Serializable Oldtype must be an Compiler error Compiler error array of some object reference type Newtype is a class Newtype is an interface Newtype is an array 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.

7. others during execution. the class of the converted expression must implement Newtype. Common runtime rules include: • If Newtype is a class. 43 . the class of the expression being converted must be or inherited from Newtype. There are three basic forms of statements: • Assignment • Condition • Iteration Statements and expressions can be viewed within a code block and are grouped syntactically between curly braces. 4.• 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. or result and are used in statements. Expressions are evaluated to produce a value. Some rules for casting are enforced at compiler time. • If Newtype is an interface. Algorithm Design Statements are found within methods and classes to describe the activities of the program. while the class of an object reference by the variable is known at runtime.

Assignment Assignment statements are the simplest form of statement.1. } In the statement above. The syntax of a conditional statement would be: if (condition) statement. the value Y is assigned to X.7. [ else statement. The code below identifies an assignment statement: { X = Y. Condition Conditional statements are in the form of if/else clauses.2.4. They “assign” a value to a variable or set parameters to an object. making the two expressions equal. ] 44 .7. 4.

the second statement. and it allows multiple statements to be used when a condition is met. the first statement is used. if the condition is met. a condition is considered a Boolean expression where a true or false value is the result. For this reason. 45 .In this example. A conditional statement does not require the else clause. but if the condition is not met.

or enhanced form of the ‘for’ statement allows the iteration over an array or collection of values. The syntax of the code is: do statement. Iteration Statements using ‘do-while’ loops have a conditional attribute but are considered iterative statements. A simpler. When the statement should not be executed but the condition still monitored. and continual execution is dependent on the declare condition remaining in place. a ‘while’ statement may be used by itself. The syntax of the statement is: for ( varDeclaration : iterative ) statement. The syntax of the ‘for’ statement is: for (initialization.3. The ‘for’ statement is similar to the ‘do-while’ loop except the condition is evaluated before executing the activity. the statement will always be executed at least once. while (condition). condition.4. 46 . This statement is used to declare or initialize variables which are limited to the scope of the condition. incrementor ) statement. In this loop.7.

] } The break statement is used to break out of a conditional statement loop by stopping the current block statement. [ case int constantExpression : statement.7. an optional default case is used. 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. The syntax of a switch statement is: switch (int expression) { case int constantExpression : statement. each branch of the statement is evaluated to a different constant integer value as a condition. 4. a switch statement can be used within the argument to identify which alternative to use. Operators 47 . In this situation. ] … [ default : statement. If none of the conditions are matched.4.When a number of alternative integer-type results are possible.

some operators will be handled before others as they have greater precedence. Java operators behave differently than operators in other languages. Operators usually carry precedence. that is. Category Unary Type Increment and decrement Unary plus and minus Bitwise inversion Boolean complement Cast Multiplication Division Modulo Addition Subtraction Ordinal Object-type Equality Operators ++ -+ ! () * / % + << >> >>> < <= > >= instanceof == != &^| && || ?: = op= Arithmetic Shift Comparison Bitwise Short-Circuit Conditional Assignment 48 . However. Java operators are also used to perform object-oriented cast and instance of operations. Operators perform traditional arithmetic and logical operations.Operators are a key aspect of any programming language.

1. a value is assigned to a variable. The scope of a variable refers to the life of a variable: that is.8. • Local variables – Tied to a method and remains as long as the method remains within the stack. A variable has bits representing a numerical value. • Block variables – exists as long as the code block is executing.4. Algorithms 4.8. The designated type of the variable acts as a place-holder for bits. A reference variable is a variable which refers to an object and the bits represent the path for getting to the object. 49 . 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. how long the variable is good for in the program. Variables Within Java. • Instance variables – created when a new instance is created and lasts as long as the instance lasts.

3. Instance variables can be primitive. public static method(Y) { } } 4. reference an object.2. Instance Variable Instance variables are defined at the class level and initiated to a default value when a new instance is created.8. The local variable will be found within the curly braces of both the class and the method.8.4. } } 50 . such as: public class X { int var. Local Variable Local variables are defined within a method and include the parameters of a method. 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. public class X { public static method(Y) { int var. They can be called automatic variables which must be assigned a value in the code.

The type void will return no value. A local variable and an instance variable can have the same name. the local variable will hide the name of the instance variable within the scope of the method is in process called shadowing. which allows explicit reference to the current object. Instances can call a static method. they can be called by name through the call name and without any objects around. Methods will take arguments which are supplied by the caller and return a value based on those arguments.4.All local variables must be explicitly initialized before they are used because they do not have default values. Methods Methods are found within the body of a class and are executed when the method is invoked or called. or the type void. 51 . The return types they may specify are a primitive type. As a result. If this occurs. Shadowing is often recognized when the special reference ‘this’ is used within the method. They will always specify a return type. a reference type. but cannot directly see or call those members within an instance. The this reference allows the reference of the enclosed object to be passed to some other method. They can be accessed directly by other static members of the class.8. Static methods belong to a class and not to the instances of that class. 4.

Increment and Decrement Operators are used to modify the value of an expression by adding or subtracting 1. Redundant brackets are used to drive how particular expressions should be evaluated. 4. The order of execution is specified by precedence and associativity. then ++x = 11 if x = 10. Unary operators use only a single operand. particular attention is used to ensure evaluation of the argument is performed correctly. such as division which uses two numbers. Unary Operators Most operators take two operands.9.9.4.x = 9 52 . the operations are performed. then -. Operators One goal of programming is to keep expressions simple. Evaluation is done from left to right requiring the leftmost expression to be evaluated first. When operands have been evaluated. if x = 10.1. however. Associativity is dealt with by going right to left. the order of evaluation is not specified by precedence or associativity. The order of evaluation of operands in an expression is fixed. therefore when creating arguments or using operators.

- Initial Value of x Expression 10 y = x++ 10 y = ++x 10 y=x-10 y=--x Final Value of y 10 11 10 9 Final Value of x 11 11 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.x post-increment and post-decrement: x++ and x. such as driving I/O ports. Within Java.Operators can position before and after the expression to affect operation. 53 . 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. pre-increment and pre-decrement: ++x and .. 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.

but can be used to allow the body of the if() statement and the else statement to be swapped leading to cleaner and shorter code. 4. + and * can be used with the equal sign to combine calculations and assign functions. there are two conditions in place: • • Assignment operators include an implicit cast.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. not twice.9. The operators. Side effects of x are evaluated exactly once. 54 . 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.2. Assignment Operators Assignment operators set the value of a variable or expression to a new value. Simple assignments use the equal sign (=). as in: x += y or x = x + y x *= y or x = x * y When using assignment operators.

Underflow refers to the forced condition where a fractional part of an integer is lost: 3. Subtract the magnitude of the right operand by the magnitude of the left one. this happens more when dividing then multiplying. Generally applied to integers.8 55 . the statement would read x = 9 % 5. Overflow refers to a larger numerical result than can be represented by the maximum number that can be represented: 64 * 4 = 256 or 100000000 in binary code.9. 64 * 4 = 0 since only the low-order eight bits of data can be represented. this happens more when multiplying then dividing.85 will become 3. A Modulo Operator will provide a value that is related to the remainder of a division. However stored as a byte variable. Traditionally. with a result value of 4.4. Typically. Modulo example: 13 % 5 6. Typically. Repeat until the magnitude of the result is less than the magnitude of the right operand. but can be applied to floating-point numbers with the following procedure: 1.4 % 2. Using Modulo operators. 2.3. a division of integrals such as 9 divided by 5 would result in an answer of 1 remainder 4. Arithmetic Operators Multiplication and division operators all primitive numeric types and characters. Two situations can occur when using these types of operators: overflow and underflow.

absolute values are used to obtain a result which is negative. Overloading applies when the same name is used for more than one piece of code.8 so 6. 56 . A + expression with two operands of primitive numeric types. Concatenation is the process of joining string objects.8 = 0.8 = 0.8 < 2.13 – 5 = 8 8–5=3 3 < 5 so 13 % 5 = 3 6. though the + operator can be uniquely applied when one operand is a string object.6 3.4 % 2.8 The sign of the result is determined by the sign of the left operand. 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.8 0. When applied to floating-point types.8 = 3.4 – 2. the result is: • A primitive numeric type • At least int. Addition and subtraction are applied to operand of numeric type. the result might have a fractional part.6 – 2. When applied to negative numbers. Operator overloading is when an operator can take different operand types.

Java defines two NaN values: Float. minus infinity. NaN values are issued to identify calculations that have no value in ordinary arithmetic.Object type to object method. Considered non-ordinal. Calculations involving infinity or square root of negative numbers can result in a NaN value. and NaN values.NaN and Double. even if it is arithmetically incorrect. • Integer calculations that cause overflow will provide a result. or any value of x including NaN will return false when using comparisons. • Integer division by zero results in an ArithmeticException.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 .toString(). 57 . • All other arithmetic will provide a result. primitive type using Integer. NaN. Arithmetic errors can occur when: • Overflow and underflow can occur when operands are too large or too small. Floating-point calculations can return a NaN. • Floating-point calculations represent out-of-range values using IEEE 754 infinity. typically a truncated bit pattern.

will return a boolean result of true or false. including char. while the right side of the argument must be a class. 58 . such as with dissimilar numeric types. Reference comparisons compare the memory locations of two objects. The left side of the argument can be any object reference expression. rather than the objects themselves. Ordinal comparison cannot handle boolean or class-type operands. the value is seen as the reference to the object. Comparison Operators All comparison operators. or relational operators.9. 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 equals() method should be used instead of the == or != operators when comparing content or semantics.4. A compiler error occurs when the left operand cannot be cast to the right operand. Object comparisons compare the data of two objects. interface. or array type. therefore comparisons of two objects will look at the references to the same objects. Object-type Comparison uses the instanceof statement which determines whether or not a given object is an instance of a particular class. Ordinal Comparison is used to test the relative value of numeric operands.4.

any other combination produces 1 Operand 1 0 0 1 1 Operand 2 0 1 0 1 AND result 0 0 0 1 XOR result 0 1 1 0 OR result 0 1 1 1 59 . 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. eXclusive-OR (XOR). 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.5.9. Bitwise Operators Bitwise operators provide operations for bitwise AND. and OR. These operators apply to integral types. They follow three rules: • AND statements will produce a positive result if both sides of the argument are the same: 1 AND 1 produces 1.4.

the result is false without regard to the right side.Using Boolean expressions with bitwise operators. These rules allow evaluation to stop at the left side of the argument. 60 . if the left operand is false. the result is true without regard to the right side. They are central to null-reference-handling and follow two basic rules: • For AND operations.6.9. Short-Circuit Logical Operators Short-Circuit logical operations are used to provide logical AND and OR operations on boolean types. the results are: Operand 1 false false true true Operand 2 false true false true AND result false false false true XOR result false true true false OR result false true true true 4. • For OR operations. They are similar to & and | operators with the ability to “short circuit” a calculation to improve efficiency. if the left operand is true.

Exceptions Programs have a specific goal in mind. Conditional Operators Also known as ternary operator. Exceptions are occasions where an abnormal execution of the program happens. Exceptions are either caught or declared All exceptions come from the java.lang.Throwable superclass.7. Condition Operators are sometimes prohibited by company style guides.9. a = x is evaluated: • if true. the conditional operator consists of three operands and acts like if/then statements.10. • Value assigned to a will be b if x is true. Expressed as a = x ? b : c. a = c The rules to follow using conditional operators include: • Expression types for band c should be compatible. a = b • if false. When exception objects are constructed: • A text message is stored inside the exception describing the 61 . and c if x is false. The circumstances of abnormal behavior are called exception conditions and represented as objects.4. 4. • Expression type for x should be Boolean. • Expression types for b and c should be assignment compatible with the type of a.

The catch block handles the exceptions. multiple catch blocks must be 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 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. getMessage() is used. printStackTrace() To retrieve the text message.circumstances that caused the exception • A visual display of the JVM’s call stack at the moment the exception is created and is available with the method. The catch block starts with a declaration within parentheses and consists of a type and a name. as its scope is within the braces. When multiple exception types are thrown. The type in the declaration must match the type thrown by the try code. 62 .throwing code } catch (Exception_type name) { //Exception-handling code } The try block contains code that throws exceptions and different exception types. The name does not have to be defined.

Processing starts with checking if the exception came from a try block. If there is no compatible catch block. A throws declaration can be combined without restriction from other modifiers. except when the block throws its own exception. If from a try block. the JVM focuses on the method that called the current method and continues until the exception is handled. If an exception does exist. the 63 . each catch block is checked in the order of appearance for compatibility with the exception. If the exception is not compatible or not thrown by a try block. 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. Declaring a method exception can be done by end a line with the throws keyword and an exception type. usually from: • The death of a the current thread • Execution of System. Compatibility refers to the exception being an instance of the class declared at the beginning of the catch block. the JVM processes it. A try block is not always needed. When an exception happens.If no exception exists. If compatibility is found with a declared exception.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. the try block runs to completion and execution continues after the last catch block. Multiple exception types may be declared using commas to separate the exceptions. the JVM checks the declared exception types.

5. 6.JVM prints out the exception’s stack trace and terminates. development and debugging of code • Should not be handled using catch blocks Any exception not a runtime exception is a checked exception. Two types of exceptions can occur: checked and runtime. Decide if the exception should be checked at runtime 2. Descriptive strings are the test that is returned when the exception is caught. Exceptions should be thrown immediately after construction to accurately represent the thread’s status at the time it was 64 . Rules for runtime exceptions are: • Can always be avoided • Must be handled during design. 7. 4. Choose the exception type 3. Check API pages Use the class related to the situation you want to signal Or create an exception class Construct an instance of the exception type 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. 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.

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. The structure of cause on cause is called exception chaining. the Java compiler insists that all exception classes thrown by the new method must be the same as the exception class thrown by the original method. 65 .lang. A cause is another exception and they happen when a method handles an exception by throwing a different exception type. The message and cause is passed to the superclass constructor.thrown. Use the getCause() method to retrieve an exception’s cause. To override a method.Exception or subclass • Runtime exceptions should extend java. All checked exception types must be represented in the method’s “throw” list.lang. The process for creating exception classes is: • Decide on a checked or runtime exception • Checked exceptions should extend java. The return type of getCause() is Throwable allowing causes to have causes.

A compiler flag controls whether assert should be treated as an identifier or as a keyword. If true.11. Release 5. The mechanism can be enabled or disabled at runtime. If Expression2 exists. than an AssertionError is thrown. Expression1 must have a boolean type Expression2 can have any type When disabled. The format for assertions is: • assert Expression1. assert was used as an identifier.4 release of Java. nothing happens: if is false. it is passed to the constructor of the AssertionError and converted to a string used as the error’s message. • assert Expression1:Expression2. 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. Before 1. 66 .4. Assertions are typically enabled during development and disabled in production. Expression1 is evaluated.4. If enabled. Assertions Assertions provide a mechanism for verifying that a class’s methods are called correctly.0 of Java automatically treats assert as a keyword. the assert statement does nothing.

Postconditions are constraints that must be met before returning from a 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.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. and class invariants. Preconditions are constraints that must be met to enter a method.11. Constraints are typically functions of its arguments and the state of its object. method name and the exact sequence of its argument types. 4. use: • Overloading – re-using with different arguments and different return type • Overriding – re-using with identical arguments and return type To re-use method names. To re-use the same name for a method. a method is uniquely identified by the combination of its fully qualified class name. Overloading and Overriding In Java. the method should terminate immediately. certain conditions must be met: 67 . the method does not return. postconditions. Constraints are typically functions of its return value and the state of its object identify a failure within the method. If not met. If not met.1. Common form of precondition testing is argument range checking.

• In a strict subclass of the class defining the original method. no special conditions apply and the two methods are not related. the overriding method must have the identical return type as the overridden method. The distinctions between overloading and overriding are: • Overloaded methods support each other. Method Overriding defines a method with exactly the same name and 68 . and exception lists.• In an unrelated class. • 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. the argument list differs in terms of the type of at least one argument. identical arguments types and order must exists and the same return type must be achieved. an overriding method replaces the overridden method. accessibility. • In the class of subclass defining the original method. • Overloaded method may freely chose a return type. Overloaded methods can have different return types. • Overloading allows multiple implementations of the same functions to have the same name. overridden methods must have argument lists of identical type and order. The methods that perform different functions should have different names. The technique improves program readability. Overloaded methods can call each other for support. • Overloaded methods must have different argument lists. 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 of subclass for a different method and is used when several methods perform closely related functions under different conditions.

Method declaration in release 5 allows an argument list which includes a variable number of args of a particular type 4. • Checked exception types that are the same as those thrown by the original method can be thrown by the overriding methods. 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. additional behavior can be added to the overriding method. type. Constructors 69 . Constructors In a general sense.11. as well as follow the same accessibility and exception list rules. and order of arguments must be identical to those of the method in a parent class. inheritance allows the code and data which is defined in a parent class to be available for use in a subclass. however. • The return type must be the same as superclass’s return type or a subclass of the return type.argument types as a method in the parent type. The extends keyword requires a subclass be an extension of the parent class. • Accessibility cannot be more restrictive than the accessibility of the original method.2. • Methods marked final cannot be overridden. Covariant return types describe an overridden method which is a subclass of the return type of the superclass version. The requirements for overriding are: • Method name. Overriding methods must use the same return type as the method it overrides.

are not inherited normally and must be defined for each class within the class. They are fundamentally the same as any other class but are declared within some class.3. If no constructors are explicitly coded for a class. including methods with some differences. They can be declared in any block. Inner Classes Inner classes. 70 . the fully qualified name of the inner class retains as part of its name the name of the class enclosing it. A constructor is invoked with a call of the for new AnyClass(argument1. Member classes refer to classes defined within a class.. are used to provide additional clarity and make programs more concise. Constructors are defined with arguments to control the construction of the parent part of the object. 4. The superclass constructor must be called before any reference is made to any part of the object. Control of the constructor can be passed to the parent class using the keyword super. If there are no arguments.11. Scope and access define the complexity of inner classes. argument 2. Default constructors have public access if the class is public and default for any other access.). the constructor is called a no-argument constructor. Overloaded constructor versions are invoked using this(arguments) and must be the first statement of the constructor. There are no special considerations related to overloading constructors. or nested classes.. The super(arguments) must be the first statement of the constructor. Typically. a default constructor is automatically created by the compiler and the constructor is called a default constructor. One constructor can call another constructor using this(arguments). not a method.

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. To define a class within a method. • Methods of a static inner class can access static variables of the enclosing class. A new operation to construct an instance of an inner class can imply the prefix this. • An object created from an inner class within a method can have some access to the variables of the enclosing method. protected. there are three considerations: • Anything declared inside a method is not a member of the class but is local to the method. Access modifiers carry the same meaning for member classes as for other members of the class. public. • Anonymous classes are possible. Sometimes. This situation is available using the new operator and if it was a member method of the outer class. methods.Normally. that is a class with no specified name. 71 . 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. such as an unrelated class. therefore they are private to the method and cannot be marked with a modifier or static. or default access. or nested classes) can be marked with private. Members of a class (variables. an instance of an inner class from a static method or other situation may be created when a this object is not available. when an inner class is created. a preexisting instance of the outer class must act as context. A member class may be marked static and carries a meaning similar to applying static to a variable associated with a class.

Anonymous classes provide a convenient approach to avoid trivial naming of classes. To construct an inner class with arguments.Any variable can be accessed by methods within an inner class provided that variable is marked final. and first use of an anonymous class all occur in the same place. Anonymous classes should remain small. The definition. some conditions do exist The structure to declare and construct an anonymous inner class: new ClassName() [/* class body. A final variable is treated as a constant. */]. Anonymous classes are unique to method scopes. */] The structure to assign an object reference into a variable: ClassName anClassName = new ClassName() [/* class body. Anonymous classes do not need a name and are used to extend another class or implement a single interface. Specific constructors cannot be defined for an anonymous inner class. 72 . construction.

Though a constructor cannot be created within an anonymous inner class. Parts of an equals() method description are: x=x If x = y.11. When an anonymous inner class extends another class and the parent class has constructors that take arguments. 4. the initializer feature from JDK 1. Contracts and Conventions A contract is an agreement about the behavior of some of the class’ methods.1 can be used and will be invoked as part of the construction process.The structure to assign an object reference as an argument to a method: aMethod(new ClassName() [/* class body */]). The most common contracts in Java are: equals and hash code. a constructor from the parent class can be invoked by specifying the argument list to the construction of the anonymous inner class. the compiler cannot determine 73 . Contracts are used to ensure that a class can interact predictably with other classes.4. If the behavior is overridden. then y = x If x = y = z. then x = z The version of equals() inherited from Object used the == operator to test for equality.

Though not part of a contract. they must have equal hash codes. 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. two unequal objects can also have equal hash codes. where xxx is the property name. • Underscores are not allowed. All subsequent letters are lowercase except for the first letter of a new word. where xxx is the property name. 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. 74 . Naming conventions are contracts that specify how a method’s name relates to its behavior. • A method that returns a value of a property is named getXxx().adherence to the contract. If two objects are equal based on their equals() methods. Violation of the contract while attempting to benefit from the contract will result in elusive bugs in the programming. Programming hash codes should balance between detecting uniqueness and running efficiently. A naming convention concerns properties of objects. • A method that modifies the value of a property is named setXxx().

Object class • Java language and JVM Threads execute with calling its start() method which doesn’t cause the thread to run. construction of threads can be done by extending Thread and implementing Runnable. A thread can be executing or in several non-executing states.lang. The scheduler determines which thread is running on each available CPU at any given time.4. The start() method registers the thread with system code called the thread scheduler/. To execute the execute the run() method of some object other than itself. When threads execute. A single-threaded Java program has one entry point (the main() method) and one exit point. the Thread class must be subclassed and implement the run() method.11.lang. Therefore. A multithreaded program has a first entry point (the main() method) followed by multiple entry and exit points for other methods. To execute its own run() method. Threads Threads create the illusion that a single Java Virtual Machine looks like multiple machines running simultaneously. they are executing a method called run(): either its own run() method or the run() method of some other object. the object owning the run() method you want must be specified. the thread is finished and considered 75 . When the run() method return.5. Thread support resides in three places: • java. an instance of the Thread class must be constructed.Thread class • java. but makes it eligible to run. Then the Thread constructor is called.

Call the set Priority() method to set priority. the thread cannot be started again. which forcibly terminates a thread but this is not a recommended practice. The data and methods of a thread are still available through a thread is dead. 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 . The thread scheduler considers priority when deciding which thread to execute. The default priority is 5. Threads created by daemon threads are initially daemon threads while threads created by 76 . Thread methods include a stop() method. from 1 to 10. Daemon Threads are infrastructure threads which are created automatically by the JVM. Threads with high priority take precedence over threads with lower priority. When an application begins. Thread methods can be forcibly terminated using interrupt(). Call the getPriority() method to return a thread’s priority. Once dead. only one nondaemon thread is in existence: the main thread.dead.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.

Sleep can be interrupted. whereupon it moves to a ready state. Threads have no control over when it is suspended. the thread does not move to a running state. When sleep is finished. Yielding allows a time-consuming thread to permit other threads to execute. The JVM runs until the only live threads are daemon.non-daemon threads are initially non-daemon threads. 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. 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. 77 . one thread can make another thread unready for an indefinite period of time. When sleeping. The format of the thread is suspend() and the resume() method is used to move the thread out of suspension. If no other threads are in a Ready state. The format is yield() and the method is a static method of the Thread class. the yielding thread can continue executing immediately. the thread may have to wait before executing again. Sleep is a static method. but to a ready state until the scheduler moves it to running. If other threads are in a Ready state. The suspended thread becomes ready when some other thread resumes it. Controlling threads refers to moving threads from one state to another state. A yielded thread goes into Ready state. When suspending. The status of daemon threads can be changed before execution by calling set Daemon() method.

Read() is a blocking method. value. a thread must acquire the object’s lock. functionality. Every object has a lock which is controlled by only one thread. waiting. the attempting thread goes into the state. 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 notify() and notifyall() methods move waiting threads out of a waiting state. To execute synchronized code. The method is blocked from continuing until the desired item is available. and other monitor states are used when a method must wait for the availability of data. Seeking Lock and becomes ready when the lock becomes available. When a thread owning a lock moves out of the synchronized code. These methods are implemented in the Object class. not the Thread.Blocking. 78 . Locks control access to the object’s synchronized code. The wait() method can only be called in synchronized code. If the lock is under another thread’s control. Threads can be blocked if a wait() call is issued or a lock for a monitor fails to be acquired. or such.

Methods from String Class The Java String class. A class lock will control access to all synchronized static code in the class.lang. once a string object is created. Deadlocking describes a class of situations that prevent a thread from executing. or java. is fundamental to using Java. The string itself will be found 79 . A number of operations on the object can appear to change the characters or length of the string. such as a thread is waiting for a condition but something in the program prevents the condition from arising. they simply return a new String object. it cannot be changed.12. The characters are stored within a regular array. all classes have a lock.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 statements • 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. by the String object will only allow access to this array from its own API. but in reality. As a result Strings are immutable: That is. 4. A string object will encapsulate a sequence of Unicode characters.String. Strings can be identified by double quotes.

The substring() method will return a portion of the string. String concatenation can be used to combine different strings. 4. Strings can be edited: more specifically. Key Methods The charAt() method allows the characters of a String to be accessed like an array.13. The replace() method will allow a substitution of portion of the string with another 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.1.12. or one at a time. The startswith() and endsWith() methods can be used find substrings within a string.within the quotes and assigned to a String variable. specifically the beginning and end of the String. Java Development Fundamentals 4. Packages Packages are organized to create programs. The trim() methods is used to remove the leading and trailing whitespace from the string. A program may have 80 .1. a new string can be created which is based on the original string. 4.13.

lang. including subpackages and top level class types and top level interface types. 81 . A package will consist of a number of compilation units which has automatic access to all types declared within the package. applet.several packages contained within it. namely class and interface types. A naming convention for a fully qualified name of a subpackage is packagename. io. and util.subpackagename. Packages are stored in a file system or database. Within the compilation units of the package are the declared members of the package. The predefined package java has subpackages called awt. The syntax of the compilation unit is: CompilationUnit: PackageDeclaration(opt) ImportDeclarations(opt) TypeDeclarations(opt) The syntax of a package declaration is: PackageDeclaration: Annotations(opt) package PackageName . lang. A package cannot contain two members of the same name. Each package will have its own set of names of types within it. net. 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 declaration is created within a compilation unit to associate the compilation unit with the package. The compilation until will automatically import all public types declared within the predefined package java.

Importing Packages The import declaration enables a static member or named type to be referenced by a simple name. 4. “javac” Command 82 .13. There are four types of import declarations: • Single-type-import – uses the canonical name of a single 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. since only one unnamed package is observable at a time based on the current directory. If the import declaration is not used.2. This unnamed package cannot contain subpackages. the fully qualified name must be used. Though Java can support than one unnamed package. the compilation unit is considered part of an unnamed package. If a package declaration does not exist. but are optional.The annotations on a package declaration are restricted to one per package. The package name must be the fully qualified name of the name. Unnamed directories are typically stored within each directory.3. 4.13. it is required to support only one unnamed packaged.

by default.class files.The compiler used in JAVA is invoked using the javac command.class file into the same directory as the .13.class file to be stored and the directory which to store the file must be specified: the syntax being: javac – d directory source/file 4.4. the . The compiler will. When working larger projects. Classpaths Classpaths are lists of directories where classes are found. the –d (destination) option with the javac command will instruct the compiler on which directory to place the . place a . 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.class and . To do this.java source file.java files. 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 83 . To complete the command. it is reasonable to separate the . The ‘javac – help’ command can be used to obtain a summary of valid options.

To distinguish between multiple paths.The classpath option allows the programmer to define which directories should be searched for classes. the colon (:) symbol is used as a delimiter between paths.) to define the current directory. the java and javac commands must work in the same way: • Both must have the same list of directories to search.class file found is used. By default. 84 . Therefore if classes with duplicate names are found in the multiple directories. it is done from left to right of the listed directory. • The list of directories must be in the same order. the first . The construction of an individual directory location required forward slashes to define the different branches in the path. • Directories containing classes standard with J2SE are searched first followed by directories defined by classpaths. the search is completed. When classpaths are searched. must be told to search the current directory by using a period (. Any number of directories can be listed in the option command. • Once the desired class is found. therefore. the order of the directories in the command will provide different results. The consistency of the shortened command with the javac command prevents its use in every situation. When searching for classes. the java and javac commands will not search the current directory. The java command will allow the classpath command to be abbreviated to –cp. • If multiple classes have the same name.

4. The following classes are found 85 . These classes can be used by programmers to use within their own programs without having to recreate the code.14.swing – defines the classes for a Swing GUI 4.lang The java. abstract Window Toolkit • javax.14.util – defines utilities and collections classes • java. The .io – defines input and output classes • java. java.lang – defines the basic language classes • java. Class Library The Java Application Programming Interface provides a collection of numerous classes that create the standard Java packages. 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. “java” Command The java command is used to invoke the Java virtual machine to run programs which have been compiled. Some of the most important packages found in the API are: • java.class file.net – defines networking and remote method invocation classes • java.4.1.class extension for the class file is not required because the java command assumes that a specified file is a .5.13.lang contains the fundamental classes required by the Java language and is imported automatically.awt – defines the classes for the GUI interface.

the value of the primitive type double wrapped into an object. Float. Long. • ClassLoader –responsible for loading classes. • Runtime – allows the application to interface with the environment.extends ThreadLocal to provide inheritance of values from a parent thread to a child thread. • Byte – the value of the primitive type byte wrapped into an object.UnicodeBlock – represents a family of character blocks in the Unicode specification. • Character – the value of the primitive type char wrapped into an object. • ProcessBuilder – used to create operating system processes.the value of the primitive type long wrapped into an object. Double.the common base class of all Java enumeration types. • Float . • Process – represents the operating system processes. Byte. and Short • Object – the root of the class hierarchy • Package – contains version information about a Java package’s implementation and specification. • Compiler – supports Java-to-native-code compilers and related services • Double .lang: • Boolean – the value of the primitive type Boolean wrapped into an object.in java. • InheritableThreadLocal<T> . • Class<T> . Integer. BigInteger. 86 . • Long . • Enum<E extends Enum<E>> .the value of the primitive type int wrapped into an object.Subset – represents particular subsets of the Unicode character set. • Integer . • Character. • Character. • Math – contains methods for performing basic numeric operations • Number – an abstract superclass for the classes BigDecimal.the value of the primitive type float wrapped into an object.instances of the class Class which represents the classes and interfaces running in a Java application.

• StackTraceElement – an element in a stack trace. • System – contains several class fields and methods which are useful.2. useful data structures and algorithms are available to programs and will reduce their programming effort.util contains a framework for collections. 4. java. The collections framework is a unified architecture for representing and using collections.14.util The java. • Thread – a program’s thread of execution.provides thread local variables • Throwable – a superclass of all errors and exceptions in the Java language. The framework allows a collection to be manipulated outside of its representation. • ThreadGroup – represents a set of threads • ThreadLocal<T> . • SecurityManager – allows a security policy to be implemented by applications. • String – represents character strings. tools for international programming.the value of the primitive type short wrapped into an object. legacy collection classes. data and time facilities. Since the structures and algorithms are stream-lined for high 87 . A collection is an object which represents a group of objects. • StringBuffer – a thread-safe. As a result of the collections framework. • StringBuilder – a mutable sequence of characters. event model. mutable sequence of characters.• RuntimePermission – used for runtime permissions. and miscellaneous utilities. • Short . • StrictMath – contains methods for performing basic numeric operations.

io package is responsible for information on system input and output through data streams.nio package uses a similar concept called channel. java. Streams are the most fundamental i/o in Java and represent a flow of data.3. The collection framework contains: • • • • • • • • • • • Collection interfaces General-purpose implementations Legacy implementations Special-purpose implementation Concurrent implementations Wrapper implementation Convenience implementations Abstract implementations Algorithms Infrastructure Array Utilities 4.performance. The framework also provides a common language for ensuring interoperability between unrelated APIS. There are several stream types available to Java from the java. rather than stream.io package: • InputStream and OutputStream – basic function for reading and writing unstructured sequences of bytes and used to build all other byte streams. 88 .14.io The java. while reducing any need to learn multiple related APIs. This flow of data. The java. or communication channel. has a writer at one end and a reader that the other. and the file system. their use will increase performance of the application. serialization.

An instance of a class implementing the Serialized interfaces will be able to save and restore from a stream. • BufferedInputStream. • FileInputStream. and PipedWriter – used in pairs to move database within an application.File class is used to encapsulate access to information about a file or directory. • InputStreamReader and OutputStreamWriter – used to convert bytes to characters or characters to bytes. PipedReader.• Reader and Writer – basic function for reading and writing a sequence of character data and used to build all other character streams. FileReader. 89 .io which automatically saves and loads the state of an object. Streams allow one-way communication in Java.io represent the ends of a simple stream. and FileWriter – allows reading and writing of files located in the local filesystems. • DataInputStream and DataOutputStream – enables the reading and writing of simple data types such as numeric primitives and String objects. PipedOutputStream. The java. the file class will store the information about those files appropriately.io. FileOutStream. • PipedInputStream. or metadata. Using streams to read and write file data. The classes in the java. • PrintStream and PrintWriter – simplifies text printing. and BufferedWriter – uses buffers to increase efficiency. Object serialization is another function of java. BufferedReader. • ObjectInputStream and ObjectOutputStream – enables the reading and writing of whole serialized JAVA objects. To create a bidirectional communication. tow streams are required: one of each type of stream. BufferedOutputStream.

awt package contains classes for creating user interfaces and using graphics and images. 4. buttons. The classes found within the package represent the windows.4. are called components.14. such as a button. Swing. tables.net Network applications are implemented using classes found within the java. which also includes: • • • • Abstract Window Toolkit (AWT) Accessibility 2D API Drag and Drop 90 . combo boxes.14. Objects within the user interface. java.swing package contains the classes used for Java’s graphical user interface toolkit. It can have a layout manager to control the visual placement of the components within the container. java. A container is a component that contains other components. and menus required to build rich client-side applications.14. trees.awt The java.swing The javax. Swing is a part of the Java Foundation Classes (JFC). java. The package has two parts for dealing with low level and high level abstractions: • o o o • o o o Low Level API handles: Addresses – network identifiers such as IP addresses Sockets – basic bidirectional data communication mechanisms Interfaces – network interfaces High Level API handles: Universal Resource Identifiers Universal Resource Locators Connections 4.net package.4.5.6. The Component class is the basis for all AWT components.

or EJB. The services handled by the EJB server include: • • • • • • • • Transaction Management Security Concurrency Networking Resource Management Persistence Messaging Deploy-time Customization 91 . the behavior of the bean can be modified without making changes to the underlying Java code.1. The idea builds on the concept of reusing Java classes to include the reuse of application functionality. is application development through building blocks. In most cases. 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. These components can be mixed and matched in various ways to provide different applications for the business. sold and used across the business worlds. Uses of Enterprise JavaBeans Enterprise JavaBeans.1. these components can be developed.5 Enterprise JavaBeans 5. Overview 5. Also called a bean.1. or EJB components.

5. Beans can be written once and deployed anywhere (The benefit is sometimes referred in the acronym WODA). An enterprise bean will implement at runtime and must be run within an EJB container. Characteristics of Enterprise JavaBeans Enterprise JavaBeans is a specification for a server and is a subset of J2EE. one must look first at the client/ 92 . if a new feature was required. JavaBeans. This means that the J2EE server must include an EJB container in order to run EJB. With EJB.1. 5. The most common javabeans are GUI components and run in a Java Virtual Machine. beans follow a naming convention used by development tools. or non-enterprise. Regular. the benefit remains the same. they are used at development time to improve efficiency in connecting different beans together. that is. or beans. the business had to wait until the application server vendor developed it. Benefits of Enterprise JavaBeans The greatest benefit of Java programming is its portability.2. Components for EJB cannot run outside of the EJB container.1. To understand the mechanics of EJB. a business was at the mercy of the application server vendor.3. the business no longer has to wait: either they can add the functionality themselves or they can go to another application server vendor. is an expression meaning reusable component. Though enterprise javabeans are reusable components too. In the early days of application development. With JavaBeans.

a servlet.server architecture. 3.1. There are three types of beans: • Entity – represents an item in persistent store. but is intercepted by the EJB object. 4. 5. • 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. Within the EJB container lays the business interface. and the Enterprise Bean. Clients can be any computer on the network. the services. or mobile device. Coding the bean class Coding the appropriate interfaces: home and component Creating an XML deployment descriptor Loading the ejb-jar file Deploying the bean on the server 93 . Building a Bean The process for building a bean covers five general actions: 1. On the server. 2. The term client encompasses any client object which is calling the particular enterprise bean on the server in question. the EJB object. 5. instantiate beans. It will pass all requests to the container which will authenticate clients. an enterprise bean. particularly a row in the table found in the database. The container will call the appropriate bean to fulfill the client’s request. a stand-alone Java app. The Client will never communicate directly with the bean. • Session – used for all other requests and typically represents a process.4. and initiate garbage collection. 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.

and the home interface is defined by the DD. with a few exceptions. the java. The component interface contains all the declared business methods. The name of the DD file must be ejb-jar. the class must be created separate and before the interface. As a result. all methods on the interface must declare a RemoteException. A create() method is used to return the component interface type and two exceptions must be called: CreateException and RemoteException. RemoteException statement must be imported: along with the javax. will create and distribute bean references to the client. The relationship between the bean class. Though the bean class can implement the component interface. The bean types contained within the bean class are of all three types of beans: Session.*. Each business method must correspond to a method in the bean class. ejb. component interface. The DD will tell the server the classes within the bean and how they are connected. The home interface is used by the client to request a reference to the component interface and. The syntax for the home interface is similar to the component interface. 94 . either the EJBObject interface or the EJBLocalObject must be extended. The EJBHome interface or EJBLocalHome interface must be extended. The client sees two interfaces.The bean class contains all the business methods that the client will call. The structure of the bean is determined by the deployment descriptor (DD). A single DD can be implemented for multiple beans within the EJB container. Additionally.rmi. the specification does not recommend this approach. from a client perspective. and Message-driven. Rather. To complete the coding of the component interface.xml. Entity.

interfaces. 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. Application assembly focuses on making a bean are usable part of an application. The bean class.Every bean must be placed into a JAR file. When combining multiple beans. and the deployment descriptor. 95 . 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 ejbjar file. The ejb-jar file is defined by the specification to house all items the bean is dependent on to perform properly. A single bean may be used as the entire application or multiple beans may be combined into a single application. The final step in the process is to deploy the bean on the server. The ejb-jar file can have any name assigned to it. This is performed in two steps: application assembly and deployment. Deployment involves naming the bean and putting the bean into the control of the server’s container. Additional information may be added to the DD during the application assembly. including classes. home interface class. The DD must be located in the META-INF directory. Tools provided by the server vendor are required to perform each step. 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.

Deployers are customize enterprise beans for a specific operating environment. they provide the ejb-jar files which contain one or more beans and a single deployment descriptor. the deployer will map the logical name from the bean provider to the actual name of the resource on the server. The purpose of the application assembler is to combine multiple enterprise beans into a single application and defining the behavior of the application.1. To the process. particularly in the areas of security and transactions. They are well knowledgeable in a particular domain. 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. The application assembler may also create clients and define the interactions between other components. a single deployment descriptor and information on application assembly. If a particular resource is required. The 96 . taking the deliverable from the application assembler and resolve any external dependencies that may be present.5. The bean provider is an expert in the business logic for a particular component within a particular domain. The Application Assembler will compile multiple enterprise javabeans provided by multiple bean providers.5. The deliverable for the application assembler is a single ejb-jar file containing one or more beans.

deployment tools. 5. The results of the method are seen on the referencing virtual machine. He knows the security users and roles for the system. how the server is configured.deployer is well knowledgeable about the specific operational domain the enterprise bean is located. RMI also uses object serialization to send objects and all the connected objects that they reference through graphs.6. the difference with RMI is its data structure which handles both the data and the methods for using the data. Its basic function is to obtain a reference to an object on a remote host and use that object on the existing virtual machine. and other low-level system services. Method invocation provides the fundamentals for communication in Java. transactions. or data transfer object (DTO). Remote Method Invocation (RMI) Enterprise JavaBeans use Remote Method Invocation (RMI).1. Similar to remote procedure calls (RPC) in C programming. The object must be serializable before it can be used remotely. particularly in the area of distributed objects. 97 . it happens on the remote host where the object resides. This is different from a nonremote object. and how the deployment descriptor should be interpreted for the environment. and the runtime environment for enterprise beans. They provide an EJB compliant server. When a method invocation is initiated on a remote object. The container and server provider is responsible for implementing the specification. Remote Method Invocation allows communication between virtual machines on different hosts. which is copied over the network to the requesting virtual machine.

The RMI has a registry used to identify a reference to a registered remote object on another host. the remote object should be an instance of the remote interface. The exception is required in case a networking error happens.RemoteException. UnicastRemoteObject class. rmi.Remote interface is extended for the application. For Java 5. This can be done by having the remote object extend UnicastRemoteObject. called the skeleton. which initiates the process to allow remote methods calls to pass remote references.0 clients and servers. The skeleton receives the remote method invocations from the stub and passes them on to the object.When a method is invoked on a remote object. The application must be running on the local host before the Java program using the registry is 98 . It is created when the java. the stub and skeleton classes must be generated explicitly and deployed with the application.rmi. For the client-side code. not an instance of its implementation class. The RMI runtime system will automatically export the class in order to begin listening for network connections.server. what is being called is some local code acting as a proxy for the object. the generation of stubs and skeleton classes are done dynamically: For earlier versions. 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.rmi. The client is able to find the initial object through the registry. The registry is implemented using the Naming calls and the rmiregistry application. This local code is code is called a stub. All methods in the remote interface must declare they can throw the java. With the object on the original host is another proxy. Remote objects are made available by using the java.

EJBObject rather than the java. the business interface for both is the same and is implemented by the receiving entity (stub and EJBObject. instances of remote objects can be created and bound to particular names in the registry. Once completed. respectively). the services provided by the server are invoked.ijb.started. When a client objects finds an object in the registry. The EJBObject will implement the remote business interface to handle remote calls from the stub. The difference between an RMI interface and a component interface is the extension of the javax.rmi. hostname. Essentially. As calls reach the remote object. and persistence. A business interface exists between the client and the stub and another exists between the stub and the remote object. The business interface is called the component interface in EJB. the EJBObject acts as the remote object which communicates with the Enterprise Bean.Remote. including security. 99 . a special URL with the rmi: protocol. The EJB container is considered the whole of the RMI heap. and object name is constructed. The RMI Naming class on the client talks to the registry and returns a remote object reference. In EJB. transactions.

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. Client View 5. flat file.5. 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 100 .2. or a database. 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.2.1. Implementations of JNDI can use either a server.

JNDI drivers reserved for directory service types are loaded at runtime. Remote Client API A primary key is required for entity beans. This process allows clients to navigate through directory services without knowing what services are present.Names are organized in JNDI in a hierarchy. In addition. which in turn provides an EJB object reference to an enterprise bean. The client uses JNDI to locate and obtain a remote reference to the EJB home. The client-side API in EJB is supported by the component interfaces and primary key. While the component interfaces and primary key are visible to the client. This binding is the result of storing either the object or a reference to the object in the directory service. The process begins with a JNDI InitialContext object. A name is bound to an object within the directory. A name can be any string or an object supporting the Name interface. The JNDI API will define the context which specifies where an object is searched. the bean class is not visible.2. 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. 5. The coding will change based on the implementation of JNDI by the EJB vendor. These drivers map to a specific directory service and are automatically loaded when a link to the directory service is chosen. 101 . JNDI enables the client to perceive the EJB server as a set of directories. a bean class and component interfaces are provided by enterprise bean developers.2. Directories have attributes associated to them which enable object searching.

mostly affecting the allowable return types and parameters.Remote types. Actual types are checked at runtime and cannot be checked by the compiler.ejb.Clients use the Remote Client API.rmi.1. the Local Client API can be used. The remote home interface and remote interface contain the supertypes of javax. it is assumed to be serialized: if this type is not serialized.Remote. 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. 102 . which are extensions of java. The remote component interfaces follow several guidelines. java. all clients will use the Remote Client API while only remote clients use the API in EJB 2. specifically the remote interface. String types. There are no special rules by Java RMI related to declared return types or parameter types.0. remote home interface. Remote interfaces are defined using Java RMI-IIOP and enforces compliance with CORBA.rmi. If a type is not a java. The Local Client API provides local component interfaces.rmi.2. an exception will be thrown. Java RMI allows actual types to be used. If the enterprise beans are located in the same EJB container in EJB 2.Remote type during runtime. Two types of return and parameter types exist: • Declared – checked by the compiler • Actual – checked at runtime. or serialized types. In EJB 1.EJBObject.ejb. The restrictions and overhead normally attributed to the Remote Client API are not present.EJBHome and javax. but they must be primitives. and the Java RMI. These interface subtypes must adhere to Java RMI specifications.0.

3. The stub is serialized and passed by value when a remote reference is passed. Objects implementing Remote are passed as remote references. Arguments are remote references passed into the create() method and the EJB object stub pointing to the same EJB object is passed by copy. a remote reference. Each bean type may have one home interface. 5.EJBHome interface. When using JNDI to access a bean. Some restrictions are placed on remote interface and value types by Java RMI-IIOP.rmi.rmi.2. which means that changes in a serialized object on one tier are not automatically reflected on the other tiers.ejb. 103 . a remote interface cannot directly extend two or more interfaces with methods of the same name.Serialized objects are copied. Remote interface either directly or indirectly. Remote interface type scan throw exceptions specific to the application. to the bean’s EJB home is obtained to implement the remote home interface. Every method defined in the remote interface is required by the Java RMI specification to throw the java. A remote interface can overload its own methods and extend the remote interface with overloaded method names. or stub. Remote Home Interface Life-cycle operations and metadata for the enterprise bean are provided by the remote home interface.RemoteException to identify problems with the communication of distributed objects. The other major restriction is serialized types cannot not implement the java. This interface will extend the javax. not referred. which is a Remote interface implemented by a distributed object stub. Method overloading is restricted: namely.

The EJBHome. This is true for entity beans because they 104 . The metadata allow enterprise beans from a client perspective to be interpreted.ejb. The methods used are specific to each enterprise bean. while a FinderException is thrown by the find methods for any errors. The EJBHome. Session beans will not have find methods: only entity beans will have find methods. This object provides a serializable reference to the remote home of an enterprise bean. Removal of the entity bean reference will delete any data referenced from the database. Removal of session bean reference will end the conversational state maintained by the session bean.getEJBMetaData() will return an instance of the javax.ejb.remote() methods. The arguments for this action will either be the javax. the remote reference of the enterprise bean on the client will become invalid because the stub of the bean no longer works. The javax. It will also define the enterprise bean as a session or entity bean. The impact of the remove methods is dependent on the bean reference removed. but knowledge of its existence is helpful when creating automatic code generators or other automatic facilities.To delete an enterprise bean.Handle of the bean or the primary key for entity beans. It allows a remote home reference to be stored and used at a later time. When the remove methods are invoked.Handle is a serializable pointer to a specific bean. EJBMetaData.getHomeHandle() method is used to call the HomeHandle by returning a javax. The EJBMetaData is used rarely by application developers.ejb. Create and find methods can be included in the remote home interfaces.ejb. the remote interface. This will describe the remote home interface. use the EJBHome.HomeHandle object. and primary key classes. Create methods will throw a CreateException if the create process cannot be completed.

which is an extension of the java. Remote interfaces are not used for system-level operations.1. Create methods in EJB 2. The base class for all remote interfaces is the javax. The same is possible for find methods in the home instance for bean-managed entities.Remote interface. The javax. such as persistence.represent uniquely identifiable data within the database.rmi. Home methods are available only to entity beans. This expansion is not required and it is not supported in EJB 1. concurrency.ejb.RemoteException at the very least. Custom exceptions can be included in the remote interface to identify abnormal conditions or errors in the business methods. Home methods are business methods invoked on the home interface and are not specific to one bean instance.ejb. Remote Interface The remote interface will define the business methods of an enterprise bean.EJBObject interface. They focus on the business problem.EJBObject interface is extended by all remote interfaces. Home methods can be defined in the home interface and consist of any methods which are not create or find methods.4.2. while the system-level operations are handled by the EJB server. They should have a corresponding ejgHome() method in the bean class. 5. in the form of create<SUFFIX>(). All remote interface methods for bean are required to throw a java. Every find<SUFFIX>() method in the home interface must correspond to an ejbFind<SUFFIX>() method in the bean.rmi.0 can be expanded using a method name as a suffix. or transactions. 105 . security.

Specific data represented by entity beans are identified using the primary key. Entity and session beans can be removed using the EJBObject. Remote references for EJB objects can be compared using the EJBObject. the reference is actually pointing to an EJB object. The primary key is required for the correct bean in the correct container. The method can only be used by EJB objects representing entity beans. It has the same impact as the EJBHome. It must also implement the java. getPrimaryKey() method. It can be used to control the scope of the remote EJB home for the EJB object.Serializable interface to ensure it can be obtained from an EJB object regardless of its form. The primary key for an entity bean can be returned by the EJBObject. Remote references to entity beans can be obtained using the findByPrimaryKey() method. Since session beans represent tasks or processes.getEJBHome() method returns a remote reference to the EJB home as a javax. In 106 . The EJBObject.isIdentity() method.ejb.remove() method. The method returns a true value is the two object references represent the same bean. The remote interface is implemented by the EJB object by delegating business method calls to the bean class.EJBHome object. primary keys are not helpful.This interface provides utility methods and return types which can be used to manage the interactions between the bean and clients. even when the object stubs are attached to different object instances.io. The methods return information about the corresponding bean instance on the server.remove() method. When a reference to the remote interface is obtained by the client.

The EJBObject. 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.2.Handle object. Any bean type can be a co-located client of a session or entity 107 . the entity data is deleted from the database and the remote reference becomes invalid.Handle is the javax.getHandle() method returns a javax. or both.5.1 specification to use the Java RMI-IIOP semantics for communication. they are required by the EJB 1. In entity beans. As a result. the Handle object can be saved in the same way that the primary key can be used. Using the Handle which is a serialized reference. The Handle interface will specify only one method.ejb.ejb.0 to provide different semantics and execution contexts for enterprise beans in the same container system. the getEJBObject(). Session and entity beans can implement remote or local interfaces. as in deployed in the same container system and executed within the same JVM. Co-located beans identify when two or more enterprise beans interact. the remove() method will release the session and the remote EJB object reference becomes invalid. Local Client API Local component interfaces are introduced in EJB 2. The Handle object will also encapsulate the details of a JNDI lookup on the container. They do not use the network for communication: though they do not incur the overhead of Java RMI-IIOP. Similar in purpose to the javax. The method will return the remote EJB object.HomeHandle. which will store and retrieve references to remote EJB homes.ejb.session beans. 5.

3. the local home interface is invoked by other co-located beans. A stateful bean retains the conversation state between method calls. and remove methods. The EJBLocalObject interface defines several methods. while a stateful bean does not. The life-cycle methods include find.ejb. Unlike a remote home interface. The Local Client API is similar to the Remote Client API: it is composed of two interfaces. Though the client can still perform method 108 . create. Session Bean Components 5. 5. Local interfaces will extend the javax.EJBLocalObject interface and remote interfaces will extend the javax. Stateful and Stateless Session Beans Session beans are either stateful or stateless. the stateful bean remembers the state of the client as long as the session is alive. In other words.bean. 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.3.EJBObject interface. a local and a local home interface.1. The business methods will match the signatures of business methods defined in the bean class.ejb. This attribute is attached to the bean at the time of deployment. The local interface defines the business methods of the enterprise bean that are invoked by co-located beans.

it can be found within a state itself. 5. 7. The bean is made by the Container. they can have instance variables like other objects. The getAdvice() call is received by the EJBObject.2. In this case. Removing a Bean The lifecycle of the session bean is dependent on whether the bean 109 . These two steps can be broken down into smaller parts. Session Bean Lifecycle The high level action of a session bean consists of creating and using the bean. an instance variable cannot maintain values which are specific to an individual client. The EJBObject stub to the client to the Home Using a Bean 6. specifically: Creating a Bean 1. The Container handles the action and the getAdvice() is called on the bean. The create() method is called by client on the home stub. The EJBObject (component interface) for the bean is created by the Container. 5. While stateless beans will not remember the client-specific state. The client calls a business method on the component interface stub using a getAdvice() method. 4.calls to stateless beans. 3. 8. this type of bean is not expected to remember anything about previous method calls. 2.3. That is. The home object receives the create() call.

For session beans. For stateful beans. the fifth is the ejbCreate() to match the create() method declared within the home interface. These matching method using the ejbCreate() method. Bean activation will wake the bean up from sleep condition for the purpose of servicing a business method from the client. Bean passivation is the act of putting a bean to sleep to conserve resources. activating the bean. Both conditions will involve bean creation. When a session bean move out of this state. the constructor 110 . passivating the bean. there may be more create() methods. use. and removal. These events are not known until a container callback method is called for the bean. 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. Four container callback methods are declared within the SessionBean interface: providing bean context. Every session bean will have at least five container callbacks: exactly five for stateless session beans. and removing the bean. Container callbacks are contained in the home interface for the bean and within the SessionBean interface of the session bean class. A stateful session beans has two additional events between use and removal: passivation and activation. In addition to the four declared within the session bean class. sitting within a state of nonexistence.is considered stateful or stateless. the container callbacks which are home-related will match each create() method declared in the home interface.

every non-transient instance variable must be a reference to: • A Serializable object • A null value 111 . and then the ejbCreate() method. the following methods are used respectively: • ejbPassivate() • ejbActivate() When ejbPassivate() completes. • setSessionContext() – must be saved for context. The state is returned when the bean times out. When moving from a method ready state to a passivated state or from a passivated state to a method ready state. If the bean is in a transaction.for the bean runs. an system exception is thrown. A passivated bean is stored in a temporary hold to conserve resources between calls. An active transaction may not be present while in this state. if cannot be passivated. or a remote() method is called by the client. • ejbCreate() – should contain initialization code. 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(). A passivated bean remains an inactive object on the heap until is it reactivated by the Container using an ejbActivate method. then the setSessioncontext(). 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.

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

the following are present: • Timeout – after the bean is passivated. It is the only connection to the Container and allows the bean to obtain security information. The bean and EJB object are killed and the client receives an exception when the stub is used again. 113 . the container will decide to kill the bean. resources are acquired and released with each business method. Creating Beans An object must be granted “beanness” in order to become a bean.3. but does not call ejbRemove(). 5. but does not call ejbRemove(). The bean and EJB object are killed and the client receives an exception when the stub is used again. “Beanness” to an object provides a context for the bean. the client doesn’t call any methods on the component interface. the container will decide to kill the bean. and more. force a transaction. In most cases. A JNDI context is provided to every bean to enable the bean to find resource manage connection factories. • ejbRemove() – all resources should be released before ending the remove state. The use of a cleanup() method called from the ejbPassivate() and ejbRemove() will ensure resources are released properly. other beans.3. • System exception – an unchecked exception is thrown during method execution.When moving from a passivated or method ready state to a ‘does not exist’ state. but in some cases resources are released within the remove() method. The point when an object becomes a bean is critical to the developer. and deploy-time constant values. and access to beans and resources. a JNDI context. A context for the bean is sometimes called the EJBContext.

3. • Exceptions declared in the home interface do not need to be declared 114 . • Stateless beans will have only one empty create() method (no arguments). • The ejbCreate methods must be public and cannot be final or static.4. The rules regarding home methods within the bean class are: • Every create method in the home must have a matching ejbCreate method in the bean class and the ejbCreate method must have a void return type.The type of bean created. • The EJBLocalHome must be extended by the local home interface and RemoteExceptions must not be declared. The rules related to the home interface are: • The local component interface must be returned by the local home interface. Bean Classes Several sets of rules must be followed when creating bean classes. while the remote component interface must be returned by the remote home interface. • Stateful beans will have one or more create() methods and can have arguments. • A CreateException must be declared by every create method in the home interface. the transaction status. and the methods used will determine how much capability is available to individual beans. • Legal RMI-IIOP types must be used for all arguments and return types for Remote home interface methods. • The EJBHome must be extended by the remote home interface and RemoteExceptions must be declared on every method. 5. regardless of local or remote connection. The create() methods must start with the ‘create’ string and can be overloaded.

• Application exceptions not declared in the home interface must not be declared for the matching create method. • Neither the local home nor component interface of a bean should be exposed through a remote component method. • Legal RMI-IIOP types must be used for all arguments and return types for remote component interface methods. Business methods in the bean class must following the rules below: • Business methods must be declared public and not final or static. • Stateless beans can have only one ejbCreate() method and must have no arguments. • The EJBObject must be extended by remote component interfaces and every method must declare RemoteExceptions. Business methods in the component interface must following the rules below: • Business method names never start with the string ‘ejb’.in the bean class. • RemoteExceptions should never be declared in the bean class. • The ‘this’ must never be passed as an argument or return value. • RemoteExceptions must not be declared in the bean class. • Business method names must not begin with the string ‘ejb’. • Exceptions declared in the component interface do not have to be declared in the bean class. • Legal RMI-IIOP types must be used for all arguments and return types for Remote component methods. 115 . • The EJBLocalObject must be extended by local component interfaces and RemoteExceptions must never be declared. • Stateful beans must have one or more ejbCreate methods and must start with the string ‘ejbCreate’. • Application exceptions must not be declared if they were not declared in the component interface for a matching business method.

• A bean class can have a superclass. either directly or indirectly.ejb.1. • The class must be public and not declared as final or abstract. The entity bean provides an objectoriented perspective to that store. where the session beans provides a process and the entity bean provides the data that the process is acted upon. • A public. 5. Characteristics of Entities Entity beans represent data which exist in an underlying persistent store.Session must be implemented by the class. A persistent store could be a relational database. • The matching home and component interface methods must be implemented by the class. Java Persistence API Entities 5.4. 116 . • The bean’s component interface is not required to be implemented by the class. In EJB application. • If a stateful bean.Some additional rules for bean classes include: • The javax. an object database. • A finalize() method must never exist in the class. entity beans are combined with session beans. or stored serialized objects in files. no-arg constructor must be in the class. the SessionSynchronization interface can be optionally implemented. Entity beans are data objects.4.

The findByPrimaryKey() method invocation is sent to the home object. entity beans allow the database to be 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. The Container initiates a bean from the bean pool to confirm the existence of the entity in the database. The bean checks for the entity using the primary key. 3. entities are not realized as entity beans until a particular entity is required in the application logic. the entity bean disintegrates. 5. the entity already exists and a new reference to the entity must be created. the entity still exists. From a client’s perspective. the business methods of the bean are called after creating the bean and having the Container allocate a new EJB object. The bean communicates the entity’s existence to the home object. This is because the entity is real. A JNDI lookup on the entity bean home is performed and a home interface reference obtained. With a session bean. a findByPrimaryKey() method on the home stub is called. If the entity is deleted. 117 . However when the entity bean is killed. 4. With entity beans.Entities are the things which are represented by entity beans. The following process for existing entities is performed: 1. 2. In most applications. This requires one or more finder methods. while the entity bean is simply a representation of something that is real.

7. 3. The container makes or finds an EJB object for the entity. A stub for the entity is returned by the Container. the process is as follows: 1. it has no identity = it does not represent any entity from the database. 5. and message-driven beans will use pools but do not go to sleep there: the pools are used for living. The create() method invocation is sent to the home object. The Container or bean inserts a new row in the database and a new primary key is generated by the bean. When a bean is passivated. a create() method on the home stub is called. Unlike session beans though. passivated entity beans remain live objects on the heap. Stateful session beans will go to sleep in a pool. RAM-using objects on the heap. 5. stateless beans. When a new entity is created.4. The ejbActivate() method is used by the Container when a bean is required to service a business method. 6. The bean is linked to an EJB object and the new primary key is obtained by the context and EJB object. A stub is returned by the Container for the new entity. not running a business method. Entity beans. Entity bean pool is called when the bean is finished with a business method. The passivation method is used to release resources not used while the bean is sitting in the pool. Entity beans can undergo passivation and activation.6. 2. The Container pulls a bean from the pool. A JNDI lookup on the entity bean home is performed and a home interface reference obtained. 4. Entity Bean Code A simple entity bean is coded as follows 118 .2.

} public String getColumnName1 () { return columnName1.getPK() .// package and imports declared public class BeanName implements EntityBean { private String columnName1. } public void setColumnName1 (String variablename) { 119 . private String columnName2. private String uniqueID. String second) { columnName1 = first. // DB INSERT return uniqueID. private String ejbCreate(String first. uniqueID = this. private entityContext context. columnName2 = second.

} 120 . } public void ejbActivate() { } public void ejbPassivate() { } public void ejbRemove() {// DELETE} public void setEntityContext(EntityContext ctx) { context = ctx.columnName1 = variablename. } public void unsetEntityContext() { } public void ejbLoad() {// DELECT} public void ejbStore() {// UPDATE} private String getPK() { return “”+ (int) (primary key algorithm). } public String getColumnName2 () { return columnName2. } public void setColumnName2 (String variablename) { columnName2 = variablename.

ejbObject. Component Interfaces A component interface of an entity bean is exactly like a session bean’s with business methods and an extension of the javax. 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() 121 .5.3.4.

RemoteException. the following code is written: create(String col String first. 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. String second) findByPrimaryKey(String key) findByCity(String city) 122 . • Every method must declare a RemoteException. • Methods can be overloaded. without beginning with ‘ejb’. • All arguments and return types must be RMI-IIOP compatible.ejb. 5.4.* and java. • Application exceptions can be declare but must not be runtime exceptions. For the home interface. • Methods can have arbitrary names.Remote component interfaces must: • Import javax.4.EJBObject. • Extend the javax.ejb.rmi. • Declare one or more business methods.

A reference to one EJB object is required for the methods.EJBHome. not just component interfaces. remote stubs are returned by create and finder methods. Both entity and session beans must extend the javax. 123 . create() and findByPrimaryKey(). 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. While entity beans can use both remove() methods.What the client sees on the other side of the interface is: create(String col String first. Business methods can be used within the home interface to return anything. With a remote interface. The problem is that multiple stubs may be returned when performing on multiple items. which are seen by the entity bean client. String second) findByPrimaryKey(String key) findByCity(String city) getEJBMetaData() getHomeHandle() remove(Handle h) remove(Object key) The final four methods above. are the same four seen by the session bean client. This allows queries to return the actual entity data and not simply the references to the entities.ejb.

• The findByPrimaryKey() method can be declared and must return the Remote component interface and declare a RemoteException and CreateException. These methods must return the Remote component interface and declare a RemoteException and CreateException.ejb.4. • All create() methods must begin with the prefix string “create”.Collection and declare both a RemoteException and a Finder Exception. ‘find’.* and java.EJBHome must be extended. it representation disintegrates. These methods must return the Remote component interface or java.5. • One or more home business methods can be declared with the following guides: o All arguments and return types must be RMI-IIOP compatible. 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. • One of more finger methods can be declared. 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. o Methods can have arbitrary names.The rules of the remote home interface are: • The javax.ejb. o Application exceptions can be declare but must not be runtime exceptions. without beginning with ‘create’. • Methods can be overloaded. • The javax. When the real thing is entity is removed from the store. or ‘remove’. o Every method must declare a RemoteException.rmi. 124 .RemoteException must be imported. • One or more create() methods can be declared.util. 5.

The ejbPassivate() and ejbRemove() are used for the third transition from method ready to 125 . and the bean class. the entity bean dies. Therefore. either an ejbCreate() or ejbPostCreate() method must be used on new entity beans or an ejbActivate() method for existing entity beans. Sometimes. 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 The first transition is performed by the constructer with a setEntityContext() method to move the bean into a pooled state. the deployment descriptor. the entity bean for that entity exists. An instance of the bean class on the heap is affected by the Container or a server. If an entity exists for a particular bean type.During the development and deployment of the entity bean. the death of a bean instance can only come from the Container or server crash. To transition further into a method ready state. but the entity bean instance returns to the pool. it consists of the home and component interface. is the entity is deleted. While the death of the bean can be tied to an event on the database. the term ‘entity bean’ is used to represent the possibility of an entity.

Synchronization is the effort of the Container.pooled. The last transition into a does not exist state occurs when the unsetEntityContext() method is used or an instance throws a system exception. The Container is responsible to ensure a negative impact is prevented when the bean and database are out of sync. but never both at the same time.6. the bean and the actual entity must remain synchronized. The call is intercepted by the Container and a transaction is started 126 . If the method affects a persistent field of the bean. A client with a reference to the bean may change the state of the bean by using a set() method. A business method is called by a client. The same temporary loss of synchronization is possible when the data within the database is updated. 5. 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 has been updated.4. In this case. the bean and the database will be out of sync temporarily until the database is updated by the bean. Synchronization Since the bean is not an entity but a representation of the entity. 2. 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. the bean must be updated with the change.

5. 4. The Container tells the database to remove the lock on the entity. The database is told by the Container to lock the row and granted access only to the Container. 7. The database is updated by the database with the new state of the bean before the transaction is ended.before obtaining the bean. 6. 127 . Multiple business methods are run by the bean in the same transaction. 3. The Bean is loaded by the Container with the entity state from the database.

7. Bean-Managed Persistence (BMP) has database access code created by the developer using JDBC statements in callback methods. and ejbRemove methods. Container-Managed Persistence (CMP) will have the container take care of all the database access code.0. Container Callbacks In addition to the ejbPassivate. obtaining a Connection. EJB-QL is written by the Bean Provider to instruct the Container on how to perform selections. including looking up a DataSource. 5. The design of the entity bean class is made by the Bean Provider. 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. and sending JDBC statements to the database. The bean’s filed which are part of the bean’s persistent state must be chosen and relate to columns in one of more database tables.4. Information found within the Deployment Descriptor provides guidance to the Container on the actual implementation of the CMP bean. Database access is controlled based on the database access code.The Container knows when the bean and the database entity need to be synchronized based on the transactions. including adding and deleting entities. Container-managed persistence (CMP) is enhanced EJB 2. entity bean interfaces have another three container callbacks. ejbActivate. 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. • ejbStore() – called by the Container to update the database to reflect 128 .

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. the bean class must have a matching ejbCreate() and ejbPostCreate() method. the component interface.4.8. 5. Entity Classes Entity bean classes consist of items from the home interface. Finder methods are part of the bean class but not defined in the bean. and virtual persistent fields. The setEntityContext(EntityContext ec) method allows the Container to give the bean a reference to its context. Every home business method must have a matching ejbHome<methodName>. Every create() method found in the home must have two methods in the entity bean: ejbCreate() and ejbPostCreate(). 129 . Each method found in the component interface must have a corresponding concrete implementation in the bean class. Every entity bean using CMP will have at least seven container callbacks. an abstract getter and setter must be provided. The entity bean has new home container callbacks.the state of the bean. entity beans set the EntityContext rather than the SessionContext. the EntityBean interface. The other difference from session beans. The EntityBean interface can be implemented either directly or indirectly. Every business method in the home must have a matching ejbHome<method> in the bean class. For each persistent field. For every create() method in the home.

The use of the ejbCreate() method must follow the rules: • Each ejbCreate<method> must match a corresponding create<method> in the home interface. These fields represent values that map to columns in the database.In the bean class code. • Methods must be declared public and must not be declared static or final. With entity beans. virtual persistent fields will exist only as abstract getters and setters. Entity Identity and Primary Keys The initialization code for the entity is coded into the ejbCreate() method. or any arbitrary application exception which is also declared in the home 130 .9. Containers will never allow entities to share the same primary key. • Method arguments must be the same as the arguments of the matching create<method>. 5. • Method names must begin with the prefix “ejbCreate”. Compound keys use two or more container-managed persistent fields. • A throws clause must be declared with CreateException. Determining the primary key is the developer. • Declared return types must be the entity bean’s primary key type. The simplest form of primary key is a direct mapping between a single field and a single column in the database. 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.4. Every entity must have a unique identity. They are not instance variables.

5. including: • One-to-One – each entity has a corresponding relationship to another single entity. • Declared return types must be void.10. Multiplicity When dealing with entities within an application. correspond 131 .4. • Many-to-Many – entities. • RemoteExceptions must not be declared. • 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. 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.interface. • One-to-Many – an entity has a corresponding relationship to multiple secondary entities. These relationships can take on many forms. whether primary or secondary. • Two or more persistent fields can be used to uniquely identify the entity by making a custom compound primary key class. except for the following: • Method names must begin with the prefix “ejbPostCreate”. Each secondary entity is associated to only one primary entity. The use of the ejbPostCreate() method follows rules similarly to the ejbCreate() method. relationships can be set between different entities.

A multiplicity of many means the object holds a collection of entity beans. Write a home business method. Select methods are developed by letting the Container build the database access code from queries. Each bean is defined with an ejb-relationship-role which establishes the multiplicity. 132 . Multiplicity will affect the return type.to multiple entities in the database. The ejb-relation is used to establish relationships between two beans. Declare the abstract select method in the bean class. 5. The different is that instead of setting and returning a value. 4. A multiplicity of one identifies objects with only one entity bean. 2. 3. The process follows as such: 1. Relationships always contain two beans. source. Java Persistence Query Language EJB-QL is a portable query language. a pair of abstract getters and setters is defined.5. Write the EJB-QL for the select query. It allows SQL-like statements to be written into the deployment descriptor. and cascade-delete for the bean. Container-managed fields exist because the fields have a getter and setter. a reference to another entity bean or collection is set and returned. cmr-field. Like container-managed relationship (CMR) fields. Implement the home business method to call the ejbSelect method.

field =?1. Navigating to another related bean referenced in a CMR field. WHERE Clause The WHERE clause is optional. either: • An abstract schema type – a range variable 133 .1.5. The second part defines the representation of the bean type as x. A collection of entities may be returned in the bean class.5. Using the dot operator will simplify the navigation. The final part.2. restricts the returned bean to those beans where the CMP field matches the first parameter of the select method. SELECT Clause The SELECT clause identifies what the query will return. Using an AND clause will allow a value to be selected rather than a whole bean. A basic code for a SELECT using WHERE is: SELECT OBJECT (x) FROM Schema x WHERE x. The WHERE clause can use: • Literals • Input parameters • Comparisons 5. The coding uses information from the deployment descriptor.field =?1 In this code. WHERE x. the first part is SELECT OBJECT (x) where it identifies all bean types of the value x.5.

but never a <cmp-field>.• A <cmp-field > single value type – a single-valued path expression The statements SELECT and FROM are mandatory. The statement OBJECT (m) is used to return a bean’s abstract schema type. Identifiers used must be valid Java identifiers. They also may not be a reserved work in EJB-QL which is: • • • • • • • • • • • • • • • • • • • SELECT FROM WHERE DISTINCT OBJECT NULL TRUE FALSE NOT AND OR BETWEEN LIKE IN AS UNKNOWN EMPTY MEMBER OF IS 134 . They must not have the same name as an <abstract-schema-name> or ejb-name> in the DD. The FROM clause declares the identification variable and defines the domain of the query.

import javax. The Container makes sure that each bean is thread-safe. The client sends the message and is referred to as the message Producer. Message-Driven Bean Class Message-driven beans provide asynchronous communications between the client and the server: entity and session beans provide synchronous communications.*.javax.6. When the Consumer receives the message. it is processed without needing a connection to the client.6.ejb.*. The lifecycle of the message-driven bean is similar to the stateless session bean.jma. 135 . while the server receives the message and is referred to as the message Consumer. The Producer will send the message and moves on. Message-Driven Bean Component 5. Multiple message beans of the same time can be processed concurrently. The processing involves the Container obtaining a bean from the pool. The Container receives the message and acknowledges it to the service. invoking the onMessage() method. The bean’s transaction is committed and the Container sends the bean back to the pool.5. import.1. with the following states: • does not exist • method ready A typical message-driven bean class is coded as: package headfirst.

System. MessageListener { private MessageDrivenContext conext.out. } Public void onMessage(Message msg) { // process the message try { if (msg instanceof textMessage) { TextMessage message = (TextMessage) msg.printIn(message. } } catch (JMSException ex) { } } 136 . public void ejbCreate() { } public void ejbRemove() {} public void setMessageDrivenContext (MessageDrivenContext ctx) { context = ctx.public class className implements MessageDrivenBean.getText() }.

The method must be public.jms. At deployment. not final or static. • The ejbRemote() and setMessageDrivenContext() methods must be in the MessageDrivenBean interface. • A public constructor must be present with no arguments. with a void return type. • No methods should be allowed to throw application exceptions. with a void return type. 5. The code found in the DD is: <enterprise-beans> <message-driven> 137 .Message is required. the DD will bind the bean to a specific topic or queue configured as a resource in the EJB server.The rules for developing a message-driven bean class are: • The javax.6.ejb. • The class must be public. and never be abstract or final.jms.MessageDrivenBean and javax.MessageListener must be implemented. Message-Driven Bean Methods Three kinds of methods are found in the bean class of a message-driven bean: • ejbCreate() • onMessage() • container callbacks The Deployment Descriptor must be told what type of messages should be listened for. • A no-arg ejbCreate() method must be present and the method must be public.2. • The onMessage() method must be defined from the MessageListener interface. A single argument of type javax. not final or static. exactly as they are declared in the interface.

one bean from each bean pool will get the message.Topic</destination</message-driven-destination> </message-driven> </enterprise-beans> 5. The Container will choose one bean from the bean pool to get the message: if multiple bean types subscribe to the topic.3. Topics can be subdivided into durable and non-durable subscriptions. A durable subscription ensures that the consumer receives all messages. Behavior of a Message-Driven Bean Message types are either topics or queues.jms. 138 . including messages gathered when the consumer is offline.<ejb-name>MessageName</ejb-name> <ejb-class>ClassName</ejb-class> <transaction-type>TransType</transaction-type> <message-driven-destination> type> <destination-type>javax. A producer will send a message and a listening consumer for the message will get a copy of the message. Non-durable subscriptions require the consumer to be online in order to receive the message.6.

where message acknowledgement is tied to successful completion of the method. all other transactions are complete. The Container knows that an error occurred by one of two methods determined by the Bean Provider. Acknowledgement ensures that messages are never lost. A queue message is a point to point message. The second method is method completion. If the consumer is processing the message and an error occurs. Once the message is processed. Message-driven beans do not have clients. When delivered successfully. If a transaction rolls back. the message goes back to the queue. A message is intended for a single user. • Call the bean’s context setter. This is used for container-managed transaction demarcation. the Container can tell the messaging service to put the message back in the queue. For a queue messages. therefore. there is no client security information. If a runtime exception is thrown. only one bean from the pool associated with the queue will get the bean. 139 . The transaction status can provide message acknowledgement by identifying the transaction commits or roll backs. The initiation of another transaction requires the sending of another message. • Call the bean’s ejbCreate() method. no home interface is present.Queues are similar to lists. the Container will tell the messaging service that the message was delivered. With no client. the message returns to the queue. This method is used for bean-managed transaction demarcation. Message-driven beans are made virtually the same way stateless session beans are made: • Call the bean’s constructor.

changes made by the transaction becomes permanent even with the server goes down and comes back up. The unit of work is either committed or rolled back in its entirety. 140 . • Isolated – transaction processing is not impacted by other transactions which are processing at the same time. • Consistent – the data remains consistent whether the transaction fails or succeeds. the transaction manager ensures that all transaction participants ready to move into the second phase. In phase one.7. Distributed transactions are supported by EJB containers through a twophase commit protocol. the transaction manager tells all transaction participants to commit or rollback. The characteristics of a good transaction are: • Atomic – either all of the transaction works or it all fails. • Durable – after a transaction is committed. In phase two. Transactions An EJB transaction is a single unit of work which is compiled to where everything succeeds or everything reverts to its previous state.5.

141 . The EJBContext has methods for both Container-managed transactions (CMT) and BMT. Transactions are managed by the container. • A called method runs without a transaction – the first transaction is not propagated and suspended. • A called method runs within its own transaction – the first transaction is not propagated and suspended. but it needs to be instructed on how to manage.transaction.EJBContext. 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. The UserTransaction interface is for beans using bean-managed transactions (BMT). and the second method runs without a transaction.ejb. The transaction code can be written into the bean class or transaction declarations put into the Deployment Descriptor. and the second method runs in a new transaction. Methods related to transactions are located in two interfaces: javax.UserTransaction and javax.Transactions are propagated through method calls.

• Start the transaction. but cannot be propagated. get a UserTransaction reference. • The validateCredit() completes and the checkout() method remains running. • End the transaction (commit or rollback) The call stack of the checkout() method proceeds as follows: • The ut. 142 . If a propagation into a BMT bean is initiated or a transaction is in progress when a method on a BMT bean is called. • The checkInventory() completes.5. The transaction waits for the BMT bean to complete its work. The transaction remains open. • The ut. • The commit() completes and the checkout() runs without a transaction.1. A stateless session or message-driven bean must not complete a transactional method without ending the transaction. • The doNotTxStuff() is called without a transaction.begin() is called and the transaction started. • The checkInventory() is called and runs in the same transaction. • The commit() is called: ending the transaction. Bean-Managed Transaction To make a BMT transaction: • From the EJBContext. A BMT bean must not start a transaction before the current transaction ends. A BMT transaction is one way: they can propagate out to a CMT bean.7. the transaction will be suspended. • The validateCredit() is called and runs in the same transaction as checkOut().begin() completes and the checkOut() method runs in a transaction.

When the method is called.7.5. the container starts and completes transactions based on the DD. 143 . • Suspend the caller’s transaction and start a new transaction. • Suspend the caller’s transaction and run the method without a transaction. the container will use the attribute to do one of the following: • Run the method in the caller’s transaction. • Throw an exception because the caller does not have a transaction.2. • Throw an exception because the caller does have a transaction. There are six attributes which are marked in the DD: • • • • • • Required RequiresNew Mandatory Supports NotSupported Never Attributes work by marking a method with one of the attributes listed above. Container-Managed Transaction With CMT.

this optional step depends on dividing clients into categories with varied degrees of access. User authentication and authorization is that portion of web services which enables clients to access the resources required by them. This step is user authentication. the message received is the same as the message sent. Three services are typically involved at this level. The first step is the presentation of user-specific information. Basic Security Mechanisms Wire-level security occurs at the transport level of a network.1.1. specifically focusing on the basic protocols which control communication between a web service and the client. The second step is determining what access or what level of access the client has. Web service security (WSS or WS Security) is a set of protocols specifying the how security is enforced on messaging in SOAP-based 144 . These credentials are presented and verified in two steps. Access is denied if this user information is incorrect. that is. The first service ensures that the service and client are who they say they are through some form of authentication. The third service ensures the integrity of the message.1. Secured resources require the client to have the proper credentials.6 Java Security 6. Known as role authorization. Security 6. The second service encrypts the data to ensure that it is not intercepted. such as username and password.

web services.1. It is handled through the exchange of digital certificates. In the symmetric approach. HTTPS HTTPS is a secure version of HTTP and provides three critical security services on top of the services provided by HTTP. WSS provides comprehensive end-to-end security. Encrypted bits become cipher bits: the input bits are considered plaintext if represented text. The cipher bits are inputted into the decryption engine along with a decryption key. • The digital certificates are checked by the browser against its truststore – a database of digital certificates trusted by the browser. 6. while the output of the encryption is ciphertext. This is usually initiated as a client challenges the web server. • The browser is typically not checked by the web server. Two different approaches are used in encryption: symmetric and asymmetric. Confidentiality is performed as a process of encryption and decryption. Both approaches will encrypt the data bits as a input into an encryption engine and the provision of an encryption key as another input. All encrypted data must be decrypted to be read. Here is the process: • The client browser challenges the web server to authenticate itself with the server responding with one or more digital certificates.2. the encryption key and the decryption 145 . They include: • Peer Authentication • Confidentiality • Integrity Peer authentication involves ensuring that both ends of a connection prove their identity to each other.

key is the same. If the computed digest differs from the sent digest. In a symmetric approach a key pair is introduced consisting of a private key and a public key. Ensuring integrity is the most straightforward of the HTTPS services. 146 . they can only be encrypted with the private key. the message is considered to be altered during transmission. The opposite process is true. symmetric methods are problematic during distribution of the keys. While the fastest approach. When message bits are encrypted with the public key. Each messages sent over HTTPS contains a digest which is recomputed by the receiver. A private key is not distributed. while the public key can be. The asymmetric approach resolves the distribution problems of the symmetric approach but is much slower.

A SAML protocol references what is transmitted. A SAML binding will determine how requests and responses for SAML map onto standard messaging or communications protocols. protocols. and bindings.1. The identity provider provides local authentication services to the principal. will rely on the identity provider to identify the user. It assumes the principal is enrolled within at least one identity provider (a producer of assertions). and encrypted assertions • HTTP – provides a transport protocol • SOAP – required use The semantics and syntax for assertions is defined by the SAML Core. A service provider. or consumer of assertions. SAML Security Assertion Markup Language (SAML) is based on XML principles and is a standard for exchanging authentication and authorization data between security domains.6. typically a user. A SAML profile is a concrete manifestation of a defined use case using assertions. It is a product of the OASIS Security Services Technical Committee. encrypted attributes.3. SAML is based on: • XML – as a standard language • XML Schema – provides structure for SAML assertion and protocols • XML Signature – a digital signature for authentication and message integrity • XML Encryption – provides elements for encrypted name identifiers. SAML uses an OpenID standard. Upon request the identity provider will pass a SAML assertion to the service provider who will use it to make an access control decision. 147 . not how.

A resource element is a data. A SAML assertion contains a packet of security information. resources and actions. A SAML protocol is a simple request/response protocol.A SAML protocol defines several SAML elements and how they are packaged. 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.4. Subjects have one or more attributes. • Authorization – declares what actions are permitted to be performed on what resources for a particular subject. XACML XACML is short for eXtensible Access Control Markup Language. They are managed by the Policy Administration Point (PAP). It is a declarative access control policy language implemented in XML. Environment elements can optionally provide additional information. An action element defines the level of access requested on a resource and can have one or more attributes. Policies are a collection of rules. 148 . which like requests. use subjects. They are transferred from identity providers to service providers and contain statements used to make control decisions. It is also a processing model used to interpret the policies. 6. A subject element is the entity requesting access.1. service or system component and has a single attribute. • Attribute – declares a name-value pair associated with a subject.

The Policy Information Point (PIP) will provide external information to the PDP. WS-Trust. WS-Security WS Security is a set of specifications for augmenting wire-level security through a unified. 6. The second layer consists of WSSecureConversation. and WS-Authorization and builds on the components of the first layer. and WS-Privacy.XAMCL utilizes obligations. A number of layered blocks are part of the architecture. The PDP evaluates and issues authorization decision. WS-Federation. The PEP intercepts a user’s access request to a resource and enforces the PDP’s decision. This directive explains what must be carried out before and after granting access. An obligation is a directive from the Policy Decision Point (PDP) to the Policy Enforcement Point (PEP).1. It runs on top of the SOAP protocol. 149 .5. end-to-end framework. The first layer of the architecture is comprised of the WSPolicy. transport0neutral.

They provide information on the mapping between the security roles and access requirements of the application with the security roles. • WS-Trust – handles how security tokens are issued. 150 . Types of Security A multitier enterprise application is built using components which are deployed into different containers.Brief descriptions of each component are below: • WS-Policy – defines the general security capabilities.1. Java EE Security Fundamentals 6.2. These deployment descriptors are external to the application. as well as how a service can determine whether a requester will follow those privacies. • WS-Authorization – covers the management of authorization data and the policies for granting access to secured resources. • WS-Federation – addresses the management of security identities across different platforms and organizations. constraints. • WS-Privacy – defines how services state and enforce privacy policies. and trust domains. specifically two types of security: • Declarative security – uses deployment descriptors to define the security requirements for the application component. renewed. The containers provide security for the components. and policies. Annotations will specify security in class files and are used or overridden by the deployment descriptors. users. • WS-SecureConversation – provides secure web service conversations across different sites. and validated. and policies specific to the environment. 6.2. security contexts.

The deployment descriptor will 151 . here’s the expected behaviors of the application: 1. The web server will provide the web client a form which is used to collect authentication data such as the user’s name and password from the user. 2. The credential received is used to determine authorization for the user to access restricted resources. The web server delivering the application will detect that the client has not authenticated itself and invoke the appropriate authentication method for resource. 2. The web client requests the main application URL. 3. 3.2. 6. Request Authenticate Authorize URL Fulfilling Request Invoking Methods Using a web client. 5. The authentication data is sent by the web client to the web server. where the data is validated. If validation succeeds.2. The validation mechanism may be located on the web server or may utilize any underlying security services. It is useful when declarative security is not enough to describe the security model of the application. 4. the web server will receive a credential for the user.• Programmatic security – used to make security decisions and is different from declarative security because the code is embedded in an application. Security Behaviors Within a simple application. a JSP uses interface and enterprise bean business logic to construct the application. the security behaviors can be defined in five basic steps: 1.

2. 6. but uses the user’s credential). The web container will test the credential against each role to map the user to the appropriate role. Functions of Security A properly implemented security mechanism will provide functions for: • Easy administration • Transparency to system users 152 . the JSP page will perform a remote method call to the enterprise bean. The above evaluation ends as soon as the web server is able to map the user to a permitted role resulting in a “authorized” outcome. the EJB container will use the security context associated with the call to determine the appropriate mapping between the caller and the role (this is different from the user. an exception is thrown by the container back to the calling JSP page. Two related security contexts are implemented using the associations: one in the web server and one in the EJB container. Access control in the bean method is enforced by the EJB container by consulting the security policy associated with the bean.3. a “not authorized” result is reached. the web server will return the result of the original request for the URL which is a JSP page. 5. Once authorized. This deployment descriptor is consulted by the web server when a user requests access to a resource by determining the acceptable security roles. 4. the container will dispatch control to the enterprise bean method. If the user cannot be mapped to any permitted role. If authorized.contain the security policies for the web resources that the user is allowed. This page allows the user to post form data required by the business logic of the application. Once complete with the form data. If a “not authorized” result is reached from this authorization step. The user’s credentials are used to establish a secure association between the JSP page and enterprise bean. For each permitted role.

The 153 . Controlled access to protected resources is provided by authorization methods. Authorization is not required for access to unprotected resources and this is typically called unauthenticated or anonymous access.• Interoperability across application and enterprise boundaries • Prevention of unauthorized access to application functions and data. Authorization is based on identification and authentication activities.2. or data privacy. Security Characteristics Components in Java EE applications can be either protected or unprotected. specifically business and personal • Accountability to system users for operations • Protection of system for service interruptions and other breaches 6. while authentication verifies the identity of the entity. Protected resources will only allow authorized users to have access. Non-repudiation techniques are used to provide evidence that a user has performed some activity in such a way that the action cannot be denied.4. particularly sensitive data. ensures that only users who are authorized to access the data can access the data. Quality of Service represents the various technologies used to provide better services over the network. Some users may have access to modify data. The effectiveness of these technologies. as well as the security policies and mechanisms can be evaluated using tamper-resistant records which can be audited. device or other entity) to be recognized by the system. Data integrity ensures that modification of data is only performed by those users authorized to modify that data. Confidentiality. Identification enables an entity (user.

message integrity.system will maintain a record of all transactions and security information. Security Implementation Mechanisms There are several mechanisms which can be used individually or groups to provide the level and type of security required by the application. server authentication. The standard defines the methods for exchanging authentication data. 6. • Java Generic Security Services (Java GSS-API) – A token-based API used to exchange messages securely and uniformly between applications on top a variety of security mechanisms. key generation and agreement. and client authentication over Internet communications. • Java Secure Sockets Extension (JSSE) – provides a framework for SSL and TLS protocols for Java and includes functionality for data encryption. • Simple Authentication and Security Layer (SASL) – an Internet protocol standard for authentication and optional establishment of a security layer between client and server applications. • Java Cryptography Extension (JCE) – Provides a framework for encryption. Security services in Java EE are provided by the component container 154 . Java SE provides the following security features and mechanisms: • Java Authentication and Authorization Service (JAAS) – implements a pluggable and extensible framework of APIs for programmatic authentication and authorization of users. These mechanisms are found in either the standard edition of enterprise editions.2.5. and Message Authentication Code (MAC) algorithms.

• Security is vulnerable because of the application’s support of multiple protocols • Data is vulnerable Transport-layer security happens through mechanisms which transmit 155 . These services are separate from the security mechanisms of the operating system and are implemented on different layers. Fine-grained access control is provided to the functions and data or the application. but not transferable to applications in other environments. such as: • Application • Transport • Message Application-layer security is provided by the component containers. The security services for a specific application type are configured to meet the needs of an application. The advantages of application-layer security are: • The needs of the application are uniquely fulfilled in the security solution. with settings specific to the application. Security properties will only protect data residing in the current application environment.and implemented using declarative and programmatic techniques. The disadvantages of application-layer security are: • The dependence on non-transferable security attributes is present in the application. Application firewalls can be used to protect the communication stream and associated application resources from attacks. • Security is fine-grained.

• A symmetric cipher is used for all information exchange.information over wire between provider and client. • Public-key encryption and certificate-based authentication is performed to exchange a key. To resolve this. the server and client can authenticate each other and negotiate an encryption algorithm and keys before data is transmitted by the application. but disappears when the data reaches the destination. and confidentiality. Using a session protected by SSL. communications are encrypted before sending. 156 . Transport-layer security is performed through a number of phases: • The server and client agree on an appropriate algorithm. message integrity. This provides point-to-point security using authentication. Security is in place from the sender and through the entire transmission. The primary protocol that allows transport-layer security is a HTTPS transport using Secure Sockets Layer (SSL).

The security is relatively complex and adds additional overhead to processing. Then the message will be decrypted by the receiver. Unlike the transportlayer security. the security stays over all hops in the transmission until the message arrives at its destination. message-layer security is end-to-end. Message-layer security uses SOAP to provide security information. The message is protected only when in transit and removed automatically when the message reaches its destination. This is done using a SOAP message and/or SOAP message attachment which travels with the message being transported. A portion of the message can be signed and encrypted for a particular receiver. The encrypted portion of the message will remain encrypted for these nodes until the intended node is reached. Unfortunately. With message-layer security. Security can be applied to part of the message and is independent of the application environment or transport protocol being used. it is an absolute approach to security where security is attached to all portions of the message regardless of the message content.• This type of security is relatively simple and much understood standard technology. It can be applied to the message body and attachments of the message. The security is tightly-coupled with the transport-layer protocol. 157 . When a message is sent. not point-to-point. it will pass through a number of intermediate nodes. The Application Server supports message security and uses Web Services Security (WSS) to secure messages.

6.2.6. Container Security

A container can provide either declarative or programmatic security. Deployment descriptors are used to provide declarative security. Deployment descriptors are XML documents describing the deployment settings for an application, a module, or a component. These documents end with an .xml extension. They allow control information to be changed without changing the source code. The Java EE server simply reads the deployment descriptor at runtime to determine the settings and apply to the application, module, or component appropriately.

Components use different formats, or schema, in their deployment descriptors. The deployment descriptor provides structural information for each component if the information is not already provided in annotations or set to defaults. The security elements of a deployment descriptor are: • An Enterprise JavaBean deployment descriptor must be contained in the EJB JAR file to support EJB components. The document is named META-INF/ejb-jar.xml and the schema is provided by the EJB 3.0 Specification. • The deployment descriptor for Web Services components is defined in JSR 109 and named as jaxrpc-mapping-info. It provides deploymenttime mapping functions between Java and WSDL. The schema for this file is provided in JSR-109, Web Services for Java EE. • Web components use a web application deployment descriptor. The file is named web.xml and the schema used is provided in the Java Servlet 2.5 Specification (JSR-154).

Annotations are a declarative programming style which utilizes both declarative and programmatic security concepts. With annotations, information about security is specified in class files. The Application Server uses this information when the application is deployed. Some
158

security information cannot be expressed in annotations and must be declared in the deployment descriptor. The use of annotation prevents the need to create boilerplate code. This is done by enabling tools to generate the required code from annotations in the same manner as declarative security. From the programmatic security aspect, security information is contained in the source file and not in side files which must be maintained whenever the source file changes.

Security information embedded in the application code utilizes programmatic security. The API for programmatic security contains two methods of the EJBContext interface and two methods of the servletHttpServletRequest interface to enable components to make business logic decisions based on the security role of the user or caller.

159

6.2.7. Securing the Application Server

The Application Server supports the Java EE 5 security model. It can be configured to provide: • Addition, deletion, and modification of authorized users • Configuration of secure HTTP and IIOP listeners • Configuration of secure JMX connectors • Definition of an interface for pluggable authorization provides using JACC • Use of pluggable audit modules • Policy permission setting and changing

Application Servers allow: • Message Security • Single sign-on for all Application Server applications in a single security domain • Programmatic login

6.2.8. Realms, Uses, Groups, and Roles

A realm is defined on a web or application server and contains a collection of users who are or are not assigned to a group. Applications will typically prompt a user for a username and password before allowing access to protected resources. The information provided by the user will be sent to the server for authentication. In some applications, authorized users will be assigned to roles which must be mapped to groups defined on the Application Server.

160

http://localhost:4848/asaadmin (use correct port number if Admin default is not being used). The principle name for the user is the common name file of the X. The Application Server is preconfigured with the realms: file. Start the Application Server 2. an identity can be associated to a set of roles to enable access to all resources protected by the roles. The certificate realm stores user credentials in a certificate database which is used the HTTPS protocol to authenticate web clients by verifying an X. Identities can be associated to groups. certificate.For web applications. The Java EE user is located in a different realm than the operating system user. In web applications. Log in the Admin Console using the user name and password of a 161 .509 certificate. Multiple realms can be managed by the Java EE server authentication service.509 certificate. a realm is a database of users and groups identifying the valid users for the web application and controlled by the same authentication policy. 3. Start the Admin Console by opening a web browser and entering the URL. The admin-realm is a file realm that stores administrator user credentials locally in the adminkeyfile file. The Admin Console is used to manage users in the same manner that users are managed in the file realm. Users are managed by the Admin Console and verified by the server authentication service for all clients except for web browser clients using the HTTPS protocol and certificates. and admin-realm. Users can be added to the Application Server with the following steps: 1. A Java EE server authentication service has no knowledge of the username and password used to log on to the operating system and cannot connect to the security mechanism for the operating system. The file realm stores user credentials in the keyfile file. Users are individuals whose identity is defined in the Application Server.

9.xml. the user identity is set up in the security context of the Application Server and populated with user data from the cryptographically-verified client certificates. 7. the person performing the deployment will map roles to security identities in the operational environment. 8. while Java EE users in the certificate realm cannot belong to an Application Server group. When adding users to the certificate realm. roles are 162 .xml and mapped in the Application Server deployment descriptor file sun-application. A group is designated for the entire Application Server while a role is associated with a specific application on the Application server. Expand the Realms node and add users to the file realm or adminrealm realm. Java EE users in the file realm can belong to an Application Server group. Security roles for an application are defined in the Java EE deployment descriptor file application.user in the admin-realm belonging to the asadmin group. Expand the Security node. In the Admin Console tree. expand the Configuration node. For Web or EJB modules. 4. Each security role is an abstract and logical grouping of the users. A group is a set of authentication users defined by common traits and defined in the Application Server. Click the manage Users button. 5. Password. Click New to add a new user and enter the correct information into the User ID. The definition of roles is at the discretion of the person assembling the application. Click OK to add user to the users list. 6. When deploying an application. Click Logout after adding all users. and Group fields. A role defines the permissions for a particular set of users to access a particular set of resources in an application. 10.

identified using a principal name and authenticated using data specifically created for authentication.xml. The data being sent is encrypted before being sent 163 . Java EE platform uses the following terms to support security requirements: • Principal – an entity authenticated by an authentication protocol in a security service deployed within an enterprise. • Security policy domain – a security domain or realm controlled by a common security policy and enforced by the security administrator of the security service.9.xml and mapped to the Application Server deployment descriptor files sunweb. Roles can be mapped to a specific user.xml.2. sun-web. or sun-ejb-jar. This file is either sun-application.xml or sun-ejb-jar. 6.xml or ejb-jar. group.xml. SSL Secure Connections Secure Socket Layer (SSL) technology provides security in the transport layer to allow communication over a secure connection for web browsers and web servers.xml. • Security attributes – associated with every principal by an authentication protocols and has a variety of uses. • Credential – contains or references information used to authenticate a principal for java EE product services.defined in the Java EE deployment descriptors web. Roles defined in the application can be mapped to users and groups defined in the realm using the security-role-mapping elements in the runtime deployment descriptor file. or both.

protected or not. User data constraints are used in the deployment descriptor to specify a requirement that protected resources must be received over a protected transport layer using a mechanism such as SSL. All constrained URL patterns and HTTP methods identified in the security constraint will be received over a protected transport layer connection. confidentiality. and integrity to the connection. The SSL HTTPS connector is enabled in the Application Server. The user data constraints are specified within the security constraint. A transport guarantee is specified in the user data constraint and can be identified as: • CONFIDENTIAL – used when the transmitted data must prevent other entities from seeing the transmission contents. • INTEGRAL – used when the data sent between the client and server cannot be changed.2.and decrypted after being received. SSL provides authentication.10. • The location of the keystore file and password must be specified in the deployment descriptor for the server. Digital Certificates 164 . To enable SSL for a server: • A connector element for an SSL connector in the server deployment descriptor must be present. 6. • NONE – the container accepts constrained requests on any connection. • A valid keystore and certificate files must be present.

Public key cryptography is used in SSL. Data encrypted with one key can only be decrypted using the other key. Java EE Application Security The following methods can be used to by Java EE security services: • Annotations • Declarative security • Programmatic security 6.1.3. 6. A value computed by the service can be encrypted using the private key. The digital signature is decrypted by the client using the public key for the server. The encrypted value is considered the digital signature. SSL requires that an associated certificate is available for each external IP address. These certificates are selfsigned and not intended for use in production.3. Security for Enterprise Beans 165 .Already created digital certificates for the Application Server can be found in the domain-dir/config/ directory. they must be generated and signed by a certificate authority. The certutil utility is used to create digital certificates in the enterprise profile. accepting secure connections. but only in development. the signature is considered authentic and can be trusted. For digital certificates to be used in production environments. Key pairs are used to establish trust across a connection. or interface. A public key and a private key make up a key pair in the mechanism. The HTTPS protocol uses digital certificates to authenticate web clients. If the value of the digital signature matches the computed value.

allows the enterprise methods to obtain the current caller principal’s name.Enterprise beans run in an Enterprise JavaBeans (EJB) container. Boolean isCallerInRole(String roleName). . The security API is used when those business methods must access the security context information.EJBContext interface provides two methods for access security information by the bean provider: java. . Through this declaration. the security role names used in the code can be mapped to the defined security roles of the assembled application. The container serves as a runtime environment within the Application Server and provides system-level services to enterprise beans. These services provide security and transactional services. 166 .security. The javax.ejb.Principal getCallerPrincipal(). The following methods are used to protect an Enterprise Bean: • • • • • • • Security Context Security Role Names Security View Annotations Elements in Deployment Descriptors IOR Security Secured Enterprise Beans The EJB container enforces security in a transparent way to the enterprise bean’s business methods.tests a current caller’s assignment to a given security role defined by the bean provider or application assembler. If this mapping is not explicitly formed. Security Role names can be declared in the enterprise bean code using the @DeclareRoles annotation or the security-role-ref elements in the deployment descriptor.

These method permissions are 167 . The USERNAME-PASSWORD authentication method is used for the enterprise bean. component interface. while either BASIC or CLIENT-CERT authentication methods are used for web service endpoints. Authentication mechanisms can be specified within the runtime deployment descriptor. Any security role referenced in the code can be declared using the @ DeclareRoles annotation. Security role references are linked to the security roles defined for an application. The declared name mused as a parameter in the isCallerInRole(String roleName) method must be the same as the parameter value. This is done by adding a <login-config> element to the runtime deployment descriptor.2. the security role name is declared using the role-name element in the DD and must be the same name used as a parameter to the isCallerInRole(String rolename) method. An optional description of the security role can be provided in the description element. The annotation is specified on a bean class to declare riles which can be tested by calling isCallerInRole from methods in the annotated class. and/or web service endpoints.it is assumed that the corresponding roles have the same name.3. Security View A security view of the enterprise bean contained in the ejb-jar file and information passed on to the deployer. When using deployment descriptor elements. A security view is a set of security roles required for a given type of user of an application to successfully access the application. 6. Interoperable Object Reference (IOR) can be configured to enable authentication for an enterprise application if annotations are used. Method permissions invoke a specified group of methods of the bean’s business interface. home interface.

the method-permission elements are used. The roles defined in the application are mapped to the users or groups defined during runtime. The union of all method permissions defined in the individual method-permission elements is called the method permission relation. Sometimes. Open the Admin Console on the Application Server. 168 . The security-role deployment element can be used to define security roles not declared by annotations. This is the process rather than using security roles and allows an application developer to continue without knowing what categories of users are defined for the realm where the application is running. The role name can be mapped to a specific user (principal). To specify method permissions using deployment descriptors. This particular mapping is performed using the security-rolemapping element in the runtime deployment descriptor. The following annotations can be used to specify method permissions: • @RolesAllowed(list of roles) – specifies a list of security role names to be mapped to security roles to permit the execution of specified methods. To enable the default mapping: 1. or both.defined for each security role. Each method is identified by the method element. Users are assigned to principals or groups by the Application Server. Each element includes a list of one or more security roles and a list of one or more methods. • @DenyAll – prevents any security role from being permitted to execute the specified methods. group. which is the default setting for principal-to-role mapping. the role name is the same as the group name defined on the Application. • @PermitAll – allows all security roles permitted to execute the specified methods. A security role or method can appear in multiple method-permission elements.

the security identity in the first call is the identity of the caller. but establishes the identity used by the enterprise bean that might be called. In this process. and the security identity of the second call can be the identity of the caller of the container or a specific identify propagated to the target enterprise bean. A Java EE security identity can be used to execute specified methods of an enterprise bean or a specific run-as identity can be specified.2. Run-as identities for the enterprise bean do not affect the identities of its callers.xml or the module layer in sun-ejb. Mappings at the application layer will apply to all contained modules and override any mappings at the module layer which have the same name. The method will make a call to the enterprise bean method in another container. Check the Enabled box for Default Principal to Role Mapping. 169 . An application client will call an enterprise bean method in an EJB container. Expand the Configuration node and then the Security node. Security role mapping in an application can happen on the application layer in sun-application.xml. 3.

2) and the Common Secure Interoperability version 2 (CSIv2) COBRA Secure Interoperability specification. 6. • as-context – describes the mechanism used to authenticate the client and contains the elements of required.6. If the deployer does not have access to a security view. • sas-context – related to the CSIv2 security attribute service. IOR Security Interoperable Object Reference (IOR) is a EJB protocol based on Internet Inter-ORB Protocol (IIOP/GIOP 1. 170 .3. How an application is deployed is specific to a web or application server. and establish-trust-in-client.3. auth-method. confidentiality.3. Some common sub-elements are: • transport-config – the root element for security between endpoint. and realm. the appropriate security policy must be set up for the enterprise bean application. It is often used when an enterprise bean deployed in the server product of one vendor is accessed from Java EE client components deployed in a product of another vendor. It contains the elements for integrity. The deployer should have access to the security view since they are responsible for ensuring the assembled application is secure after being deployed.4. IOR configurations are specified in Sun-specific xml files as the iorsecurity-config elements. Deployment of Secure Enterprise Beans The security view is mapped to mechanisms and policies used by the security domain in the operating environment. establish-trust-intarget.

When accessing protected web resources. Application Client Security The authentication requirements and techniques for application clients are the same as those for Java EE components. When accessing unprotected web resources. A security credential is required for accessing EJB methods. typically a generic unauthenticated. Any user or group can invoke a method. an unauthenticated user is required to specify a name and password when modifying the server using the Admin Console. The specification of the credential is based on the implementation. the following authentication methods may be used: • Basic HTTP • SSL Client • HTTP login form When accessing protected enterprise beans. Authentication data can be gathered in a class: if 171 . In an Application Server. if the deployer has granted full access to the method. no authentication is necessary. 6.Web applications can accept unauthenticated web clients and allow calls from the client to the EJB container. The user can be authenticated by the container when the application is started or each time a protected resource is accessed. authentication is required.5.3. A role used in application to grant authorization to a user or group can be modified by specifying a value for Anonymous Role. The authentication service is provided by the application client container and integrates with the native platform’s authentication system to provide single sign-on capabilities.

• The callback handler performs and user interaction which is requested and set the appropriate values for the callbacks. The design of 172 .auth.callback. The login module will remain independent of other interactions between the application and users.auth. appserv.ProgrammaticLogin class which has several login and logout methods.security. When using programmatic login. the client code will supply any user credentials. this is done through com.CallbackHandler interface is implemented.security. Programmatic login is specific to the server. EIS Applications With EIS applications.sun. The callback handler must support Callback objects specified in the package javax.callback. Login modules will use the interface to gather identity information and supply information to users. security.the class name is specified in the deployment descriptor and the javax.6. 6. While the login module and the callback handler is communication. the following process is performed: • Callbacks are sent by the login module to the handle method of the callback handler. When using an EJB client. the connection to an EIS resource is requested by the components and requires a sign-on for the requestor. When the CallbackHandler interface is passed on to the login context by the application after implementation and forwarded to the login modules running underneath.3.

The following elements can be configured in the deployment descriptor for the resource adapter: • Authentication mechanisms – either BasicPassword which supports the javax.resource. as well as the determination of the user name and password for establishing a connection.security. • Managed by the component.PasswordCredential interface or Kerbc5 which supports the javax. • Reauthentication support – determines if the resource adapter will reauthenticate existing Managed-Connection instances. Security information is passed on through the getConnection method.spi.resource.security. Resource adapters are software components at the system level which enables network connectivity to external resource managers.this EIS sign-on can be one of two options: • Managed by the container.GenericCredential interface. Security maps are used with the Application Server to map the 173 . On the Java EE platform. The ra.xml file is edited to configure the security settings for a resource adapter. a resource adapter will expand functionality by implementing a standard service API for Java EE or define and implement a resource adapter for a connector to an external application system. where the responsibility for configuring and managing the EIS sign-on falls to the container. The interface between the Java EE platform and a resource adapter is the Java EE service provider interface (Java EE SPI).spi. where the component code in the application managed the EIS sign-on. • Security permissions – specifies the required security permission for the resource adapter code.

The security map used is defined for the connection pool for the connector. 174 . If no match exists. The check determines the mapped back end EIS principal. the Application Server will use wild card characters to determine the mapped-back-end EIS principle.application’s caller identity to a suitable EIS principal. This is performed in container-managed situations. When a principal of the application invokes a request to an EIS. the security map is used by the Application Server to check for the exact principal. This is especially useful when EIS operations are required to execute as a specific identity.

Values specified in annotations are generally overridden by values in the deployment descriptor. Expand the Connectors node. Some of the security related to web applications is configured when installing or deploying the application to the web container. security.The Admin Console is used to manage security maps. Fundamentals of Web Application Security Web components in the Java EE platform provide dynamic extension capabilities for a web server. The services include dispatching. Expand the Resources node. and life-cycle management. providing the services of a runtime platform. They are supported by a web container. From the console: 1. or web service endpoints. Select the Security Maps page.4. 175 .4. 5. 2. These components are comprised of Java servlets. Select a Connector Connection Pool from the list or create a new connector connection pool.1. JSF pages. The combination of annotations and descriptors allow the deployer to setup of the appropriate security policy for the application. 6. Select the Connector Connection Pools node. Web Application Security 6. concurrency. 3. This is usually found in the form of annotations or deployment descriptors. JSP pages. 4.

Role References When using the isUserInRole method. • getUserPrincipal – determine the principal name for the current user and returns a Principal object. However. the value used by it is a String representing the role name of the user. Caller Identity Checks The container should manage security transparently to the web component.2. the container will default to checking the provided role name against a list of all security roles defined in the web application. The HttpServletRequest interface allows security information about the component caller to be accessed using the following methods: • getRemoteUser – used to determine the user name being authenticated for the client. Roles can be declared using annotations or deployment descriptor elements.3.6. they utilize the security API for Java EE. 6. When a <security-role-ref> element is not declared in a deployment descriptor and the isUserInRole is called.4. The name of the role being called by the web component is mapped to the name of the security role defined for the application. The mapping is defined as the security role reference. there are a few times when web component methods must access information on the security context. 176 .4. To do this. The default method limits the ability to change role names without recompiling the servlet calling the application. • isUserInRole – determines a specific security role the remote user may be assigned.

The <web-app> element is the root element for web applications and contains the following elements related to security in a web application: • <security-role-ref> . an optional description of the reference. The deployment descriptor may use the metadata-complete attribute in the web-app element. and manages the use of HTTPS. Values specified in both the annotations and the deployment descriptor will utilize the deployment descriptor. but a value has been declared in annotations. This is continued with each servlet. If a value has not been declared in the deployment descriptor. the deployer will independently determine the requirements it needs. the deployment descriptor will examine class files for annotations. When not defining security requirements. The attribute defines the completeness of the deployment descriptor or the need to examine the class files of a JAR file for any annotations related to deployment. Deployment descriptors are used when using declaratively stated security.used in conjunction with the security-role-ref 177 . support user authentication. the annotation will be used.4.declares a security role reference in the code of the web application and consists of the security role name. If no attribute is declared or the result is false. Information passed to the deployer is used to define method permissions for security roles.6. • <security-role> . while annotations are used for programmatically stated security. Security Requirements Security is initiated for a deployed application either declaratively or programmatically.4. and an optional link to a security role.

will establish an authentication requirements and the names of roles authorized to access the URL patterns and HTTP methods declared by the security constraint • <user-data-constraint> . 6. the realm the user is being authenticated.will establish a requirements for receiving constrained requests over a protected transport later connection.element to map roles defined in the code and roles defined for the web application. • <login-config> .5. Security constraints define who web content is protected by defining the access privileges. or CONFIDENTIAL Security constraints called through the RequestDispatcher method will not work.defines the access privileges to a collection of resources using a URL mapping and consisting of sub-elements such as <web-resource-collection>. <auth-constraint>. thus providing a transport guarantee of either NONE. • <security-constraint> . Security constraints are defined in the deployment descriptor and contain the elements of: • <web-resource-collection> . and additional attributes relevant to form-based login. They will work for the original request URI only: the portion of the URL after the host name and port.a list of URL patterns and HTTP operations describing the protected resources • <auth-constraint> .4.specifies the methods used for user authentication to access web content. Separate security constraints can be defined for different resources in the application. Secure Connections 178 . and <user-dataconstraint>. INTEGRAL.

179 . The choices for the guarantee are NONE. or CONFIDENTIAL. INTEGRAL.All constrained URL patterns and HTTP methods specified in the security constrained may be required by a user data constraint to be received across a protected connection such as HTTPS. The user data constraint will specify a transport guarantee.

FORM. 2. The server authenticates the user in the realm specified and returns the resource requested. The process for basic authentication is: 1. 180 . The auth-method sub-element which defines the authentication method provides the choices for BASIC. 4. a secure transport mechanism can be used. CLIENT-CERT. Authentication Mechanisms The login-config element is declared in the deployment descriptor for the application to specify an authentication mechanism.6. 3.6. This form of authentication will verify the validity of the user name and password by comparing the provided values against a database of authorized users. HTTP Basic Authentication does not provide a secure authentication method because the user name and password is sent over the network as Base64 encoded text and the target server is not authenticated. The client enters the user name and password in the dialog box which returns to the server. A dialog box is returned by the web server requesting the user name and password.4. The element will configure the method for authentication and the realm name to be used for the application. Access to a protected is requested by the client. As a result. HTTP Basic Authentication requires a user name and password be requested by the server for any web client. DIGEST. user names and passwords can be easily decoded and are exposed by any person intercepting the transmission. To increase the security of the transmissions. or an authentication scheme which is specific to a vendor.

If the client fails authentication or authorization. The content of the user dialog box is sent as plain text. 2. the principal for the authenticated user is checked to ensure authorization to access the resource. The login screen and error pages presented to the user are customized. The server attempts authentication of the user. When using form-based authentication. If the client is unauthenticated. they are redirected by the server to a login page. Secure Socket Layer (SSL) provides data encryption. message integrity. and optional client authentication over a TCP/IP connection. The target server is not authenticated either. Access to a protected resource is requested by the client. A Public Key Certificate (PKC) is required in HTTPS Client Authentication. This form of authentication is more secure than basic or form-based authentication because it utilizes HTTP over SSL (HTTPS).The aesthetics of the login process can be controlled through form-based authentication. they are redirected to an error page. In order to use HTTPS Client Authentication. making form-based authentication not very secure. 181 . The login form is completed by the client and submitted to the server. server authentication. The web server will authentication using the PBC when client authentication is specified. 4. 3. If authentication succeeds. the server must be configured to support SSL and the client must have a valid PKC. If the user is authorized the server will redirect the client to the resource through a stored URL path. the process follows: 1. The user names and passwords are exposed unless all connections are over SSL.

by utilizing either certificates or user name and passwords. 6. The user name and password is verified by the server. Unlike HTTP basic authentication.When using mutual authentication. The certification for the server is verified by the client. If successful. If successful. 4. If the verification is successful. the client sends its certificate to the server. 6. The certification for the server is verified by the client. 5. 5. 3. 182 . It is not implemented in the Application server and is not used widely. the client sends its user name and password to the server. 2. The process for certificate-based mutual authentication is: 1. If the verification is successful. The certification for the client is verified by the server. 2. Access to a protected resource is requested by the client. the server will grant access to the protected resource. The process for mutual authentication using user names and passwords is: 1. 3. the server and client will authenticate each other. the password is transmitted in an encrypted form rather than a Base64 encoding. HTTP Digest Authentication will use a user name and password for authentication. Access to a protected resource is requested by the client. The web server presents its certificate to the client. The web server presents its certificate to the client. the server will grant access to the protected resource. 4.

Authentication Authorization Requesting resources Providing resources 183 .7 Practice Exam 7. Refresher “Warm up Questions” The following multiple-choice questions are a refresher. C. Question 1 Which of the following is used in Security Assertion Markup Language? A. D. B. SOAP HTTP XML All of the above Question 2 Security policies found in the deployment descriptor provide applications information for what security behavior? A. D. C.1. B.

Java GSS-API JAAS JSSE SASL Question 4 What is the primary purpose of an application firewall? A. B. B. C. Protect the communication stream Provide point-to-point security Provide security information using SOAP All of the above Question 5 What type of document is a deployment descriptor? A. C. D. C. D. HTML XML JSP JAR 184 . D. B.Question 3 Which of the following security mechanisms in Java SE provide SSL support? A.

B. D. what convention would be used? A. C. B. C.Question 6 Which of the following security features is not available to Application Servers in a Java EE environment? A. Realms Groups Roles Any of the Above 185 . Programmatic login Message security Single sign-on Physical lock Question 7 If trying to associate users to a particular application on the Application Server. D.

what is required? A. B. D. B. C. Connector element Encryption Valid keystore Certification files Question 9 To secure enterprise beans when accessing its methods. Security Credential Security Role Deployment Descriptor Role Mapping 186 .Question 8 Which of the following does not need to be present to enable a SSL HTTPS connector in the Application Server? A. C. D.

what sub=element of the configuration is used to authenticate the client? A. C. D. D. C. B. sas-context as-context transport-config ior-security-config 187 . <security-role-ref> <login-config> <security-constraint> <security-role> Question 11 In Interoperable Object Reference (IOR). B.Question 10 Which web application element defines the access privileges to a collection of resources? A.

Realms Roles Groups All of the above Question 14 Which of the following is not used in pure programmatic security? A. B. B. sun-ejb-jar. C. D.Question 12 Which of the following deployment descriptor files are used at runtime by the application to define and map users and groups to roles? A. Deployment Descriptors Annotations EJBContext interfaces servletHttpServletRequest interfaces 188 .xml sun-application. C.xml All of the above Question 13 Users can be associated to what security construct? A.xml sun-web. D. B. D. C.

D. HTTPS SSL SOAP RIP Question 16 Which of the following layers are security mechanisms not implemented by the security services in Java EE? A. B. C. D. C. Application Transport Message Physical 189 .Question 15 What is the primary protocol used at the message-layer of an application to security information? A. B.

Question 17 The maintaining of records for all transactions and security information in an enterprise is a function of what technology concept? A. B. D. Confidentiality Quality of Service Integrity Authentication Question 18 Which of the following steps of an application occurs immediately before fulfilling a client’s request? A. Invoking methods Requests Authorization of URLs Authentication 190 . C. D. B. C.

C. WS-Trust WS-Policy WS-Authorization WS-Federation 191 . From the deployment descriptor From within the EJB container From the Java Virtual machine From the server Question 21 Which of the WS-Security components manages security identities? A. Authentication C. B. Confidentiality B. Authorization Question 20 Where do EJB components run at application runtime? E. G. H. F. D.Question 19 Encryption and decryption are processes behind what security concept? A. Integrity D.

Encryption Message Integrity Secure Exchange of Data None of the above 192 . C. D. D. B. how many related security contexts are created? A. C.Question 22 When working with a calling JSP page and an enterprise bean. none one two As many as required Question 23 What type of framework is provided by the Java Cryptography Extension (JCE) security mechanism? A. B.

B.xml web. D. Support of multiple protocols Fine-grained control Security is applied to the message body Portions of messages can be secured independently of other portions Question 25 What is the name of the deployment descriptor used for components of Web Services? A. C. C.xml jaxrpc-mapping-info.Question 24 Which of the following is an advantage of security at the application layer? A. D. B. ejb-jar.xml None of the above 193 .

C. B. C.509 certification? A. file admin-realm admin-keyfile certificate Question 27 What is an entity that can be authenticated in a security officially called? A.Question 26 Which preconfigured realm identifies a user’s credentials using an X. D. Credential Principal Attribute Group 194 . D. B.

D. B. D. which of the following authentication methods are appropriate? A. Associating users with security roles Allowing business methods to access security context information Providing encryption and decryption features All of the above Question 29 When accessing protected web resources. B. C. SSL Client Basic HTTP HTTP login form All of the above 195 . C.Question 28 What is the security API associated to an EJB container used for? A.

Question 30 Which security constraint for a web application provides a list of URL patterns and HTTP operations? A. D. B. B. Resource Adapter Security Context Security View Deployment Descriptor 196 . C. D. C. <user-data-constraint> <auth-constraint> <web-resource-collection> None of the above Question 31 What is used to by EIS applications to enable network connectivity to external resource managers? A.

CONFIDENTIAL FULL NONE INTEGRAL 197 . D.Question 32 Which of the following annotations specify list of security role names which are mapped to security roles permitted to execute specific methods? A. C. @PermitAll @RolesAllowed @DenyAll @AllowRoles Question 33 Which of the following transport guarantees specified in user data constraints is used to prevent data being transmitted from being changed between the client and server? A. B. D. B. C.

B. D.Question 34 Which of the following preconfigured realms of an Application Server is not managed using the Admin Console? A. B.0 Specification JSR-109 Java Servlet 2. C. D. C.5 Specification JSR-220 198 . certificate admin-realm file None of the above Question 35 The schema for a web application deployment descriptor is defined in what document? A. EJB 3.

D. B.Question 36 Public-key encryption is a process found in what security layer of an application? A. D. Application Transport Message Any of the above Question 37 Which of the following is an Internet protocol standard for authentication and methods for exchanging authentication data? A. B. Simple Authentication and Security Layer Java Secure Sockets Extension Java Generic Security Services Java Authentication and authorization Service 199 . C. C.

C. B. Programmatic security Declarative security External security Annotated security 200 . Transparent operation Ease-of-use administrations Prevention of unauthorized access Isolation of application operations Question 39 Deployment Descriptors are used for what form of security? A. D. C. D.Question 38 Which of the following is not a function of a properly implemented security function? A. B.

Authorization Identification Authentication Integrity 201 . C. D. B.Question 40 Which security action provides the verification of a user’s credentials to allow access to resources? A.

8

Answer Guide

8.1. Answers to Questions

Question 1 Answer: D Reasoning: Security Assertion Markup Language (SAML) is based on XML, XML Schema, XML Signature, XML Encryption, HTTP, and SOAP.

Question 2 Answer: B Reasoning: Security policies are declared in the deployment descriptor. These policies provide information on which users have the authority to access which resources and at when level. This is the process of authorization.

Question 3 Answer: C Reasoning: Java Secure Sockets Extension (JSSE) provides the framework to support SSL and TLS protocols to allow data encryption, server and client authentication, and message integrity.

202

Question 4 Answer: A Reasoning: Application firewalls are implemented on the application layer and will protect the communication stream and application resources from attack. They are generally restricted to support a single application environment.

Question 5 Answer: B Reasoning: Deployment descriptors are XML documents.

Question 6 Answer: D Reasoning: Although locks may be available for the physical hardware of the server, it is not within the scope of security for Java EE.

Question 7 Answer: C Reasoning: Groups are used to associate users across the entire Application Server while roles are used to provide association to a specific application on the Application Server. An Application Server is typically associated to a particular server environment or application environment.
203

Question 8 Answer: B Reasoning: SSL provides encryption services which do not need to be present before enabling a SSL HTTPS connector.

Question 9 Answer: A Reasoning: A security credential is required to access EJB methods in a secure enterprise beans.

Question 10 Answer: C Reasoning: The <security-constraint> element defines the privileges to access a set of resources. The <login-config> element specifies the methods used in user authentication. The <security-role-ref> and <security-role> elements declares a security role reference in the code of the web application and maps the security role defined for the web application to those defined by the code.

Question 11 Answer: B Reasoning: The ior-security-config element contains the other mentioned sub-elements. The as-context sub-element describes a mechanism for authenticating the client.

204

xml.Question 12 Answer: D Reasoning: All of the files mentioned – sun-ejb. Roles define the permissions for sets of users. and sun-application. Deployment descriptors will use security-role-mapping elements to map users and groups to roles defined in the application.xml. groups. and roles. The API for programmatic security will provide two methods of the EJBContext and servletHttpServletRequest interfaces. As a result user can be associated to realms. Question 14 Answer: A Reasoning: Deployment descriptors are strictly used in declarative security and therefore cannot be used in programmatic security. sun-web. Annotations are used in a declarative programming style and encompass security concepts used by declarative and programmatic security implementations. Groups are a set of users with a common trait.jar. Question 13 Answer: D Reasoning: A realm is a database of users and groups.sml. are used at runtime. 205 .

The effectiveness of these technologies is reliant on the auditable records of all transactions and security information related to the enterprise. They are separate from mechanisms found in the hardware or operating system. and message layers. SOAP is used at the message layer of the application to provide security information.Question 15 Answer: C Reasoning: The HTTP protocol is a transport protocol which provides no security. 206 . The physical layer does not have any implemented security mechanisms for Java EE. RIP is a protocol used by routers for identifying and managing locations of nodes on the network. SSL can be attached to HTTPS to provide security features and is commonly referred to as HTTPS. transport. Question 16 Answer: D Reasoning: Java EE security mechanisms are implemented on the application. Question 17 Answer: B Reasoning: Quality of Services describes the set of technologies used to provide better service over the network.

Authenticate. Question 20 Answer: B Reasoning: The most correct answer is the EJB container. and WS-Authorization. Components of the bean cannot run outside the container. The WS-Federation component handles the management of security identifies across multiple platforms and organizations.Question 18 Answer: C Reasoning: All security behaviors within an application can be defined in five basic steps in the following order: Request. 207 . WS-SecureConversation. Authorize URL. Fulfill Request. and Invoke Methods. Question 21 Answer: D Reasoning: WS Security is comprised of the following components: WSPolicy. WS-Trust. WS-Privacy. Question 19 Answer: A Reasoning: Confidentiality is performed using the processes for encryption and decryption. WS-Federation. An enterprise bean must run within an EJB container.

making control of security particularly fine-grained. Question 23 Answer: A Reasoning: JCE provides a framework for encryption.Question 22 Answer: C Reasoning: Security contexts provide mapping information and two are implemented when a secure association between the JSP page and the enterprise bean is created. security settings for security can be configured specific to an application environment. One security context is created in the web server and the second in the EJB container.xml and components of a web application use web. key generation and agreement. However. Support of multiple protocols by an application is considered a disadvantage to security becomes it expands the number of vulnerabilities which need to be addressed. while the last two apply to transport layer and message-layer security respectively. and MAC algorithms. 208 . Question 24 Answer: B Reasoning: The first two choices apply to application-layer security.xml: EJB components use ejb-jar. Question 25 Answer: C Reasoning: Components of Web Services use the deployment descriptor named jaxrpc-mapping-info.xml.

Question 26 Answer: D Reasoning: The preconfigured realms found on an Application Server are file. SLL Client. Question 29 Answer: D Reasoning: Access to protected web resources can be obtained using the authentication methods of HHTP. certificate. Question 28 Answer: B Reasoning: The security API used with EJB is used to allow business methods access to information relevant to the ELB’s security context. and admin-realm. The certificate realm will store user credentials in a database and verification is through an X. Question 27 Answer: A Reasoning: Principals are entities authenticated by an authentication protocol in a security service.509 certificate. 209 . and/or a HTTP login form.

210 .Question 30 Answer: C Reasoning: The <web-resource-collection> provides a list of URL patterns and HTTP operations in the deployment descriptor which describes the protected resources of the web application.

211 . The @RolesAllows is applied to a specific list of security role names. INTEGRAL is the choice when the data sent between the client and server cannot be changed. Question 33 Answer: D Reasoning: FULL is not a designated transport guarantee. while @Denyall restricts all roles from executing specific methods. They expand the functionality of the Java EE platform by enabling connectivity over the network to resource managers outside the network.Question 31 Answer: A Reasoning: Resource adapters are software components. Question 34 Answer: A Reasoning: Only the file realm and the admin-realm realm are managed using the Admin Console. Question 32 Answer: B Reasoning: The @AllowRole annotation does not exist. @PermitAll allows all roles to execute specific methods.

5 Specification. Question 36 Answer: B Reasoning: Public-key encryption and certificate-based authentication are security mechanisms implemented at the transport layer to ensure a secure transmission of data. Question 38 Answer: D Reasoning: A security mechanisms which is properly implemented will provide an appropriate level of interoperability between applications and enterprise boundaries and not isolation of functions.Question 35 Answer: C Reasoning: The schema used for deployment descriptors of web applications is provided by JSR-154 or the Java Servlet 2. 212 . Question 37 Answer: A Reasoning: Simple Authentication and Security Service (SASL) is an Internet protocol standard for authentication and defines the methods used to exchange authentication data.

This make them part of declarative security. 213 .Question 39 Answer: B Reasoning: Deployment descriptors are used to define security requirements through declarations in the file. Question 40 Answer: C Reasoning: Authentication is the security process for verifying user’s credentials to allow access to server resources. The other form of security is programmatic.

Larry. Kalin. 2nd Edition. McGraw-Hill Osborne Media: 2008 Mughal.: 2006. Bert. Cade. Sun Certified Enterprise Architect for Java EE Study Guide. GIAC information: www. Learning Java. Addison-Wesley Professional: 2008. Prentice Hall: 2010 The Java EE 5 Tutorial for Sun Java System Application Server 9. 2006. A Programmer’s Guide to Java SCJP Certification: A Comprehensive Primer. Simon.giac. Head First Java. Third Edition. Bert. Pearson Certification: 2003. Oracle: Sept 2010. Second Edition. Hall. Knudsen.1.: 2003. O’Reilly Media Inc. Marty and Brown. Sybex: San Francisco. and Rasmussen. Prentice Hall: Santa Clara. 2nd Edition. Patrick. O’Reilly Media Inc.: 2005. Alain. Rolf W. 3rd Edition. Kathy and Bates. Martin. O’Reilly Media Inc. Complete Java 2 Certification Study Guide. Java Web Services: Up and Running.com 214 . Sierra. Head First EJB.9 References Heller. Sierra. Sierra. Khalid A. SCJP Sun Certified Programmer for Java 6 Study Guide Exam. O’Reilly Media Inc. Kathy and Bates. Kathy and Bates. Philip and Roberts. Humphrey. Core Servlets and JavaServer Pages: Volume 1: Core Technologies.: 2005. Sun Certification Training Guide: Java 2 Enterprise Edition Web Component Developer Exam. Bert. Jonathan and Niemeyer. Trottier. Mark and Sheil. 2005.

theartofservice.com 215 .com.au www.Websites www.org www.artofservice.theartofservice.

You're Reading a Free Preview

Download
scribd