User:KillersKRL/Java

Java
JDK 6 Documentation

Java Platform SE 6

instanceof

Keywords

Endian

Primitive Types

XOR Bytes

Search Tutorial

Processing XML with Java

Creating Custom Events

Dali and JPA

Java Encryption
JCE

JCA

Examples

Example PBE

PBEKeySpec

Java Downloads
Java EE Downloads

Java SE Downloads

Web Containers

Java Tips, Tricks, and Examples
1. Jarring up files jar cf lmegabyte.jar com/lmegabyte/domain/*.class com/lmegabyte/beans/*.class META-INF/persistence.xml c - Tells the jar utility to create a new jar file that contains the files indicated. f - Tells tells jar to redirect the standard output to a new file. See also: java.util.zip

JBoss
Mainpage

Downloads

Installing

Example EJB3

Configuring JBoss 4.0

Using JBoss Behind a Firewall

JBoss Tips, Tricks, and Examples
Create a Properties File for the Client application and using InitialContext 1. Select New/Other/JBoss Tools Web/Properties File 2. Give the name of the file jndi.properties. 3. Add the following name value pairs in the properties file. a. java.naming.factory.initial  = org.jnp.interfaces.NamingContextFactory b. java.naming.factory.url.pkgs = org.jboss.naming:org.jnp.interfaces c. java.naming.provider.url     = jnp://localhost:1099 4. Example code to get InitialContext and access to the remote bean package lesson.client; import java.io.*; import java.util.*; import javax.naming.*; import lessons.stateless.*; public class TestClient {       public static void main(String[] args) {          try {             Properties props = new Properties; String userDir = System.getProperty("user.dir"); System.out.println("UserDir: " + userDir); props.load(new FileInputStream(userDir + "//src/lesson//client//jndi.properties")); InitialContext ctx = new InitialContext(props); HelloWorld hello = (HelloWorld)ctx.lookup("TestApplication/HelloWorldBean/remote"); System.out.println(hello.getMessage); }          catch(Throwable ex) {            ex.printStackTrace; }       }     }

Example create Context in code without properties file public static Context getInitialContext throws Throwable {      Properties p = new Properties; p.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory"); p.put(Context.URL_PKG_PREFIXES,       "org.jboss.naming:org.jnp.interfaces"); p.put(Context.PROVIDER_URL,           "jnp://localhost:1099"); return new javax.naming.InitialContext(p); } Example go.bat file for starting the JBoss Server echo off setlocal

set JAVA_HOME=c:\dev\LARS\JAVA\



set cmd=%SFSL_ROOT%\runtime\localhost\workstation\jboss\bin\run.bat echo Starting WHP - JBoss server now echo   using JAVA_HOME=%JAVA_HOME% echo   using SFSL_ROOT=%SFSL_ROOT% echo   running %cmd%

%cmd%

endlocal

MySQL
Mainpage Downloads Documentation Downloads Forums mySQL ODBC Driver 5.1 Online Documentation CREATE TABLE Syntax Datatype Default Values

Install notes for MySQL and Java Connector:
1. Open up port 3306 on the firewall. 2. For the java connector add location to the mysql-connector-java-[version]-bin.jar to the CLASSPATH environment variable. 3. root is the main username used for loggin into mySQL command line tool as well as MySQL Administrator. 4. mysql -u root -p can be used to login from the command line

MySQL Notes
1. To use MySQL as an ODBC datasource for programs like Enterprise Architect add a new datasource in Start/Settings/Administrator Tools/Data Sources (ODBC). 2. Use TIMESTAMP datatype instead DATETIME if you need to default the value to CURRENT_TIMESTAMP

Eclipse Notes for MySQL
1. To connect to the mySQL database open the View Database Source Explorer. 2. Right click on Databases tab and select New to setup a connection to a database. 3. Select Generic JDBC Connection in the New Connection Profile dialog. 4. Enter a Name and Description in the New JDBC Connection Profile. Check off Auto-connect at startup if you want that and Click Next. 5. Select a driver from the drop-down. If the MySQL JDBC Driver then click the elipse ... button. 6. If the MySQL JDBC Driver hasn't been created for the version click the version and select the Add in the Driver Definitions dialog. 7. In the Edit Driver Definition ... more to come ...

Tomcat
Mainpage

Apache Derby
1. Mainpage 2. Downloads 3. Accessing Derby from Creator 4. Developer's Guide 5. Tools and Utilities Guide Notes for Apache Derby 1. Add port 1527 to exceptions.

Eclipse
Mainpage

Corner Articles

Plugin Central

Help

Key Combination Shortcuts

Ctrl+Shift+O - Organize Imports

F4 Hierarchy

F3 Go to definition

Eclipse Downloads
Eclipse Downloads

Downloads By Project (EMF, UML2, and etc.)

Amateras UML

Eclipse Modeling Framework

Graphical Editing Framework

Test and Performance Tools Platform

Visual Editing Project

WTP - Web Tools Platform
Data Tools Platform Project

Derby Downloads

Other
Annotations are like attributes in C#

Acronyms
DAO - Data Access Objects

DAS - Domain Application Server

DTP - Eclipse Data Tools Platform

EAI - Enterprise Application Integration

EJB - Enterprise Java Beans

EJB QL - Enterprise JavaBeansQuery Language HQL - Hibernate Query Lanaguage Java RMI-IIOP - Java RMI API using CORBA IIOP protocol JAXB - Java Architecture for XML Binding

JAX-RPC API - (Java API for XML-Based RPC)

JAX-WS - Java API for XML Web Services

JAR - Java Archive File JCA - Java EE Connector Architecture. This defines a portable programming model for interfacing with enterprise information systems.

JMX - Programmatic Java Management Extensions

JMS - Java Messaging Service

JNDI - Java Naming and Directory Interface

JPA - Java Persistent API Wiki

a. Using Java Persistence API JSF - Java Server Faces

JSP - Java Server Pages

JSR - Java Specification Request

JTA - Java Transaction API JTS - Java Transaction Service MOM - Message-Oriented Middleware

ODA - Open Data Access

ORM - Object to Relational Mapping

POJO - Plain Old Java Objects

SOA - Service-Oriented Architecture

SOAP - Simple Object Access Protocol

WSDL - Web Service Definition Language

WSDP - Java Web Services Developer Pack

WTP - Web Tools Platform

Enterprise JavaBeans 3.0, 5th Edition by Bill Burke and Richard Monson-Haefel
1. Java Persistence API (JPA) replaces container-managed persistence with Plain Old Java Objects (POJO)

2. EJB Component (an enterprise bean), Java Persistence object (an entity bean)

3. Three type of beans - Entity Beans, Session Bean, Message Driven Bean

4. EJB business system - BEA's WebLogic, Pramatic, Sybase's EAServer, IBM's WebSphere

5. Open Source projects - JBoss, Apache Geronimo, JOnas

6. Java servlet is a server-side component that generates HTML and XML data for the presentation layer of a web Application. Struts, JSF components, EJB Message-driven beans area also Server-Side components

7. Sun Microsystem's definition of Enterprise JavaBeans architecture is as follows: The Enterprise JavaBeans architecture is a component architecture for the development and deployment of component-based distributed business applications. Applications written using the Enterprise JavaBeans architecture are scalable, transactional, and multi-user secure. These applications may be written once, and then deployed on any server platform that supports the Enterprise JavaBeans specification.

8. Enterprise JavaBeans is a standard server-side component model for distributed business applications.

9. Persistence layer maps objects to database storage so they can be queried, loaded, updated, and removed without having go to thru the API such as JDBC.

10. Entity beans are mapped using Java Persistence metadata to a database and can be worked on without writing any JDBC connection code.

11. EJB 3.0 supports asynchronous messaging thru the Java Messaging Service (JMS). You can use the same JMS API to send messages to Progress's SonicMQ or IBM's MQSeries

12. Web Services are network applications that use SOAP and WSDL to exchange information in the form of XML documents.

13. EJB 3.0 supports both RPC-style and document-style messaging. Support for web services is based on a web service: JAX-WS

Entity Beans
1. In the JPA specification are available only as POJO's, and are mapped to tables in a relational database.

2. Can be allocated, serialized, and sent across the network like any other POJO, contain a primary key field just like a table in the database. The primary key can be a class or primitive type.

3. Represents the behavior, validation and data of a business object. It doesn't even have to be marked as serializable.

4. Must be annotated with the @javax.persistence.Entity. 5. Must container a primary key field annotated with the @javax.persistence.Id.

6. In JPA, an application interacts directly with entity bean classes and does not interact thru an interface like a session bean.

7. To interact with entity beans, JPA provides a service called the javax.persistence.EntityManager.

8. Are different from EJB session beans because they are just POJO's and don't implement local or remote interfaces.

9. For deployment, entity beans are grouped into a set of classes called a persistence unit.

10. persistence.xml is the deployment descriptor that provides information about the provider of the database for each persistence unit.

11. Once you have defined the XML deployment descriptors and entity bean classes they must be packaged up in a Java Archive (JAR) file.

12. Represents data that is shared and may be accessed concurrently. The persistence provider needs to protect the data represented by the shared bean while allowing many clients to access the logical entity bean simultaneously. In the Java Persistence specification, the persistence container protects shared entity data by making a copy of the entity bean instance on a per-transaction basis. To protect against multiple access one method is to set the JDBC isolation level to SERIALIZED.

Enterprise Java Beans
1. Server side components which are Session and Message-Driven beans.

2. These beans do not represent persistence to a database like entity beans but model interactions.

Session Beans 1. Can be accessed using a variety of distributed object protocols, are extensions of the client application, and manage processes or tasks. 2. Provides an interface to what methods are available.

3. The remote interface represents the business methods which are accessed outside the EJB container. It is tagged with the @javax.ejb.Remote annotation. 4. The local interface represents the business methods that other beans in the same EJB container have access too. It is tagged with the @javax.ejb.Local annotation.

5. Interaction with session beans are always with the interfaces never the class implementation.

6. Don't have to implement any EJB-specific or any callback notifications

5. Are annotated as @javax.ejb.Stateful or @javax.ejb.Stateless.

6. Do not support concurrent access.

Stateless Session Beans
1. State between method calls are not maintained. 2. In Instance Pooling the life cycle of session beans exist in one of three states.

a. No state - has not be instantiated and provides the beginning of the life cycle. b. Pooled state - has been instatiated by the container but has not been associated with an EJB request. c. Ready state - has been associated with an EJB request and ready to respond to business method invocations.

Stateful Session Beans
1. State between method calls are maintained. 2. Don't participate in instance pooling. 3. Use activation to conserve resource. 4. EJB Server can evict from memory to conserve resources by serializing conversational state to secondary storage. When a client invokes a method on the EJB object, a new stateful session bean instance is created and its state is restored from the initial bean. 5. During Passivation, the bean is disassociated from its EJB object and its state saved to secondary storage. The bean instance's state is held relative to its EJB object so that after the bean has been passivated, it is safe to remove the bean instance from the EJB object and evict it from memory. The @javax.ejb.PrePassivate annotation can be placed on the bean and is called prior to passivation in order to close connections and etc. 6. During Activation, the bean's instance state is restored from secondary storage relative to its EJB object. When a method is called, the EJB container automatically creates a new instance and restores its fields state from secondary storage that was saved during passivation. The EJB object can then delegate the method invocation to the bean as normal. The @javax.ejb.PostActivate annotation can be placed on the bean and is called immediately after the bean has been instantiated. It can be used to reset transient fields to an initial value. Example Remote Session Bean: import javax.jms.*; import javax.persistence.*; import javax.ejb.*; @Stateful public class FooBean implements FooBeanRemote {     //The EJB Container injects these two annotated items @PersistenceContext private EntityManager entityManager; @EJB private ProcessItemRemote process; //These are entity beans retrieved via the EntityManager private CustomerFoo customer; private ItemFoo item; public void setCustomer(CustomerFoo cust) {        //Persist new CustomerFoo entity to storage entityManager.create(cust); customer = cust; }     public void setItem(int id) {        //Query information from persistent storage item = entityManager.find(ItemFoo.class, id) }     //This entity bean because unmanaged and detached from the EntityManager public PurchaseItemFoo purchaseItem(String card, double price) throws Throwable {        if (customer == null) throw new Exception("CustomerFoo has not been set. This is required to make a purchase."); if (item == null) throw new Exception("ItemFoo has not been set. This is required to make a purchase."); try {           //Create and persist entity bean to storage PurchaseItemFoo purchaseItem = new PurchaseItemFoo(customer, item, new Date); entityManager.persist(purchaseItem); //Process credit care for ItemFoo thru the remote session bean process.byCredit(customer, card, price); //Return purchased item entity bean return purchaseItem; }        catch(Exception ex) {           throw new EJBException(e); }     }   }

Message Driven Beans
1. Are asynchronous beans that process messages coordinating tasks involving other session and entity beans and subscribes or listens to messsages.

2. Implement one or message delivery methods (ex: onMessage) defineded in a message interface. The container will call these methods when a message arrives. 3. Are annotated with the @javax.ejb.MessageDriven.

4. Do not implement local, remote, or endpoint interfaces for message driven beans.

5. Can support any messaging system by implementing the JCA 1.5 contracts.

6. Are integration points for other applications interested in working with EJB applications. 7. Performs tasks using other entity and session beans. 8. Fullfill the same role as stateless session beans. 9. In Instance pooling each type of message-driven bean has its own instance pool that services incoming messages. 10. For concurrency it refers to the processing of more than one message at a time. NOTE: EJB 3.0 containers must support JMS-based message-driven beans, which implement javax.jms.MessageListener.

Example Message Driven Bean: import javax.jms.*; import javax.persistence.*; import javax.ejb.*; @MessageDriven public class FooBean implements MessageListener {     @PersistenceContext private EntityManager entityManager; @EJB private ProcessItemRemote; public void onMessage(Message message) {        try {           MapMessage fooMsg = (MapMessage)message; //Query information from message CustomerFoo customer = (CustomerFoo)fooMsg.getObject("CustomerFoo"); ItemFoo itemFoo = (ItemFoo)fooMsg.getObject("ItemFooID"); double price = fooMsg.getDouble("price"); String card = fooMsg.getString("card"); //Persist customer record entityManager.persist(customer); //Process credit care for ItemFoo thru the remote session bean process.byCredit(customer, card, price); }        catch(Exception ex) {           throw new EJBException(ex); }     }   }

Endpoint Interfaces
1. These interfaces represents business methods accessed outside the EJB Container via SOAP and is annotated with javax.jws.WebService.

EJB 3.0 Containers
1. Clients outside the container access the enterprise beans's using the remote interfaces.

2. Clients outside the container have the option of accessing stateless session beans as web services.

3. Clients within the container use local interfaces.

4. Must support JMS-based message-driven beans, which implement the javax.jms.MessageListener interface.

5. Is responsible for creating bean instances and managed on the server such as storage.

6. All EJB types register events that the EJB container emits. Once a container allocates and injects referenced services into and EJB instance it will call a method annotated with @javax.annotation.PostConstruct

7. javax.ejb.EJBContext is an interface that is implemented by the container and is part of the bean-container contract.

8. Session beans subclasses from javax.ejb.SessionContext. Message-driven beans subclasses from javax.ejb.MessageDrivenContext. These context types provide information about its environment, container, the client using the enterprise bean, and the bean itself. This information can be used while processing requests.

9. The enterprise bean's interface with the container provides JNDI to lookup resources and other beans.

10. Jave EE Connector Architecture defines an interface between Enterprise Information Systems (EISs) and Java EE container systems. It is the job of the EJB container to pool and maintain EIS connections, enroll the EIS in transactions, propagate security creditials, and etc. 11. Are requires to support the Secure Sockets Layer (SSL 3.0) and the IETF-standard Transport Layer Security (TLS 1.0) protocols for securing connections between clients and enterprise beans.

EJB Servers
1. EJB 3.0 requires that every EJB server support Java RMI-IIOP (The Java Remote Method Invocation over Internet Inter-ORB Protocol Technology. 2. EJB 3.0 requires support for SOAP 1.2 via the JAX-PRC API. 3. Primary Services that complete the Enterprise JavaBeans platform. These provide the infrastructure necessary for a three-tier system. 4. EJB servers automatically manage all of the primary services.

Primary Services
1. Concurrency a. Session beans are not concurrent. b. Entity and Message-Driven beans can accessed concurrently c. EJB servers handle concurrency, the bean's methods do not have to be made thread-safe. d. EJB specification prohibits the user of synchronized keyword. e. EJB specification explicitly prohibits beans from creating threads. 2. Transaction Management a. Is a unit of work or a set of tasks that are executed as a whole and each task must be completed in order to be a successful transaction. b. The EJB server monitors the transaction to ensure that all the tasks are completed successfully. b. Transactions are managed automatically. You don't need to use any API's to manage a bean's involvement in a transaction. c. By declaring the transactional attributes at deployment time tells the EJB server how to manage the bean at runtime. 3. Persistence a. Entity beans are the only type of bean that is persistent. Session and Message-Driven are not persistent. b. Entity beans represent the behavior and data associated with real-world entities like people, places or things. c. The Java Persistence model is plain Java-based model (POJO Persistence). d. Entities bean classes can be created outside the scope of the EJB container. e. An Entity bean can be attached/detached from the container management, sent around the network to remote clients, saved to disk, can be reattached to the EJB container using the EntityManager.merge method. f. Entity Bean instances are attached to persistent storage through the EntityManager service. g. EntityManager provides the CRUD as well a query methods for entity beans. h. When a bean instance is attached, the container manages the persistence state of the bean and automatically synchronized with persistent storage. 4. Object Distribution a. EJB client view only includes the remote bean interfaces, bean endpoint interfaces, and entity bean class instances so long as the entity bean class implements the java.io.Serializable. b. EJB client view doesn't include session bean class instances, the EJB container, instance swapping, or any other implementation specifics of session bean. 5. Asynchronous Enterprise Messaging a. Requires the EJB container to reliably route messages from JMS clients to JMS-MDBs. b. Requires the JMS providers to attempt redelivery if failure occurs. Most EJB vendors will place a limit on the number of times a message can be redelivered. After that, its usually placed in a "dead message" repository, where it can be reviewed by an administrator. c. Enterprise messages may be persistent to disk or a database till it can be properly delivered to their intended clients. d. Persistent messages must survive system failures. If the EJB server crashes, these messages must still be available for delivery when the server comes back up. c. Enterprise messaging is transactional which means if a JMS-MDB fails while processing a message, that failure will abort the transaction and force the EJB container to redeliver the message to another message-driven bean instance. d. Message-driven beans, stateless session beans, and entity beans can send JMS messages. 6. EJB Timer Service a. Can be used to schedule notifications that are sent to enterprise beans at specific times. b. Can be set on entity, stateless session, and message-driven beans. c. Session and entity beans, the bean sets the timer itself. d. Some EJB container systems may support message-driven bean timers to perform batch processing. 7. Naming (JNDI) a. Provide clients with a mechanism for locating distributed objects or resources. b. Must provide object binding and a lookup API. Object Binding is the association of a distributed object with a name or identifier. Lookup API provides the client with an interface to the naming system. c. EJB mandates the use of JNDI as a lookup API on Java clients. d. JNDI supports any kind of naming and directory service. e. Java client applications can use JNDI to initiate a connection to an EJB server and to locate a specific EJBs. Example JNDI: using javax.naming.*; ...     Context jndiContext = new InitiateContext; HelloWorld hello = (HelloWorld)jndiContext.lookup("TestApplication/HelloWorldBean/remote"); System.out.println(hello.getMessage); 8. Security - EJB servers can support as many as three kinds of security: a. Authentication - validates the identity of a user usually with a login screen with user name and password. b. Authorization -  security policies that regulate access permissions a user has available. c. Secure communication - communication channels between a client and a server which can be secured with encryption.

Transaction-scoped
1. Live as long as a transaction and be closed when the transaction completes 2. Only application server managed persistence contexts can be transaction-scoped. pseudocode: @PersistentContext(unitName="titan") EntityManager entityManager; @TransactionAttribute(REQUIRED) public Customer someMethod {          Customer = entityManager.find(Customer.class, 1); cust.setName("new name") return cust; }

Extended persistence
1. Live longer than a transaction. 2. Remain managed after a transaction completes. 3. Can only be injected on a @Stateful session bean. pseudocode: Customer cust = null; transaction.begin; //start transaction 1 cust = extendedEntityManager.find(Customer.class, 1); transaction.commit; //transaction 1 ends transaction.begin; //start transaction 2 cust.setName("Bill"); extendedEntityManger.flush; transaction.commit; //cust instance remains managed and changes are flushed

Persistence.xml
1. Deployment descriptor for entity bean classes that are managed/persisted thru the EntityManager 2. Defines identities and configuration properties of each persistent unit. 3. File is located in the META-INF directory in one of the following possible locations: a. Plain JAR File within the class path of a regular Java SE program. b. EJB-JAR file. c. JAR file in a WEB-INF/lib diretory in a web archive file (.war). d. JAR file in a root of an enterprise archive (.ear) c. JAR file in the EAR lib directory. 4. Each persistent-unit must have an identity name="someEntityManagerName" which will be used when binding the EntityManager to each persistent unit defined in the XML file.  (0..*) - name is the identity tag. (Optional) transaction-type="JTA" attribute can also be added which defaults to JTA for Java EE and RESOURCE_LOCAL of SE Optional sub elements: a.  - just a comment b.  - This is a fully qualified name of a class that implements the javax.persistence.PersistenceProvider interface. c. java:/DefaultDS - usually defined for JTA or RESOURCE_LOCAL d. ../lib/customer.jar - This specifies additional jars to be scanned. NOTE: - By default the JAR file that contains this XML will be scanned from the root for any classes annotated with the @javax.persistence.Entity annotation. e.  - If you are using JTA or RESOURCE_LOCAL f.  - This points to the orm.xml file for mapping classes in this persistence unit and the database they are mapped too. g. com.lmegabyte.comain.FooEntityBean (0..*) - Defines one or more fully qualified entity bean classes (POJOs) that will be managed by the EntityManager/JPA. h.  - Defines comma delimited list of fully qualified entity bean classes to exclude from being scanned. i. <properties> - Define a set of vendor-specific properties passed to the persistence provider. <property name="org.hibernate.hbm2ddl">update - Vendor specific properties. </persistent-unit> ...

javax.persistence.EntityManager
1. Maps a fixed set of classes to a particular database.

javax.persistence.EntityManagerFactory
EntityManagerFactory interface: package javax.persistence public interface EntityManagerFactory {       EntityManager createEntityManager; EntityManager createEntityManager(java.util.Map map); void close; boolean isOpen; }

Java SE 1. Required to create instances of EntityManager(s). 2. Get an EntityManager factory by calling the Persistence.createEntityManagerFactory("CRM") static method. Java EE 1. Is not required to use the factory to get an EntityManager. 2. Call factory.close to free up any resources. 3. Can be injected directly into a field or setter method of your EJBs using the @javax.persistence.PersistenceUnit annotation. 4. Is automatically closed by the EJB container when the instance is discarded. import javax.persistence.*; import javax.ejb.*; @Stateless public MyBean implements MyBeanRemote {       @PersistenceUnit(unitName="CRM") private EntityManagerFactory factory; //This one is injected thru the setter method private EntityManagerFactory factory2; @PersistenceUnit(unitName="CUSTDB") public void setFactory2(EntityManagerFactory f)       { this.factory2 = f;       } } Obtaining a Persistence Context 1. If the EntityManagerFactory is JTA-enabled, then must enlist the EntityManager instance within a transaction by calling the EntityManager.joinTransaction method or changes will not be synchronized with the database. 2. Is required if you create an EntityManager when calling the EntityManagerFactory.createEntityManager

javax.persistence.Persistence
Peristence class: public class Persistence {       public static EntityManagerFactory createEntityManagerFactory(String unitName); public static EntityManagerFactory createEntityManagerFactory(String unitName, java.util.Map properties); } Java SE 1. Is responsible for bootstrapping an EntityManagerFactory:

Java EE 2. It is strongly recommended to use the @PersistentContext annotation or XML equivalent when using Java Persistence with EJBs. @Stateful public class MyStatefullBean implements MyStatefulRemote {       @PersistenceContext(unitName="titan", type=PersistenceContextType.EXTENDED)<BR/> private EntityManager manager; ...    }

Recommended Books to Read
Enterprise JavaBeans 3.0 (O'Reilly), 5th Edition by Bill Burke and Richard Monson-Haefel JBoss at Work (O'Reilly): A Practical Guide by Tom Marrs; Scott Davis Database Programming with JDBC and Java (O'Reilly)

Java Distributed Computing (O'Reilly)