Pages

Tuesday, July 5, 2011

Learning Ubuntu - On 11.04 version

To connect from Ubuntu to any other machine:

Applications -> Accessories -> Terminals

ubuntu@ubuntu: ssh username@host_name

Enter password: password

username@host_name:







Wednesday, December 1, 2010

Spring - TIBCO - JMS Integration - Asynchronous Approach

In Synchronous approach we used <jms:outboundGateway> in Asynchornous approach we will use <jms:outbound-channel-adapter> and <jms:message-driven-channel-adapter>:

Here is your messaging xml configuration should look like:

    <channel id="outboundMessageChannel">    </channel>
    <channel id="inboundMessageChannel">    </channel>
    <channel id="preMarshalledMessageChannel"/>
    <channel id="unMarshalledMessageChannel"/>


    <jms:outbound-channel-adapter id="jmsMessageOut"
                                  channel="outboundMessageChannel"
                                  jms-template="jmsTemplate"/>


    <si-xml:marshalling-transformer id="marshallerWithPoller"
                                    input-channel="preMarshalledMessageChannel"
                                    output-channel="outboundMessageChannel"
                                    marshaller="jaxbMarshaller"
                                    result-transformer="resultToStringTransformer"/>


    <si-xml:unmarshalling-transformer id="defaultUnmarshaller"
                                      input-channel="inboundMessageChannel"
                                      output-channel="unMarshalledMessageChannel"
                                      unmarshaller="jaxbMarshaller"/>


    <jms:message-driven-channel-adapter id="jmsMessageIn"
                                        channel="inboundMessageChannel"
                                        destination="messageToStoreReplyQueue"
                                        connection-factory="connectionFactory"
            />


    <service-activator id="testMessageEndPoint" input-channel="unMarshalledMessageChannel"
                       method="handleMessageResponse" auto-startup="true">

    <beans:bean class="com.test.ResponseService"/>
    </service-activator>


To listen your responses you should create the service-activator class which is "ResponseService" and when ever there is a message in "unMarshalledMessageChannel" your service activators method "handleMessageResponse" will be invoked with appropriate unmarshalled message.

For total configuration refer to my other post - http://myjavatechnologies.blogspot.com/2010/11/spring-integration.html

Happy Integration!

Monday, November 29, 2010

Linux Commands Reference

How to view simple text files in Linux ?

Command: Cat file_name (This is a nice way to view short files that fit on your screen.)

Command: less file_name (If the files are so long that they don't fit on your screen, less automatically paginates the file, you can use Page Up and Page Down keys to moves through the file and type "q" to quit the file.

How to clear the screen in Linux ?

Command: clear

Wednesday, November 17, 2010

Spring - TIBCO - JMS Integration - Synchronous Approach

Here I am going to provide how to use Spring Integration with JMS and TIBCO synchrnously.

For simplicity I divided into 2 different XML files called as :

- tibcoContext.xml and
- messagingContext.xml,

These both files should be imported in your spring applicationContext.xml (or) what ever name given in your project.

The namespaces for tibcoContext.xml goes here:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:integration="http://www.springframework.org/schema/integration"
       xmlns:jms="http://www.springframework.org/schema/integration/jms"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:stream="http://www.springframework.org/schema/integration/stream"
       xmlns:si-xml="http://www.springframework.org/schema/integration/xml"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/integration
                           http://www.springframework.org/schema/integration/spring-integration-1.0.xsd
                  http://www.springframework.org/schema/integration/jms
                  http://www.springframework.org/schema/integration/jms/spring-integration-jms-1.0.xsd
                  http://www.springframework.org/schema/context
                  http://www.springframework.org/schema/context/spring-context.xsd
                  http://www.springframework.org/schema/integration/stream
                  http://www.springframework.org/schema/integration/stream/spring-integration-stream-1.0.xsd
                  http://www.springframework.org/schema/integration/xml
                  http://www.springframework.org/schema/integration/xml/spring-integration-xml-1.0.xsd">

The namespaces for messagingContext.xml goes here:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:beans="http://www.springframework.org/schema/beans"
             xmlns:jms="http://www.springframework.org/schema/integration/jms"
             xmlns:stream="http://www.springframework.org/schema/integration/stream"
             xmlns:si-xml="http://www.springframework.org/schema/integration/xml"
             xmlns:context="http://www.springframework.org/schema/context"
             xmlns:tx="http://www.springframework.org/schema/tx"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/integration
                           http://www.springframework.org/schema/integration/spring-integration-1.0.xsd
                           http://www.springframework.org/schema/integration/jms
                           http://www.springframework.org/schema/integration/jms/spring-integration-jms-1.0.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/integration/stream
                           http://www.springframework.org/schema/integration/stream/spring-integration-stream-1.0.xsd
                                 http://www.springframework.org/schema/integration/xml
                                 http://www.springframework.org/schema/integration/xml/spring-integration-xml-1.0.xsd ">

Coming to configuration in tibcoContext.xml file:

Step 1: You need the below connection factory in order to connect to your EMS server:

<bean id="tibConnectionFactory" class="com.tibco.tibjms.TibjmsQueueConnectionFactory">
        <property name="serverUrl" value="tcp://localhost:7222"/>
        <property name="userName" value=""/>
        <property name="userPassword" value=""/>
</bean>


<bean id="connectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory">
        <property name="targetConnectionFactory" ref="tibConnectionFactory"/>
        <property name="sessionCacheSize" value="10"/>
        <property name="cacheProducers" value="true"/>
        <property name="cacheConsumers" value="true"/>
 </bean>


Step 2: Configure the Queue where you need to send the messages:

<bean id="senderQueue" class="com.tibco.tibjms.TibjmsQueue">
        <constructor-arg value="jms/tibcoSenderQueue"/>
</bean>


Step 3: Configure the Jaxb Marshaller to Marshal and unmarshall the messages you would like to send and receive:

<bean id="jaxbMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
        <property name="classesToBeBound">
            <list>
                <value>com.test.Test1</value>
                <value>com.test.Test2</value>
            </list>
        </property>
</bean>


Step 4: Configure the transformer to convert your payload result to String:

<bean id="resultToStringTransformer"
          class="org.springframework.integration.xml.transformer.ResultToStringTransformer"/>


Step 5: The last and final step in your tibcoContext.xml is to configure the Gateway to send and recieve the Messages:

    <integration:gateway id="dynamicQueryMessageGateway"
                         default-request-channel="senderChannel"
                         service-interface="com.test.ISenderGateway"/>

     <integration:gateway id="dynamicQueryReplyGateway"
                         default-reply-channel="marshaledRecieverChannel"
                         service-interface="com.test.IRecieverGateway"/>


Now We need to create the above gateway interfaces in our code which looks like below:

@Service("senderGatewayService")
public interface ISenderGateway {

    @Gateway(requestChannel = "senderChannel")
    public void sendMessage(@Header("requestType") String requestType, TestOb ob);
}


@Service("receiverGatewayService")
public interface IRecieverGateway {

    @Gateway(replyChannel = "marshaledRecieverChannel", replyTimeout = 5000)
    public ResultOb recieveMessage();

}

Now here the configuration of messagingContext.xml file:

Step 1: Create Approprate required channels:

<channel id="senderChannel"/>
<channel id="marshaledSenderChannel"/>

<channel id="recieverChannel"/>
<channel id="marshaledRecieverChannel">
        <queue/>
</channel>


Step 2: Create Marshaler on SenderChannel:

<si-xml:marshalling-transformer id="defaultMarshaller"
                                    marshaller="jaxbMarshaller"
                                    input-channel="senderChannel"
                                    output-channel="marshaledSenderChannel"
                                    result-transformer="resultToStringTransformer"/>


Step 3: Create JMS outbound gateway on marshaledSenderChannel which holds the results after marshaling:

 <jms:outbound-gateway id="outBoundGateway"
                          request-channel="marshaledSenderChannel"
                          request-destination="senderQueue"
                          connection-factory="connectionFactory"
                          reply-channel="recieverChannel"/>


Step 4: Create unmarshaler on the receiverChannel:

<si-xml:unmarshalling-transformer id="defaultUnmarshaller"
                                      input-channel="recieverChannel"
                                      output-channel="marshaledRecieverChannel"
                                      unmarshaller="jaxbMarshaller"/>


Here we finished all the required configuration for sending and recieving jms messages using spring integration in Synchronous way.

Client code to test the above:

@Autowired
    private ISenderGateway senderGateway;


@Autowired
    private IReceiverGateway receiverGateway;


public void testSynchronousMessaging() {
        try {
                      
            senderGateway.sendMessage("requestType", testOb);

            System.out.println(receiverGateway.recieveMessage());
        } catch(Exception e) {
            e.printStackTrace();
        }

}

Any comments, improvments or suggetions are welcome.

Spring - Annotation Based Spring MVC

Assuming that the student knows basic web application structure and all the configuration files required for Basic web application.
Assuming that the student knows Servlets.

To create Annotation based Spring MVC web application please follow the below steps:

Step 1 : Update your web.xml file with following configuration:

    <servlet>
        <servlet-name>spring-mvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring-mvc</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>

DispatcherServlet - Spring's Web MVC framework is designed around a DispatcherServlet that dispatches requests to handlers, with configurable handler mappings, view resolution, locale and theme resolution as well as support for upload files.
A central servlet that dispatches requests to controllers and offers other functionality facilitating the development of web applications.
Is an expression of the “Front Controller” design pattern.

It is completely integrated with the Spring IoC container and as such allows you to use every other feature that Spring has.


The framework will, on initialization of a DispatcherServlet, look for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and create the beans defined there.

Step 2 : Create spring-mvc-servlet.xml under WEB-INF directory. (Observe that the file name should start with servlet-name of the DispatcherServlet-servlet.xml.)

Step 3 : The Basic spring-mvc-servlet.xml looks like below:

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

</beans>

Step 4 : spring-mvc-servlet.xml file will contain all of your Spring Web MVC-specific components (beans). The exact location of this configuration file can be changed via a DispatcherServlet initialization parameter. You can specify that in web.xml like below:

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:/spring/spring-context.xml</param-value>
    </context-param>

Step 5 : Just as with any other view technology you're integrating with Spring, for JSPs you'll need a view resolver that will resolve your views. The most commonly used view resolvers when developing with JSPs are the InternalResourceViewResolver and the ResourceBundleViewResolver.

Add the below configuration in your spring-mvc-servlet.xml file: (I am using InternalResourceViewResolver here in this example)

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

Step 6 :  Here as we are going to use annotations instead of configuring our Controllers in xml files, we also need to add the following configuration in spring-mvc-servlet.xml file, so that container scans all the controller components at the initialization of DispatcherServlet and they will be available.

    <context:component-scan base-package="com.sritech.samples">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

Step 7 : Your web application lib directory also need the following spring jars:

spring.jar
spring-webmvc.jar
commons-logging.jar


These jars will be deployed to the server and they are also used during the build process.

The above configuration allows your DispatcherServlet to scan for all the controllers in the specified package (Ex: com.sritech.samples).

All above 6 Steps are one time configuration you have to do to create your annotation based Spring MVC application.

Example 1:- Create Welcome Page using SimpleWelcomeController and Simple JSP.

Step 1 : Create the controller class:

package com.sritech.samples.mvc.example1;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class SimpleWelcomeController {

    @RequestMapping("/example1/welcome.htm")
    public void elementaryGreeter() {
    }
}

The @Controller annotation indicates that a particular class serves the role of a controller. There is no need to extend any controller base class or reference the Servlet API. You are of course still able to reference Servlet-specific features if you need to. The basic purpose of the @Controller annotation is to act as a stereotype for the annotated class, indicating its role. The dispatcher will scan such annotated classes for mapped methods, detecting @RequestMapping annotations.

The @RequestMapping annotation is used to map URLs like '/example1/welcome.htm' onto an entire class or a particular handler method.

Step 2 : Create the JSP.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Welcome to Spring MVC</title>
</head>

<body>
        Hello everyone! Welcome to Spring MVC: Example 1
</body>
</html>

Step 3 : Now create the war file and deploy into your Tomcat Server. (Any Web Server or application Server).

Step 4 : After the application is deployed go the below link:

http://server-name:portNumber/spring-mvc-samples/example1/welcome.htm

Step 5 : You will be seeing the following output on your screen:

Welcome to Spring MVCHello everyone! Welcome to Spring MVC: Example 1


Surprised!

Continue...

Spring Dependency Injection

Without the concept of dependency injection, a consumer who needs a particular service in order to accomplish a certain task would be responsible for handling the life-cycle (instantiating, opening and closing streams, disposing, etc.) of that service. Using the concept of dependency injection, however, the life-cycle of a service is handled by a dependency provider (typically a container) rather than the consumer. The consumer would thus only need a reference to an implementation of the service that it needed in order to accomplish the necessary task.

A kind of Inversion of Control (IoC)

● “Hollywood Principle” – Don't call me, I'll call you

● “Container” resolves (injects) dependencies of components by setting implementation object (push)

● As opposed to component instantiating or Service Locator pattern where component locates implementation (pull)

● Martin Fowler calls Dependency Injection

EJB Vs Spring

EJB are Java EE platform components where we can get the benefits of life cycle management, bean management, transaction management and security Services. EJB's are called heavy weight components due to their complexity.

Many lightweight components are designed to overcome the shortcomings of EJB. They lightweight in that they can support simple Java objects as components. A challenge of lightweight containers is how to decouple dependencies between components. IOC has proved to be an effective solution to this problem. Where IOC is a general design principle DI is a concrete design pattern the embodies this principle.

Example 1

Problem: Design an application for generating different types of reports (text, pdf and html reports) for different time periods (daily, monthly and quarterly).


Solution:


public interface ReportGenerator {
    public void generateReport(String reportContent);
}

public class TextReportGenerator implements ReportGenerator{
    public void generateReport(String reportContent) {
        System.out.println("Text Report:" + reportContent);
    }
}

public class HtmlReportGenerator implements ReportGenerator{
    public void generateReport(String reportContent) {
        System.out.println("HTML Report:" + reportContent);
    }
}

public class PdfReportGenerator implements ReportGenerator{
    public void generateReport(String reportContent) {
        System.out.println("PDF Report:" + reportContent);
    }
}

public class ReportService {
    private ReportGenerator reportGenerator = new TextReportGenerator(); // Service is directly contacting concrete class of ReportGenerator here.

    public void dailyReport() {
        reportGenerator.generateReport("Daily Report Content");
    }

    public void monthlyReport() {
        reportGenerator.generateReport("Monthly Report Content");
    }

    public void quarterlyReport() {
        reportGenerator.generateReport("Quarterly Report Content");
    }
}


ReportService is creating the instance of ReportGenerator internally, so it has to be aware of which concrete class of ReportGenerator to use. This will cause a direct dependency fromReportService to either of the ReportGenerator implementations.

To avoid dependency between these I am going to introduce container:

import java.util.HashMap;
import java.util.Map;

public class Container {
    public static Container instance;
    private Map<String, Object> components;

    public Container() {
        components = new HashMap<String, Object>();

        instance = this;

        ReportGenerator reportGenerator = new TextReportGenerator();
        components.put("reportGenerator", reportGenerator);

        ReportService reportService = new ReportService();
        components.put("reportService", reportService);
    }

    public Object getComponent(String id) {
        return components.get(id);
    }
}

Now I am going to change the ReportService class to:

public class ReportService {
    private ReportGenerator reportGenerator = (ReportGenerator)Container.instance.getComponent("reportGenerator");
    ...
}

This modification means that ReportService doesn’t have to worry about which ReportGenerator implementation to use, so you don’t have tomodify ReportService any more when you want to switch report generator implementation.

Now we will test our code by writing main class:

public class TestReport {
    public static void main(String[] args) {
        Container container = new Container();
        ReportService reportService =
                (ReportService) container.getComponent("reportService");
        reportService.dailyReport();
    }
}

Result is: Text Report:Daily Report Content

conclusion: employing a container can help reduce coupling between different components within a system, and hence increase the independence and re usability of each component. In this way, you are actually separating configuration (e.g., which type of report generator to use) from programming logic (e.g., how to generate a report in PDF format) in order to promote overall system re usability.

Using a Service Locator to Reduce Lookup Complexity:

To reduce the lookup complexity of your components, you can apply one of Sun’s core Java EE design patterns, Service Locator. The idea behind this pattern is as simple as using a service locator to encapsulate the complex lookup logic, while exposing simplemethods for lookup. Then, any component can delegate lookup requests to this service locator.

Now we will create simple ServiceLocator class and move the lookup logic of ReportService into this class.

public class ServiceLocator {
    private static Container container = Container.instance;

    public static ReportGenerator getReportGenerator() {
        return (ReportGenerator) container.getComponent("reportGenerator");
    }
}

Now change the ReportService class to:

public class ReportService {
    private ReportGenerator reportGenerator = ServiceLocator.getReportGenerator();
    ...
}

Applying Inversion of Control and Dependency Injection (Now we will finally apply the DI pattern to remove the dependency between ReportService and ServiceLocator.

The idea of this principle is to invert the direction of resource retrieval. In a traditional lookup, components seek resources by making requests to a container, and the container duly returns the resources in question.With IoC, the container itself actively delivers resources to its managed components. A component has only to choose a way of accepting the resources.

Now we will change our ReportService class like below:

public class ReportService {
    private ReportGenerator reportGenerator; //No need to lookup, container is responsible to supply this.

    public void setReportGenerator(ReportGenerator reportGenerator) {
        this.reportGenerator = reportGenerator;
    }
   
    ...

}

Now our Container class looks like below:

import java.util.HashMap;
import java.util.Map;

public class Container {

    private Map<String, Object> components;

    public Container() {
        components = new HashMap<String, Object>();

        ReportGenerator reportGenerator = new TextReportGenerator();
        components.put("reportGenerator", reportGenerator);

        ReportService reportService = new ReportService();
        reportService.setReportGenerator(reportGenerator);
        components.put("reportService", reportService);
    }

    public Object getComponent(String id) {
        return components.get(id);
    }
}


-> Now we can completely remove the ServiceLocator here because we are no more using that.
-> Service classes are completely independent of dependencies, container is responsible for supplying the dependencies.
-> Spring Container uses same technique to provide dependencies.



Different Types of Dependency Injection

Injecting a dependency via a setter method is not the only way of implementing DI. You will need different types of DI in different scenarios.

There are three main types of DI:

• Interface injection (Type 1 IoC)
• Setter injection (Type 2 IoC)
• Constructor injection (Type 3 IoC)

Setter and Constructor Injections are most widely used once. Interface injection is seldom used.


Hope it is helpful and Happy Learning!

Why Spring?

  1. Wiring of components through Dependency Injection – Promotes de-coupling among the parts that make the application.
  2. Design to interfaces – Insulates a user of a functionality from implementation details.
  3. Test-Driven Development (TDD) – POJO classes can be tested without being tied up with the framework.
  4. Declarative programming through AOP – Easily configured aspects, esp. transaction support.
  5. Simplify use of popular technologies
    – Abstractions insulate application from specifics, eliminate redundant code
    – Handle common error conditions
    – Underlying technology specifics still accessible
  6. Conversion of checked exceptions to unchecked.
  7. Not an all-or-nothing solution – Extremely modular and flexible.
  8. Well designed
    – Easy to extend
    – Many reusable classes
  9. Integration with other technologies
    – EJB for J2EE
    – Hibernate, iBates, JDBC (for data access)
    – Velocity (for presentation)
    – Struts and WebWork (For web).