Sun Certified Enterprise Architect - Quick Reference
Date: May 2001
Author: Chris Broecker
This memo contains quick reference information that I found useful in preparing for the “Sun Certified Enterprise Architect for the J2EE platform (SCEA)” exam offered by Sun Microsystems, Inc.
Feel free to send any feedback to chris_broecker@yahoo.co.uk.
Encapsulation: Hiding the specifics of how data are represented and operations are implemented behind a public interface that is as simple as possible.
Inheritance: A more specific class inherits interface and/or implementation from a more general base class. The specific class “is a” base class, e.g. a Circle is a Shape.
Use of interfaces: Instead of referring to classes directly, operations are often described more flexibly in terms of interfaces. The interface defines a contract of features that a class has to supply. The specific instance used at runtime can be any object that implements the interface and does not have a specific base class.
Encapsulation and use of interfaces are very good tools for reducing complexity and coupling, improving the maintainability of any system. Inheritance has to be used with some care, but can also be used effectively to avoid duplication and create flexible systems.
The Unified Modelling Language (UML) is a graphical language that unifies the industry’s best engineering practises for modelling systems. It consists of
· UML Semantics (formal specification)
· UML Notation Guide (visual guide used by practitioners)
· UML Extensions (objectory process for software engineering, business modelling)
· Object Constraint Language (OCL): for expressing constraints and conditions
UML 0.9 has been defined in June 1996 by the Three Amigos (Booch, Rumbaugh, Jacobson). Further refined in UML 1.0 (Jan 1997) and UML 1.1 (Nov 1997).
Use Case diagrams |
|||
Structure |
Behaviour |
Implementation |
Environment |
Class diagrams |
Sequence diagrams |
Component diagrams |
Deployment diagrams |
Refer to Fowler for details. Note that implementing an interface is called ‘Realisation’ in UML.
Software architecture is the study of large software systems, from the perspective of their structure.
The study of software architecture concerns itself with achieving non-functional qualities (see below) in large systems.
Scalability - the ability to support the required quality of service as the load increases
Maintainability - the ability to correct flaws in the existing functionality without impacting other components/systems
Reliability - the assurance of the integrity and consistency of the application and all of its transactions. Reliability spans from the OS to the Application to the service provided.
Availability - the assurance that a service/resource is always accessible
Extensibility - the ability to add/modify additional fuctionality without impacting existing functionality
Manageability - the ability to manage the system in order to ensure the continued health of a system with respect to scalability, reliability, availability, performance, and security.
The following table outlines some inherent properties of common architectures.
|
Single tier |
Two-tier |
Three- or Multi-tier |
Scalability |
Very limited |
Still limited, DB connections |
Good. Resource pooling possible, hardware can be added if and when need arises. |
Maintainability |
Poor, tight coupling |
Difficult, data access and business logic are mixed |
Good, layers can be changed independently. |
Reliability |
OK, Data consistency is simple because one storage |
|
|
Availability |
Poor, single point of failure |
Poor, DB server is still single point of failure |
Excellent with appropriate redundancy architecture. |
Extensibility |
Poor, tight coupling |
Difficult, data access and business logic are mixed. Code is dependent on DB schema. |
Good, layers can be changed independently. |
Performance |
OK |
Poor, DB Server can become bottleneck. Each client requires a connection, no pooling. High network bandwidth required, because all data has to travel to client. |
Good. Because the system is scalable, performance can be influenced by choosing the right system components. Bottlenecks can be removed at the relevant layer. |
Manageability |
Relatively easy |
Poor, complex client installation and maintenance |
OK |
Security |
OK |
Problematic, because client has too much control. |
Good. Only certain services can be accessed, no direct database access. Firewalls and authentication and authorization systems help to further control access. |
Notes |
No distribution |
Two options:
Combine Presentation with Business layer (Thick client), or some Business
with DB layer (Thin client, use Stored Procs) |
More difficult to program because distribution, concurrency, transactions, security, resource management have to be understood and taken care of. The EJB architecture helps to reduce this overhead. |
A failure is a discrepancy between the desired or specified and the actual behaviour of a system. Failures are external symptoms of faults (defects).
Fault tolerance is the ability to prevent failures even when some of the system components have faults. The key to achieving fault tolerance is redundancy. Redundancy requires replication:
Hot backup: Extra, live copies (replicas) of an object are serving client requests and synchronise continuously with the primary object. If the primary object fails, one of the copies takes over.
Warm backup: Backup copies of an object run, but don’t serve clients. Synchronisation happens at certain, regular intervals. In case of a failure, a copy takes over from the last synchronisation point.
Cold backup: The primary object synchronises with stable storage in certain intervals. In the case of a failure, a new object is instantiated and reads the storage for set-up.
Fault handling includes service replication, fault detection, fault recovery, and fault notification.
Fault detection is often done by using heartbeats (server sends periodical signal to monitor) or polling (monitor checks server once in a while).
Fault handling in CORBA involves Replica Managers and Replica Service Agents.
Active Replication: Every replica handles requests and replies. Interceptor has to block extra calls to third objects and extra responses (same as hot backup).
Passive Replication: One primary replica handles requests and synchronises state with secondary replicas. Requests are also logged. For fail-over, a secondary replica becomes primary and processes all requests after the last synchronisation point (same as warm backup).
DNS Round Robin: Spreading incoming IP packets among a number of DNS addresses equally. That means that each subsequent packet is sent to the next address in a list, until the end of the list is reached and the next packet is sent to the first address again. This is a simple load-balancing strategy. It does not take into account the actual load on the machines.
Data Access Objects: Encapsulate the data access logic for a session bean or other component in a separate class. If you provide a common interface, multiple data access implementations can be provided, e.g. for different database systems. They simplify maintenance of code, make the path to CMP easier, and can be automatically generated by sophisticated tools. DAO’s are a bit like EJB’s, but don’t offer distributed access and transaction control. If these features are not needed, they are easier to use. There is a standard proposal for DAO’s called JDO (Java Data Objects).
Options for integrating legacy systems include CORBA, RMI-IIOP, JNI, and Messaging.
CORBA is a unifying standard for distributed object systems. CORBA is managed by OMG, and can be used with many platforms and languages. Disadvantages: Complex standard, slow-moving.
In a CORBA architecture, objects communicate through ORBs, using IIOP as the protocol.
Object Adaptor: Maps object references to implementations, activates object if necessary. Portable Object Adaptor (POA) now widely used.
Repositories: Interface and implementation repositories are used by ORBs.
IDL: Interfaces are defined in the OMG IDL and can be compiled to a concrete language interface, e.g. Java, C, C++,COBOL, Ada, Smalltalk. IDL-to-Java Mapping defines details for Java.
Invocation: Static invocation uses pre-compiled stubs and skeletons for a specific language and object. Dynamic invocation does not use stubs and skeletons, but discovers object and methods dynamically using the Dynamic invocation interface (DII) at the client and dynamic skeleton interface (DSI) at the server. There are similarities between DII and using COM’s IDispatch interface.
Corba Object Services (COS): Naming, Event (asynchronous messages), Object Transaction Service (OTS), Concurrency control, Security
Goal: Marry RMI and CORBA. Connect RMI clients to CORBA servers and vice versa.
Benefits: Greater re-usability, legacy integration, robust firewall navigation. In the future support for transaction and security contexts can be added (new EJB/IIOP standard).
RMI-IIOP works with CORBA 2.3 ORBs. Required specs: Objects-by-value (IIOP does not traditionally support pass-by-value) and Java-to-IDL.
Java-to-IDL mapping defines how RMI and IIOP work together and the necessary RMI restrictions that are known as RMI/IDL. The mapping enables Java-to-IDL compilers to be written that take a Java remote interface and produce a corresponding CORBA interface specification in IDL.
Connectivity |
RMI Server |
RMI-IIOP Server |
CORBA Server |
RMI Client |
OK |
OK |
Not possible |
RMI-IIOP Client |
OK |
OK |
Restrictions apply |
CORBA Client |
Not possible |
OK |
OK |
EJB 1.1 mandates RMI-IIOP API to be present. However, there may still be two kinds of EJB servers: CORBA based and proprietary. The latter do not use CORBA, but implement communication differently (not using IIOP).
Narrowing: Direct cast does not work on IIOP, PortableRemoteObject.narrow has to be used. In RMI direct cast works because Stub class can be loaded dynamically over the net.
Two new packages for RMI-IIOP: javax.rmi (PortableRemoteObject) and javax.rmi.CORBA (internal) (Normal RMI package is java.rmi).
No distributed garbage collection: Manually unregistering is necessary via unexportObject method.
RMI-IIOP clients must use JNDI. RMI registries and COS Naming can be plugged into JNDI.
Tools: Generation of RMI-IIOP stubs and skeletons: “rmic - iiop". IDL-to-Java compiler: “idlj”. Java-to-IDL-compiler: “rmi -idl”.
Note: Making object public through both JRMP and IIOP at the same time is possible.
Java IDL embeds Java into the CORBA world. It includes a new Java IDL API (org.omg.CORBA, org.omg.CosNaming) and tools including an IDL-to-Java compiler (idltojava) and an ORB.
The ORB includes the Java-to-IDL and Objects-by-Value specs (both mandated by CORBA 2.3 and necessary for RMI-IIOP connectivity). It does not define an interface repository, however, so no dynamic lookup of parameters is possible.
Sun recommendation: Java IDL should be used when accessing existing CORBA servers is the main purpose, whereas RMI-IIOP should be used when serving requests from CORBA clients is the main purpose.
Process: Write interface in IDL, compile to Java (results in interface and several classes). Use interface in client programming. Descend server from generated ImplBase class (aka ‘implementation skeleton’).
IDL-to-Java also generates ‘Stub’ class (client proxy), ‘Holder’ class (for out or inout parameters) and ‘Helper’ class (for narrowing and reading/writing).
ORB interface (org.omg.CORBA.ORB) and implementations (e.g. com.sun.CORBA.iiop.ORB). Getting an ORB: static ORB.init.
NamingContext in package org.omb.CosNaming.
Object references: Temporary references (through proxy) and long-lived ‘stringified’ interoperable object references (IOR).
Java Native Interface (JNI) is a standard for linking Java to native programs written in other languages like C and C++.
A good way to integrate a legacy application that is not written in Java into a distributed system is to wrap the application using JNI and make it accessible through RMI.
Enterprise Java Beans: A standard server-side component model for component transaction monitors.
1996 Microsoft introduced MTS, one of the first CTM. Middleware solutions suffered from vendor-specific APIs. In 1997, EJB was created, refined 1999 in version 1.1.
interface Thing extends javax.ejb.EJBObject (extends java.rmi.Remote)
Declares business methods. Every method must throw RemoteException (see RMI)
interface ThingHome extends javax.ejb.EJBHome (extends java.rmi.Remote)
Create methods: One or more create methods with arbitrary signatures. Return remote interface. Throw CreateException, RemoteException, plus custom exceptions.
Find methods [Entity beans only]: At least findByPrimaryKey(PkClass), possibly others. Starting with ‘findBy’. Return single bean remote interface or Enumeration/Collection of remote interfaces. Throw FinderException, RemoteException, plus custom exceptions.
Remove: remove() is automatically inherited.
class ThingBean implements javax.ejb.EntityBean/SessionBean (extend javax.ejb.EnterpriseBean, which extends java.io.Serializable)
1. Fields: Transient, persistent (CMP/BMP) according to bean type, see below
2. Business methods:
Must have methods matching signatures of remote interface. However, RemoteException does not have to be declared as thrown. Class should not implement the remote or home interface.
3. EJB methods:
ejbCreate: One version matching each create method in home interface. Return PkClass for entity beans and void for session beans.
ejbPostCreate [Entity beans only]: One version matching each create method in home interface. Return void. When this is called, the EJBObject exists in the EntityContext and the object is stored in the persistence store.
ejbActivate/ejbPassivate: Acquire/release resources like database connections, sockets.
ejbLoad/ejbStore [Entity beans only]: Used for BMP, also for dealing with CMP and calculated fields.
ejbFind [Entity beans with BMP only]: One version for each signature in home interface, return primary key class or Enumeration/Collection of primary keys.
ejbRemove: May remove aggregated beans, often empty.
class ThingPK implements java.io.Serializable
Fields must be public. Must define no-argument constructor. Must redefine equals and hashCode.
For CMP, fields must be a subset of the container managed fields and have same names and types.
Custom key classes as described above are called compound keys. Single-field keys can also be used by defining a single (Wrapper class or String) field and referencing it in the <primkey-field> tag.
In EJB 1.1, definition of the primary key for an entity can be deferred until deployment.
Stateless: Bean is attached to client only during method execution, no memory.
Stateful: Bean handles specific client, state can be passivated. All fields not marked as transient have to be serializable or primitive types.
For stateful session beans, the following references are guaranteed to be maintained by the container:
· Home/remote references of other beans
· JNDI contexts and SessionContext
· UserTransaction
EJB methods: setSessionContext: Called after ejbCreate, SessionContext is passed and can be stored. Can also be used to set up JNDI contexts. Usually empty for stateless beans.
Two states: Not Existent, Ready
Constructor, setSessionContext, ejbCreate move from Not Existent to Ready. Business methods stay in Ready.
Three states: Not Existent, Ready, Passivated.
Constructor, setSessionContext, ejbCreate move from Not Existent to Ready. Business methods stay in Ready. ejbPassivate moves from Ready to Passivated.
Additional state for transactions: Ready in Transaction.
Business method with transaction moves from Ready to Ready in Transaction. Methods commit and beforeCompletion, afterCompletion(true) move from Ready in Transaction to Ready. Same holds true for rollback and afterCompletion(false).
Are optional in EJB 1.0, mandatory in EJB 1.1.
Container Managed Persistence (CMP): Container persists object state at chosen points in time. ejbLoad and ejbStore are still called, but can be empty. Fields to persist must be public and listed in deployment descriptor. Finder methods are not implemented, but are defined by container tools. In EJB 1.1, CMP fields can include remote references to other beans.
Bean Managed Persistence (BMP): Bean is responsible for persisting state in ejbCreate, ejbLoad, ejbStore, and ejbRemove methods. Synchronisation points with persistence store are still chosen by the container. Finder methods must be implemented. An EJBException (RuntimeException!) should be thrown when SQL or other system errors occur during persistence handling.
EJB methods: setEntityContext/unsetEntityContext:
Three states: Not Existent, Pooled, Ready.
Constructor and setEntityContext move from Not Existent to Pooled. Finding stays in Pooled. ejbCreate and ejbPostCreate move from Pooled to Ready. ejbStore and business methods stay in Ready. ejbPassivation moves from Ready to Pooled.
In EJB components and code called by them, the following restrictions apply to enable the EJB container to handle scalability, load balancing, and other middleware services.
· No use of static fields or methods. Singleton pattern can still be implemented using JNDI
· No thread control
· No direct I/O access
· No use of customised socket factories
Package javax.ejb
EJBHome: getEJBMetaData(), getHomeHandle() [EJB 1.1], remove(Handle), remove(Object primKey)
EJBObject: getEJBHome(), getHandle(), getPrimaryKey() [Entity], isIdentical(EJBObject), remove()
EJBContext: getEJBHome(), getCallerPrincipal(), isCallerInRole(String), getEnvironment() [deprecated], getUserTransaction(), getRollbackOnly(), setRollbackOnly()
EntityContext: getEJBObject(), getPrimaryKey()
SessionContext: getEJBObject()
Exceptions: CreateException (extended by DuplicateKeyException), FinderException (extended by ObjectNotFoundException), RemoveException, EJBException (RuntimeException, extended by NoSuchEntityException)
In other packages: java.lang.IllegalStateException
Note that primary keys do not include the home interface whereas the handle does, so an EJB object is identified by its home interface plus primary key or the handle, which provides a getEJBObject() method for easy access.
Transactions implement the ACID properties: They are atomic, consistent, isolated and durable.
Transactions can be managed by the bean (Session Beans only) or by the container.
Bean managed transactions make use of the Java Transaction API (JTA) to begin transactions and perform commit or rollback (using the javax.transaction.UserTransaction class).
Container managed transactions allow the assignment of transaction types to specific methods:
NotSupported: The method is always executed outside the current transaction.
Supports: The transaction state is left as is
Required: When not in a transaction, a new one is started.
RequiresNew: A new transaction is always started.
Mandatory: Not being in a transaction results in an exception.
Never: Being in a transaction results in an exception.
Container managed transactions can be influenced through EJBContext.setRollbackOnly.
Transactions are automatically rolled back with system exceptions, but not with application exceptions.
One or more Enterprise Java Beans are deployed in .jar files. These contain the necessary Java class files, possible other files and a deployment descriptor called ‘META-INF/ejb-jar.xml’. The deployment descriptor is in XML format since EJB 1.1.
Root tag: <ejb-jar>, main sub-tags: <enterprise-beans> and <assembly-descriptor>
Optional sub-tags: <description>, <display-name>, <small-icon>, <large-icon> (same for beans)
<entity> or <session> wrapping each bean definition, containing:
· <ejb-name>: Unique identifier, also default for JNDI lookup
· <home>, <remote>, <ejb-class>: Fully qualified class names
· <env-entry><env-entry-name></…><env-entry-type></…><env-entry-value></…></…
·
<ejb-ref><ejb-ref-name>Other</…><ejb-ref-type>Entity/Session</…>
<home>OtherHome</…><remote>Other</…></…>
·
<resource-ref><res-ref-name>subdir/Sample</…><res-
type>Class</…>
<res-auth>Container/Application</…></…>, <description>
possible
·
<security-role-ref><role-name>(Matching
isCallerInRole call></…>
<role-link>(Matching assembly descriptor role,
optional)</…></…>, <description> possible
<session only>
· <transaction-type>Bean/Container</…>
· <session-type>Stateful/Stateless</…>
<entity> only:
· <reentrant>: Sould always be false
· <persistence-type> (Bean/Container), <prim-key-class>, <primkey-field>
· For CMP: <cmp-field><field-name>Name</…></… >
Note that Entity Beans transactions are always container-managed.
<security-role>: <description>, <role-name>
<method-permission>: <role-name>, <method>*
<container-transaction>: <method>*, <trans-attribute> (NotSupported, Supports, Required, RequiresNew, Mandatory, Never)
*<method><ejb-name>Name</…><method-name>Name
or * </…></…>, optionally also
<method-param> to distinguish signatures and <method-intf> to
distinguish Home/Remote.
Java Directory and Naming Interface (JNDI) is a standard interface to naming and directory services such as LDAP, X.500, COS Naming.
Package javax.naming.
Usage: Obtaining an InitialContext, passing properties if required, calling lookup with path or name.
For RMI-IIOP and thus EJB 1.1, narrowing is required:
ThingHome thingHome = (ThingHome) PortableRemoteObject.narrow(remoteRef, ThingHome.class);
The JNDI context java:comp/env is used as the standard initial context for bean home and remote references. For access from inside other EJB’s, the subcontext ejb should be used and appropriate references be defined in the deployment descriptor.
Bulk accessors for entity bean properties to reduce network round-trips.
Dependent objects should be immutable, e.g. Address object passed back from Customer bean. Also called value objects.
Only fine-grained objects should be dependent value objects, other objects with more state and behaviour should be beans on their own.
Session beans as façade for entity beans to reduce network round-trips.
Avoid chaining stateful session beans because of timeout problems.
Data Access Objects can hide complexities of DB access and make schema or DB changes easier.
The Transport control protocol and Internet protocol (TCP/IP) form the Internet’s transmission basis.
IP: Lower level, packet-based, connectionless, no guaranteed delivery.
TCP: Higher level, connection-oriented, error-correction.
Other application-level protocols are based on TCP/IP, e.g. FTP, HTTP.
SSL runs above TCP/IP and below application-level protocols. It supports client and server authentication, and privacy through encryption.
Handshake process: Authenticate server to client, select cipher supported by both client and server, optionally authenticate client to server, use public-key encryption to exchange keys, establish encrypted SSL session.
Standard port |
Protocol/Service |
Comment |
21 |
FTP |
File transfer protocol |
23 |
telnet |
Remote login |
25 |
SMTP |
Simple mail transfer protocol |
80 |
HTTP |
WWW transmission protocol |
110 |
POP3 |
Post office protocol |
161 |
SNMP |
Simple network management protocol |
443 |
SSL |
Secure sockets layer |
389 |
LDAP |
Lightweight directory access protocol |
636 |
LDAPS |
LDAP over SSL |
- |
IIOP |
Internet Inter-Orb Protocol |
1099 |
JRMP |
Java remote method protocol |
Design patterns formalise solutions to particular problems that are often faced in OO design.
Patterns are described by:
· The problem they solve
· A diagram and description of the proposed solution
· A discussion of benefits and possible issues with the application of the pattern
Create objects not directly, but using a method of some base class. Hides information about what particular object is constructed and how. Subclasses of the base class can instantiate the correct class. Defers instantiation to subclasses.
Example: Abstract Application object provides createDocument method, so that MyApplication can use its own MyDocument class.
Group together a number of factory methods. Provide an interface for the generation of a whole group of related objects, so that different factories can create objects for different frameworks or platforms.
Example: Abstract GraphicsFactory, concrete OpenGLFactory and Direct3Dfactory classes
Ensure there is exactly one instance of a class and provide convenient access to it.
A class dedicated to creating some object type. Hides specifics of the object creation. Can offer mutiple methods to create objects step-by-step.
Particularly useful if a number of otherwise different classes have similar construction patterns. Builders can be used to build Composites.
Example: Building objects from file representations in certain formats
Provides a clone method on objects, so that new, similar objects can be cloned instead of newly created. Thus, a pool of ready-made objects could be used without knowing about their details.
Useful if creation is costly and objects that are needed differ only slightly.
Wrapper around other class that adjusts interface to suit needs. Contains other object and delegates requests to it.
Controls access to a class, hides location and persistence. Can defer instantiation.
Example: RMI Stub
Provides a simplified interface to a complex set of inter-related classes. Reduces coupling.
Example: Session bean provides access to several entity beans.
Separates abstract and concrete inheritance trees.
Fairly large-scale pattern; if it is used, then often in conjunction with Abstract Factory.
Example: Java AWT peer classes
Share objects with a lot of intrinsic (immutable) data. Pass all extrinsic data needed to methods.
Example: Character class in text processing
Derive a group class that composes base class instances from the bass class itself. Complete object hierarchies can then be built.
Example: AWT Components
Derive from base class and contain instance of base class. Can add new functionality to any class instance derived from base.
Same class diagram as Proxy
Example: Java IO, BufferedReader
Provide an interface to externalize an object’s state so that it can be re-set to that state later.
Example: Usage in undo operation
Provide a hook in a base class that accepts an abstract operation to be performed on an element. Particularly useful for Composite hierarchies or other structures which should be flexibly usable.
Example: Perform printing, type checking, and metrics gathering on Abstract Syntax Tree
Accesses a container while hiding the specific container used.
Example: C++ Standard Template Library (STL), java.util.Enumeration
Define a separate class to represent an object’s state. Useful if actions are very state-dependent and the number of states is likely to change. State-dependent methods are delegated to the State class.
Example: TCP Connection class with states ‘closed’, ‘established’, and ‘listen’
Separates an action (or request) from its invocation (or trigger).
Example: Menu systems
Method for event handling in hierarchical systems. Events get passed on from most specifically affected class to container classes and eventually the root default handler.
Example: Displaying GUI help
Controls communication between systems of classes. Avoids complex coupling across systems.
Example: Systems management mediator controlling several processes
Defines a standard interface for notification of object changes, decoupling the observable from the observers. One-to-many relationship from observable to observers.
Example: Multiple views on one set of data
Encapsulates an algorithm used to perform a task, enabling dynamically switching the algorithm.
Example: Pluggable caching strategy
Define a language and a corresponding grammar to define instances of a domain. An abstract expression class can be derived from the grammar. Parsers create syntax trees for processing.
Example: Regular expressions for searching
Parameterises certain aspects of a class, making it easy to create new classes with certain properties. Defining parameters or behaviour is done by sub-classing and overriding methods.
Methods can be abstract hooks that have to be defined in sub-classes or template methods that use the hooks to define some common behaviour. Concrete, independent operations are also possible.
Example: InputStream defines read(buf) and read(buf,off, len) in terms of the template method read().
Message-Oriented-Middleware (MOM) provides a common reliable way for programs to create, send, receive and read messages in any distributed Enterprise System.
MOM ensures fast, reliable asynchronous electronic communication, guaranteed message delivery, receipt notification and transaction control.
The Java Message Service (JMS) provides a standard Java-based interface to MOM.
Point-To-Point Messaging: Multiple senders, single receiver
Publish-Subscribe Messaging: Multiple senders, multiple receivers
Request-Reply Messaging: This is the normal synchronous model and can be implemented by using two related asynchronous messages.
The JMS API defines separate interfaces for point-to-point (Queue) and publish-subscribe (Topic), so that service providers can choose to support just one model.
Supports distributed transactions.
Package: javax.jms
Base class: |
Destination |
Connection |
Connection |
Session |
Message |
Message |
Point-to-point: |
Queue |
Queue |
Queue |
Queue |
Queue |
Queue |
Publish-subscribe: |
Topic |
Topic |
Topic |
Topic |
Topic |
Topic |
MessageListener interface for MessageConsumer: void onMessage(Message msg).
There are also various message classes depending on content type, e.g. TextMessage, BytesMessage, MapMessage.
QueueBrowser can be used to look at a queue without consuming any messages.
The call createSubscriber creates a subscriber that only sees messages while connected, whereas with createDurableSubscriber messages are queued for the subscriber.
Lookup concrete ConnectionFactory through JNDI. Lookup topic/queue trough JNDI. Get connection from factory. Call start on connection. Create session from connection (passing flags for acknowledgement, transaction mode).
· Sender: Create sender from session (passing queue). Create message from session. Send message using sender instance, passing delivery mode and message instance.
· Receiver: Create receiver from session (passing queue). In endless loop: Call receive on Receiver, returning message, handle message.
· Publisher: Create publisher from session (passing topic). Create message from session. Publish message using publisher instance.
· Subscriber: Create subscriber from session (passing topic). Call setMessageListener on subscriber.
At the end: Close session. Close connection.
To be usable across national and regional boundaries, applications have to adapt to local customs. Cultural-dependent aspects of an application that need to be adapted include:
· Data Input
· Data Storage
· Data Formatting
· Localizing content
These aspects affect the following objects:
· Text: Messages, Labels, Errors, other content
· Numbers: Plain numbers, currency values, percentage values
· Dates and Time
· Images, Sounds and other data
Internationalisation is sometimes abbreviated as I18N because there are 18 chars between I and N.
Locale class captures properties of a local environment: language and region.
· Language is specified by ISO 639 two-letter code in lowercase, e.g. fr, en
· Region is specified by ISO 3166 two-letter code in uppercase, e.g. CA, US
Getting locales: 1. Locale.getDefault() 2. new Locale(lang, region) 3. Locale.UK (this is a constant).
Each JVM has a default locale which can be changed by specifying the system properties ‘user.language’ and ‘user.region’.
Check available locales: Locale.getAvailableLocales() or DateFormat.getAvailableLocales()
A ResourceBundle is a container for key-value pairs that are locale-dependent.
Can be specified in a .properties file or in a class (best derived from ListResourceBundle).
Retrieval: ResourceBundle.getBundle(name[, locale]). Looks for most specific first, then drops region, language, tries default locale instead of desired, then overall default. Prefers classes over .properties.
Access: getString(name), getStringArray(name), getObject(name)
Base class Format, Usage: ‘format(something)’ for output and ‘parse(String)’ for input
Creation: getNumberInstance, getPercentageInstance, getCurrencyInstance (pass Locale optionally)
Creation: getDateInstance, getTimeInstance(), getDateTimeInstance (pass Locale optionally)
SHORT, MEDIUM, LONG, FULL formats
Composition: Uses a NumberFormat for time formatting.
Subclass: SimpleDateFormat allows specifying date/time formats in details using pattern strings.
Creation: new MessageFormat(pattern), also static usage via format(pattern, arguments)
Replaces parameters in message strings, e.g. “{0} not found at {1, time}” becomes “SomeFile.java not found at 11:30 PM”, but with a different pattern becomes “11 Oct 99, 11:30:00: SomeFile.java missing”
Properties are just an extension of Hashtable for representing key-value pairs; they don’t support internationalisation explicitly.
The primitive Java character type and the Java String class are based on Unicode. Unicode is a two-byte character set that includes all relevant symbols of languages currently in use throughout the world. Unicode comes with a variety of encodings
To actually display certain characters, relevant fonts have to be installed.
The Collator class (java.text) should be used for sorting international strings.
Input and output streams operate on bytes, whereas readers and writers operate on characters. Characters are based on Unicode and support internationalisation.
Where byte and character streams meet, a character encoding is needed. The classes OutputStreamWriter and InputStreamReader use encodings to read and write characters to and from byte streams. JVM’s may differ in what encodings are supported.
There is always a default encoding for any JVM. Examples of encodings are UTF-8 and ISO-LATIN-1, as defined by the IANA Charset Registry.
Cryptography, Digital signatures and Certificates can be used to increase the security of a system. Java offers a number of interfaces for related services. Firewalls are also important for protecting the gateway between trusted and untrusted networks.
Eavesdropping: Information is kept intact, but privacy is compromised.
Tampering: Information in transit is changed or replaced and then sent on.
Impersonation: Information passes to the wrong person, who poses as the intended recipient. Persons or systems can pretend to be somebody else (Spoofing) or something else (Misrepresentation).
Privacy: Communication between two parties is unintelligible to an intruder.
Tamper detection: Verify that information has not been changed in transit.
Authentication: Confirm that the sender of the information is who he claims to be.
Non-repudiation: Prevents senders from claiming at a later date the information was never sent.
One key is used for encryption and decryption.
Problem is key exchange between remote parties. Advantage is efficient implementation.
Also called “ asymmetric cryptography”. Pair of two associated keys: The private key is kept secret; the public key is published openly.
Encryption with public key ensures privacy.
Message digest or one-way hash function: Number of fixed bit length that changes with every subtle change in the message and cannot be reversed.
Digital signature: Encryption of the message digest with the public key.
Method: Send digital signature along with message. Receiver calculates message digest of the received message and compares with the decrypted message digest.
Problem: Verify validity of a person’s public key.
Certificate: Electronic document that identifies an individual, a server, a company, or some other entity and associates the entity with a public key.
Certification authority (CA): Validates identity and issues certificates.
Certificates contain identity name, expiration date, CA name and digital signature, and other information like a serial number.
Network authentication can be password-based or certificate-based. Advantage of certificates: Password does not need to be sent across the network. Single-sign on is easier.
X.509 v3: ITU Standard for certificate content. X.509 v3 binds a distinguished name (DN) to a public key. DN is a series of name-value pairs, e.g. uid=doe,e=doe@abc.com,cn=John Doe,o=ABC,c=US, like in LDAP.
X.509 Data Section: 1) Version no of X.509 standard 2) Serial number (unique to CA) 3) Information 4) Public Key Info: Algorithm and Data 5) Validity Period 6) Subject’s DN 7) Optional extensions
X.509 Signature Section: 1) Algorithm or cipher used by the CA 2) Digital signature of certificate by CA
Certificate chains: Hierarchy of CA’s, parents certifying children. Allows verifying certificates by just having the trusted public key of the root CA.
Public Key Infrastructure (PKI): Set of standards and services that facilitate the use of public-key cryptography and X.509 v3 certificates.
Key recovery or key escrow: Ability to retrieve backups of private keys under certain, carefully defined conditions. Example is the m-of-n principle, m of n trusted individuals have to agree.
Public Key Cryptography Standards (PKCS): Set of standards driven by RSA Labs with broad industry support. Includes RSA public-key and Diffie-Hellman algorithms.
Security architecture has changed from JDK 1.1 to 1.2. In JDK 1.1, the ‘sandbox model’ distinguished between remote code (applets) that was run with security restrictions in the sandbox, whereas local code was totally trusted. With Java 2, all application code is subject to security control.
The Java language supports writing safe code: Strong type checking, automatic memory management, range checking, JRE bytecode verifier.
The Java 2 platform explicitly supports access control to various important resources like files and sockets through permissions and the SecurityManager.
Protection domain: Conceptual set of resources that are currently available to a principal.
Permissions are resolved by checking the protection domain assigned to a class.
Two main protection domains: Application and system.
Permission: Abstract base class for all permissions, e.g. java.io.FilePermission.
PermissionCollection: List of permissions of same type. Permissions: List of PCs.
Types of permissions: (Basic), File, Socket, Property, Property, Runtime, AWT, Net, Security, All
Defining new permissions: Descend from Permission, implement implies method.
CodeSource: Defines URL of a remote codebase along with associated certificates.
Policy: The current security policy. Policy.getPolicy(), getPermissions(CodeSource)
ProtectionDomain: Uniquely identified by a CodeSource. A class belongs to exactly one PD.
AccessController: Has checkPermission method (also called by SecurityManager)
AccessControlContext: Defines state of access control, used to pass access info between threads.
Principal: Interface for entities like persons, companies, used in X.509 certificates
Create public/private key pairs, issue cert requests (for sending to CA), manage key store.
Signing and verifying JAR files. “jarsigner [options] jar-file alias”
Can be found in {JDK Home}/lib/security
Java.security – Security Properties File
Java.policy – System Policy File
Cacerts – Certificates Keystore File
Package java.security.
Engine classes: MessageDigest, Signature, KeyPairGenerator, KeyStore, SecureRandom etc.
Interface are implemented by providers.
Default provider SUN is shipped with Sun’s JDK 1.2, includes DSA, MD5, SHA-1, X.509 certs, JKS.
Supports access control based on who runs the code. J2SE only supports access control based on where code is coming from and who signed it.
Implements Pluggable Authentication Module (PAM).
Principal: Named entity or account. (Roles and Groups are Principals as well.)
Subject: Person or Service using a system. Represented by a set of Principals.
Credential: Additional security info about a subject, e.g. certificate, password. Public/Private
Two-phase login like two-phase commit.
Authorisation: Policy files like Java 2 policies, with new principal key word.
Extensions to the Java Cryptography Architecture (JCA), that is part of J2SE.
Provides SSL (Secure Sockets Layer) 3.0 and TLS (Transport Layer Security) 1.0.
SSLSocket and SSLServerSocket classes
HTTPS support
Package javax.net.ssl
A firewall is a system that enforces an access control policy between two networks.
Purpose of firewalls: Control incoming and outgoing travel, address translation, monitoring.
Screening types: Check whether data have been requested, check sender, check content.
Network Address Translation (NAT): Make it seem like all outgoing traffic originates from the firewall.
Attack types: Information theft, Information sabotage, Denial of service.
Firewalls are certified by the ICSA (International Computer Security Agency).
Packet filter firewalls: Based on information in single IP packets; port, source/dest IP address
Application-level proxy servers: Inspection of data for specific services, e.g. HTTP, FTP, SMTP
Stateful packet inspection firewalls: Stores requests and checks incoming data against them.
De-militarised zones (DMZ): Zone for protected, controlled public access, separate from intranet.
Virtual Private Networks (VPN). VPN’s are more cost-effective than leased lines or dial-in.
Virus detection
Load Balancing
Router/Firmware-based firewalls: Built into router. Usually limited capabilities available.
Software-based firewalls: Sophisticated applications on a workstation. Difficult to maintain.
Dedicated firewall appliances: Best solution. High throughput, less maintenance, more security.