-------------------------------------------------------------------------------- EJBs Remote Interface • Extend EJBObject • Business methods Home Interface • Extend EJBHome • Methods to create and destroy ejb objects Bean Class • Implements SessionBean, Entity Bean, or MessageBean EJB Object Deployment Descriptors specify: • Bean mgmt. And lifecycle requirements. Things like fully qualified name of bean class, type of bean (stateful session, entity, etc.), fully qualified name home interface, fully qualified name of remote interface, ejb alias. • Persistence requirements • Transaction requirement • Security requirement. Access control entries and what roles the bean should run in. Stateful Session Beans Can’t be re-entrant, will throw an exception. EjbCreate() method can take parameters. Passivation: ejbPassivate() called prior to passivation. • When passivated the following things are saved: o Non-transient primitive attributes o Non-transient Object attributes (need to be Serializable?) o EJB Object references o Home references o EJB context references o JNDI naming contexts Activation: ejbActivate() called immediately after activation. Lifecycle Stateless Session Beans Can’t be re-entrant, will throw an exception. Lifecycle Entity Beans javax.ejb.EntityBean ejbCreate() ejbPostCreate() //One for every corresponding create method ejbRemove() ejbActivate() ejbPassivate() ejbStore() ejbLoad() ejbFind() //Only defined for bean-managed persistence, can have a bunch of these. Returns primary key or a collection of them. ejbFindByPrimaryKey //Required to have at least this one Creation: • Client calls create(…) on home interface, which is delegated to corresponding ejbCreate(…) method on bean class. Can have many versions of create() method. Destruction: • Client calls remove() on EJBObject or home interface which is delegated to ejbRemove() on bean class. Database data is destroyed. Only one version of remove() method. Deployment Descriptor Elements: • Persistence type, i.e. bean-managed or container-managed. • Fully qualified name of primary key class • Whether or not bean is re-entrant • Resource-ref for things like JDBC driver • Transactional properties. Deployment Descriptor Elements for CMP: • Define container-managed persistent fields, must match the abstract getter/setter methods in the bean class. • Define EJB-QL for the various find() methods Entity Beans can also be pooled. Passivation: Calls ejbStore() and then ejbPassivate(). Activation: Calls ejbActivate() and then ejbLoad(). Finding EntityBeans Clients call the various “find” methods that you’ve defined on the Home interface and the container delegates to the “ejbFind” methods that you’ve implemented on the bean class. Just like with “create” methods, the “ejbFind” methods will return primary keys while the “find” method on the Home interface will return an EJB Object to the client. EntityContext—allows you to get the EJBObject and the PrimaryKey. Lifecycle Note: Class.newInstance() and setEntityContext() only called when container wants to increase its pool, not necessarily when client connects. Message Driven Beans Messaging When to Use Messaging • For better DB performance. Reduce load by putting request onto queue and DB will process later. • Quick response. For methods that return void, don’t keep client waiting by blocking. • Smooth load balancing. Have servers pull for the message instead of load balancer push to the ones they guess are least burdened. • Prioritize requests. • Integrate disparate systems because many legacy systems use messaging. • Loosely coupled systems so that applications don’t have to know about each other at compile time. • Geographically disperse systems • Parallel processing by launching a series of messages and continue processing. • Reliability by using persistent queues and topics. • Many-to-many communications. When Not to Use Messaging • When you’re not sure if the operation will succeed. Synchronous calls can throw exceptions. • When you need a return value on the method. • When you need an operation to be part of a larger transaction. • When you need to propagate the client’s identity to the server. • When you are concerned about request performance. Messaging takes a hit because of messaging middleman such as queue or topic. • When you need strongly-typed OO system. • When you want a tighter, more straightforward system. Can offer better performance because client does not block waiting for server to process request. However, may take performance hit from messaging middleman. Can offer better reliability because messages can be stored in persistent queue and you can define quality of service. Supports multiple sends and receivers. Publish/Subscribe: Many to many. Uses a topic. Point-to-Point: One to one???.…many consumers can register with the queue but message is consumed only once. Transactions Entity beans should not use bean-managed transactions because you need to do ejbLoad() before a transaction and an ejbStore() after a transaction but the bean itself can never explicitly call those methods. With Entity beans and Stateless Session beans, user-managed transactions can’t start in one method and end in another because these beans are shared across multiple clients. With Stateful Session beans, you can start and end transactions in different methods. Transactional attributes on EJBs can be specified at bean and method levels. In case of both, then method level attributes take precedence. With Entity beans, transactional attributes must also be specified on Home methods. REQUIRED—Bean will participate in existing transaction or start its own if one does not exist. Use this if you want your bean to always run in a transaction. A flexible attribute that allows you to join existing transaction or create your own depending on the scenario. SUPPORTS—Bean will participate in existing transaction or none if none is present. A little tricky because your bean may or may not be running in a transaction and it’s always hard to be sure. MANDATORY—There must be an existing transaction when bean is called, otherwise TransactionRequiredException is thrown. A good safe attribute to use, guarantees that your bean is running in a transaction. However, this relies on third party to start transaction. Good if your bean is part of larger system such as workflow or something. NOT-SUPPORTED—Current transaction will be suspended when bean is called if there is a current transaction. Use this only when certain that bean’s methods don’t need ACID properties. REQUIRES_NEW—Container will always start a new transaction and current one will be suspended if it exists. Useful if your bean needs ACID properties but you don’t want other external logic to participate in that transaction. NEVER—Bean cannot be in any transaction, otherwise a RemoteException is thrown. Useful when you want to make sure your bean clients don’t use transactions. Permissible Transactional Attributes for Each Bean Type Transaction Attribute Stateless Session Bean Stateful Session Bean Implementing SessionSynchronization Entity Bean Message-Driven Bean Required Yes Yes Yes Yes RequiresNew Yes Yes Yes No Mandatory Yes Yes Yes No Supports Yes No No No NotSupported Yes No No Yes Never Yes No No No Isolation Levels: Dirty reads--occur when application reads data that hasn’t been committed yet so that data may not be available at the next read. Unrepeatable reads—occur when you read some data but upon reading it again, the value has changed. Can happen when you read data and then someone overwrites the value with something else so that when you read again, the value has changed. Phantom reads—occur when you perform a query, get some results, and then when you perform a query again you get some additional results because someone inserted some new data that matched the query. Difference between phantom and unrepeatable is that in phantom new data appears whereas with unrepeatable, the values have changed. • READ UNCOMMITTED: No isolation guarantees but highest performance. Use this only when you know that your component runs without any other concurrent transactions also running. • READ COMMITTED: Solves dirty read because you can’t read data that hasn’t been committed. However, unrepeatable and phantom reads can still occur. Guarantees that data you read is consistent. Good for applications that read data to do a report or a snapshot. Default isolation level for most databases such as Oracle and SQL Server. • REPEATABLE READ: Solves dirty read and unrepeatable read problem. Basically locks the data you read for updating, like a “SELECT FOR UPDATE”. Good for applications where you’re reading data that you will later update based on the values you just read in. • SERIALIZABLE: Solves all three problems because it enforces that transactions execute serially with respect to each other. Use for mission critical systems where you can’t have any types of data errors and inconsistencies, but drags down your performance. Isolation Level Dirty Reads Unrepeatable Reads Phantom Reads READ UNCOMMITTED Yes Yes Yes READ COMMITTED No Yes Yes READ REPEATABLE No No Yes SERIALIZABLE No No No Unfortunately no standard way to set isolation levels in EJBs…must do it through your resource manager such as JDBC or through the datastore. javax.ejb.SessionSynchronization afterBegin() beforeCompletion() afterCompletion(Boolean txSuccess) Implement SessionSynchronization in your Stateful Session Beans if you need to be aware of transactional events. Only if you’re using container-managed transactions. With bean-managed, you’re demarcating the transactions so you already know when these events occur. Internationalization/Localization java.text package—contains classes and interfaces for handling text in locale-specific ways java.io package—contains classes for importing/exporting non-Unicode data java.util package—contains the Locale class and localization classes. Also contains the formatting classes. Locale—class to represent an identifier for a geographical, political, or cultural locale. ResourceBundle—abstract base class representing container of resources for specific locales. New resources can be added to an instance of ResourceBundle or new ResourceBundles can be added to a system without affecting the code. ListResourceBundle—abstract subclass of ResourceBundle that manages resources in a list. Resources can be any Object. PropertyResourceBundle—concrete subclass that manages resources in a Properties object. Resources have to be strings. Calendar and time zone support is provided by Calendar and TimeZone classes and subclasses. Calendar provides methods for converting longs to dates and TimeZone encapsulates various time zone offsets. Formatting: • Format—abstract base class that encapsulates the logic for formatting locale-sensitive information. Part of java.text package. • DateFormat—abstract base class for parsing and formatting date and time values in locale-specific ways. SimpleDateFormat is a concrete subclass that does this stuff. • NumberFormat—abstract base class for formatting and parsing numbers. Contains static methods for getting different kinds of locale-specific number formats. DecimalFormat is a concrete subclass for formatting decimal numbers. ChoiceFormat another concrete subclass that allows you to format how to display a range of numbers. • MessageFormat—provides a means to format concatenated messages in locale-specific ways. Takes a set of objects, formats them, and then inserts them in the pattern at the appropriate places to build the message. Locale-Sensitive String Operations Things like searching, sorting, collating, etc. • Collator—abstract base class for performing locale-specific String comparisons. Subclasses implement different comparison algorithms. RuleBasedCollator (provided with JDK) is a concrete subclass that provides simple, data-driven, table collator. • CollationElementIterator—used as an iterator to walk through each character of an international String. • CollationKey—represents a String to compare when using Collator. Comparing two of these returns the relative order of the strings they represent. Using this is faster than actual String comparisons. • BreakIterator—contains methods for finding boundaries of line breaks, sentences, words, and characters in text. • CharactorIterator—defines protocol for bi-directional iteration over a set of Unicode characters. Methods return either the index or the character value. Classes implement this interface to provide this functionality for various sequences of characters. StringIterator class provides this functionality for iterating over a string. Character Set Conversion Use InputStreamReader, OutputStreamWriter, and String for converting between Unicode and other encodings. Firewalls Basic Services: • Block incoming data that might contain hacker attack. • Hide information about topology of the network. Make it seems like all requests come from one IP address. • Screen outgoing traffic. 3 basic types. Packet Filter Firewall: Looks at the information related to IP address of a packet, types of connections, etc. and then provides filtering based on that. Uses this info. to decide which packets to let through and which to deny. IP spoofing may fool some of these. Application-Level Proxies: Work at the application level to provide proxy services. Allows more specific inspection of the packets. Can use application level knowledge to decide what to filter. Usually requires separate proxy for each type of application you want to filter. Stateful Packet Inspection Firewall: Examines and remembers outgoing packets so that when incoming packets come in, that information will be used to determine whether or not to let the incoming packets through. For example, if an incoming packet wasn’t requested by any outgoing packets, it will be filtered. Security Java sandbox consists of following elements: • Byte code verifier • Access controller • Security manager • Class loader (applet class loader, url class loader, rmi class loader, default internal class loader, custom built class loaders) • Security package (security provider interface, message digests, keys, certificates, digital signatures, encryption) AccessController Checking permission is done by checking the permissions associated with the protection domain for each method on the stack starting from the top. If each protection domain on the stack allows access, then it is granted. Using PrivilegedAction and PrivilegedExceptionAction, protection domains can grant privileges to code that has called it but not to code that it calls. GuardedObject Allows you to embed another object within it such that all access to that object will first have to go through a guard, usually the AccessController. MessageDigest Small sequence of bytes that represents the actual input data. In order to use the digest, you also need a copy of the original data so that you can calculate the digest on it again and compare it to the digest that was given to you. For example, to do authentication, the user needs to enter his id/password but you don’t want that to be sent in clear text over the network so they send you the digest instead. Then you take that and compare it to a digest that you calculate on their password and if it matches the digest they sent to you, then you can authenticate them. Message digests do not need any key to calculate. Also you can’t derive anything about the actual data from the digest. Digital Signature Used to uniquely identify an entity, non-repudiation. The way it works is you calculate a message digest on some piece of data and then you encrypt that digest with your private key. Then you send that data along with the encrypted digest to the other party. The other party then uses that data to calculate another digest and then encrypts it with your public key. Then they compare it to the signature that you sent them and if it matches, then your identity is verified. Certificate Contains 3 pieces of information: • Name of entity for whom certificate has been issued, known as the “subject” • Public key associated with the subject • Digital signature of the issuer (some CA) of the certificate which verifies the information in the certificate. Java Security AccessController introduced in 1.2. In 1.2, classes on the CLASSPATH can also be subject to a security model. Bytecode verifier verifies the Java language safety constraints of the bytre code: • In 1.1, all non-local classes are sent thru byte code verification. • In 1.2, all classes except core Java classes are sent thru verification. Classloaders work with security manager to enforce security roles: • Classloader knows where class was loaded from. • Knows whether or not the class came with a digital signature. • Different instances of classloaders group classes into different namespaces based on which instance of the classloader loaded it. In 1.2, SecureClassLoader was introduced. In 1.2, URLClassLoader was introduced. Classloaders have to load the system classes first. Trusted vs. Untrusted Classes In JDK 1.0, classes loaded from CLASSPATH are considered trusted while those loaded from a class loader are untrusted. In JDK 1.1, same rules apply but a class loaded from a jar file may have a digital signature giving it more privileges. In JDK 1.2, classes form core API are trusted and other classes are given privileges based on where they were loaded (codebase, codesource?). However, this requires special command-line args. BY default, classes from CLASSPATH are considered trusted. Thread Security Threads are grouped into a hierarchy---in theory, the policy of security should be such that threads may only manipulate threads that are below them in the hierarchy. In JDK 1.1, this isn’t true, each applet is given an individual thread group and threads within that group can manipulate other threads within that group without respect to any hierarchy. In JDK 1.2, thread hierarch operates as expected. Untrusted classes may only manipulate threads that they have created. Untrusted classes may only manipulate thread groups that they have created. Threads of untrusted classes must belong to specified groups (what the hell does this mean?). AccessController CodeSource: encapsulation of location from which classes were obtained. Permission: encapsulation of request to perform a particular operation. Policies: encapsulation of all the specific permissions that should be granted to specific code sources. ProtectionDomain: encapsulation of a codesource and the permissions granted to that particular code source. Security Policy Policy file: • Collection of policy entries. • Each entry is specific to one code source and should list all permissions for that code source. • Single policy file can have multiple entries. • May contain an additional entry to specify the location of the keystore in which public keys for the signers listed the policy file should be found. • Each grant entry represents a protection domain. Protection Domain Each class in the VM may belong to one and only one protection domain. Set by the class loader when the class is defined. The permissions for any particular operation can be considered to be the intersection of all permissions of each protection domain on the stack at the time the operation is called. Using the “doPrivileged” method of the AccessController, you can temporarily allow a class to perform an action that it normally would not be allowed to do. Keys Key factory and key specifications available only in Java 1.2. They allow for exporting and importing keys using various specifications. Keys from the Sun provider use DSA algorithm. Key pair generation is done by KeyPairGenerator, a standard engine of Java security. Key Management Key Certificate Identities “Keytool” stores individual private and public keys with retrieval subject to a password. “Keystore” is the database of the keytool. Keytool works on a file that contains a set of private keys and certificates for those keys. Each entry in the keystore has: • Alias: name for referencing that entity • One or more certificates for that entity’s identify. • Optionally, a private key which can be protected by a password. Represented by the “KeyStore” class. There are 2 types of entries: Key entry and Certificate entry. Key entries contain both public and private keys and may contain multiple certificates in a certificate chain. Certificate entries contain only public keys in a certificate. Signed Classes Delivered as signed jar files. In JDK 1.1, use “javakey” to sign it. In JDK 1.2, use “jarsigner” to sign it. Each file in a jar file may be signed by a different group of identities and some may not be signed. Encryption “KeyGenerator” class used for generating new secret keys. “SecretKeyFactory” converts from algorithmic or encoded key specifications to actual key objects and translates keys from one implementation to another. “KeyAgreement” class can also be used to generate secret key between multiple people. SunJCE provider uses “Diffie-Hellman” protocol for generation. Applet Security Most browsers limit a lot of things that applets can do. Sun’s appletviewer allows more access to applets. Two ways in which applets can be considered trusted: • Applet is installed on local disk in a directory in the CLASSPATH. • Applet is signed by identity marked as trusted in your identity database (keystore?). Applets cannot do the following things with files: • Check for the existence of the file. • Read the file • Write the file. • Rename the file. • Create a directory on the client file system • List the files in this file (as if it were a directory) • Check the file’s type. • Check the timestamp of when the file was modified. • Check the file’s size. Using Sun’s appletviewer, you can grant applets special privileges to perform those file operations. Applets cannot open network connection to any host other than the one it came from (the host where the html page was obtained or the host specified in the codebase parameter of the applet tag. To open network connection, the host name has to be specified exactly the same. If you used an IP address, you can’t use a name now and vice versa. Applets loaded through client’s local file system using CLASSPATH can do the following: • Read and write files. • Load libraries on the client. • Execute processes. • Exit the VM. • Are not passed through bytecode verifier. Legacy Integration • Data-level integration From the point of view of a Java application, this type of integration focuses on the access of legacy databases or files by either session beans or entity beans. It also includes access to newly developed data feeds, produced by the legacy system, for the specific purpose of data access. XML is often used for this integration technique because XML is a platform-independent approach for sharing data. The advantages of data-level integration are that it is fairly straightforward and quick to implement. The disadvantages include increased data coupling between applications, thereby increasing your maintenance burden; the inability to access important behavior such as data validation and critical business rules; and the need to write significant data cleansing/formatting code for poorly designed data. • Application-interface integration With this approach, you leverage the application programming interfaces (APIs) exposed by your applications to access both the data and the functionality encapsulated by legacy systems. The advantage of application-interface integration is that this approach is fairly standard within the industry; many packages such as SAP and PeopleSoft include C-APIs that you can access via Java Native Interface (JNI) code. The main disadvantages are that software developed within your organization rarely has a defined API; the APIs may be limited in scope and may not offer the behavior that you need (or in a manner that you need it); and APIs are often function-oriented in nature and not object-oriented. • Method-level integration With this approach, business logic is shared as a collection of shared methods, or operations that your software can invoke. For example, common operations to update customer data, to validate a credit card transaction, or to deposit money into a bank account may be made available in a common repository or reusable framework that all applications have access to. The advantages of method-level integration are that it often provides fine-grained access to common business functions; a wide range of applications (including both Java and non-Java) can access the operations; and invoking the methods is straightforward. The disadvantage is that the fine-grained nature of the common methods can make it difficult to support transactions or to support common technical services, such as security access control, without significant scaffolding in each method. • User interface-level integration This technique focuses on accessing existing applications through their user interfaces, a process called screen scraping, in which user keystrokes are simulated to implement the interaction with the legacy software. Screen scraping is a common technique used by Web-based aggregator sites, for example Vertical One, to present personalized views of financial or other types of information. The advantage is that this is a time-tested and common approach for legacy integration, one that is taken by many user interface testing tools such as Mercury Interactive's WinRunner or SQA Suite from Rational Corporation. The main disadvantage is that this approach can be slow: you need to wait for the legacy application to render the screen that you are scraping, and any changes to the legacy user interface necessitate changes to your integration code.