Monday, August 31, 2009

The Good Enough Revolution

In an article 'The Good Enough Revolution: When Cheap and Simple Is Just Fine', Wired claims that the future of technology, warfare and medicine will be filled with 'good enough' solutions. Situations where feature-rich and expensive products are replaced with bare-bones infrastructures and solutions.


We now favor flexibility over high fidelity, convenience over features, quick and dirty over slow and polished. Having it here and now is more important than having it perfect.


The good news in this is that this trend is ideally suited to our times. During the worst recession in 75 years, it's the light and simple products that are needed. And I believe, that this trend also applies to the software industry. Designing a solutions, building a product, doing a project: There is the need for the solutions that easily fits 80% of the customers needs.
If that 80 percent number rings a bell, it's because of the famous Pareto principle, also known as the 80/20 rule. And it happens to be a recurring theme in Good Enough solutions. It could be expected, that you can reach a 80% solutions with less than 20% of the money. The remaining 20% of the features are the ones that hurt and boost the costs. But where to draw the line? Which are the 20% of features to skip? This part is not too easy to answer. Answering the following questions should guide you.


What's available?

There are many examples out there, where lean startups and small-scale enterprises offer solutions that best fit the needs for less money. This could mean, your are not using any closed source products but open source alternatives. Another interpretation could be, you are using pre build component sets and skipping the expensive self made development. Look at the available solutions. Take some time to investigate the features and select the solutions which already adresses most of your needs.


What's inimitable?

There are obvious examples, like (not realy) differing processes (HR,FI). If you are thinking about buying a solution and "customizing" it to your needs, focus on things that are true differentiators. In most of the cases, you will realize, that there are'nt too many parts which make your process inimitable.
Another good example is the UI and it's flow. There are prebuild solutions out there for user interactions, which are broadly accepted. Look at yahoo and their UI components, the JBoss Richfaces and many other examples. If there is a skinning mechanisms available and you plan to run more than two projects on the same component set: use it! If not. Forget about it. If the datagrid allows for paging, be happy. If you need additional information (number of results, aggregate of pages or other, possibly nasty things) that are not available through simple customizing: Forget about it.


What's thwarting me?

Already found your 80% solution? But still having difficulties? It is'nt the right technology? right? :) Some PHP or Ruby stuff? But your company/customer is using Enterprise Java? Perfect. Sounds like you are getting trouble with the technology department. You could possibly look out for some kind of technolgy adapter like Quercus (running PHP in JEE) or Glassfish running JRuby for example. Anyhow, it's important not to break the rules but to bend them to fit your needs. If you sill cannot get to any solution: Remember, that there is still a suitable exit. Do some analysis on the business case and convince them. If they don't want your cheeper solution, that they should pay the bills. If this does not work, you still have a perfect basis for further budget discussions.


What is the issue?

Using Enterprise Java since more than eight years makes me belive that there is an advantage in standardization and guidelines within companys. Programming easy to maintain and well documented projects still has a right to exist. And designing such solutions will still be more expensive that just buying or downloading any simple PHP or other script based solution developed by some people in the backyard. But after all this mainly applies to about 10 to 15% of all the applications in a company. If your project does not fit into this 10 to 15% of applications, you are free to choose any language, framework, technolgy you like. If not: Forget about the simple "Good Enough" approaches and look for smaller parts in your scope to apply the principles. For example you can still use existing libraries but build the basic application yourself instead of using an existing open source project.

As a conculusion, you should keep in mind to regulary see beyond your own nose. Don't just stick to things as they have ever been. Always ask yourself the questions about the 80% solution. About truely inimitable parts and the value of a "here and now" solution.

Thursday, August 27, 2009

FacesTrace - tracing your JSF applications

Ever wondered, where your JSF app spends it's evenings? FacesTrace aims to enhance the traceability of JavaServer Faces based applications. It collects several trace information and performance metrics and presents them on the
page being traced. It is related to but not dependent on PrimeFaces.
The main metrics and information covered are:

• JSF LifeCycle visualizer
• Performance Tracker
• Scoped Attributes
• Log4J appender
• FacesMessage Lister
• Component Tree visualizer

I tryed it with weblogic 11g and it works fine.
FacesTrace has a single jar called facestrace-{version}.jar, it has no dependency to any other PrimeFaces module and can be used seperately. The only other dependency you need is a recent commons-logging-{version}.jar.
FacesTrace setup is simply about having the facestrace jar in your classpath. No other configuration beside the *.jsf mapping needed. FacesTrace is both compatible with Facelets and JSP. In order to display the trace information, simply add trace=true request parameter to the page youʼre tracing.


http://localhost:7001/myapp/mypage.jsf?trace=true


Performance Tracker
The performance tracker keeps track of how long each jsf phase takes and displays the execution times.

Lifecycle Tracker
Visualizes the JSF Request Lifecycle and displays each phases's state in different color. Green means, the phase is executed with success. Red means, the phase caused an error. Gray indicates, that the phase was never executed.

Variables
Displays each key-value pair in different scopes like application, session, request, cookies,params and more.

Faces Messages
Displays FacesMessages added to the FaceContext for the request being processed.

Logs
FacesTrace has it's own appender, setting the log4j to use this appender will alow
FacesTrace to display the logs at the page

Component Tree
The component tree of the view, can be traversed using the dhtml tree view of the
FacesTrace.

Monitoring Performance Using the WebLogic Diagnostics Framework

Mike Cico wrote a quick tour of your options for gathering server and application performance data from Oracle WebLogic Server which was published on otn.oracle.com.
The articel focuses on using WLDF to instrument an application and monitor its performance via the WLDF console.

In detail it focuses on:
* Monitoring for SLA violations
* Monitoring CPU load
* Graphing method and MBean data
* Finding bottleneck methods

If you want to start over with the WLDF for the first time, you could also have a first look at the introductional article by Rebecca Sly.

Mike Cico is a senior developer on the WebLogic Server Diagnostics Framework team with Oracle. When not doing that, he has been known to spend time with his family camping, bike riding, and skiing; when not doing those things, he's usually lifting weights down at his local gym.

Tuesday, August 25, 2009

Next Generation Java Programming Style

Stephan Schmidt wrote a nice blogpost about the next generation Java programming style. Many developers move away from Java to new languages like Ruby, Python, Groovy, Erlang, Scala. If you are trapped with Java, you can still use some of the benefits of those new languages.


  1. Final is your new love

  2. No setters

  3. Do not use loops for list operations

  4. Use one liners

  5. Use many, many objects with many interfaces

  6. Use Erlang-Style Concurrency

  7. Use Fluent Interfaces

  8. Data Transfer Objects without setters and getters



About the author: Stephan Schmidt is head of development at brands4friends. He has over 25 years of programming experience, more than 15 years of internet technology experience and 10 years experience in agile. He was head of development, consultant and CTO in different companies and is a speaker, author and blog writer. He specializes in organizing and optimizing software development helping medium companies and startups by increasing productivity with lean software development and agile methodologies.

Book review: Real World Java EE Patterns - Rethinking Best Practices by Adam Bien



I got the chance to look at the digital edition of Adams newest book. All "Bien works" promise real world knowledge and code you need to develop lean and maintainable Java EE 5 / 6 applications. Therefore I was quite excited to see his new book.

Real World Java EE Patterns - Rethinking Best Practices guides you to efficient code and best practices in a structured way, with real world examples.

The first two chapter sum up, what you should already know. Basic JEE principles (EJB, JPA, JMS, JCA, JTA, Dependency Injection, Convention Over Configuration, Interceptors, REST), Transactions, Isolation Levels, Core J2EE patterns. In short, this is more like a "history of the internet section".

Chapters three to five realy deal with patterns. Starting with business layer patterns for domain driven and service oriented architectures, over to patterns for integration of asynchronous, legacy, or incompatible resources and finaly infrastructural patterns for eager-starting of services, thread tracking and more.

Chapter six finaly is about pragmatic Java EE Architectures. With a discussion of superfluous patterns and outdated best practices. Things like DAOs, Business Delegates, Data Transfer Objects extensive layering, indirections and more. Beside this, the introduces lean and pragmatic service and domain driven architectures, based on the discussed patterns.

As a conclusion: A good book to start over again with patterns in JEE6. If you skip the first two parts and focus on the "pattern" itself, it can be a very usefull ressource for you. As always, Adam's books are fun to read and easy to understand even for non native speakers :)

The online PDF version is available from Lulu.com.
(If you use the the promo code: "README" you will save 10% off)

Have a look at http://press.adam-bien.com/, too.

Monday, August 24, 2009

Best Eclipse Plugins

I am always on the hunt for new eclipse plugins, that eases development. There is a very (too) short list of them up to now.
How about you? Do you have favourite plugins? Which ones?

- Oracle Enterprise Pack for Eclipse
http://www.oracle.com/technology/software/products/oepe/index.html

- JadClipse
http://sourceforge.net/projects/jadclipse/

- Subclibse
http://subclipse.tigris.org/

For SVN Versions <= 1.5
Subclipse is an Eclipse Team Provider plug-in providing support for Subversion within the Eclipse IDE.

- Subversive
http://www.eclipse.org/subversive/

For SVN Versions >= 1.5
The Subversive project aims to provide Subversion (SVN) integration for Eclipse.
The Subversive plug-in gives you the ability to work with this CVS successor
version control system from the Eclipse workbench.

- Explore FS
http://www.junginger.biz/eclipse/

ExploreFS is a tiny plugin (~6KB) that opens a selected file in the folder of the native file manager.
It adds "Explore in File System" to the context menu of Eclipse's package explorer, resource navigator, and other views.

- Log4E
http://log4e.jayefem.de/update

Log4E is an Eclipse Plugin which helps you to set up your logger easily in Java Projects.
It assists you in several tasks: logger declaration, logger Insertions at certain method entries,
substitution of System out's, modification of already existing logger statements.
Log4E has active support for Log4j, Commons Logging and JDK 1.4 Logging.

Friday, August 21, 2009

Sparks and White Noise: A New Oracle/Sun World

Read a great post about the hottest merger these days. Even if still some legal things need to be cleared, the merger is proceeding!


Now that a lot of the dust has settled around this wild and crazy saga, it's time to take a serious look at what the impact will be on the industry and those who work in it.


Sparks and White Noise: A New Oracle/Sun World

Official Oracle press release here: U.S. Department of Justice Approves Oracle Acquisition of Sun

Thursday, August 20, 2009

Tune your Weblogic Server Application

During the days of the worldwide financial crisis the wish for effective and efficient applications comes up more often, too. If you have a performing application you could possible use some smaller hardware or serve more users. This article compiles some performance tuning aspects, you could use together with your JEE Application and Weblogic server. Performance tuning is one of the most challenging parts of application development. It’s highly dependent on the platform you are running and you need quite a bit experience to get the right feeling for the right screws to twiddle. This article is meant as an overview to give a brief understanding of the places, you can put your hands on. Anyway, as in most cases the overall solution will not be to change all described settings but find the ones, relevant for your application needs.


Pool Sizes
Pool Size is the magic deep inside of your Weblogic. For nearly all kinds of ressources you can configure them. This includes pools for JDBC connections, Stateless Session EJBs, and MDBs.
If you increase the Pool Size it will maximize concurrency for the expected thread utilization. In almost any case, when your application is slow and you CPU is still down, you will get a performance boost.
Introduced with WebLogic Server releases 9.0 every server instance uses a self-tuned thread-pool. Even if it is self-tuned, you can still optimize such pools by configuring the Workmanagers.
Before 9.x series you were able to configure separate thread pools for separate objects. Now all Weblogic Server instances use one single thread pool, in which all types of work are executed.
The server prioritizes work based on defined rules and run-time metrics, including the actual time it takes to execute a request and the rate at which requests are entering and leaving the pool.
On behalf of this the thread pool changes its size automatically to maximize throughput. The queue monitors throughput over time and based on history, determines whether to adjust the thread count or not.
For example, if historical throughput statistics indicate that a higher thread count increased throughput, the server increases it. Similarly, if statistics indicate that fewer threads did not reduce throughput, the count will be reduced.
To modify this behaviour you can configure a set of scheduling guidelines and associate them with one or more applications, or with particular application components (e.g. Servlets, EJB).

To manage work in your applications, you define one or more of the following Work Manager components:

• Fair Share Request Class
• Response Time Request Class
• Min Threads Constraint
• Max Threads Constraint
• Capacity Constraint
• Context Request Class

You can configure Work Managers at the domain level, application level, and module level in one of the following configuration files, or using the administration console:

• config.xml
Work Managers defined here can be assigned to any application, or application component, in the domain.
• weblogic-application.xml
Work Managers defined here can be assigned to that application, or any component of that application.
• weblogic-ejb-jar.xml or weblogic.xml
Work Managers specified at the component-level can only be assigned to that specific component.
• weblogic.xml
Here you can configure Work Managers for a Web application.

Here is a sample configured to use Request Classes:


<work-manager>
<name>highpriority_workmanager</name>
<fair-share-request-class>
<name>high_priority</name>
<fair-share>100</fair-share>
</fair-share-request-class>
<min-threads-constraint>
<name>MinThreadsCountFive</name>
<count>5</count>
</min-threads-constraint>
</work-manager>


You can configure Request Classes, Context Request Class, Constraints and Stuck Thread Handling components within a workmanager. For more details on all of them, have a look at the official documentation.

To reference the workmanager, you just put a reference comparable to the following into your component configuration file (e.g. web.xml) for example:


<init-param>
<param-name>wl-dispatch-policy</param-name>
<param-value>highpriority_workmanager</param-value>
</init-param>


The best way to determine the appropriate pool size is to monitor the pool's current size, shrink counts, grow counts, and wait counts during an application run. To do this, just have a look at the diagnostics console within the Weblogic admin console. During normal operations the preconfigured self-tuned thread-pool does all the work for you. Tuning Work Managers can have positive but also negative effects. Therefore you need quite a bit experience to do this the right way.


Prepared Statement Cache
When you use a prepared statement or callable statement in an application or EJB, there is considerable processing overhead for the communication between the application server and the database server and on the database server itself. To minimize the processing costs, WLS can cache prepared and callable statements used in your applications. When an application or EJB calls any of the cached statements they will be reused out of the cache. This reduces CPU usage on the database server which improves performance for the current statement and leaves enough CPU cycles for other tasks.

Each connection in a data source has its own individual cache of prepared and callable statements used on the connection. However, you configure statement cache options per data source. That is, the statement cache for each connection in a data source uses the statement cache options specified for the data source, but each connection caches its own statements. Statement cache configuration options include:
• Statement Cache Type
This defines the algorithm which determines the statements to store in the statement cache.
o When you select LRU (Least Recently Used, the default) as the Statement Cache Type, WebLogic Server caches prepared and callable statements used on the connection until the statement cache size is reached.
o When you select FIXED as the Statement Cache Type, WebLogic Server caches prepared and callable statements used on the connection until the statement cache size is reached. When additional statements are used, they are not cached.

• Statement Cache Size
The number of statements to store in the cache for each connection. The default value is 10.

The Statement Cache Size attribute determines the total number of prepared and callable statements to cache for each connection in each instance of the data source. By caching statements, you can increase your system performance. However, you must consider how your DBMS handles open prepared and callable statements. In many cases, the DBMS will maintain a cursor for each open statement. This applies to prepared and callable statements in the statement cache. If you cache too many statements, you may exceed the limit of open cursors on your database server.

For example, if you have a data source with 10 connections deployed on 2 servers, if you set the Statement Cache Size to 10 (the default), you may open 200 (10 x 2 x 10) cursors on your database server for the cached statements.

You configure the Statement Cache Options within the Weblogic Admin Console at a single Datasource.

Logging Last Resource Optimization
When using transactional database applications, consider using the JDBC data source Logging Last Resource (LLR) transaction policy instead of XA. The LLR optimization can significantly improve transaction performance by safely eliminating some of the 2PC XA overhead for database processing, especially for two-phase commit database insert, update, and delete operations.


WebLogic Server supports the Logging Last Resource (LLR) transaction optimization through JDBC data sources. LLR is a performance enhancement option that enables one non-XA resource to participate in a global transaction with the same ACID guarantee as XA. LLR is a refinement of the “Last Agent Optimization.” It differs from Last Agent Optimization in that it is transactionally safe. The LLR resource uses a local transaction for its transaction work. The WebLogic Server transaction manager prepares all other resources in the transaction and then determines the commit decision for the global transaction based on the outcome of the LLR resource’s local transaction.

The LLR optimization improves performance by:

• Removing the need for an XA JDBC driver to connect to the database. XA JDBC drivers are typically inefficient compared to non-XA JDBC drivers.
• Reducing the number of processing steps to complete the transaction, which also reduces network traffic and the number of disk I/Os.
• Removing the need for XA processing at the database level

• When a connection from a data source configured for LLR participates in a two-phase commit (2PC) global transaction, the WebLogic Server transaction manager completes the transaction by:

• Calling prepare on all other (XA-compliant) transaction participants.
• Inserting a commit record to a table on the LLR participant (rather than to the file-based transaction log).
• Committing the LLR participant's local transaction (which includes both the transaction commit record insert and the application's SQL work).
• Calling commit on all other transaction participants.

For a one-phase commit (1PC) global transaction, LLR eliminates the XA overhead by using a local transaction to complete the database operations, but no 2PC transaction record is written to the database.

The Logging Last Resource optimization maintains data integrity by writing the commit record on the LLR participant. If the transaction fails during the local transaction commit, the WebLogic Server transaction manager rolls back the transaction on all other transaction participants. For failure recovery, the WebLogic Server transaction manager reads the transaction log on the LLR resource along with other transaction log files in the default store and completes any transaction processing as necessary. Work associated with XA participants is committed if a commit record exists, otherwise their work is rolled back.

Configure the LLR at a single Data Source (Transactions-Options Page) via the adminstration console. For more optimization information have a look at the Programming WebLogic JTA section


Connection Backlog Buffering
You can tune the number of connection requests that a WebLogic Server instance will accept before refusing additional requests. The Accept Backlog parameter specifies how many Transmission Control Protocol (TCP) connections can be buffered in a wait queue. This fixed-size queue is populated with requests for connections that the TCP stack has received, but the application has not accepted yet.
You can configure the Backlog Buffering at a single server instance via the administration console.
To not get in trouble with this, you should have a look at the basic OS Tuning information on TCP for Webglogic Server

Chunk Size
A chunk is a unit of memory that the WebLogic Server network layer, both on the client and server side, uses to read data from and write data to sockets. To reduce memory allocation costs, a server instance maintains a pool of these chunks. For applications that handle large amounts of data per request, increasing the value on both the client and server sides can boost performance. The default chunk size is about 4K. Use the following properties to tune the chunk size and the chunk pool size:

• weblogic.Chunksize
Sets the size of a chunk (in bytes). The primary situation in which this may need to be increased is if request sizes are large. It should be set to values that are multiples of the network’s maximum transfer unit (MTU), after subtracting from the value any Ethernet or TCP header sizes. Set this parameter to the same value on the client and server.
• weblogic.utils.io.chunkpoolsize
Sets the maximum size of the chunk pool. The default value is 2048. The value may need to be increased if the server starts to allocate and discard chunks in steady state. To determine if the value needs to be increased, monitor the CPU profile or use a memory/ heap profiler for call stacks invoking the constructor weblogic.utils.io.Chunk.
• weblogic.PartitionSize
Sets the number of pool partitions used (default is 4). The chunk pool can be a source of significant lock contention as each request to access to the pool must be synchronized. Partitioning the thread pool spreads the potential for contention over more than one partition.

JPA instead of CMP
Ok. It's not a big secret anyhow. CMP is dead and the following section should be outdated at all. Anyway, there are a lot of older applications out there and not all of them will be migrated to JPA. If you are planning this, you are safer with performance tunings of your JPA implementation at all. From a Weblogic point of view this is/was Kodo. I personaly never really was a friend of Kodo. And after Bea went over to Oracle we all should stick to what is far better: ToplinkEssentials and EclipseLink. Nobody minds if you use Hibernate. If you are using JPA, the first thing to keep an eye open for is the fetching strategy. Basacaly you can choose between eager and lazy loading. Depending on the implementation you use, there may be additional fetch strategies. If you have them, use them and make them fit your applications needs. Beside the basics, all frameworks offer some more advanced performance management options. Starting from caching (which is no part of the specification so far) up to special monitoring and optimizing tools.

Optimistic or Read-only Concurrency
Use optimistic concurrency with cache-between-transactions or read-only concurrency with query-caching for CMP EJBs wherever possible. Both of these two options leverage the Entity Bean cache provided by the EJB container.

• Optimistic-concurrency with cache-between-transactions work best with read-mostly beans. Using verify-reads in combination with these provides high data consistency guarantees with the performance gain of caching.

The EJB Container caches stateful session beans in memory up to a count specified by the max-beans-in-cache parameter specified in weblogic-ejb-jar.xml. This parameter should be set equal to the number of concurrent users. This ensures minimum passivation of stateful session beans to disk and subsequent activation from disk which yields better performance.

Entity beans are cached at two levels by the EJB container. Transaction-Level Caching, once an entity bean has been loaded from the database, it is always retrieved from the cache whenever it is requested when using the findByPrimaryKey or invoked from a cached reference in that transaction. Note that getting an entity bean using a non-primary key finder always retrieves the persistent state of the bean from the data base. Caching between transactions, entity bean instances are also cached between transactions. However, by default, the persistent state of the entity beans are not cached between transactions. To enable caching between transactions, set the value of the cache-between-transactions parameter to true.

Is it safe to cache the state? This depends on the concurrency-strategy for that bean. The entity-bean cache is really only useful when cache-between-transactions can be safely set to true. In cases where ejbActivate() and ejbPassivate() callbacks are expensive, it is still a good idea to ensure the entity-cache size is large enough. Even though the persistent state may be reloaded at least once per transaction, the beans in the cache are already activated. The value of the cache-size is set by the deployment descriptor parameter max-beans-in-cache and should be set to maximize cache-hits. In most situations, the value need not be larger than the product of the number of rows in the table associated with the entity bean and the number of threads expected to access the bean concurrently.

• Query-caching is a WebLogic Server 9.0 feature that allows the EJB container to cache results for arbitrary non-primary-key finders defined on read-only EJBs. All of these parameters can be set in the application/module deployment descriptors.

The concurrency-strategy deployment descriptor tells the EJB container how to handle concurrent access of the same entity bean by multiple threads in the same server instance. Set this parameter to one of four values: Exclusive, Database, Optimistic and ReadOnly.

The ReadOnly value is the most performant. When selected, the container assumes the EJB is non-transactional and automatically turns on cache-between-transactions. Bean states are updated from the data base at periodic, configurable intervals or when the bean has been programmatically invalidated. The interval between updates can cause the persistent state of the bean to become stale. The ReadOnly is the only concurrency-strategy for which query-caching can be used.
Entity bean instances are also cached between transactions. However, by default, the persistent state of the entity beans are not cached between transactions. To enable caching between transactions, set the value of the cache-between-transactions parameter to true.


Local Interfaces
Use local-interfaces or use call-by-reference semantics to avoid the overhead of serialization when one EJB calls another or an EJB is called by a servlet/JSP in the same application. Prior to Weblogic Server versions 8.1 call-by-reference is turned on by default.For releases of WebLogic Server 8.1 and higher, call-by-reference is turned off by default.

You can do this in the weblogic-ejb-jar.xml for example like this:


<weblogic-enterprise-bean>
<entity-descriptor>
<ejb-name>AccountBean</ejb-name>
...
<enable-call-by-reference>False</enable-call-by-reference>
</entity-descriptor>
</weblogic-enterprise-bean>


Use Relationship caching (if using CMP)
Using eager relationship caching allows the EJB container to load related entity beans using a single SQL join. Use only when the same transaction accesses related beans.
Relationship caching—also known as “pre-fetching” or “eager relationship caching’—improves the performance of entity beans by loading related beans into the cache and preventing multiple queries by issuing a join query for the related bean. If a set of beans is accessed as part of the same unit of work, then your application should load them into cache at the same time.

• Relationship caching is supported for one-to-one, one-to-many, and many-to-one relationships. It is not supported for many-to-many relationships.
• When using weblogic-ql, this feature only works with finder methods that return references to either EJBObject or EJBLocalObject beans.

Specify the relationship-caching element in weblogic-cmp-jar.xml, as shown in this example:


<relationship-caching>
<caching-name>cacheMoreBeans</caching-name>
<caching-element>
<cmr-field>accounts</cmr-field>
<group-name>acct_group</group-name>
<caching-element>
<cmr-field>address</cmr-field>
<group-name>addr_group</group-name>
</caching-element>
</caching-element>

<caching-element>
<cmr-field>phone</cmr-field>
<group-name>phone_group</group-name>
</caching-element>
</relationship-caching>


HTTP Sessions
As a general rule, you should optimize your application so that it does as little work as needed with sessions. If possible, you should always try to get away without using any session persistance at all. But you required, wls offers five session persistence mechanisms you can use. They are configurable at the Web application layer. Which mechanism you choose for your application depends on various factors, like session size, session life cycle, reliability, and session failover requirements. For example, a Web application with no failover requirements could be maintained as a single memory-based session; whereas, a Web application with session fail-over capability could be maintained as replicated sessions or JDBC-based sessions, based on their life cycle and object size.

In terms of pure performance, in-memory session persistence is a better overall choice when compared to JDBC-based persistence for session state.While all session persistence mechanisms have to deal with the overhead of data serialization and deserialization, the additional overhead of the database interaction impacts the performance of the JDBC-based session persistence and causes it to under-perform compared with the in-memory replication. However, in-memory-based session persistence requires the use of WebLogic clustering, so it isn’t an option in a single-server environment.

On the other hand, an environment using JDBC-based persistence does not require the use of WebLogic clusters and can maintain the session state for longer periods of time in the database. One way to improve JDBC-based session persistence is to optimize your code so that it has as high a granularity for session state persistence as possible. Other factors that can improve the overall performance of JDBC-based session persistence are: the choice of database, proper database server configuration, JDBC driver, and the JDBC connection pool configuration.

WebLogic Server tracks and replicates changes in the session by attribute so you should:

• Aggregate session data that changes in tandem into a single session attribute.
• Aggregate session data that changes frequently and read-only session data into separate session attributes

For example: If you use a a single large attribute that contains all the session data and only 10% of that data changes, the entire attribute has to be replicated. This causes unnecessary serialization/deserialization and network overhead. You should move the 10% of the session data that changes into a separate attribute.


Performance test and profile your application
Last but not least you should keep an eye on the overall performance of your application. There are many different ways to do this. Some of them are more difficult than others. Which type you choose, depends on the results you want to achieve. If you want to have a quickstart into performance tests and methodologies, have a look at the articel "Approaches to Performance Testing" on otn from Matt Maccaux.

Wednesday, August 19, 2009

Using JavaMail with Weblogic Server

WebLogic Server includes the JavaMail API version 1.3. Using the JavaMail API, you can add email capabilities to your enterprise java applications. It provides access to Internet Message Access Protocol (IMAP)- and Simple Mail Transfer Protocol (SMTP).

JavaMail depends on configuration files that define the mail transport capabilities of the system. The weblogic.jar file contains the standard configuration files from Sun, which enable IMAP and SMTP mail servers for JavaMail and define the default message types JavaMail can process. If you do want to extend JavaMail, download JavaMail from Sun and follow Sun’s instructions for adding your extensions. Then add your extended JavaMail package in the WebLogic Server classpath in front of weblogic.jar.

First thing to do is to configure a JavaMail Session in WebLogic Server. This allows server-side modules and applications to access JavaMail services with JNDI, using Session properties you preconfigure for them (e.g. mail hosts, transport and store protocols, and the default mail user). Applications that are heavy email users benefit because the mail session creates a single javax.mail.Session object and makes it available via JNDI to any module that needs it.

You can override any properties set in the mail session in your code by creating a java.util.Properties object containing the properties you want to override. Then, after you look up the mail session object in JNDI, call the Session.getInstance() method with your Properties object to get a customized Session.

To create a mail session in weblogic admin console:

  1. In the Administration Console, expand Services and select Mail Sessions.

  2. Click the New button.

  3. Enter a name for your mail session and click OK.

  4. On the Mail Sessions page, click the new mail session name.

  5. On the Mail Sessions: Configuration page, in JNDI Name, enter a unique JNDI name.

  6. In Properties, specify information for connecting to an existing mail server.

  7. save your changes



A simple example of sending a message with java mail:

// Look up the mail session
InitialContext ic = new InitialContext();
Session session = (Session)
ic.lookup("sampleMailSession");

// Construct a MimeMessage.

String to = "some@adress.net";
String subject = "some example subject";
String messageTxt =
"Some example message body text";

Message msg = new MimeMessage(session);
msg.setFrom();
msg.setRecipients(
Message.RecipientType.TO,
InternetAddress.parse(to, false));
msg.setSubject(subject);
msg.setSentDate(new Date());
// Content is stored in a MIME
// multi-part message
// with one body part
MimeBodyPart mbp = new MimeBodyPart();
mbp.setText(messageTxt);

Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp);
msg.setContent(mp);

//Send the message
Transport.send(msg);

Now mobile support for my blog

As of today, my blog got mobified :) You can now use a mobile version (not too pretty by now) of my blogposts.
If you are visiting this site, you should be automatically redirected to: http://eisele.mobify.me/blog/.
Hope, this is helpfull.

Tuesday, August 18, 2009

J2EE to JEE5 or JEE6 Migration

More and more mature projects think about migrating these days. After a couple
of years of successfull development it is time to decide weather to
switch to updated enterprise java versions or to keep the old ones.
Looking out for the JEE6 release, which is getting closer each day, I will have
a look at some things to keep in mind if you are thinking about updating your J2EE
projects.

Migrate to JEE5 or JEE6?
Even if the final version of the JEE6 specificatione is getting closer, there are
only few pre-release versions of JEE6 appservers available already. And with the
late integration of JSR-299 and JSR-330 there are still some major pending changes.
In a business sense, this puts unneeded risk to your projects. If you have some
more time for migrating (target time mid of 2010) it would be worth waiting. Otherwise it will be best to update to JEE5.

Migrate to JEE5 or keep J2EE?
Basically these are your choices. Keep it or migrate. The main decision driver are
the business requirements. Do you have to update your application server version but
keep all the code and no need for making changes? Go ahead and rely on the JEE5 backward
compatibility. You have bigger changes to do? Possible performance problems? Expensive
refactorings planned? Give JEE5 a chance and migrate. Third option is to mix both strategies.
Only change parts of the implementation that needs to be touched and leave the rest J2EE style.

Effort estimation
The migration effort highly depends on the implementation quality and complexity of your application.
Starting with plain webapplications up to full blown CMP1.x/2.x projects your technical complexity
grows and the migration efforts will do so, too. The worser your code quality and arcitectures are,
the bigger are your migration efforts. Following this, the worst kind of migration project would be
a CMP 1.x enterprise applications with hardly any architectural concepts, bad documentation and
really poor code quality.


Risks and Problems
Most risky is the migration not only from one specification version to another but from one
appserver to another verdor's version. In this case you probably would have to cope with
vendor specific solutions (proprietary classes and/or features, deployment descriptors, specific behaviour).
Another problem could arise from special frameworks (e.g. Weblogic Diagnostics). If you depend heavily on
such features, you should probably try to no change the application server vendor in a first step.

Requirements for migration
Your project should meet some requirements before you think about migration.
You should have:
- ... some testcases at hand. Especially if you are going to migrate the persistence layer!
- ... a testdatasource available.
- ... two test environments (old and new)
- ... code that compiles with JDK 1.5 (check for incompatibilities/deprecations)
- ... thought about moving your development project settings to a JEE5 project.

Friday, August 14, 2009

Enterprise Java - a firmer grasp of the fundamentals

This blog is about Enterprise Java. The word "Enterprise" mainly refers to the fact, that it need some more that just plain
Java to run applications that fulfill enterprise requirements. Beside the fact, that most of them were tried to be adressed
by the Java standard with a nearly equal name (JSR 316) there is still lot to learn about this topic beside the basics.
Here are some hints and best practices for beginners wanting to gain a firmer grasp of the fundamentals.
These tips assume, that you already knwo about OOP and Java in general.

1) Read, read, read, read and understand
The Enterprise Java Specification is incredibly thorough and has truly helpful comments following each included standard.
Before asking questions or trying to figure out an issue on your own, save some time and just head straight to the
documentation. Another good place to look for answers and get a deeper understanding about the collaboration of the
standards is the Duke's Bank Sample application. Also known as the JEE Tutorial. Besid this, it is always a good idea
to have a look at the documentation of the application server of your choice.

- JSR 313 Documentation
- Duke's Bank Tutoral
- Certified Java Application Servers

2) Get used to exceptions and learn to read them
You’ll find bugs in your code that you might not have spotted earlier, as not all bugs keep the application from working.
There are different levels of strictness in the reporting that you can use. Depending on the framework, application server
or JDK you are using, you have to configure error reporting the right way.

- JDK Logging
- Commons Logging
- Log4j

3) Use an enterprise IDE
IDE’s (Integrated Development Environments) are helpful tools for any developer.
While they’re not for everyone, an IDE definitely has its place. IDE’s provide tools like

* syntax highlighting
* code completion
* error and deprocation warnings
* refactoring (reworking)
* appserver integration.

And many other features. There are plenty of great IDEs out there that support Enterprise Java. Have a look and take
your choice:

- Eclipse IDE
- Netbeans
- IntelliJ
- OEPE

4) Try some frameworks
Starting with JEE 5 the specification got much easier to use. Anyway, there are still some concepts that feel to
overengineered. Some frameworks try to fight this and reach the goal of providing enterprise grade applications on
a different track. Beeing a skilled developer, you should have seen some of them. Take your time and experiment with them.

- Springframework
- JBoss Seam

5) Try different O/R Mappers
JEE 5 introduced the Java persistence API (JPA). Beside the reference implementation, that ships with the specification
there are plenty other, very good and stable O/R mappers available out there. Most of them have a moving history and
come with advantages or disadvantages depending on your needs. To use the right O/R mapper, it is worth seeing some.

- Hibernate
- EclipseLink
- OpenJPA

6) Don’t Repeat Yourself (DRY)
DRY stands for Don’t Repeat Yourself, and it’s a valuable programming concept, no matter what the language.
DRY programming, as the name implies, is ensuring that you don’t write redundant code.

7) Think about readable code
If you don’t use indentations and white space in your code, the result looks may look like a painting.
Ensure that your code is readable and easy to search because you’ll most definitely be making changes in the future.
IDEs and advanced text editors can add indentation automatically. Take your time to adjust the default settings to
meet your needs. Have a look at available code-templates and best practices out in the web or other projects.

8) Think in tiers
Maintenability is one of the trickiest parts in JEE development. There are plenty of options for architecting your
software. The first paradigma is about tiers. Separete the client from the logic and the database access. spend some
time reading about tiers and how to decouple them.

9) Be aware of dependencies
Even if your follow tip 7, you still have to think about dependencies. You can have a couple of dependencies not only
inside your code and tiers but also with your libraries and infrastructure components. Make shure, you are using the
right and only the needed dependendencies wherever they may appear. Handle them on different levels (Architecture,
Development, Build and Depolyment)

10) Stick to naming conventions
Naming this isn’t just for your own good. There’s nothing worse than trying to find your way through some other
programmer’s nonsensical naming conventions. Help yourself and others by using names that make sense for your
classes, variables and declarations. It's worth taking a look at the basic Sun naming conventions. There are plenty
of different project or customer sets out there, too. Respect them and don't think of them as unneeded. One aspect
of JEE programming is about teams. Most likely you will not be the only one working on a project. Sticking to naming
conventions makes live much easier for all involved team members.

11) Comment your code
Aside from plain formatting, you’ll also want to use inline comments and JavaDoc to
annotate your code. You’ll thank yourself later when you’re needing to go back and find something in the code,
or if you just can’t remember what a certain function did. It’s also useful for anyone else who needs to look
over your code. Remember, that your most likely will not be the only one writing code in an enterprise grade project.

12) Decide on the right plattform to start learning with
There are some application servers out there for free. Well known are Sun's Glassfish, Apache's Geronimo or even Redhat's
JBoss. Beside this, you could always decide to start over with a free for development edition of one of the major commercial
vendors, like Oracle's Weblogic, IBM's Websphere or SAP's AS Java. No matter, which version you start over.
This will always be your home to come back to. Therefore it could be
worth thinking about your future needs. What plattform is your company using? Which area of interest drives my developments?

13) Never, Ever Trust Users
If your application has places for user input, you should always assume that they’re going to try to input naughty code.
I am not implying that users are bad people. It’s just a good mindset. A great way to keep your application
hacker-free is to always initialize your variables and validate input on any way to safeguard your site from attacks
(e.g. XSS, SQL Injection).


14) Ask for Help
It’s only human nature to want to hide the fact that we don’t know much about a certain topic.
Nobody likes being a rooky! But how are we going to learn without asking? Feel free to use forums, StackOverflow or
event the vendors support base to ask more seasoned JEE developers questions.


Have any ideas and tips of your own? I’m sure you do! Comments welcome!

Thursday, August 13, 2009

DOAG Conference Sessions approved

Got two sessions approved for the DOAG Conference (17.-19.11.09) in Nürnberg.

DOAG Conference 2009

First will be about clustering basics with Oracle Weblogic Server.
Second is about Sun (Oracle) Glassfish Server.

Have a look at the complete conference program as pdf.

Monday, August 10, 2009

Things I have in common with Martin Fowler :)

Read this post by Martin Fowler today. He is talking about his hobby photography. As you may know, this is something I love, too. He even owns the same cam and started with nearly the same set of lenses :)


We geeks like photography because it provides the veneer of an artistic endeavor while allowing us to indulge in lots of technical details and spend money on expensive toys.


After all, it's good to read that even the smartest and hard working people think about their work-live balance and are able to take some realy cool and sharp "shots" :)

You can see some of my work over here at my flickr account.

Wednesday, August 5, 2009

JPA: Optimistic locking and concurrency

The JPA provides a relatively easy way to persist objects, however, there are certain cases that often require a deeper understanding of the consequences that can take place. In two recent posts, Carol McDonald and Felipe Gaucho walk you through two such cases. Carol McDonald first discusses concurrency and locking in the context of the new JPA 2.0 version, while in a second post Felipe Gaucho talks about optimistic locking in the current JPA release and what's in store on this same topic for JPA 2.0


About Carol McDonald
As a Java Technology Evangelist at Sun Microsystems, Carol McDonald has spoken at various conferences including JavaOne, Java University, Sun Tech Days, Sun Network, Sun Code Camps, JDJEdge, and JUGs including Machester, Boston, Maine, Cologne, FAA, Richmond, Memphis, D.C...

About Felipe Gaucho
Felipe Gaucho works as senior software engineer at Netcetera AG in Switzerland. He is a well known Brazilian JUG leader and open-source evangelist.

OEPE Support for Eclipse 3.5

The new Oracle Enterprise Pack for Eclipse 11gR1 (11.1.1.2.0) is out.

What's new in this release: (Details)
* Support for Eclipse 3.4 and 3.5
* Support for generation of JAX-WS webservices from Spring Beans
* JAX-WS Webservice bindings editor provides a graphical UI for defining bindings, async mappings, and hander chains.
* Deployment descriptor editor for weblogic-ejb-jar.xml allows visual editing and validation of EJBs for deployment on WebLogic Server
* JSR 88 deployment plan editor simplifies the creation and management of deployment plans on WebLogic Server
* Enhancements to Oracle DTP plug-ins make working with Oracle – specific database features easy in Eclipse.

More information about OEPE can be found here

Installing Oracle Enterprise Pack for Eclipse using the Eclipse Update Manager:
You use the Eclipse Update Manager for Eclipse 3.5 Galileo as follows:

1. Select Help > Install New Software.
2. Click Add to add a new update site.
3. In the Add Site dialog, enter http://download.oracle.com/otn_software/oepe/galileo, and then click OK.
4. Select Oracle Enterprise Pack for Eclipse, verify that all of the subcomponents are selected, and then click Next.
5. Confirm information presented in the Install Details, and then click Finish.

Java EE 6 will be around November

As announced today on The Aquarium from pelegri the new JEE6 specification will include both JSR 330 and JSR 299. A blog entry from Roberto Chinnici explains the details about:


I'm happy to announce that, thanks to the work of many individuals, we've come to a positive resolution on this issue. Here are the key points:

* JSR-299 will be updated to use the JSR-330 annotations
* The initial draft of JSR-330 has evolved to take into account requirements coming from JSR-299
* Both JSRs will be part of the Java EE 6 Platform


This very late addition of a new JSR changes the release date of the platform to sometime in November:


Overall, we expect these changes to add four-six weeks to the schedule for Java EE 6. That would put the final release some time in November.

Monday, August 3, 2009

myfears - dev preview

I am working on a myfear.com/.de redesign these days. Not only in terms of visual design but in content and feature dimensions, too :)

If you are interested to have a first look, browse to: http://my-fear.appspot.com.
Love to hear about your feedback and ideas!