Monday, October 21, 2013

Java based Google Driving Direction

Pulling information from Google Today i create a desktop application which used previous post information to utilize the Google Map. In this application i get the same information in my application which you see on google map to find driving direction.




Here is the code which is used to grab all this information from Google into your application
First you need to download the html parser API which used in this application download Parser


---------------------------- start Mydirection class-----------------------------------
import java.awt.Color;
import java.awt.TextArea;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.tags.Div;
import org.htmlparser.tags.TableColumn;
import org.htmlparser.util.NodeList;

public class Mydirection
{
  String Latitude;
  String Longitude;
  String Loc1;
  String Loc2;

  public void FindDirection(String startloc, String endloc, String type)
  {
    try
    {
      startloc = startloc.replaceAll(" ", "+");
      endloc = endloc.replaceAll(" ", "+");

      String html = ReadHTML(startloc, endloc);

      Parser p = new Parser();
      p.setInputHTML(html);

      Parser p2 = new Parser();
      p2.setInputHTML(html);

      Parser p3 = new Parser();
      p3.setInputHTML(html);

      NodeFilter[] Filter = { new NodeClassFilter(TableColumn.class),
        new HasAttributeFilter("class", "ddptlnk noprint") };

      AndFilter af = new AndFilter(Filter);
      NodeList page = p.parse(af);

      NodeFilter[] Filter2 = { new NodeClassFilter(Div.class),
        new HasAttributeFilter("id", "sxdist") };

      AndFilter af2 = new AndFilter(Filter2);
      NodeList page2 = p2.parse(af2);

      if (type == "byName")
      {
        this.Loc1 = startloc;
        this.Loc2 = endloc;

        if (page2.size() == 0)
        {
          String startlatlong = findLatLong(startloc);

          String endlatlong = findLatLong(endloc);

          FindDirection(startlatlong, endlatlong, "byLatLong");
        }
      }
      String des = "";
      NodeFilter[] Filter3 = { new NodeClassFilter(Div.class),
        new HasAttributeFilter("class", "dir_snp") };

      AndFilter af3 = new AndFilter(Filter3);
      NodeList page3 = p3.parse(af3);
      if (page3.size() > 0) {
        Node as3 = page3.elementAt(0);
        des = as3.getNextSibling().toPlainTextString();
        des = des.replaceAll("x26#160;", " ");
      }

      ServerGUI2.TA.setText("");

      String start = this.Loc1.toUpperCase();
      String end = this.Loc2.toUpperCase();

      start = replacePluse(start);
      end = replacePluse(end);

      findLatLong(this.Loc1);
      double lat1 = Double.parseDouble(getLatitude());
      double lon1 = Double.parseDouble(getLongitude());

      findLatLong(this.Loc2);
      double lat2 = Double.parseDouble(getLatitude());
      double lon2 = Double.parseDouble(getLongitude());

      double AreaDis = getDistByHaversine(lat1, lon1, lat2, lon2, "km");
      DecimalFormat dec = new DecimalFormat("###.##");

      ServerGUI2.TA.setForeground(Color.BLACK.darker());
      ServerGUI2.TA.append("\t Driving directions from " + start + " to " + end + ": \n ");
      ServerGUI2.TA.append("\t Areal Distance:" + dec.format(AreaDis) + "  Driving Distance: " + des + "\n \n");

      ServerGUI2.TA.setForeground(Color.blue);

      if (page.size() > 0) {
        int increment = 1;
        for (int i = 0; i < page.size(); ++i) {
          Node as = page.elementAt(i);
          Node as2 = page2.elementAt(i);

          String distance = as2.toPlainTextString();
          distance = distance.replaceAll("x26#160;", " ");
          ServerGUI2.TA.append(increment + ": " +
            as.toPlainTextString() + " \t (" + distance + ") \n");

          ++increment;
        }
      } else {
        ServerGUI2.TA.setForeground(Color.red);
        ServerGUI2.TA.setText("");
        ServerGUI2.TA
          .append("\n \n Ohhhh Sorry i am not aware from this Location! \n");
      }
    }
    catch (Exception y)
    {
      y.printStackTrace();
    }
  }

  public String replacePluse(String ch)
  {
    CharSequence inputStr = ch;
    String patternStr = "\\+";
    String replacementStr = " ";

    Pattern pattern = Pattern.compile(patternStr);

    Matcher matcher = pattern.matcher(inputStr);
    String res = matcher.replaceAll(replacementStr);

    return res;
  }

  public String ReadHTML(String Startloc, String Endloc)
  {
    StringBuffer bf = new StringBuffer();
    Writer output = null;
    String output1 = "";
    try
    {
      String url = "http://www.google.com/mapmaker?hl=en&ctype=0&saddr=" +
        Startloc +
        "&daddr=" +
        Endloc +
        "&dirflg=&gw=56&ll=28.185932,70.704924&spn=8.824988,20.566406&z=6";

      URL urlcon = new URL(url);
      HttpURLConnection uc = (HttpURLConnection)urlcon.openConnection();

      BufferedReader in = new BufferedReader(
        new InputStreamReader(uc.getInputStream()));
      String inputLine;
      while ((inputLine = in.readLine()) != null)
      {
        String inputLine;
        bf.append(inputLine + "\n");
      }
      in.close();

      String st = bf.toString();
      byte[] b = st.getBytes();
      StringBuilder sss = new StringBuilder();
      for (int i = 0; i < b.length; ++i) {
        if (b[i] == 92)
          b[i] = 0;
        else {
          sss.append((char)b[i]);
        }
      }
      String res = sss.toString();

      CharSequence inputStr = res;
      String patternStr = "x3c";
      String replacementStr = "<";

      Pattern pattern = Pattern.compile(patternStr);

      Matcher matcher = pattern.matcher(inputStr);
      output1 = matcher.replaceAll(replacementStr);

      output1 = output1.replaceAll("x3e", ">");
    }
    catch (Exception t) {
      t.printStackTrace();
    }
    return output1;
  }

  public String findLatLong(String City)
  {
    String locLatlong = "";
    try
    {
      City = City.replaceAll(" ", "+");

      String url = "http://maps.google.com/maps/geo?q=" +
        City +
        "&+output=xml&oe=utf8\"" +
        "&sensor=true&key=ABQIAAAAVu6FLnwHDZ7nt0cmZfpnmRQVl2aZopxmRHQArsVnI0wW3Lv2qhQYvEEjT-yKshCHcutI9eBuDiqrIQ";

      URL urlcon = new URL(url);
      HttpURLConnection uc = (HttpURLConnection)urlcon.openConnection();

      BufferedReader in = new BufferedReader(
        new InputStreamReader(uc.getInputStream()));

      StringBuffer bf = new StringBuffer();
      String inputLine;
      while ((inputLine = in.readLine()) != null)
      {
        String inputLine;
        bf.append(inputLine + "\n");
      }
      in.close();

      StringTokenizer st = new StringTokenizer(bf.toString());
      while (st.hasMoreTokens())
        if (st.nextToken().startsWith("\"coordinates\"")) {
          st.nextToken();
          setLongitude(st.nextToken().replaceAll(",", ""));
          setLatitude(st.nextToken().replaceAll(",", ""));

          locLatlong = st.nextToken().replaceAll(",", "") + "," + st.nextToken().replaceAll(",", "");
        }
    }
    catch (Exception t)
    {
      t.printStackTrace();
    }
    return locLatlong;
  }

  public String getLatitude()
  {
    return this.Latitude;
  }

  public void setLatitude(String latitude)
  {
    this.Latitude = latitude;
  }

  public String getLongitude()
  {
    return this.Longitude;
  }

  public void setLongitude(String longitude)
  {
    this.Longitude = longitude;
  }

  double getDistByHaversine(double lat1, double lon1, double lat2, double lon2, String unit)
  {
    double dLat = lat2 - lat1;
    double dLong = lon2 - lon1;

    double a = Math.sin(deg2rad(dLat / 2.0D)) *
      Math.sin(deg2rad(dLat / 2.0D)) +
      Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
      Math.sin(deg2rad(dLong / 2.0D)) *
      Math.sin(deg2rad(dLong / 2.0D));

    double c = 2.0D * Math.atan2(Math.sqrt(a), Math.sqrt(1.0D - a));

    return 6378.6999999999998D * c;
  }

  private double deg2rad(double deg)
  {
    return deg * 3.141592653589793D / 180.0D;
  }

  private double rad2deg(double rad)
  {
    return rad * 180.0D / 3.141592653589793D;
  }
---------------------------- End Mydirection class-----------------------------------


---------------------------- start ServerGUI2 class-----------------------------------
import java.awt.Color;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;

class ServerGUI2 extends Frame
  implements ActionListener
{
  JButton exitButton;
  JButton connectButton;
  JButton okButton;
  static TextArea TA;
  private JTextField start;
  private JTextField end;
  Label l1;
  Label l2;
  JLabel hint;

  public ServerGUI2()
  {
    this.connectButton = new JButton(" Find ");
    this.connectButton.setBounds(130, 200, 90, 30);
    add(this.connectButton);
    this.connectButton.addActionListener(this);

    this.exitButton = new JButton(" Close ");
    this.exitButton.setBounds(240, 200, 90, 30);
    add(this.exitButton);
    this.exitButton.addActionListener(this);

    this.l1 = new Label("Starting Location");
    this.l2 = new Label("Ending Location");

    this.l1.setBounds(20, 60, 110, 25);
    this.l2.setBounds(20, 95, 100, 25);

    this.start = new JTextField("street city,proviance");
    this.end = new JTextField("street city,proviance");


// you can use any image or animation if need, set if required
    URL myurl = super.getClass().getResource("/beancar.gif");

    ImageIcon icon = new ImageIcon(myurl,
      "a pretty but meaningless splat");

    this.hint = new JLabel("Image and Text", icon, 0);
    this.hint = new JLabel(icon);

    this.hint.setBounds(470, 40, 140, 110);
    add(this.hint);
    this.hint.hide();

    this.start.setBounds(140, 60, 200, 25);
    this.end.setBounds(140, 90, 200, 25);
    add(this.l1);
    add(this.l2);

    add(this.start);
    add(this.end);

    setBackground(Color.lightGray);
    setLayout(null);
    setSize(700, 580);
    setTitle("You Never Lost");

    TA = new TextArea("", 10, 30);
    TA.setBounds(90, 250, 550, 310);
    add(TA);
    TA.disable();
  }

  public void actionPerformed(ActionEvent ae)
  {
    String str = ae.getActionCommand();

    if (str.equals(" Find ")) {
      String startloc = this.start.getText();
      String endloc = this.end.getText();
      Mydirection ob = new Mydirection();

      ob.FindDirection(startloc, endloc, "byName");
      this.hint.show();
      TA.enable();
    }

    if (str.equals(" Close "))
      System.exit(0);
  }
}

---------------------------- End ServerGUI2 class-----------------------------------


and last simple runner class..


---------------------------- End DirectionGUI  class-----------------------------------  
 public class DirectionGUI 
{
  public static void main(String[] args)
  {
    ServerGUI2 serverGUI = new ServerGUI2();
    serverGUI.show();
  }
}



---------------------------- End DirectionGUI  class-----------------------------------


If you using any editor like Eclipse simple create these classes and run the application using DirectionGUI class, A new Frame will open and you put your starting and ending point and press button and see the results in your application.

Thanks

How to find distance b/w two points

You are normally using Google map to find the distance b/w any two points of any location



If you need such a information from code then try the below code.
In my another blog i already show you how to find the Latitude and Longitude of any point so Reusing the previous information we again create a Java based solution to find the distance.

I write a code to implement the Haversine formula which is an equation important in navigation, Giving great-circle distances between two points on a sphere from their longitudes and latitudes. It is a special case of a more general formula in spherical trigonometry, the law of Haversines, relating the sides and angles of spherical "triangles".

Below is the code of implementing the formula

----------------------------------------- start code ----------------------------------------------------------------------

  double getDistByHaversine(double lat1, double lon1, double lat2, double lon2, String unit)
    {
        double dLat  =lat2 - lat1;// -2.20306276 = -1.10153138
        double dLong = lon2 - lon1;// 1.28540039
   
        double a =Math.sin(this.deg2rad(dLat/2)) * Math.sin(this.deg2rad(dLat/2)) + Math.cos(this.deg2rad(lat1)) * Math.cos(this.deg2rad(lat2)) * Math.sin(this.deg2rad(dLong/2)) * Math.sin(this.deg2rad(dLong/2));// -0.01922417 * -0.01922417 + 0.83214027 * 0.85284337 * 0.01121700 * 0.01121700 = 0.00036957 + 0.00008929 = 0.00045886
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));// = 2 * atan2(0.02142102,0.99977054) = 2 * 0.021422658624589 = 0.04284532
   
        return 6378.7*c;  //= 273.29742514 kms from ibd to lhr
    }


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

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


 public static void main(String a[])
    {
 TestDistance ob=new TestDistance();

// find the latitude and longitude from first example
 System.out.println(ob.getDistByHaversine(Double.parseDouble("32.9697"), Double.parseDouble("-96.80322"), Double.parseDouble("29.46786"), Double.parseDouble("-98.53506"), "K") + " km\n");

---------------------------------------- End code -------------------------------------------------------------------------- 

Enjoy Google with JAVA.

How to read Latitude/Longitude from Google of any point

Today i share a trick by which we can get the latitude and longitude of any point directly from Google map.

JNDI DataSource in Spring

There are several ways to configure JNDI based data source in Spring. The following steps explains the JBoss JNDI data-source implementation in spring.I just showing quick way tutorial which save your time and brain :)

Open the mssql-ds.xml file from your JBoss deployment directory(D:\APP_servers\jboss-4.2.0.GA\server\default\deploy).
if file not exist simply create the xml file with that name. the contents inside the file are simple like


Now come to Spring configuration file,I create the hibernate Session Factory bean which required data-source so my spring configuration some thing look like that



So this is very simple way to define and use of JNDI DS in spring. 

Thanks



How display images in jsp which are outside the web container

This post not related to any Java framework but general web programming using simple jsp and servlet.
Yesterday my friend having a problem, he have different images path in database and he want to show these images which are actually outside the web container (not in image folder of project but on system location ex: /user/home/image).
Here is the code that how we can display images on jsp page.

Now suppose image Path in your database are like user/home/images/mypic.jpg or in windows D:/images/ mypic.jpg

step1: First create the Servlet in your project which containing the code like this one


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class DisplayImage
 */
public class DisplayImage extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * Default constructor.
     */
    public DisplayImage() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try{
            String imagePath=request.getParameter("img");

            response.setContentType("image/gif");

            File f = new File(imagePath);
            FileInputStream fin = new FileInputStream(f);
            byte[] buffer = new byte[fin.available()]; 
            fin.read(buffer);
            fin.close();
            OutputStream o = response.getOutputStream();
            o.write(buffer);

            o.flush();
            o.close();
            }
            catch(Exception e)
            {
            e.printStackTrace();
            }    
}
          }
  

Step2: Now when you read the jpg file path in other servlet or in you controller just forward the response on any jsp which showing all the images.
In your jsp if you want to show multiple images just create a loop on array or list and use this HTML img tag to show the images

<img alt="My img" src="<%=request.getContextPath()%>/DisplayImage?img=<%=yourPathFromDB%>"></img>


When this jsp is called directly or when control come to this it will call the DisplayImage servet which show the response simply because we set the response Content Type image/gif.

Enjoy..