Monday, March 29, 2010

New Website -seenuonjava.com

I have been thinking about getting a new website for a while. The main reason for that is to show things in action that I talk in my posts. So I looked around for Tomcat and JBoss hosting and after doing some cost comparisons finally I settled on http://www.dailyrazor.com/ for their price. If you are interested check my site seenuonjava.com and check out working application for Java Thread Concurrency to Web Services and Integration post at http://seenuonjava.com/app/ecommerce-1.0.0-SNAPSHOT/

Monday, March 22, 2010

Hibernate org.hibernate.NonUniqueObjectException

You probably got this exception because your are trying to insert or update in a loop with some changes like

for (Record record : recordList) {
record.setName(name[i]);

...
...
session.saveOrUpdate(record);
}

When you have a persisted object and you change a value on it, it becomes dirty and hibernate needs to flush these changes to your persistence layer. So that Hibernate can synchronize the underlying persistent store with persistable state held in memory.
Flush and clean session to fix it, like below.

 for (Record record : recordList) {
record.setName(name[i]);
...
...
session.saveOrUpdate(record);
session.flush();
session.clear();
}
Check out my site seenuonjava.com for more

Wednesday, March 17, 2010

Hibernate Distinct Rows

In Hibernate when we do left outer join, sometimes you may get us duplicate rows, as Hibernate entities that we are joining, are themselves joined with some other entities.

For example:

We are joining Class A and Class B but class A already has a join with Class C which may give us
duplicate rows. In cases like these Hibernate has DISTINCT_ROOT_ENTITY for rescue, like below.

 @Transactional(readOnly = true)
@SuppressWarnings("unchecked")
public List<Group> getGroups (String id) {
logger.info("Id is " + id);
Session session = sessionFactory.getCurrentSession();
List<Group> groups = session.createCriteria(Group.class)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
.add(Restrictions.eq("id", id
.list();
return groups;
}
Check out my site seenuonjava.com for more.

Tuesday, March 16, 2010

Ordered ActiveMQ in Action

I have been thinking about getting ActiveMQ in Action (MEAP)for few days. After reading the first chapter (free to download) I am very impressed. I bought it a couple of days ago and I got to say that it is a great book and highly recommend it.

Best Tomcat Web Hosting

I have been looking around for hosting companies that provide either Tomcat 6 or JBoss hosting. I found a few that provide JBoss hosting but are way too expensive for me.

The idea is to use the new site as my development playground, sand box for my experiments and tutorials etc. So far I have found the following companies that provide Tomcat.

http://www.visionwebhosting.net/
Looks great, especially at $4/month but it seems like their regular plan supports
Tomcat 5.5.27, where as I am looking for Tomcat 6.
http://www.webhostingjava.net/
These guys support
Tomcat 5.5.27 too and little expensive for me at $20 /month.
http://www.dailyrazor.com/
So far the best I found at $6.95/month.

I am leaning towards http://www.dailyrazor.com/ as price is very reasonable and the best thing is they provide developer hosting. Let me know if you know any other hosting companies that provide Tomcat or JBoss hosting.

Monday, March 15, 2010

Java Thread Concurrency to Web Services and Integration

This is the first post in a series of discussions that talk about real world requirements and possible technology solutions in Java. This discussion talks about java thread concurrency and leads to the next article, whose primary focus will be SOA. The main purpose of the series is to discuss the best architectural solutions and alternatives to common requirements.

One of the common requirements these days is getting data from partners, for example getting stock prices, trading prices, checking if an item is available, supply chain information etc. One of my clients is a huge ecommerce company that sells electronics and other consumer goods online. Besides selling items from its own stock it has partnered with other companies for specific items. The sample application presented here is modeled after real world application and shows basic implementation using java queue and executor with spring MVC.

Besides concurrency, our sample application implements producer-consumer problem with BlockingQueue and ExecutorService(A.K.A. threadpoolexecutor (from google adwords suggest)).

Use Case:
When a customer searches for an item, the application searches for matches in its inventory system and partners’ inventory systems. For example, if a customer wants to search cameras he types “camera” in the website’s search box and submits. Upon submit, our application searches for available cameras, in the inventory system combines the results with results it received from external partners for display.


Sequence Diagram:
The following abstract sequence diagram shows order of processes that take place.

When a search request for an item comes to SearchController (Spring MVC controller), it invokes RequestProcessor.

 List searchResult = RequestProcessor.processRequest("camera");





RequestProcessor is the main class of the application and it is composed of a thread pool and a queue. Once invoked from the controller as above, it performs the following processes.

1. Get necessary information about partners like names, urls, usernames, passwords etc, search string and submits to ExecutorService, so that it can search all the partners concurrently.

 public List<String> processRequest(String searchString) {


for (int i = 0; i < partners.size(); i++) {
submitToThreadPool(searchRequest);

}
}//end processRequest
private static void submitToThreadPool(SearchRequest request) {
// uses Executors factory methods.
threadPool.execute(new ResultProcessor(request));
}// submitToThreadPool
2. While external partners are being searched for the item, it searches internal inventory system.

3. After results are received from internal inventory system, get results from partners from queue that are put in by ResultProcessor.
 String result = resultsQueue.poll(5, TimeUnit.MILLISECONDS);


4. Combine results from internal inventory system with results from external partners for display.

ResultProcessor implements Runnable and gets the search results from the partners. Once the results are received from partners, it puts them on the Queue for RequestProcessor (refer to step 3 above).

 private void getSearchResultsFromPartners(SearchRequest request) {


//gets results from partners and puts them on the queue
Resultsqueue.offer(partner.getMatchedItems(request .getSearchString()));
}//end getSearchResultsFromPartners


ResultProcessor implements Runnable and runs in a separate thread for each external partner concurrently.

Besides ArrayBlockingQueue, java.util.concurrent package contains bounded and unbounded queues like ConcurrentLinkedQueue, DelayQueue, LinkedBlockingQueue, PriorityBlockingQueue and SynchronousQueue.

BlockingQueue are best suited for producer-consumer queues, as they supports operations that wait for space, so producer threads can place data and wait for queue to be not empty, so consumer threads can get the data. This decoupling of producer and consumer allows for variable rates of data production and consumptions. Take a look at java.util.concurrent package for more information.

Executor is the primary abstraction of task execution in java. Executor provides a way of decoupling task submission from how each task will be run, including details of thread use, scheduling, etc. Combined together Blocking queue and Executor is the perfect recipe to implement producer-consumer pattern like we did.

In our next post we will expand our example to include different ways of connecting to external partners including web services using Apache CXF.

Download code from here. If you like to deploy the application and see it in action, copy ecommerce-concurrent.war file from target directory to your server. If you wish to build it yourself go to ecommerce-concurrent directory from command line and run “mvn package” to build war file.

Thursday, March 11, 2010

Spring and DWR Integration Setp by Step

It’s been a couple of years since I used DWR last time. After spending sometime on configuration I got it working on my current project with the following configuration. Add the following xml file to your project along with other spring context files you have. You can download xml file from my site seenuonjava.com


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.directwebremoting.org/schema/spring-dwr http://www.directwebremoting.org/schema/spring-dwr-2.0.xsd">

<dwr:controller id="dwrController" debug="true" />

<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="alwaysUseFullPath" value="true" />
<property name="order" value="3" />
<property name="mappings">
<props>
<prop key="/dwr/**/*">dwrController</prop>
</props>
</property>
</bean>

<!-- Java Class that DWR calls -->
<bean id="dwrContractNumCheck" class="com.seenu.test.dwr.ContractsNumCheckDwr">
<!--DWR generated JavaScript name for above java class-->
<dwr:remote javascript="dwrContractNumCheck">
<!--Method for DWR to be included in the above JavaScript-->
<dwr:include method="checkNumOfContracts" />
</dwr:remote>
</bean>

<!--
Call to the above method returns Contract object,
so define a converter for it
-->

<dwr:configuration>
<dwr:convert type="bean" class="com.seenu.test.entity.Contract" />
</dwr:configuration>

</beans>


In my next post I will talk about end to end example.