Spring

Implementing SOA using Opensource Apache Camel JMS Component on WebLogic 12c

Hi,

In one of our previous example we have talked about how we can use “Apache Camel based EJB Client accessing the EJBs deployed on WebLogic 12c”, Now we will see how we can develop a simple Web Application using Apache Camel Servlet which will accept inputs form the user and then will process those inputs (like adding the input numbers) and then the generated HTMPL output will be send to the WebLogic JMS Queue.

As part of this example we are going to use the “org.apache.camel.component.jms.JmsComponent” and Apache Camel “servlet:” endpoint. The Camel JMS component is a general purpose JMS integration point that can be used to integrate Apache Camel with any JMS client library. Using the Camel JMS component, it is possible to define JMS consumer endpoints (at the start of a Camel route) and JMS producer endpoints (at the end of a Camel route). Similarly The servlet: component provides HTTP based endpoints for consuming HTTP requests that arrive at a HTTP endpoint that is bound to a published Servlet.

For more information on Camel JMS Endpoint can be found at : http://camel.apache.org/jms.html . This component allows messages to be sent to (or consumed from) a JMS Queue or Topic. It uses Spring’s JMS support for declarative transactions, including Spring’s JmsTemplate for sending and a MessageListenerContainer for consuming.

Apache Camel’s API and out-of-the-box components implement many common enterprise integration patterns (EIPs), making it relatively simple and easy to do integration tasks such as connecting web services, performing XSL transformations, logging audits, and more. Camel supports most of the Enterprise Integration Patterns. See: http://camel.apache.org/enterprise-integration-patterns.html

What this demo is about ?

As part of this demo we will see how to use Apache Camel based WAR on latest WebLogic 12.2.1 (12c). While running this demo we will learn about the following things:

1. How to develop a Apache Camel based Camel Servlet to accept http request param inputs and to process them.

2. How to use the Apache Camel JMS Component to send the JMS Message (processed data) to the WebLogic Queue.

3. How to deploy the Camel based WebApplication on WebLogic using WebLogic 12.2.1 using maven plugin “weblogic-maven-plugin”. If you get any kind of error while using this plugin then refer to the article How to use WebLogic 12c provided Maven Synchronization Plug-In ?

4. Configuring JMS Connection Factory and the JMS Queues using WLST.

5. We are going to use Apache Camel 2.16.0, Spring 4.1.6.RELEASE and WebLogic 12.2.1 release for this demo.

Configuring JMS Queue and ConnectionFactory

Step-1). First create a directory some where in our filesystem where we will be keeping our projects. We will create a directory as “CamelServlet_With_JMSEndpoint_Demo”

 $ mkdir -p Camel-on-WebLogic12c/CamelServlet_With_JMSEndpoint_Demo

 $ mkdir -p Camel-on-WebLogic12c/CamelServlet_With_JMSEndpoint_Demo/src/main/java/beans

 $ mkdir -p Camel-on-WebLogic12c/CamelServlet_With_JMSEndpoint_Demo/src/main/resources

 $ mkdir -p Camel-on-WebLogic12c/CamelServlet_With_JMSEndpoint_Demo/src/main/webapp/WEB-INF

Step-2). Lets write the “Camel-on-WebLogic12c/domains.properties” file where we will define all the properties which will be used by the WLST script to configure the JMS Queue and ConnectionFactory.

############ WebLogic 12c JMS Queue and Connection Factory related Configuration #########

# 1 - Connecting details
server.url = t3://localhost:7001
username = weblogic
password = weblogic1
 
# 2 - JMSServer details
jms.server.name = My_JMSServer
store.name = MyJDBCStore
tragated.jms.server.name = AdminServer
 
# 3 - SystemModule Details
system.module.name = My_SystemModule
tragated.system.module.name = AdminServer
 
# 4 - ConnectionFactory Details
connection.factory.name = My_ConnectionFactory
connection.factory.jndi.name = My_CF
 
# 5 - Unit Of Order Details
unit.of.order.value = 1
 
# 6 - SubDeployment & Queue Details
queue.sub.deployment.name = Sub_My_Queue
queue.name = My_Queue
queue.jndi.name = My_Q

Step-3). Now we will write a simple WLST Script which will use the above properties file and configure the JMS resources on WebLogic. Create a file as “Camel-on-WebLogic12c/configureJMS.py”

#############################################################################
#
# @author Copyright (c) 2010 - 2011 by Middleware Magic, All Rights Reserved.
#
#############################################################################
 
from java.io import FileInputStream
import java.lang
import os
import string
 
propInputStream = FileInputStream("domain.properties")
configProps = Properties()
configProps.load(propInputStream)
 
# 1 - Connecting details
serverUrl = configProps.get("server.url")
Username = configProps.get("username")
Password = configProps.get("password")
 
# 2 - JMSServer details
jmsServerName = configProps.get("jms.server.name")
storeName = configProps.get("store.name")
tragatedJMSServerName = configProps.get("tragated.jms.server.name")
 
# 3 - SystemModule Details
systemModuleName = configProps.get("system.module.name")
tragatedSystemModuleName = configProps.get("tragated.system.module.name")
 
# 4 - ConnectionFactory Details
connectionFactoryName = configProps.get("connection.factory.name")
ConnectionFactoryJNDIName = configProps.get("connection.factory.jndi.name")
 
# 5 - Unit Of Order Details
unitOfOrderValue = configProps.get("unit.of.order.value")
 
# 6 - SubDeployment & Queue Details
queueSubDeploymentName = configProps.get("queue.sub.deployment.name")
queueName = configProps.get("queue.name")
queueJNDIName = configProps.get("queue.jndi.name")
 
#7 - Weblogic Bridge Details:
weblogicDestinationBridge = configProps.get("weblogic.destination.bridge")
weblogicAdapterJNDINoTX = configProps.get("weblogic.adapter.jndi.name")

#8 - Widlfly bridge details:
wildflyDestinationBridge = configProps.get("wildfly.destination.bridge")
wildflyServerUrl = configProps.get("wildfly.server.url")
wildflyJMSUsername = configProps.get("wildfly.jms.username")
wildflyJMSUserPassword = configProps.get("wildfly.jms.password")
wildflyInitialContextFactory = configProps.get("wildfly.initial.context.factory")
wildflyJMSConnectionFactory = configProps.get("wildfly.remote.connection.factory.jndi.name")
wildflyJMSQueueJndi = configProps.get("wildfly.jms.destination.jndi.name")




redirect('wlst.log','false')
 
# 1 - Connecting to the Destination 
connect(Username,Password,serverUrl)
 
edit()
 
# 2 - JMSServer details
print "================== JMSSever ==================="
startEdit()
cmo.createJMSServer(jmsServerName)
print "Created a JMSServer !!"
cd('/Deployments/'+jmsServerName)
cmo.setPersistentStore(getMBean('/FileStores/'+storeName))
print "PersistentStore has been set for the JMSServer !!"
set('Targets',jarray.array([ObjectName('com.bea:Name='+tragatedJMSServerName+',Type=Server')], ObjectName))
print "Targeted the JMSServer !!"
activate()
print ""
 
# 3 - SystemModule Details
print "================== SystemModule ==================="
startEdit()
cd('/')
cmo.createJMSSystemResource(systemModuleName)
print "Created a SystemModule !!"
cd('/SystemResources/'+systemModuleName)
set('Targets',jarray.array([ObjectName('com.bea:Name='+tragatedSystemModuleName+',Type=Server')], ObjectName))
print "Targeted the SystemModule !!"
activate()
print ""
 
# 4 - ConnectionFactory Details
print "================== ConnectionFactory ==================="
startEdit()
cd('/JMSSystemResources/'+systemModuleName+'/JMSResource/'+systemModuleName)
cmo.createConnectionFactory(connectionFactoryName)
cd('/JMSSystemResources/'+systemModuleName+'/JMSResource/'+systemModuleName+'/ConnectionFactories/'+connectionFactoryName)
cmo.setJNDIName(ConnectionFactoryJNDIName)
print "Created a ConnectionFactory !!"
cd('/JMSSystemResources/'+systemModuleName+'/JMSResource/'+systemModuleName+'/ConnectionFactories/'+connectionFactoryName+'/SecurityParams/'+connectionFactoryName)
cmo.setAttachJMSXUserId(false)
cd('/JMSSystemResources/'+systemModuleName+'/JMSResource/'+systemModuleName+'/ConnectionFactories/'+connectionFactoryName)
cmo.setDefaultTargetingEnabled(true)
print "Targeted the ConnectionFactory !!"
activate()
print ""
 
# 5 - SubDeployment & Queue Details
print "================== SubDeployment & Queue ==================="
startEdit()
cd('/SystemResources/'+systemModuleName)
cmo.createSubDeployment(queueSubDeploymentName)
print "Created a SubDeployment for Queue !!"
cd('/JMSSystemResources/'+systemModuleName+'/JMSResource/'+systemModuleName)
cmo.createQueue(queueName)
print "Created a Queue !!"
cd('/JMSSystemResources/'+systemModuleName+'/JMSResource/'+systemModuleName+'/Queues/'+queueName)
cmo.setJNDIName(queueJNDIName)
cmo.setSubDeploymentName(queueSubDeploymentName)
cd('/SystemResources/'+systemModuleName+'/SubDeployments/'+queueSubDeploymentName)
set('Targets',jarray.array([ObjectName('com.bea:Name='+jmsServerName+',Type=JMSServer')], ObjectName))
print "Targeted the Queue to the created subdeployment !!"
activate()
print ""

cmd = "rm -f wlst.log"
os.system(cmd)

Step-4). Now we will start the WebLogic 12.2.1 instance and then we will open a terminal to run the above mentioned WLST script. We will run the “setWLSEnv.sh” script in the terminal first so that it will set the CLASSPATH properly with the required JARs.

$ cd /Users/jsensharma/NotBackedUp/Installed/wls1221/wlserver/server/bin

$ . ./setWLSEnv.sh 

CLASSPATH=/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/lib/tools.jar:/Users/jsensharma/NotBackedUp/Installed/wls1221/wlserver/modules/features/wlst.wls.classpath.jar:
PATH=/Users/jsensharma/NotBackedUp/Installed/wls1221/wlserver/server/bin:/Users/jsensharma/NotBackedUp/Installed/wls1221/wlserver/../oracle_common/modules/org.apache.ant_1.9.2/bin:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/bin:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/jsensharma/NotBackedUp/Installed/wls1221/wlserver/../oracle_common/modules/org.apache.maven_3.2.5/bin
Your environment has been set.

Step-5). Running the WLST script in the same terminal.

######  Running the WLST commands as following: #######

$ cd /PATH/TO/Camel-on-WebLogic12c

$ java weblogic.WLST configureJMS.py 

Initializing WebLogic Scripting Tool (WLST) ...
Welcome to WebLogic Server Administration Scripting Shell
Type help() for help on available commands

================== JMSSever ===================
Created a JMSServer !!
PersistentStore has been set for the JMSServer !!
Targeted the JMSServer !!

================== SystemModule ===================
Created a SystemModule !!
Targeted the SystemModule !!

================== ConnectionFactory ===================
Created a ConnectionFactory !!
Targeted the ConnectionFactory !!

================== SubDeployment & Queue ===================
Created a SubDeployment for Queue !!
Created a Queue !!
Targeted the Queue to the created subdeployment !!

Developing the Camel Based WebApp

Step-6). First of all we will write a Simple Bean which will include out business logic of adding two numbers and produce an HTML output containing the sum. For this we will write “MathBean.java” inside the “CamelServlet_With_JMSEndpoint_Demo/src/main/java/beans” as following:

package beans;

public class MathBean {
     private String firstNo="1000";
     private String secondNo="2000";

	public String getFirstNo() {
		return firstNo;
	}

	public void setFirstNo(String firstNo) {
		this.firstNo = firstNo;
	}

	public String getSecondNo() {
		return secondNo;
	}

	public void setSecondNo(String secondNo) {
		this.secondNo = secondNo;
	}
 
    public String addTwoNumbers(String firstNo, String secondNo) {
        System.out.println("[MathBean] addTwoNumbers("+firstNo+","+secondNo+") invoked.");
        int sum = Integer.parseInt(firstNo) + Integer.parseInt(secondNo);
        String result=    "<HTML>" +
                          "   <HEAD><TITLE> Add Numbers Camel Servlet test </TITLE></HEAD>" +
                          "   <BODY>" +
                          "       [MathBean] Sum of " +firstNo+" And "+secondNo+ " is = " + sum + 
                          "   </BODY>" +
                          "</HTML>";
            return result;
        }
}

Step-7). Now we will write a simple “web.xml” file as following which will define the CamelServlet and also declare the Spring “ContextLoaderListener” listener. In the same file we will define the Camel configuration file via “contextConfigLocation” context param. Place the “web.xml” file inside the “CamelServlet_With_JMSEndpoint_Demo/src/main/webapp/WEB-INF/”

<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

  <display-name>Camel Servlet WAR</display-name>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:camel-config.xml</param-value>
  </context-param>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <servlet>
    <servlet-name>CamelServlet</servlet-name>
    <servlet-class>org.apache.camel.component.servlet.CamelHttpTransportServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>CamelServlet</servlet-name>
    <url-pattern>/camel/*</url-pattern>
  </servlet-mapping>

</web-app>

Step-8). Now we will write a simple “index.html” page inside the “CamelServlet_With_JMSEndpoint_Demo/src/main/webapp/”. This Html page will simple provide a form to the user so that they can enter two number which will be later processed bu the camel servlet after submitting the HTML form.

<html>
	<body>
		<h2>MiddlewareMagic: Camel Add Servlet Demo</h2>
		<table>
			<form action="camel/addNumbers">
				<TR><TD>Enter First Number </TD> <TD><input type="text" name="firstNumber" value="200"/></TD></TR>
				<TR><TD>Enter Second Number </TD> <TD> <input type="text" name="secondNumber" value="300"/></TD></TR>
				<TR><TD><input type="reset" value="Clear"/> </TD> <TD> <input type="Submit" value="Add the Numbers and Store result in WebLogic JMS Queue My_Q" /></TD></TR>
			</form>
		</table>
	</body>
</html>

Step-9). Now we will write the Apache Camel context file “camel-config.xml” which defines how the various camel endpoints will work. In order to know more about this please refer to: http://camel.apache.org/configuring-camel.html
Lets create the “camel-config.xml” file inside “CamelServlet_With_JMSEndpoint_Demo/src/main/resources”

<?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:camel="http://camel.apache.org/schema/spring" xmlns:p="http://www.springframework.org/schema/util" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">

     <bean id="mathBean" class="beans.MathBean" />

     <camelContext xmlns="http://camel.apache.org/schema/spring">
       <route id="addNumbersRoute">
           <from uri="servlet:///addNumbers"/>
           <transform>
               <method bean="mathBean" method="addTwoNumbers(${header.firstNumber},${header.secondNumber})"/> 
           </transform>
           <inOnly uri="weblogicJMS:My_Q" />
       </route>
     </camelContext>


     <!-- WebLogic JndiTemplate Settings --> 
     <bean id="jmsJndiTemplate" class="org.springframework.jndi.JndiTemplate">
           <property name="environment">
              <props>
                 <prop key="java.naming.factory.initial">weblogic.jndi.WLInitialContextFactory</prop>
                 <prop key="java.naming.provider.url">t3://localhost:7001</prop>
              </props>
           </property>
     </bean>

     <bean id="jndiDestinationResolver" class="org.springframework.jms.support.destination.JndiDestinationResolver">
          <property name="jndiTemplate" ref="jmsJndiTemplate"/>
     </bean>

     <bean id="jmsConnectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
          <property name="jndiTemplate" ref="jmsJndiTemplate"/>
          <property name="jndiName" value="My_CF"/>
     </bean>
     
     <bean id="jmsConfiguration" class="org.apache.camel.component.jms.JmsConfiguration">
          <property name="connectionFactory" ref="jmsConnectionFactory"/>
          <property name="destinationResolver" ref="jndiDestinationResolver"/>
     </bean>
          
     <bean id="weblogicJMS" class="org.apache.camel.component.jms.JmsComponent">
          <property name="configuration" ref="jmsConfiguration" />
     </bean>

</beans>

Step-10). Now the most important part in which we will be writing the maven “pom.xml” which will compile and build the above artifacts and will package them as part fo a WAR file. We will be using the “weblogic-maven-plugin” Weblogic plugin in this pom sothat we can easily deploy the WAR to weblogic 12c as well.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

	<modelVersion>4.0.0</modelVersion>
	<groupId>my.camel.servlet.demo</groupId>
	<artifactId>HelloCamelServletWebApp</artifactId>
	<version>1.0</version>
	<packaging>war</packaging>
	<name>HelloCamelServletWebApp Demo</name>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<version.compiler.plugin>2.3.1</version.compiler.plugin>
		<maven.compiler.target>1.7</maven.compiler.target>
		<maven.compiler.source>1.7</maven.compiler.source>
		
		<!-- Camel and Spring related properties -->
		<version.apache.camel>2.16.0</version.apache.camel>
		<version.spring>4.1.6.RELEASE</version.spring>
		
		<!-- Weblogic Plugin related properties -->
		<middleware.home>/Users/jsensharma/NotBackedUp/Installed/wls1221</middleware.home>
        <admin.server.url>t3://localhost:7001</admin.server.url>
        <admin.username>weblogic</admin.username>
        <admin.password>weblogic1</admin.password>
	</properties>

	<dependencies>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${version.spring}</version>
		</dependency>

		<dependency>
			<groupId>org.apache.camel</groupId>
			<artifactId>camel-spring</artifactId>
			<version>${version.apache.camel}</version>

			<!-- As we do not want the following JARs inside the "WEB-INF/lib" Hence excluding them : jaxb-api-2.2.7.jar jaxb-core-2.2.7.jar jaxb-impl-2.2.7.jar -->
			<exclusions>
				<exclusion>
					<groupId>com.sun.xml.bind</groupId>
					<artifactId>jaxb-api</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.xml.bind</groupId>
					<artifactId>jaxb-impl</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.xml.bind</groupId>
					<artifactId>jaxb-core</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.apache.camel</groupId>
			<artifactId>camel-servlet</artifactId>
			<version>${version.apache.camel}</version>
			<!-- As we do not want the following JARs inside the "WEB-INF/lib" Hence excluding them : jaxb-api-2.2.7.jar jaxb-core-2.2.7.jar jaxb-impl-2.2.7.jar -->
			<exclusions>
				<exclusion>
					<groupId>com.sun.xml.bind</groupId>
					<artifactId>jaxb-api</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.xml.bind</groupId>
					<artifactId>jaxb-impl</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.xml.bind</groupId>
					<artifactId>jaxb-core</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-jms</artifactId>
            <version>${version.apache.camel}</version>
			<!-- As we do not want the following JARs inside the "WEB-INF/lib" Hence excluding them : jaxb-api-2.2.7.jar jaxb-core-2.2.7.jar jaxb-impl-2.2.7.jar -->
			<exclusions>
				<exclusion>
					<groupId>com.sun.xml.bind</groupId>
					<artifactId>jaxb-api</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.xml.bind</groupId>
					<artifactId>jaxb-impl</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.xml.bind</groupId>
					<artifactId>jaxb-core</artifactId>
				</exclusion>
			</exclusions>
        </dependency>
	</dependencies>

	<build>
		<finalName>${project.artifactId}</finalName>
		<resources>
			<resource>
				<directory>src/main/resources</directory>
				<filtering>true</filtering>
			</resource>
		</resources>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>${version.compiler.plugin}</version>
				<configuration>
					<source>${maven.compiler.source}</source>
					<target>${maven.compiler.target}</target>
				</configuration>
			</plugin>
			
			<plugin>
                <groupId>com.oracle.weblogic</groupId> 
                <artifactId>weblogic-maven-plugin</artifactId> 
                <version>12.2.1-0-0</version> 
                <configuration> 
                    <middlewareHome>${middleware.home}</middlewareHome>
                    <adminurl>${admin.server.url}</adminurl>
                    <user>${admin.username}</user>
                    <password>${admin.password}</password>
                    <name>${project.build.finalName}</name>
                    <upload>true</upload> 
                    <action>deploy</action> 
                    <source>${project.build.directory}/${project.build.finalName}.${project.packaging}</source>          
                </configuration> 
            </plugin>
		</plugins>
	</build>

</project>

Building and Deploying the Camel WebApp

Now we are going to build and deploy the WebApplication to WebLogic 12.2.1 version. We will use Maven plugins to achieve the same. So before using the maven we need to setup the PATH and M2_HOME as following:

For Unix Based OS

$ export M2_HOME=/PATH/TO/apache_maven_3.2.3
$ export JAVA_HOME=/PATH/TO/jdk1.8.0_60
$ export PATH=$JAVA_HOME/bin:/PATH/TO/apache_maven_3.2.3/bin:$PATH

$ cd /PAYTH/TO/Camel-on-WebLogic12c/CamelServlet_With_JMSEndpoint_Demo
$ mvn clean install weblogic:deploy

For Windows Based OS

$ set M2_HOME=C:\PATH\TO\apache_maven_3.2.3
$ set JAVA_HOME=C:\PATH\TO\jdk1.8.0_60
$ set PATH=%JAVA_HOME%/bin;C:\PATH\TO\apache_maven_3.2.3\bin;%PATH%

$ cd C:\Camel-on-WebLogic12c\CamelServlet_With_JMSEndpoint_Demo
$ mvn clean install  weblogic:deploy

Step-11). Now we are going to build and deploy it on WebLogic as following using mvn clean install weblogic:deploy:


$ cd CamelServlet_With_JMSEndpoint_Demo

$  mvn clean install weblogic:deploy

[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building HelloCamelServletWebApp Demo 1.0
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ HelloCamelServletWebApp ---
[INFO] Deleting /Users/jsensharma/NotBackedUp/MM_Tests/WLS/Camel-on-WebLogic12c/CamelServlet_With_JMSEndpoint_Demo/target
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ HelloCamelServletWebApp ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 2 resources
[INFO] 
[INFO] --- maven-compiler-plugin:2.3.1:compile (default-compile) @ HelloCamelServletWebApp ---
[INFO] Compiling 1 source file to /Users/jsensharma/NotBackedUp/MM_Tests/WLS/Camel-on-WebLogic12c/CamelServlet_With_JMSEndpoint_Demo/target/classes
[INFO] 
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ HelloCamelServletWebApp ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/jsensharma/NotBackedUp/MM_Tests/WLS/Camel-on-WebLogic12c/CamelServlet_With_JMSEndpoint_Demo/src/test/resources
[INFO] 
[INFO] --- maven-compiler-plugin:2.3.1:testCompile (default-testCompile) @ HelloCamelServletWebApp ---
[INFO] No sources to compile
[INFO] 
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ HelloCamelServletWebApp ---
[INFO] No tests to run.
[INFO] 
[INFO] --- maven-war-plugin:2.2:war (default-war) @ HelloCamelServletWebApp ---
[INFO] Packaging webapp
[INFO] Assembling webapp [HelloCamelServletWebApp] in [/Users/jsensharma/NotBackedUp/MM_Tests/WLS/Camel-on-WebLogic12c/CamelServlet_With_JMSEndpoint_Demo/target/HelloCamelServletWebApp]
[INFO] Processing war project
[INFO] Copying webapp resources [/Users/jsensharma/NotBackedUp/MM_Tests/WLS/Camel-on-WebLogic12c/CamelServlet_With_JMSEndpoint_Demo/src/main/webapp]
[INFO] Webapp assembled in [45 msecs]
[INFO] Building war: /Users/jsensharma/NotBackedUp/MM_Tests/WLS/Camel-on-WebLogic12c/CamelServlet_With_JMSEndpoint_Demo/target/HelloCamelServletWebApp.war
[INFO] WEB-INF/web.xml already added, skipping
[INFO] 
[INFO] --- maven-install-plugin:2.4:install (default-install) @ HelloCamelServletWebApp ---
[INFO] Installing /Users/jsensharma/NotBackedUp/MM_Tests/WLS/Camel-on-WebLogic12c/CamelServlet_With_JMSEndpoint_Demo/target/HelloCamelServletWebApp.war to /Users/jsensharma/.m2/repository/my/camel/servlet/demo/HelloCamelServletWebApp/1.0/HelloCamelServletWebApp-1.0.war
[INFO] Installing /Users/jsensharma/NotBackedUp/MM_Tests/WLS/Camel-on-WebLogic12c/CamelServlet_With_JMSEndpoint_Demo/pom.xml to /Users/jsensharma/.m2/repository/my/camel/servlet/demo/HelloCamelServletWebApp/1.0/HelloCamelServletWebApp-1.0.pom
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building HelloCamelServletWebApp Demo 1.0
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- weblogic-maven-plugin:12.2.1-0-0:deploy (default-cli) @ HelloCamelServletWebApp ---
weblogic.Deployer invoked with options:  -noexit -deploy -username weblogic -name HelloCamelServletWebApp -source /Users/jsensharma/NotBackedUp/MM_Tests/WLS/Camel-on-WebLogic12c/CamelServlet_With_JMSEndpoint_Demo/target/HelloCamelServletWebApp.war -upload -adminurl t3://localhost:7001
<Dec 13, 2015 5:49:59 PM IST> <Info> <J2EE Deployment SPI> <BEA-260121> <Initiating deploy operation for application, HelloCamelServletWebApp [archive: /Users/jsensharma/NotBackedUp/MM_Tests/WLS/Camel-on-WebLogic12c/CamelServlet_With_JMSEndpoint_Demo/target/HelloCamelServletWebApp.war], to configured targets.> 
Task 6 initiated: [Deployer:149026]deploy application HelloCamelServletWebApp on AdminServer.
Task 6 completed: [Deployer:149026]deploy application HelloCamelServletWebApp on AdminServer.
Target state: deploy completed on Server AdminServer

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 6.831 s
[INFO] Finished at: 2015-12-13T17:50:01+05:30
[INFO] Final Memory: 37M/699M
[INFO] ------------------------------------------------------------------------

Once the Application is deployed on WebLogic we should be able to see the following kind of output on weblogic logs which indicates that the camel context is initialized.

Output on WebLogic console.


Dec 13, 2015 5:50:00 PM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization started
Dec 13, 2015 5:50:00 PM org.springframework.web.context.support.XmlWebApplicationContext prepareRefresh
INFO: Refreshing Root WebApplicationContext: startup date [Sun Dec 13 17:50:00 IST 2015]; root of context hierarchy
Dec 13, 2015 5:50:00 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [camel-config.xml]
Dec 13, 2015 5:50:00 PM org.apache.camel.impl.DefaultCamelContext start
INFO: Apache Camel 2.16.0 (CamelContext: camel-1) is starting
Dec 13, 2015 5:50:00 PM org.apache.camel.management.ManagedManagementStrategy doStart
INFO: JMX is enabled
Dec 13, 2015 5:50:00 PM org.apache.camel.impl.converter.DefaultTypeConverter doStart
INFO: Loaded 189 type converters
Dec 13, 2015 5:50:00 PM org.apache.camel.impl.DefaultRuntimeEndpointRegistry doStart
INFO: Runtime endpoint registry is in extended mode gathering usage statistics of all incoming and outgoing endpoints (cache limit: 1000)
Dec 13, 2015 5:50:00 PM org.apache.camel.impl.DefaultCamelContext doStartCamel
INFO: AllowUseOriginalMessage is enabled. If access to the original message is not needed, then its recommended to turn this option off as it may improve performance.
Dec 13, 2015 5:50:00 PM org.apache.camel.impl.DefaultCamelContext doStartCamel
INFO: StreamCaching is not in use. If using streams then its recommended to enable stream caching. See more details at http://camel.apache.org/stream-caching.html
Dec 13, 2015 5:50:01 PM org.apache.camel.impl.DefaultCamelContext doStartOrResumeRouteConsumers
INFO: Route: addNumbersRoute started and consuming from: Endpoint[servlet:///addNumbers]
Dec 13, 2015 5:50:01 PM org.apache.camel.impl.DefaultCamelContext start
INFO: Total 1 routes, of which 1 is started.
Dec 13, 2015 5:50:01 PM org.apache.camel.impl.DefaultCamelContext start
INFO: Apache Camel 2.16.0 (CamelContext: camel-1) started in 0.156 seconds
Dec 13, 2015 5:50:01 PM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization completed in 898 ms
Dec 13, 2015 5:50:01 PM org.apache.camel.component.servlet.CamelHttpTransportServlet init
INFO: Initialized CamelHttpTransportServlet[name=CamelServlet, contextPath=/HelloCamelServletWebApp]

Testing the Web Application

Now as the application is deployed on WebLogic 12.2.1 hence lets access the URL and submit the form:

http://localhost:7001/HelloCamelServletWebApp/
OR
http://localhost:7001/HelloCamelServletWebApp/camel/addNumbers?firstNumber=200&secondNumber=300

As soon as we submit the data (two numbers) in the form presented by the application we will be able to see that the JMS Queue has got a JMS Message in it.

Listing JMS Queue Messages on WLS Console

Listing JMS Queue Messages on WLS Console

Source Code:
The Source code for this demo can be found at:

https://github.com/jaysensharma/MiddlewareMagicDemos/tree/master/WebLogic/JMS/Camel-on-WebLogic12c
.
.

Regards
Jay SenSharma


Spring Basic Demo

Jay SenSharma

Jay SenSharma

Few More Demos Here: (Binding/Accessing JNDI names Using Spring Framework)

Here is a very simple example which demonstrates us …How to lookup in the JNDI tree of WebLogic Server 10.3 using the Spring Framework. To run this example you need to download at least two JARs “Spring.jar” and “spring-jdbc.jar”. The best way to get these JARs is to browse to Spring framework website. But I have a very simple way for you to get these jars …please refer to http://findjar.com/ and just specify the JAR file name there  or if you remember any of the class name which is there inside these JAR then that will also work for you.

Once you have done with downloading with these JARs then start writing the Spring Bean class.

Step 1).  Writing the Spring Bean class.

package pack;
import java.io.Serializable;
public class EmployeeBean implements Serializable
{
private static final long serialVersionUID = 1L;
private int empNo;
private String empName;

public EmployeeBean()
{
System.out.println(“nt EmployeeBean Object Instantiated”);
}

public void init()
{
System.out.println(“nt init() of EmployeeBean”);
empNo=1111;
empName=”AAAA”;
}

public int getEmpNo() {
System.out.println(“ttgetEmpNo()”);
return empNo;
}

public void setEmpNo(int empNo) {
this.empNo = empNo;
System.out.println(“ttsetEmpNo()”);
}

public String getEmpName() {
System.out.println(“ttgetEmpName()”);
return empName;
}

public void setEmpName(String empName) {
System.out.println(“ttsetEmpName()”);
this.empName = empName;
}

public String toString() {
return “n&lt;BR&gt;*********************n&lt;BR&gt;Emp Name: ” + empName + “n&lt;BR&gt;Emp Num: ” + empNo  ;
}
}

Step 2). Now we need to write the Spring Configuration XML file, here we need to define the Bean information’s like following


<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE beans PUBLIC “-//SPRING//DTD BEAN//EN” “<a href="http://www.springframework.org/dtd/spring-beans.dtd">http://www.springframework.org/dtd/spring-beans.dtd</a>“>

<beans>
<bean id=”employee”  init-method=”init”>
<property name=”empNo” value=”1000″/>
<property name=”empName” value=”Jack”/>
</bean>

<bean id=”dataSource”>
<property name=”jndiName”>
<value>jdbc/MyDS</value>
</property>
</bean>
</beans>

Step3). Now we need to provide the mapping of the Spring Configuration file into the web.xml file


<?xml version=”1.0″ encoding=”UTF-8″?>
<web-app xmlns:xsi=”<a href="http://www.w3.org/2001/XMLSchema-instance">http://www.w3.org/2001/XMLSchema-instance</a>” xmlns=”<a href="http://java.sun.com/xml/ns/javaee">http://java.sun.com/xml/ns/javaee</a>” xmlns:web=”<a href="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd</a>” xsi:schemaLocation=”<a href="http://java.sun.com/xml/ns/javaee">http://java.sun.com/xml/ns/javaee</a> <a href="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd</a>” id=”WebApp_ID” version=”2.5″>
<display-name>SpringOne</display-name>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/applicationContext.xml</param-value>
</context-param>

<servlet>
<servlet-name>MyJNDIServlet</servlet-name>
<servlet-class>servlets.MyJNDIServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyJNDIServlet</servlet-name>
<url-pattern>MyJNDIServlet</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>SpringContextServlet</servlet-name>
<servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

Step 4). No we need to create a simple Servlet using Spring APIs to perform a JNDI lookup on the Server for the a DataSource which has the JNDI Name as “jdbc/MyDS” Object.


package servlets;
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
import java.net.URL;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;

public class MyJNDIServlet extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
PrintWriter out=res.getWriter();
try
{
URL url=Thread.currentThread().getContextClassLoader().getResource(“applicationContext.xml”);
System.out.println(“nnt URL: “+url);
String file=url.getFile();
System.out.println(“nnt FILE: “+file);

BeanFactory factory = new XmlBeanFactory(new FileSystemResource(file));
javax.sql.DataSource bean=( javax.sql.DataSource)factory.getBean(“dataSource”);
out.println(“<h3>org.springframework.jndi.JndiObjectFactoryBean (dataSource) Bean: “+bean);
System.out.println(“ntorg.springframework.jndi.JndiObjectFactoryBean (DataSource)Bean: “+bean);
out.println(“<h4>GOT the CONNECTION :=> ds.getConnection() : “+bean.getConnection());
//System.out.println(“ntds.getConnection() : “+bean.getConnection());

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

Step 5). Compile the “EmployeeBean.java” and “MyJNDIServlet.java” classes by adding the Spring.jar and Spring-jdbc.jar files in the CLASSPATH of the command prompt.


javac    -d  .  MYJNDIServlet.java

javac    -d  .  EmployeeBean.java

Step 6). Now place the compiled classes and the Spring Configuration “applicationContext.xml” file inside the “WEB-INF/classes” directory.

Step 7).  Place the “spring.jar” and “spring-jdbc.jar” files inside the “WEB-INF/lib” directory.

Step 8). Write a Simple “index.jsp” page with a link to your Servlet…



<%@ page language=”java” contentType=”text/html;charset=UTF-8″%>
<center>
<a href=”MyServlet”>Click Here To Test Simple SpringBean.</a>
<BR><BR>
<a href=”MyJNDIServlet”>Click Here To Test <B><i>JNDI Spring Bean</B></i>.</a>

Step 9). Create a WAR File of above contents and then before deploying it on the Server. Finally Create a DataSource on the Server with the JNDI Name “jdbc/MyDS”.

Step 10). Deploy the Application On the Server and then access the MyJNDIServlet to perform a JNDI lookup using Spring Framework.

regards

Jay SenSharma


Enabling Spring Console Extension

Hi,

Jay SenSharma

Jay SenSharma

Here is a Simple demonstration to Enable Spring Console Extension to Monitor the Spring Bean Details in AdminConsole.  For more details please refer to : http://download.oracle.com/docs/cd/E12840_01/wls/docs103/programming/spring.html#wp1081223

Step1). Create a Directory somewhere sothat we can develope a Simple Spring Application inorder to achieve this:

Example: C:PostOnSpring

Step2). Open a Command Window  and run “. ./setWLSEnv.sh”

Step3). Use the following command to deploy the “weblogic-spring.jar” file as a Library (Optional Package) in the targeted Server where we are intended to deploy our Spring Applications.

For details of  Optional Package TestCase/Demo —>please refer to : Optional Packages In WebLogic

C:PostOnSpring>java weblogic.Deployer -library -deploy -source C:bea103wlserver_10.3serverlibweblogic-spring.jar -targets AdminServer -adminurl t3://localhost:7001 -user weblogic -password weblogic

Step4). Login to Admin Console —>Home—>Preferences (Link top of the page)—> Extensions (TAB)—>     spring-console (Check)

and then click on the “Enable” Button

Step5). Restart your Server in order to take the Changes Affect.

================Developing Spring Application Part================

Step6). Create a Spring WebApplication directory with name “SpringBeanReference” inside “C:PostOnSpring”.

Step7). Create “index.jsp” page inside “C:PostOnSpringSpringBeanReference”.

Step8). Create “META-INF” and “WEB-INF” Directories inside “C:PostOnSpring”

Step9). Inside “META-INF” directory provide the “MANIFEST.MF” file with the following informations…to make sure that the Application gets linked to the Optional Package which we have deployed on step 2)

Extension-List: WeblogicSpring
WeblogicSpring-Extension-Name: weblogic-spring
WeblogicSpring-Specification-Version: 10.3.0.0
WeblogicSpring-Implementation-Version: 10.3.0.0

NOTE: Make Sure that there is no extra spaces in the Above  4 lines either at the beginning or at the end of each lines.

Step10). Create a “lib” directory inside “C:PostOnSpringSpringBeanReferenceWEB-INF” and place the following 3-Jar files there:

spring.jar
wlcommons-logging.jar
commons-logging.jar

Step11). Create “classes” Directory inside “C:PostOnSpringSpringBeanReferenceWEB-INF” and provide the following 1-Interface and 1-Implementation Class there like following:

“HelloService.java”

package pack;
public interface HelloService {
public String sayHello(Name name);
}

and
“HelloService_Impl”

package pack;
public class HelloService_Impl implements HelloService {
    public HelloService_Impl()
      {
        System.out.println("ntHelloService_Impl() object Created...");
       }

    public String sayHello(Name name)
       {
         System.out.println("ntsayHello() of HelloService_Impl called");
         return "**** Hello  " + name.getFirstName() + " " + name.getLastName();
        }
}

Step12). CCompile above two classes there:

C:PostOnSpringSpringBeanReferenceWEB-INFclasses> javac -d . HelloService.java
C:PostOnSpringSpringBeanReferenceWEB-INFclasses> javac -d . HelloService_Impl.java

Step13). Provide a Simple Servlet just to see beans are accessible on not inside “C:PostOnSpringSpringBeanReferenceWEB-INFclasses” provide the “MyServlet.java.java”

package servlets;
import javax.servlet.http.*;
import java.io.*;
import javax.servlet.*;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import pack.Name;
public class MyServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

public void service(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
PrintWriter out=res.getWriter();
ServletContext servletContext =this.getServletContext();
WebApplicationContext springContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
// Call your HelloBean here
}
}

Step14).  Provide the follwing “applicationContext.xml” … inside “C:PostOnSpringSpringBeanReferenceWEB-INF” directory

Step15).Please provide the “web.xml” file ..inside “C:PostOnSpringSpringBeanReferenceWEB-INF” like following;

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Spring_ReferenceBean</display-name>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>servlets.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>MyServlet</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

</web-app>

Step16). Provide the “commons-logging.properties” file inside “C:PostOnSpringSpringBeanReferenceWEB-INFclasses” with the following Line of code inside it:

org.apache.commons.logging.LogFactory = weblogic.logging.commons.LogFactoryImpl

Step17).Deploy the Application and then Login to the AdminConsole…..

Deployments—> Deployment Summary—> SpringBeanReference —->Configuration (Tab)—>Spring Framework (SubTab)

.
.
Thanks
Jay SenSharma

1 Comment more...

Copyright © 2010-2012 Middleware Magic. All rights reserved. |