Search This Blog

Thursday, February 19, 2009

How to Find out whether you are using 64 bit JDK or 32 bit JDK

 

Write this sample java program

import java.util.Enumeration;
import java.util.Properties;

public class Class1 {
    public Class1() {
    }

    public static void main(String[] args) {
        Class1 class1 = new Class1();
        Properties p = System.getProperties();
        Enumeration keys = p.keys();
        while (keys.hasMoreElements()) {
          String key = (String)keys.nextElement();
          String value = (String)p.get(key);
          System.out.println(key + ": " + value);
        }

    }
}

Run the program

and check for the propert sun.arch.data.model if this shows 32 then you are running in a 32 bit JVM. If this shows 64 bit then you are in 64 bit JVM.

For the 64 bit you run the java using the following option  $ORACLE_HOME/jdk/bin/java –d64

This shows sun.arch.data.model: 64

Resolving ClassNotFound Exceptions

When you are running a Java program or compiling a java program you got a class not found error, going through all the JAR files for finding this particular class file is quite tedious.

The program given below can help you to search inside the jar and/or zip files and tells you whether the file you are looking for is present or not.

Code Example

Below you will find the code example, how you use it and what result you can expect out of it.

SearchJars.java
  package mypackage7;

import java.util.zip.*;
import java.io.*;
import java.util.*;

public class SearchJars {

static String s3;
static String s4 ="";
static int i1 = 0;
static int i2 = 0;

public static void main(String args[]) {
if (args.length != 2) throw new IllegalArgumentException("Wrong Number of Args !! java SearchJars Direcory_Name filename ");
File f1 = new File(args[0]);
s3 = args[1];
traverse(f1);
System.out.println("\n\n============== Results ============================");
System.out.println("Searced "+ i1 +" Files in "+ args[0] +" And Found "+i2 +" Entries. ");
System.out.println(s4);
}


public static void traverse(File f) {
String s1 = f.getAbsolutePath();

if (s1.toUpperCase().indexOf(".JAR") != -1 || s1.toUpperCase().indexOf(".ZIP") != -1 ) {
System.out.println("Searching "+ s1 +" .....");
i1++;
try {
ZipFile zf = new ZipFile(s1);
for (Enumeration entries = zf.entries(); entries.hasMoreElements();) {
String s2 = ((ZipEntry)entries.nextElement()).getName();
if (s2.indexOf(s3) != -1 ) {
System.out.println("Found "+s2 + " In " +s1);
i2++;
s4 = s4 + "Found "+s2 + " In " +s1 + "\n";
}
}
} catch (IOException e) {}
}

if (f.isDirectory()) {
String[] children = f.list();
for (int i=0; i<children.length; i++) {
traverse(new File(f, children[i]));
}
}
}
}


Program Usage

java.exe mypackage7.SearchJars D:\oracle\jdev1012\BC4J\jlib DateConvertor

Program Output


  Searching D:\oracle\jdev1012\BC4J\jlib\adfjclient.jar  ..... 
Found oracle/jbo/uicli/jui/DateConvertor.class In D:\oracle\jdev1012\BC4J\jlib\adfjclient.jar
Searching D:\oracle\jdev1012\BC4J\jlib\adfmejb.jar .....
Searching D:\oracle\jdev1012\BC4J\jlib\adftags.jar .....
Searching D:\oracle\jdev1012\BC4J\jlib\bc4jdatum.jar .....

============== Results ============================
Searced 4 Files in D:\oracle\jdev1012\BC4J\jlib And Found 1 Entries.
Found oracle/jbo/uicli/jui/DateConvertor.class In D:\oracle\jdev1012\BC4J\jlib\adfjclient.jar

Wednesday, February 18, 2009

Best Freeware Software

For the Folder Sizes http://www.jam-software.com/freeware/index.shtml (TreeSize Free)

For the English Dictionary WORDWEB FREE* VERSION http://wordweb.info/free/

Take a backup of the original DVD’s DVD Shrink http://www.dvdshrink.org/

Best Java Decompiler JD-Gui http://java.decompiler.free.fr/

Ftp Utility FileZilla  http://filezilla-project.org/

Free RAR/Unzip utility http://www.tugzip.com/

File Editor NotePad Plus  http://notepad-plus.sourceforge.net/uk/site.htm

Free Download Manager http://www.freedownloadmanager.org/

Ipod Backup Utlity

http://www.getsharepod.com

CPU Information CPU-Z

Friday, February 13, 2009

How to Send/Browse Messages to AQ via OC4J in a Standalone Java program

Set up your queues and AQ resource adapter etc using the following article.

http://rreddy.blogspot.com/2009/02/how-to-use-simple-mdb-with-oracle.html

The only difference with the Servlet and the standalone code with the connection factories and the queues JNDI lookup’s.

<resource-ref-mapping location="TEST_AQ/QueueCF" name="CommonConnectionFactory">

For the standalone java program we use the ConnectionFactory as java:comp/resource/TEST_AQ/QueueConnectionFactories/QueueCF

This can be found from the file oc4j-ra.xml file                    

For the queue we use the JNDI location for the Queue as

<message-destination-ref-mapping name="TestQueue" location="TEST_AQ/MyQueue/Queues/MYQUEUE" />

But for the standalone java client we use the  java:comp/resource/TEST_AQ/Queues/MYQUEUE                             
Example to Send a Message to JMS

package mdbaq;
import java.io.*;

import java.net.URL;

import java.util.Date;

import java.util.Hashtable;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.jms.* ;
import javax.jms.Queue;
import javax.naming.*;

public class SendJMS {
    public SendJMS() {
    }

    public static void main(String[] args) {
        SendJMS sendJMS = new SendJMS();
        Queue queue=null;
        QueueSession queueSession=null;
        QueueSender queueSender=null;
        Context jndiContext = null;
        QueueConnectionFactory queueConnectionFactory = null;
        QueueConnection queueConnection = null;

            try {

                  Hashtable env = new Hashtable();
                  //  Standalone OC4J connection details
                  env.put(Context.INITIAL_CONTEXT_FACTORY, "oracle.j2ee.rmi.RMIInitialContextFactory");
                  env.put(Context.SECURITY_PRINCIPAL, "oc4jadmin");
                  env.put(Context.SECURITY_CREDENTIALS, "welcome1");
                  env.put(Context.PROVIDER_URL, "ormi://localhost:23791");
                  jndiContext = new InitialContext(env);

            } catch (NamingException e)
            { System.out.println("Exception occurred: " + e.toString()); }

            try {
             //   queueConnectionFactory = (QueueConnectionFactory) jndiContext.lookup("jms/qcf");
        queueConnectionFactory = (QueueConnectionFactory) jndiContext.lookup("java:comp/resource/TEST_AQ/QueueConnectionFactories/QueueCF");
         //       queue = (Queue)jndiContext.lookup("jms/demoQueue");
                 queue = (Queue)jndiContext.lookup("java:comp/resource/TEST_AQ/Queues/MYQUEUE");
            queueConnection = queueConnectionFactory.createQueueConnection();
            queueSession= queueConnection.createQueueSession(true,Session.AUTO_ACKNOWLEDGE);
            queueSender = queueSession.createSender(queue);
            queueConnection.start();
            } catch (Exception e) {
            System.out.println("Exception occurred: " + e.toString());
            e.printStackTrace();
            }

        try {

        TextMessage message = queueSession.createTextMessage();
        message.setText("Test "+new Date());
        queueSender.send(message);
        queueSession.commit();
        } catch (JMSException e) {
        System.out.println("Exception occurred: " +e.toString());
            e.printStackTrace();
        }

        System.out.println( " Message Sent .....");

        }

    }

Example For Browsing the message

package mdbaq;

import java.util.Enumeration;

import java.util.Hashtable;

import javax.naming.InitialContext;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.Message;
import javax.jms.QueueSession;
import javax.jms.QueueBrowser;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;

import javax.jms.TextMessage;

import javax.naming.Context;

public class Browser
{
    public static void main(String[] args) throws Exception
    {
       // get the initial context
        Hashtable env = new Hashtable();
        //  Standalone OC4J connection details
        env.put(Context.INITIAL_CONTEXT_FACTORY, "oracle.j2ee.rmi.RMIInitialContextFactory");
        env.put(Context.SECURITY_PRINCIPAL, "oc4jadmin");
        env.put(Context.SECURITY_CREDENTIALS, "welcome1");
        env.put(Context.PROVIDER_URL, "ormi://localhost:23791");
       InitialContext ctx = new InitialContext(env);
       // lookup the queue object
      // Queue queue = (Queue) ctx.lookup("jms/demoQueue");
       Queue queue = (Queue) ctx.lookup("java:comp/resource/TEST_AQ/Queues/MYQUEUE");
       // lookup the queue connection factory
       QueueConnectionFactory connFactory =
       //(QueueConnectionFactory) ctx.lookup("jms/qcf");
      //  (QueueConnectionFactory) ctx.lookup("java:comp/resource/TEST_AQ/QueueConnectionFactories/QueueCF");
       (QueueConnectionFactory) ctx.lookup("java:comp/resource/TEST_AQ/QueueConnectionFactories/QueueCF");
       // create a queue connection
       QueueConnection queueConn = connFactory.createQueueConnection();
       // create a queue session
       QueueSession queueSession = queueConn.createQueueSession(false,
           Session.AUTO_ACKNOWLEDGE);
       // create a queue browser
       QueueBrowser queueBrowser = queueSession.createBrowser(queue);
       // start the connection
       queueConn.start();
       // browse the messages
       Enumeration e = queueBrowser.getEnumeration();
       int numMsgs = 0;
       // count number of messages
       while (e.hasMoreElements()) {
          Message message = (Message) e.nextElement();
         TextMessage msg = (TextMessage) message;
           System.out.println(msg.getText());
          numMsgs++;
       }
       System.out.println(queue + " has " + numMsgs + " messages");
       // close the queue connection
       queueConn.close();
    }
}

Run the Java program using the following option

java -classpath D:\MDB-AQ\classes;D:\temp2\jms.jar;D:\temp2\jta.jar;D:\temp2\pcl.jar;D:\temp2\aqapi13.jar;D:\temp2\ojdbc14.jar;D:\temp2\connector.jar;D:\temp2\jazncore.jar; D:\temp2\dms.jar;D:\temp2\bcel.jar;D:\temp2\mail.jar;D:\temp2\oc4j-internal.jar;D:\temp2\oc4jclient.jar;D:\temp2\adminclient.jar   mdbaq.Browser

How to view AQ Queues via OC4J with the hermes tool

For the OC4J memory based JMS queues you can use the link below.

Hermes Configuration for OC4J memory based JMS

This article explains how  to view AQ based queues with hermes.

Set up your queues and AQ resource adapter etc using the following article.

http://rreddy.blogspot.com/2009/02/how-to-use-simple-mdb-with-oracle.html

From an OC4J install copy all these files to a temp directory

adminclient.jar
aqapi13.jar
bcel.jar
connector.jar
dms.jar
javax77.jar
jazncore.jar
jms.jar
jndi.jar
jta.jar
oc4j-internal.jar
oc4jclient.jar
ojdbc14.jar
optic.jar
pcl.jar

From the Hermes Tool create a classpath using the following ,

<classpathGroup id="ORACLE-SOA">
       <library jar="D:\TEMP\aqapi13.jar" noFactories="true"/>
       <library jar="D:\TEMP\jms.jar" noFactories="true"/>
       <library jar="D:\TEMP\optic.jar" noFactories="true"/>
       <library jar="D:\TEMP\jta.jar" noFactories="true"/>
       <library jar="D:\TEMP\oc4jclient.jar" noFactories="true"/>
       <library jar="D:\TEMP\ojdbc14.jar" noFactories="true"/>
       <library jar="D:\TEMP\bcel.jar" noFactories="true"/>
       <library jar="D:\TEMP\connector.jar" noFactories="true"/>
       <library jar="D:\TEMP\adminclient.jar" noFactories="true"/>
       <library jar="D:\TEMP\oc4j-internal.jar" noFactories="true"/>
       <library jar="D:\TEMP\dms.jar" noFactories="true"/>
       <library jar="D:\TEMP\jazncore.jar" noFactories="true"/>
       <library jar="D:\TEMP\pcl.jar" noFactories="true"/>
   </classpathGroup>

Create a session using the following entries

<factory classpathId="ORACLE-SOA">
        <provider className="hermes.JNDIQueueConnectionFactory">
            <properties>
                <property name="binding" value="java:comp/resource/TEST_AQ/QueueConnectionFactories/QueueCF"/>
                <property name="initialContextFactory" value="oracle.j2ee.rmi.RMIInitialContextFactory"/>
                <property name="providerURL" value="ormi://localhost:23791"/>
                <property name="securityCredentials" value="welcome1"/>
                <property name="securityPrincipal" value="oc4jadmin"/>
            </properties>
        </provider>
        <connection clientID="" connectionPerThread="false">
            <session audit="false" id="OEMS" reconnects="0" transacted="true" useConsumerForQueueBrowse="false"/>
        </connection>
        <destination domain="1" name="java:comp/resource/TEST_AQ/Queues/MYQUEUE"/>
        <extension className="hermes.ext.DefaultHermesAdminFactory">
            <properties/>
        </extension>
    </factory>

The important entries are

binding ==>> java:comp/resource/TEST_AQ/QueueConnectionFactories/QueueCF

This can be found from the file oc4j-ra.xml file \

<connector-factory location="TEST_AQ/QueueCF" connector-name="TEST_AQ">
        <config-property name="jndiLocation" value="QueueConnectionFactories/QCF"/>

For the MDB we use the ConnectionFactory as TEST_AQ/QueueCF but for the hemes tool we need to use this as QueueConnectionFactories/QCF.

destination domain==> java:comp/resource/TEST_AQ/Queues/MYQUEUE                              For the MDB we use this as TEST_AQ/MyQueue/Queues/MYQUEUE but for the hermes tool we need use TEST_AQ/Queues/MYQUEUE.

After this send a message to the AQ using the script                               

DECLARE
enqueue_options dbms_aq.enqueue_options_t;
message_properties dbms_aq.message_properties_t;
message_handle RAW(16);
Message SYS.AQ$_JMS_TEXT_MESSAGE;
BEGIN
Message := Sys.Aq$_Jms_Text_Message.Construct;
Message.Set_Text(to_char(sysdate, 'DD/MM/YYYY HH24:MI:SS'));
dbms_aq.enqueue(queue_name => 'MYQUEUE',
enqueue_options => enqueue_options,
message_properties => message_properties,
payload => message,
msgid => message_handle);
COMMIT;
END;

Wednesday, February 04, 2009

How to Get the HTTP request and responses with OC4J/OAS

For the Stand alone oc4j use the following

java   -Doracle.oc4j.trace.finest=com.evermind.server.http  -Dhttp.request.debug=true -jar oc4j.jar

09/02/05 12:58:22 FINE: EvermindHttpServletRequest.init GET /j2ee/test.jsp HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, applicat
ion/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, application/xaml+xml, applicati
on/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/x-silverligh
t, */*
Accept-Language: en-us
UA-CPU: x86
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Mozilla/4.0 (compatible; MSIE 6.0; Wi
ndows NT 5.1; SV1) ; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; FDM; .NET CLR 3.0
.04506.648; .NET CLR 3.5.21022)
Host: xxx.xx.oracle.com:8888
Connection: Keep-Alive
Cookie: JSESSIONID=2009-02-05 12:58:22.734 NOTIFICATION  J2EE JSP-0008 Unable to dispatch JSP Page : Exception:java.io.
FileNotFoundException: C:\oc4j10134\j2ee\home\default-web-app\j2ee\test.jsp (The system cannot find
the path specified)
09/02/05 12:58:22 FINEST: EvermindHttpServletResponse.commit *********** RESPONSE ************
09/02/05 12:58:22 FINEST: EvermindHttpServletResponse.commit HTTP/1.1 404 Not Found
Date: Thu, 05 Feb 2009 07:28:22 GMT
Server: Oracle Containers for J2EE
Connection: Keep-Alive
Keep-Alive: timeout=15, max=100
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked

09/02/05 12:58:22 FINEST: EvermindHttpServletResponse.commit *********** RESPONSE DONE ************

For the OAS add the following in the opmn.xml file

-Doracle.oc4j.trace.finest=com.evermind.server.http -Dajp.debug=true -Dhttp.request.debug=true

 

How to use mod_security module with HTTP Server to check the request and response headers

You can also use mod_security module to check the requests and responses.

Add the following at the end of the httpd.conf

On linux

LoadModule security_module libexec/mod_security.so

On Windows

LoadModule security_module modules/ApacheModuleSecurity.dll
AddModule mod_security.c

<IfModule mod_security.c>
    # Turn the filtering engine On or Off
     SecFilterEngine On                                                                                             
     # Make sure that URL encoding is valid
     SecFilterCheckURLEncoding On                                             
     # Unicode encoding check
     SecFilterCheckUnicodeEncoding Off                                        
     # Only allow bytes from this range
     SecFilterForceByteRange 0 255                                            
     # Only log suspicious requests
     SecAuditEngine On                                                        
     # The name of the audit log file
     SecAuditLog logs/audit_log
     # Debug level set to a minimum
     SecFilterDebugLog logs/modsec_debug_log
     SecFilterDebugLevel 0
</IfModule>

and restart the HTTP Server.

Now check the audit_log file in $ORACLE_HOME/Apache/Apache/log directory.

========================================
UNIQUE_ID: Qw2LjJhFqD0AABvSLj8
Request: 152.69.168.191 - - [25/Aug/2005:14:42:57 +0530] "GET
/test_opencursor/Controller?recordID=2&counter=1 HTTP/1.1" 200 5
Handler: oc4j-handler
----------------------------------------
GET /test_opencursor/Controller?recordID=2&counter=1 HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg,
application/x-shockwave-flash, application/vnd.ms-excel,
application/vnd.ms-powerpoint, application/msword, */*
Accept-Encoding: gzip, deflate
Accept-Language: en-us
Connection: keep-alive
Host: localhost
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR  1.1.4322)
Oracle-ECID: 1124961164:152.69.168.61:7122:0:1,0
HTTP/1.1 200 OK
Set-Cookie:
JSESSIONID=9845a83dce5dad8a271451048cb9a5fc0cb23f83960.e3uMb3eObheLe34SchaNaNu
Na41ynknvrkLOlQzNp65In0; Path=/test_opencursor
Cache-Control: private
Keep-Alive: timeout=15, max=100
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: application/octet-stream
========================================

This gives the request and response.

Tuesday, February 03, 2009

How to use a Simple MDB with Oracle Database provider in 10. 1.3

1. Create the following entries in the data-sources.xml file

<managed-data-source connection-pool-name="AQ Connection Pool"
jndi-name="jdbc/aq"
name="AQ Connection Pool"/>
<connection-pool name="AQ Connection Pool">
<connection-factory
factory-class="oracle.jdbc.pool.OracleDataSource"
user="jmsuser" password="jmsuser"
url="jdbc:oracle:thin:@incq128ad:1521:ias1012"/>
</connection-pool>

2. Login to sql*plus and create the AQ objects

CONNECT system/manager;
DROP USER jmsuser CASCADE ;
GRANT CONNECT, RESOURCE,AQ_ADMINISTRATOR_ROLE TO jmsuser IDENTIFIED BY jmsuser ;
CONNECT jmsuser/jmsuser;
BEGIN
dbms_aqadm.create_queue_table ( queue_table=> 'TEST', queue_payload_type=> 'SYS.AQ$_JMS_TEXT_MESSAGE', sort_list=> '', comment=> '', multiple_consumers=> FALSE, message_grouping=> DBMS_AQADM.NONE, non_repudiation => DBMS_AQADM.NONE, storage_clause=> '', compatible=> '8.1', primary_instance=> '0', secondary_instance=> '0');
COMMIT;
END;
BEGIN
dbms_aqadm.create_queue(queue_name=> 'MYQUEUE', queue_table=> 'TEST', queue_type=> DBMS_AQADM.NORMAL_QUEUE, max_retries=> '5', retry_delay=> '0', retention_time=> '0', comment=> '');
COMMIT;
END;
BEGIN
dbms_aqadm.start_queue('JMSUSER.MYQUEUE', TRUE, TRUE);
COMMIT;
END;

3. Test whether the enqueing and dequing is working fine or not
Open a sqlplus window and login as jmsuser and run the following sql.

enque.sql
---------
DECLARE
enqueue_options dbms_aq.enqueue_options_t;
message_properties dbms_aq.message_properties_t;
message_handle RAW(16);
Message SYS.AQ$_JMS_TEXT_MESSAGE;
BEGIN
Message := Sys.Aq$_Jms_Text_Message.Construct;
Message.Set_Text(to_char(sysdate, 'DD/MM/YYYY HH24:MI:SS'));
dbms_aq.enqueue(queue_name => 'MYQUEUE',
enqueue_options => enqueue_options,
message_properties => message_properties,
payload => message,
msgid => message_handle);
COMMIT;
END;

Open another sqlplus window and login as jmsuser and run the following sql.

deque.sql
---------
set serveroutput on;
declare
deqopt dbms_aq.dequeue_options_t;
mprop dbms_aq.message_properties_t;
msgid RAW(16);
payload SYS.AQ$_JMS_TEXT_MESSAGE;
begin
deqopt.navigation := DBMS_AQ.FIRST_MESSAGE;
--deqopt.wait := 1;
dbms_aq.dequeue(
queue_name => 'MYQUEUE',
dequeue_options => deqopt,
message_properties => mprop,
payload => payload,
msgid => msgid );
commit;
dbms_output.put_line('The Message Sent to the Queue is: ' || payload.TEXT_VC);
end;

Now you should see the message in the sql*plus window as
The Message Sent to the Queue is: 13/03/2008 17:48:34
4. Start the oc4j container and access the EM Application Server Control
Go to the Administration TAB
Click on the Database Persistence link.

5. In this screen click on the deploy Button
Give the "Resource Adapter Module Name" as : TEST_AQ
And select the Radio Button
"Add a new resource provider to be used by this connector" Give the "Resource Provider Name" as TEST_AQ and
select the "Datasource JNDI Location" as jdbc/aq.

This will add the following values to the application.xml file

<resource-provider name="TEST_AQ" class="oracle.jms.OjmsContext">
<description></description>
<property name="datasource" value="jdbc/aq" />
</resource-provider>

Restart the oc4j container after this.

6. Now click on this Resource Adapter
and select the TAB
Connection Factory and select the QueueConnectionFactory
TEST_AQ/QueueCF
7. Now Click On "Administrated Objects" TAB and enter the following value

Choose the ObjectClass as oracle.j2ee.ra.jms.generic.AdminObjectQueueImpl
Give the JNDI Location as TEST_AQ/MyQueue and resourceProviderName as
TEST_AQ.

Software Requirements/Prerequisites

8. From the JDeveloper Create a Message driven and change the OnMessage Method

package mdbaq;
import javax.ejb.EJBException;
import javax.ejb.MessageDrivenBean;
import javax.ejb.MessageDrivenContext;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
public class MessageDrivenEJBBean implements MessageDrivenBean, 
                                             MessageListener {
    private MessageDrivenContext _context;
    public void ejbCreate() {
    }
    public void setMessageDrivenContext(MessageDrivenContext context) throws EJBException {
        _context = context;
    }
    public void ejbRemove() throws EJBException {
    }
    public void onMessage(Message message)
            {
                    System.out.println("Received message: " + message);
                    TextMessage msg = null;
            try {
                if (message instanceof TextMessage) {
                    msg = (TextMessage) message;
                    System.out.println("MESSAGE BEAN: Message received: " 
                        + msg.getText());
                } else {
                    System.out.println("Message of wrong type: " 
                        + message.getClass().getName());
                }
            } catch (JMSException e) {
                e.printStackTrace();
                       } catch (Throwable te) {
                te.printStackTrace();
            }
            }
}

9. Open the ejb-jar.xml and have the following entries

<?xml version = '1.0' encoding = 'windows-1252'?>
<ejb-jar 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/ejb-jar_2_1.xsd" version="2.1" xmlns="http://java.sun.com/xml/ns/j2ee">
  <enterprise-beans>
    <message-driven>
      <description>Message Driven Bean</description>
      <display-name>MessageDrivenEJB</display-name>
      <ejb-name>MessageDrivenEJB</ejb-name>
      <ejb-class>mdbaq.MessageDrivenEJBBean</ejb-class>
      <messaging-type>javax.jms.MessageListener</messaging-type>
      <transaction-type>Container</transaction-type>
      <message-destination-type>
javax.jms.Queue
</message-destination-type>
    </message-driven>
  </enterprise-beans>
  <assembly-descriptor/>
</ejb-jar>

Open the orion-ejb-jar.xml file

<?xml version = '1.0' encoding = 'windows-1252'?>
<orion-ejb-jar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://xmlns.oracle.com/oracleas/schema/orion-ejb-jar-10_0.xsd" schema-major-version="10" schema-minor-version="0">
    <enterprise-beans>
        <message-driven-deployment name="MessageDrivenEJB"
                                   connection-factory-location="TEST_AQ/QueueCF"
                                   destination-location="TEST_AQ/MyQueue/Queues/MYQUEUE"/>
    </enterprise-beans>
</orion-ejb-jar>

11. Create a simple Servlet to send the message to the Queue

package mdbaq;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.jms.* ;
import javax.jms.Queue;
import javax.naming.*;
import java.util.* ;
public class HelloWorld extends HttpServlet {
Queue queue;
QueueSession queueSession;
QueueSender queueSender;
Context jndiContext = null;
QueueConnectionFactory queueConnectionFactory = null;
QueueConnection queueConnection = null;
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>Hello MDB </TITLE></HEAD>");
out.println("<BODY>");
try {
TextMessage message = queueSession.createTextMessage();
message.setText(req.getParameter("subject"));
queueSender.send(message);
queueSession.commit();
} catch (JMSException e) { System.out.println("Exception occurred: " +e.toString());}
out.println("<H3> " + req.getParameter("subject") +" Message Sent .....</H3>");
out.println("</BODY></HTML>");
}
public void init(ServletConfig config) throws ServletException
{
super.init(config);
try {
jndiContext = new InitialContext();
queueConnectionFactory = (QueueConnectionFactory) jndiContext.lookup("CommonConnectionFactory");
queue = (Queue)jndiContext.lookup("TestQueue");
} catch (NamingException e)
{ System.out.println("Exception occurred: " + e.toString()); }
try {
queueConnection = queueConnectionFactory.createQueueConnection("jmsuser","jmsuser");
queueSession= queueConnection.createQueueSession(true,Session.AUTO_ACKNOWLEDGE);
queueSender = queueSession.createSender(queue);
queueConnection.start();
} catch (JMSException e) {System.out.println("Exception occurred: " + e.toString());}
}
}

12. The web.xml
Add the following entries to the web.xml file

<resource-ref>
<res-ref-name>CommonConnectionFactory</res-ref-name>
<res-type>javax.jms.QueueConnectionFactory</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
    </resource-ref>
    <message-destination-ref>
        <description></description>
        <message-destination-ref-name>TestQueue</message-destination-ref-name>
<message-destination-type>javax.jms.Queue</message-destination-type>
<message-destination-usage>Produces</message-destination-usage>
<message-destination-link>TestQueue</message-destination-link>
    </message-destination-ref>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list> 

<?xml version="1.0"?>
<orion-web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://xmlns.oracle.com/oracleas/schema/orion-web-10_0.xsd"  deployment-version="10.1.3.3.0"
deployment-time="1205407531953"
jsp-cache-directory="./persistence"
jsp-cache-tlds="standard"
temporary-directory="./temp"
servlet-webdir="/servlet/"
context-root="/aq"
schema-major-version="10" schema-minor-version="0" >
<resource-ref-mapping location="TEST_AQ/QueueCF" name="CommonConnectionFactory">
</resource-ref-mapping>
<message-destination-ref-mapping name="TestQueue" location="TEST_AQ/MyQueue/Queues/MYQUEUE" />
<web-app>
</web-app>
</orion-web-app>

14. Create a simple index.html to invoke the Servlet that sends the message to the AQ.

<html>
<head>
</head>
<body>
<form action="helloworld">
<b>Subject: </b><input type="text" name="subject"><br>
<input type="submit" value="Log">
</form>
</body>
</html>

Configuring the Sample Code

use Jdeveloper to open the project

Running the Sample Code

Run the URL http://xxx.xx.oracle.com:8888/aq/helloworld?subject=test123

Sample Code Output

08/03/13 18:50:44 Received message: oracle.j2ee.ra.jms.generic.TextMessageWrapper@bb5e2d
08/03/13 18:50:44 MESSAGE BEAN: Message received: test123

Sunday, February 01, 2009

Ravi Reddy Test Blog

Ravi Reddy
Test 123