June 23, 2014

Working with JSTL inside Java Spring application

How to use Java Standard Tag Library in Java Spring Application


Description : JSTL provides functionality to Java Sever Page, You can replace JSTL forJSP tags. Date format, internationalization are main facilities of JSTL. You need to download and add JSTL-version.jar file to run the code. This post will explains you how to jstl in your java web application.

Inside html (your jsp page)
first you need to add the following taglib (to include jstl function to your jsp page)

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>


To display jstl value use the follwing code

<div id="jstlExampleId" class="JSTL example"><a href="events.html"> JSTL </a><a href="trivenimap.html"> Java server pages    </a> <a href="trivenimap.html"> ${unit.unitName}    </a></div>


Installing jstl to your project :

copy and paste jstl-version.jar (say jstl-1.2.jar) to Webapp/WEB-INF/lib folder in your application. Only thing you have to ensure that you have no duplicates/older version of jstl jar file in your classpath

Software Requirements :

servlet container 2.5 or above, Tomcat 6.0 or above

Java bean class (Model class) : TriveniUnit.java

public class TriveniUnit {

private String unitName = "Java Spring Jstl example";
    public String getUnitName() {
        return unitName;
    }
    public void setUnitName(String unitName) {
        this.unitName = unitName;
    }

}


Create a controller class and add the following code. returning triveniUnit object to JSP page as Modelandview object. Here the model name is unit so you need to call all jstl value in the name of unit
see ${unit.unitName}
 in jsp page. This is called Expression Language  ${}

@Controller
public class ContactController {

    @RequestMapping(value = "/trivenimap", method = RequestMethod.GET)
    public ModelAndView triveniMaps() {
        System.out.println(" Java JSP Spring Java Standard Tag Library Example ");
        TriveniUnit triveniUnit = new TriveniUnit();
       return new ModelAndView("triveniMap" , "unit", triveniUnit);
     }

}


project structure


Please provide your feedback

http://javabelazy.blogspot.in/

June 13, 2014

Security system :Motion Detection System in java

Motion detection system in java : alert when any one pass before system camera

Description : This is a small example for security system in java which send alert through mail and sound while any trespassers pass before your camera connected to system (computer). The program is developed in java media framework. You need jmf.jar and mds.jar to run that code. For sending mail using java mail service application you need to download mail.jar file. The project consist of only 3 packages. Only you have to do is to create a java application in eclipse. copy and paste the following code to your project. compile it and run. Make sure you had added all the jar files to your project. Create a javasecurityalert wave file. Please provide your feed back through comments. Please rate the post.



MainFrame.java
package com.mds.frames;
import java.awt.Container;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import com.mds.serv.AePlayWave;
import com.mds.serv.AlarmSound;
import com.mds.serv.ImageCompare;
import com.mds.serv.MDSMailer;
import com.mds.serv.SwingCapture;
public class MainFrame extends JFrame implements Runnable {
private static final long serialVersionUID = 1L;
    private java.awt.Container c = null;
    private com.mds.serv.SwingCapture sc = null;
    private JPanel videoPanel = null;
    private Image refImg = null;
    private Image currentImg = null;
    private File saveImgDir = null;
    private ImageCompare imc = null;
    private AlarmSound as = null;
    private static boolean alarm = true;
    private AePlayWave playWave = null;
    private Thread t2 = null;
    private Thread t1 = null;
    private JButton captureButton = null;
    private static int num = 0;
    private File saveCaptureDir = null;
    private Thread t3 = null;
    private JButton imgSet = null;
    private JButton start = null;
    private JFileChooser jf = null;
    private Thread mainThread = null;
    private JButton stop = null;
   /**
     * This is the default constructor
     */
    public MainFrame() {
        super();
        initialize();
    }
  /**
     * This method initializes this
     *
     * @return void
     */
    private void initialize() {
        this.setSize(900, 550);
        this.setContentPane(getContainer());
        this.setTitle("Motion Detection System");
        this.addWindowListener(new WindowAdapter()
        {
            @Override
            public void windowClosing(WindowEvent e)
            {
//                playerclose();
                System.exit(0);
            }
        });
      
    }
  
    private Container getContainer()
    {
        c = new Container();
       imgSet = new JButton();
        imgSet.setText("Set Reference Image");
        imgSet.setBounds(680,180,200,25);
        imgSet.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                videoPanel.setEnabled(true);
                refImg = sc.imageCapture();
//                sc.saveJPG(refImg, s)
            }
        });
        c.add(imgSet);
      
        jf = new JFileChooser();
        start = new JButton("Start Detection");
        start.setBounds(680,230,200,25);
        start.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                saveImgDir = chooseSaveImgDir().getParentFile();
                if(refImg!=null)
                {
                    if(mainThread == null)
                    {
                        startNewThread();
//                        System.out.println("MainThread Started");
                    }
                    else if(mainThread.isAlive())
                        mainThread.resume();
                }
                else
                    showDialog("Set Reference Image");
              
            }
        });
        c.add(start);
      
        stop = new JButton("Stop");
        stop.setBounds(680,280,200,25);
        stop.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                try {
                  
//                    if(mainThread == null)
                    if(mainThread.isAlive())
                        mainThread.suspend();
                  
                } catch(NullPointerException e1) {
                    showDialog("Detection Not Started Yet");
                }
              
            }
        });
        c.add(stop);
      
        sc = new SwingCapture();
        videoPanel = sc.getPlayerPanel();
        videoPanel.setEnabled(false);
        c.add(videoPanel);

        playWave = new AePlayWave("alarm.wav");
        t2 = new Thread(playWave);
          
      
        try {
            Thread.sleep(10000);
//            refImg = sc.imageCapture();
//            sc.saveJPG(currentImg, "D:\\Backups\\Saved\\img.jpg");
//            sc.saveJPG(refImg, "c:\\RefImg.jpg");
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
      
        captureButton = new JButton();
        captureButton.setText("Capture Frame");
        captureButton.setBounds(680,330,200,25);
        captureButton.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e)
                {
                    saveCaptureDir = chooseSaveImgDir();
                    System.out.println(saveCaptureDir.getAbsolutePath()+saveCaptureDir.getName());
//                    if(!saveCaptureDir.exists())
//                        saveCaptureDir.mkdirs();
                    SwingCapture.saveJPG(sc.imageCapture(),saveCaptureDir.getAbsolutePath());
                    num++;
                }
          
        });
        c.add(captureButton);      
        return c;
      
    }
  
    private void startNewThread()
    {
        mainThread = new Thread(this);
        mainThread.start();
    }
  
    private void showDialog(String message)
    {
        JOptionPane.showMessageDialog(this, message);
    }
  
    private File chooseSaveImgDir()
    {
        File file = null;
        if(jf.showSaveDialog(this)==JFileChooser.APPROVE_OPTION)
        {
            file = jf.getSelectedFile();
//            System.out.println(saveImgDir.getName());
        }
        return file;

    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        int i =0;
//        saveImgDir = new File("D:\\Backups\\Saved");
        if(saveImgDir==null)
        {
            chooseSaveImgDir();
        }
//        if(!saveImgDir.exists())
//            saveImgDir.mkdirs();
        while(true)
        {
            try {
//                Thread.sleep(250);
                currentImg = sc.imageCapture();
                imc = new ImageCompare(refImg,currentImg);
//                t3 = new Thread(imc);
//                t3.run();
                if(!imc.compare())
                {
                  
                    System.out.println("hi");
                    t2.run();
                    SwingCapture.saveJPG(currentImg, saveImgDir+"\\img"+i+".jpg");
                    MDSMailer m = new MDSMailer(saveImgDir+"\\img"+i+".jpg");
                    t3 = new Thread(m);
                    t3.start();
                    refImg = currentImg;
                }
              
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            i++;
        }
    }

  
    public static void main(String[] args) {
      
        MainFrame m = new MainFrame();
        m.setVisible(true);
//        Thread t = new Thread(m);
//        t.start();
    }
  

}

-------------------------------------
LoginFrame.java


package com.mds.frames;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
public class LoginFrame extends JFrame {
    private static final long serialVersionUID = 1L;
    private JPanel jContentPane = null;
    private JLabel NameLabel = null;
    private JLabel PassLabel = null;
    private JTextField NameTextField = null;
    private JPasswordField PasswordField = null;
    private JButton LoginButton = null;
    private JButton ClearButton = null;
    /**
     * This is the default constructor
     */
    public LoginFrame() {
        super();
        initialize();
    }
    /**
     * This method initializes this
     *
     * @return void
     */
    private void initialize() {
        this.setSize(500, 400);
        this.setContentPane(getJContentPane());
       
        this.setTitle("Login");
    }
    /**
     * This method initializes jContentPane
     *
     * @return javax.swing.JPanel
     */
    private JPanel getJContentPane() {
        if (jContentPane == null) {
            PassLabel = new JLabel();
            PassLabel.setBounds(new Rectangle(75, 170, 100, 30));
            PassLabel.setText("Password : ");
            NameLabel = new JLabel();
            NameLabel.setBounds(new Rectangle(75, 120, 100, 30));
            NameLabel.setText("Name : ");
            jContentPane = new JPanel();
            jContentPane.setLayout(null);
            jContentPane.add(NameLabel, null);
            jContentPane.add(PassLabel, null);
            jContentPane.add(getNameTextField(), null);
            jContentPane.add(getPasswordField(), null);
            jContentPane.add(getLoginButton(), null);
            jContentPane.add(getClearButton(), null);
           
        }
        return jContentPane;
    }
    /**
     * This method initializes NameTextField   
     *    
     * @return javax.swing.JTextField   
     */
    private JTextField getNameTextField() {
        if (NameTextField == null) {
            NameTextField = new JTextField();
            NameTextField.setBounds(new Rectangle(225, 120, 180, 30));
        }
        return NameTextField;
    }
    /**
     * This method initializes PasswordField   
     *    
     * @return javax.swing.JPasswordField   
     */
    private JPasswordField getPasswordField() {
        if (PasswordField == null) {
            PasswordField = new JPasswordField();
            PasswordField.setBounds(new Rectangle(225, 170, 180, 30));
        }
        return PasswordField;
    }
    /**
     * This method initializes LoginButton   
     *    
     * @return javax.swing.JButton   
     */
    private JButton getLoginButton() {
        if (LoginButton == null) {
            LoginButton = new JButton();
            LoginButton.setBounds(new Rectangle(140, 230, 80, 25));
            LoginButton.setText("Login");
            LoginButton.addActionListener(new ActionListener () {
                public void actionPerformed(ActionEvent e) {
                   
                   
                    if(NameTextField.getText().compareTo("admin")==0)
                    {
//                        System.out.println("clicked");
                        if(String.valueOf(PasswordField.getPassword()).equals("mds"))
                        {
                       
                            MainFrame m = new MainFrame();
//                            m.setBounds(0,0,900,600);
                            m.setVisible(true);
                            closeWindow();
                        }
                        else
                            showMessageDialog("Invalid Username or Password");
                    }
               
                }
            });
        }
        return LoginButton;
    }
   
    private void showMessageDialog(String message)
    {
        JOptionPane.showMessageDialog(this, message);
    }
   
    private void closeWindow()
    {
        setVisible(false);
        dispose();
    }
   

    /**
     * This method initializes ClearButton   
     *    
     * @return javax.swing.JButton   
     */
    private JButton getClearButton() {
        if (ClearButton == null) {
            ClearButton = new JButton();
            ClearButton.setBounds(new Rectangle(240, 230, 80, 25));
            ClearButton.setText("Clear");
            ClearButton.addActionListener(new ActionListener () {
                public void actionPerformed(ActionEvent e) {
                    NameTextField.setText("");
                    PasswordField.setText("");
                }
            });
        }
       
        return ClearButton;
    }
   
    public static void main(String[] args) {
       
        LoginFrame l = new LoginFrame();
        l.setVisible(true);
    }}

-------------------

June 05, 2014

Multiple Marker on Google Map

Google Map to view multiple marker example


Description :How to add google map to your java application: To view multiple markers on same google map. while clicking on the marker, the details of that branch will be shown in a separate div. The website can be useful for large business firms to show their branches. The first 3 line of code is of java spring ( No need of it for google map). Here we use simple google map marker instead of complex one.

the css for the html page is shown below (javasourcecode.css)

You can see a combo box on the google map, currently that feature won t work, working code for that will be updated shortly. The location details can be added through json object, using jquery and ajax will smooth-en your code.

Java Google Map multiple marker apps
Google map with multiple marker

jquery google map maker in java web application


<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title> Who will be the winner of football world cup 2014 </title>
      <link href="css/javasourcecode.css" rel="stylesheet" type="text/css" />

  <script src="http://maps.google.com/maps/api/js?sensor=false"></script>
  <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.1.min.js"></script>
  <script type="text/javascript" src="js/units.js"></script>
<script>


function initialize() {
  var mapOptions = {
    zoom: 11,
    center: new google.maps.LatLng(1.319154,5.918564)
  }
  var map = new google.maps.Map(document.getElementById('map-canvas'),
                                mapOptions);

  setMarkers(map, beaches);
}
var infowindow = new google.maps.InfoWindow({
    maxWidth: 160
  });
// get javascript object here pass it to beach
//var triveniUnits = getUnits();
//alert(' Winner : '+triveniUnits.length);
var beaches = [
  ['Brazil', 1.253069,5.78281,'images/worldcup.png',4],
  ['Argentina', 1.291158,75.74415,'images/worldcup.png',5],
  ['Belgium', 1.273474,5.774783,'images/worldcup.png',3],
  ['Spain', 1.294241,5.815177,'images/worldcup.png',2],
  ['England ', 1.305014,5.876385,'images/worldcup.png',1]
];

function setMarkers(map, locations) {
  var markers = new Array();
  var marker;
  for (var i = 0; i < locations.length; i++) {
    var beach = locations[i];
    var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
        marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
title: beach[0],
        //zIndex: beach[3]
    });
        markers.push(marker);
     
google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {
            //var infoWinwhtml = '<div id="infowindow" style="width:320px; height:200px;" ><H4>'+locations[i][0]+'</H4></br><p><img src="'+locations[i][3]+'" alt="World cup football 2014"></p></div>';
             //infowindow.setContent(locations[i][0]);
             var infoWinwhtml = '<div id="infowindow"><H4>'+locations[i][0]+'</H4></div>';
             infowindow.setContent(infoWinwhtml);
             var infoHtml = '<div  class="triveniInfo"><H4>'+locations[i][0]+'</H4></br><p><img src="'+locations[i][3]+'" alt="Triveni Image"><h6> Distance : 200km </h6></p></div>';
              marker.setAnimation(google.maps.Animation.BOUNCE);
              infowindow.open(map, marker);
              var sidediv = document.getElementById('content-window');
              sidediv.innerHTML = infoHtml;
            }
          })(marker, i));
  }
}

google.maps.event.addDomListener(window, 'load', initialize);

    </script>
  </head>
  <body>
  <div id="headerId" class="header">
<div id="logo" class="logos"><img src="images/worldcupLogo.jpg" alt="cfed Logo"></div>
<h1> How to integrate Google map features in java spring source code</h1>
<div id="menuTabsId" class="menuTabs"><a href="worldcupEvents.html"> event</a><a href="worldcupmap.html"> view map </a></div>

</div>
  <div id="panel">
  <b>Select: </b>
    <select id="worldcup football" onchange="calcRoute();">
      <option value="worldcup">Belgium</option>
      <option value="st louis, mo">Germany</option>
      <option value="joplin, mo">Spain</option>
      <option value="oklahoma city, ok">England</option>
      <option value="amarillo, tx">Brazil</option>
</select>
  </div>
    <div id="map-canvas" style="width:80%; height:80%; float:left"></div>
    <div id="content-window" style="width:20%; height:80%; float:left"></div>

  <div id="footerId" class="footer">
http://nikzblog/</div>
  </body>
</html>

javasourcecode.css


/*External Cascading style sheet for the above html code*/


/* Google map css */

html, body, #map-canvas {
        height: 100%;
        margin: 0px;
        padding: 0px
}

#panel {
        position: absolute;
        top: 120px;
        left: 20%;
        margin-left: -180px;
        z-index: 5;
        background-color: #fff;
        padding: 5px;
        border: 1px solid #999;
}


/* Developed by shimjith kumar */
+Shimjith Kumar 

.logos{
    float: left;
}

.header{
    height:100px; 
    background-color: #EEEEEE;
}

.header h1{
    margin-bottom: 0;
    text-align: center;
}

.footer{
      background-color: #FFA500;
    height: 2%;
    clear: both;
    text-align: center;
}


.menuTabs{
    position:relative;
    top:0px;
    width:80px;
    height:20px;
    float:right;  
}


/*  external css design in java application */
.triveniInfo h4{
    text-align: center;
}
.triveniInfo p{
    text-align: center;
}

/* google map info window css design */
#infowindow h4{
    text-align: center;
}
#infowindow p{
    text-align: center;
}

Thanks for reading the code, Please provide your feedback through comments

author : +Shimjith


http://javabelazy.blogspot.in/

June 01, 2014

Facebook comments