Wednesday, February 22, 2012

GeoLocation - Distance between two Lat/Lons

public class Distance {

public static void main(String[] args) {
Distance d = new Distance();
System.out.println(d.distance(32.9697, -96.80322, 29.46786, -98.53506, 'M') +" Miles !!!");
System.out.println(d.distance(32.9697, -96.80322, 29.46786, -98.53506, 'K') +" KMs !!!");
System.out.println(d.distance(32.9697, -96.80322, 29.46786, -98.53506, 'N') +" Nautical Miles !!!");

}

//Calculate distance between two lat/lons in Miles, KMs, NMs.
private double distance(double lat1, double lon1, double lat2, double lon2, char unit) {
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2))
+ Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2))
* Math.cos(deg2rad(theta));

dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
if (unit == 'K') {
dist = dist * 1.609344;
} else if (unit == 'N') {
dist = dist * 0.8684;
}
return (dist);
}


// converts decimal degrees to radians
private double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}


// converts radians to decimal degrees
private double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}


}

Tuesday, February 21, 2012

JMX

With  eclipse 

  • go to Help > Software Updates > Find and Install...
  • check Search for new features to install and click Next >
  • click on New Remote Site...
  • in the New Update Site window, type:
  • click on OK
  • check eclipse-jmx and click on Finish
  • expand the features and select the latest one. Then click on Next >
  • check I accept the terms in the license agreement and click on Next >
  • click on Finish
  • once all the plug-ins are downloaded, click on Install All
  • finally, when ask to restart Eclipse, click on Yes

With JBOSS TOOL SET

JMS Architecture

Basic JMS API Concepts

This chapter introduces the most basic JMS API concepts, the ones you must know to get started writing simple JMS client applications:
  • JMS API architecture
  • Messaging domains
  • Message consumption
The next chapter introduces the JMS API programming model. Later chapters cover more advanced concepts, including the ones you need to write J2EETM applications that use message-driven beans.

2.1   JMS API Architecture

A JMS application is composed of the following parts.
  • JMS provider is a messaging system that implements the JMS interfaces and provides administrative and control features. An implementation of the J2EE platform at release 1.3 includes a JMS provider.
  • JMS clients are the programs or components, written in the JavaTM programming language, that produce and consume messages.
  • Messages are the objects that communicate information between JMS clients.
  • Administered objects are preconfigured JMS objects created by an administrator for the use of clients. 
  • Native clients are programs that use a messaging product's native client API instead of the JMS API. An application first created before the JMS API became available and subsequently modified is likely to include both JMS and native clients.
Figure 2.1 illustrates the way these parts interact. Administrative tools allow you to bind destinations and connection factories into a Java Naming and Directory InterfaceTM (JNDI) API namespace. A JMS client can then look up the administered objects in the namespace and then establish a logical connection to the same objects through the JMS provider.
 
Figure 2.1   JMS API Architecture

2.2   Messaging Domains

Before the JMS API existed, most messaging products supported either the point-to-point or the publish/subscribe approach to messaging. The JMS Specification provides a separate domain for each approach and defines compliance for each domain. A standalone JMS provider may implement one or both domains. A J2EE provider must implement both domains.
In fact, most current implementations of the JMS API provide support for both the point-to-point and the publish/subscribe domains, and some JMS clients combine the use of both domains in a single application. In this way, the JMS API has extended the power and flexibility of messaging products.

2.2.1   Point-to-Point Messaging Domain

A point-to-point (PTP) product or application is built around the concept of message queues, senders, and receivers. Each message is addressed to a specific queue, and receiving clients extract messages from the queue(s) established to hold their messages. Queues retain all messages sent to them until the messages are consumed or until the messages expire.
PTP messaging has the following characteristics and is illustrated in Figure 2.2.
 
Figure 2.2   Point-to-Point Messaging
  • Each message has only one consumer.
  • A sender and a receiver of a message have no timing dependencies. The receiver can fetch the message whether or not it was running when the client sent the message.
  • The receiver acknowledges the successful processing of a message.
Use PTP messaging when every message you send must be processed successfully by one consumer.

2.2.2   Publish/Subscribe Messaging Domain

In a publish/subscribe (pub/sub) product or application, clients address messages to a topic. Publishers and subscribers are generally anonymous and may dynamically publish or subscribe to the content hierarchy. The system takes care of distributing the messages arriving from a topic's multiple publishers to its multiple subscribers. Topics retain messages only as long as it takes to distribute them to current subscribers.
Pub/sub messaging has the following characteristics.
  • Each message may have multiple consumers.
  • Publishers and subscribers have a timing dependency. A client that subscribes to a topic can consume only messages published after the client has created a subscription, and the subscriber must continue to be active in order for it to consume messages.
The JMS API relaxes this timing dependency to some extent by allowing clients to create durable subscriptions. Durable subscriptions can receive messages sent while the subscribers are not active. Durable subscriptions provide the flexibility and reliability of queues but still allow clients to send messages to many recipients. For more information about durable subscriptions,  

Use pub/sub messaging when each message can be processed by zero, one, or many consumers. Figure 2.3 illustrates pub/sub messaging.
 
Figure 2.3   Publish/Subscribe Messaging

2.3   Message Consumption

Messaging products are inherently asynchronous in that no fundamental timing dependency exists between the production and the consumption of a message. However, the JMS Specification uses this term in a more precise sense. Messages can be consumed in either of two ways:
  • Synchronously. A subscriber or a receiver explicitly fetches the message from the destination by calling the receive method. The receive method can block until a message arrives or can time out if a message does not arrive within a specified time limit.
  • Asynchronously. A client can register a message listener with a consumer. A message listener is similar to an event listener. Whenever a message arrives at the destination, the JMS provider delivers the message by calling the listener's onMessage method, which acts on the contents of the message.



=========================================================================



JMS Parent
Publish-Subscribe Domain
Point-To-Point Domain
DestinationTopicQueue
ConnectionFactoryTopicConnectionFactoryQueueConnectionFactory
ConnectionTopicConnectionQueueConnection
SessionTopicSessionQueueSession
MessageProducerTopicPublisherQueueSender
MessageConsumerTopicSubscriberQueueReceiver, QueueBrowser
Table 1: Relationship of  Point-To-Point and Publish-Subscribe interfaces

Wednesday, January 18, 2012

Sowmya, Chandra Batch-1

Understanding the structure of web applications

Web Applications use a standard directory structure defined in the Servlet specification. When developing web applications on J2EE platform, you must follow this structure so that application can be deployed in any J2EE compliant web server. (Tomcat, Weblogic, Jboss, websphere etc.. )
A web application has the directory structureas shown in below figure.

J2EE Web Application Directory Structure
The root directory of the application is called the document root. Root directory is mapped to the context path. Root directory contains a directory named WEB-INF. Anything under the root directory excepting the WEB-INF directory is publically available, and can be accessed by URL from browser. WEB-INF directory is a private area of the web application, any files under WEB-INF directory cannot be accessed directly from browser by specifying the URL like http://somesite/WEB-INF/someresource.html. Web container will not serve the content of this directory. However the content of the WEB-INF directory is accessible by the classes within the application. So if there are any resources like JSPs or HTML document that you don’t wish to be accessible directly from web browser, you should place it under WEB-INF directory.

WEB-INF directory structure

WEB-INF directory contains
  • WEB-INF/web.xml deployment descriptor
  • WEB-INF/classes directory  --> all class files unders this folder loaded by tomcat sercer to memory
  • WEB-INF/lib directory

/WEB-INF/web.xml

web.xml is called the web application deployment descriptor. This is a XML file that defines servlets, servlet mappings, listeners, filters, welcome files etc. Deployment descriptor is a heart of any J2EE web application, so every web application must have a web.xml deployment descriptor directly under WEB-INF folder.

/WEB-INF/classes

The classes directory is used to store compiled servlet and other classes of the application. If your classes are organized into packages, the directory structure must be reflected directly under WEB-INF/classes directory. The classes directory is automatically included in CLASSPATH.

/WEB-INF/lib

Lib directory is used to store the jar files. If application has any bundled jar files, or if application uses any third party libraries such as log4j, JDBC drivers which is packaged in jar file, than these jar files should be placed in lib directory.
All unpacked classes and resources in the /WEB-INF/classes directory, plus classes and resources in JAR files under the /WEB-INF/lib directory are included in classpath and made visible to the containing web application.
There are many changes in Servlet 3.0 Specification, web.xml file is optional, servlets, listeners and filters are no longer required to be defined in web.xml, instead they can declared using annotations. web.xml file can be devided into multiple files called webfragments.
Note Directory and file names are case sensitive.
Simple Servlet example

  1. How to write the servlet class.
  2. How to compile the Servlet class
First of all we need to create the directory structure for our sample web application as explained in the above tutorial. Create the directory structure as shown in below figure.




package jsptube.tutorials.servletexample;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class WelcomeServlet extends HttpServlet {

@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

System.out.println("This is the frist Servlet ");


}


public void destroy() {

}
}

Now compile the servlet class as explained below.
Open the command prompt and change the directory to the servlet-example/WEB-INF/src/jsptub/tutorials/servletexample directory. Compile the WelcomeServlet.java using the following command. javac WelcomeServlet.java It will create the file WelcomeServlet.class in the same directory. Copy the class file to classes directory. All the Servlets and other classes used in a web application must be kept under WEB-INF/classes directory.
Note: to compile a servlet you need to have servlet-api.jar file in the class path.
The deployment descriptor (web.xml) file.
Copy the following code into web.xml file and save it directly under servlet-example/WEB-INF directory.

<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">
 
 <servlet>
  <servlet-name>WelcomeServlet</servlet-name>
  <servlet-class>jsptube.tutorials.servletexample.WelcomeServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>WelcomeServlet</servlet-name>
  <url-pattern>/WelcomeServlet</url-pattern>
 </servlet-mapping>
 <welcome-file-list>
  <welcome-file> /pages/form.html </welcome-file>
 </welcome-file-list>
</web-app>

Our sample application can be accessed at http://localhost:8080/Servlet-example/WelcomeServlet. If tomcat server is running on port other than 8080 than you need to change the URL accordingly.

Access the servlet from the HTML form SUBMIT button also.

write index.html as below

<html>
<body>
<form action="./WelcomeServlet" >

<input type="submit" value="Click me" />

</form>
</body>

1. open the index.html from the browser  ervlet-example/http://localhost:8080/Servlet-example/index.htmlindex.html
2. click on the Button, we will see that Servlet gets executed.
3. Tomcat console displasys the SOP that we have implemented in the doGET method.

Monday, December 19, 2011

How do I configure Weblogic Application server to connect to Postgres?

How do I connect to a Postgresql database from within an EJB using Weblogic server?
For some reason I spent many hours failing to get this to work before I finally cracked it. Here are the notes I made when I succeeded.
  1. The driver classes (postgresql.jar file) must be on the server CLASSPATH.
    For example, copy it to the WLHOME/ext directory, and edit the script WLHOME/config/mydomain/startWebLogic.cmd
    Append "./ext/postgresql.jar" to the CLASSPATH setting there.
  2. Start the WebLogic server for your domain.
  3. Create a JDBC Connection Pool which connects to the Postgres database, either by:
    1. ) Using the administrative console:
       - Configure a new JDBC Connection Pool
           - General tab:
        - Name: Any name you like for your pool (eg MyPoolName)
        - URL: jdbc:postgresql://hostname:port/database
          eg jdbc:postgresql://smirnoff.uk.ingenotech.com:5432/homepages
        - Driver Classname: org.postgresql.Driver
        - Properties: user=ed password=anything
        - ACL Name: (blank)
        - Password: The real password to connect to the database, this
                    will be kept encrypted and substituted for the value 
                    you put in "Properties".
              - Press "Create" 
          - Go to the "Targets" tab
              - Select "myserver" from the "Abailable" list and move it
                to "Chosen".  Apply.
        - Create a JDBC Data Source which references the Connection Pool above
          - Configure a new JDBC Data Source - Configuration Tab
            - Name: Any name you like (eg MyDataSource)
            - JNDI Name:  Make this the same as "Name" above (MyDataSource).
            - Pool Name: The name of the ConnectionPool created above (MyPoolName)
            - Press "Create" 
          - Go to the "Targets" tab
            - Select "myserver" from the "Available" list and move it
              to "Chosen".  Apply.
      

    2. ) or by using the command line as follows:
        java -cp {path to weblogic.jar} weblogic.Admin -url localhost:7001 \
             -username system -password password \
             CREATE_POOL .... TBD ....
      

    3. ) or, with the server stopped, edit the WLHOME/config/mydomain/config.xml file:
        - Add the following to create a connection pool:
          <JDBCConnectionPool DriverName="org.postgresql.Driver"
                                 MaxCapacity="10" 
                                 Name="MyPoolName"
                                 Password="{3DES}yIsebsUSRdE="
                                 Properties="user=ed;password=secret" 
                                 Targets="myserver"
                                 URL="jdbc:postgresql://hostname:port/database"/>
      
        - Add the following to create a Data Source referencing that pool:
          <JDBCDataSource JNDIName="MyDataSource" 
                             Name="MyDataSource" 
                             PoolName="MyPoolName" 
                             Targets="myserver"/>
      

  4. Define a reference to your Data Source in the EJB deployment descriptor files:
    In ejb-jar.xml within the section add:
    <resource-ref>
     <res-ref-name>jdbc/MyPoolName</res-ref-name> <!-- This is the name chosen for the Connection Pool with "jdbc/" prepended -->
     <res-type>javax.sql.DataSource</res-type>
            <res-auth>Container</res-auth>
          </resource-ref>
    

    In weblogic-ejb-jar.xml within the <weblogic-enterprise-bean> section add:
    <reference-descriptor>
          <resource-description>
            <res-ref-name>jdbc/MyPoolName</res-ref-name> <!-- This is the name chosen for the Connection Pool with "jdbc/" prepended -->
     <jndi-name>MyDataSource</jndi-name> <!-- this is the name you chose for the DataSource -->
          </resource-description>
        </reference-descriptor>
    
  5. In your bean or a suitable utility class, write a "getConnection()" method which returns a Connection object which you can then use in the usual way. This will do a JNDI lookup to find a javax.sql.DataSource object configured in your server and obtain a Connection from that. The name used to obtain your DataSource is, confusingly, not the JNDI name but the set above, beneath the java:comp/env hierarchy as follows:
    private Connection getConnection() throws NamingException
    {
        InitialContext ic = new InitialContext();
        DataSource ds = (DataSource)ic.lookup("java:comp/env/jdbc/MyPoolName");
        return ds.getConnection();
    }
    
  6. Here is an example of how to use your Connection "in the usual way"...
    Connection conn = null;
    PreparedStatement st = null;
    try
    {
        conn = getConnection();
        // Prepare your SQL statement, substitute "somevalue" for the first "?" parameter.
        st = conn.prepareStatement("SELECT COL1, COL2, COL3 FROM TABLENAME WHERE COL1 = ?");
        st.setString(1, somevalue);
    
        // Execute the SQL and read the rows returned
        ResultSet rs = st.executeQuery();
        while (rs.next())
        { // Read and process each row of the ResultSet
     String col1 = rs.getString(1);
     String col2 = rs.getString(2);
     String col3 = rs.getString(3);
     // etc...
        }
    }
    catch (SQLException ex)
    {
        System.out.println("SQL exception occurred" +ex);
    }
    finally
    {
        try
        {
     if (st != null)
         st.close();
        }
        catch (SQLException ex)
        {
        }
    
        try
        {
     if (conn != null)
         conn.close();
        }
        catch (SQLException ex)
        {
        }
    }