December 30, 2014

Java program to check a string is palindrome

How to check whether a string is palindrome

Palindorme in java source code : Palindrome are strings, that remains unchanged even when reversed for example "mom","malayalam",etc







import java.util.Scanner;

/**
 * Worldcup cricket 2015
 */

/**
 * @author Moto
 *
 */
public class Palindrome {

    /**
     * @param args
     */
    public static void main(String[] virat) {
        // TODO Auto-generated method stub
        Palindrome palindromeNumber = new Palindrome();
        palindromeNumber.checkPalindrome();

    }

    private void checkPaliandrome() {
        // TODO Auto-generated method stub
        String str = null;
        System.out.println(" Please enter the string that you want to check is that a paliandrome");
        Scanner scanner = new Scanner(System.in);
        str = scanner.next();
        //str= "worldcupcricketekcircpucdlrow";  //test value
        //System.out.println(str);
        int len = str.length();
        System.out.println(len);
        int first =0;
        int last =len-1;
        int flag = 0;
        int loopLen = len/2;
        //System.out.println(str.charAt(first));
        //System.out.println(str.charAt(last));
      
        for(int count=0;count<loopLen;count++){
          
            if(str.charAt(first)!=str.charAt(last)){
                flag =1;
                break;
            }
              
          
            //System.out.println(str.charAt(first)+"--"+str.charAt(last));
            first=first+1;
            last=last-1;
        }
      
        String output = flag ==0? " paliandrome" : "not a paliandrome";
        System.out.println(str+ " is "+output);
    }

}

 

 if you want to know how to use ternary operator please visit this link
http://javabelazy.blogspot.in/

November 26, 2014

How to find Geometric Mean of a number in java

Finding Geometric mean of a number source code


/**
 *
 */
package javabelazy;

import java.util.Scanner;

/**
 * @author caner erkin
 *
 */
public class GeometricMean {
   
   
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        GeometricMean gm = new GeometricMean();
        gm.findGM();

    }

    private void findGM() {
        // TODO Auto-generated method stub
        int totNumb = 0;
      
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Enter number of values:");
        totNumb = keyboard.nextInt();
        double mulNumb = 1;
        for (int i=0;i<totNumb;i++){
            int numb = 0;
            int itr = i+1;
            System.out.println(" enter the "+itr+"number : ");
            numb = keyboard.nextInt();
            mulNumb = mulNumb * numb;
        }
      
        System.out.println(" geometric mean "+ Math.sqrt(mulNumb));
    }


}

This post is a solution for the question post in stack over flow

see the post

G20 submit 2015 will be held at Turkey city :antalya

http://javabelazy.blogspot.in/

October 19, 2014

Sending File from System to System in java

How to send a file from one system to another using java code

Description :The program will help you to send a file from one computer to another in network through a socket. the port number here used is 8025 (we eliminate all 1024 reserved ports, for example 21 are reserved port for ftp).  developer can declare the port number as static final. The server application will send a file specified by the user through socket where the client application receives it. please provide feedback after running the code, check the java source code.This is an example for java networking application.



CLIENT SERVER
SENDING IMAGE FROM CLIENT TO SERVER IN JAVA



FTPServer.java

/**
 *
 */
package pakistan;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author javabelazy
 *
 */
public class FTPServer {
  
    ServerSocket serverSocket = null;
    Socket socket = null;
    int data = -1;
    DataOutputStream dataOutputStream = null;
    OutputStream outputStreams = null;
    DataInputStream dataInputStream = new DataInputStream(System.in);
    String fileNameNew = null;
    String string = null;
    File file = null;
    FileInputStream fileInputStream = null;
  

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        FTPServer ftpServer = new FTPServer();
        ftpServer.sendFile();

    }

    private void sendFile() {
        // TODO Auto-generated method stub
        string = new String();
        try{
            //d = new DataInputStream(System.in);
            System.out.println(" Enter the file name to be transfered ");
            fileNameNew=dataInputStream.readLine();
            file = new File(fileNameNew);
            fileInputStream = new FileInputStream(file);
            serverSocket= new ServerSocket(8025);
            socket=serverSocket.accept();
            outputStreams=socket.getOutputStream();
            dataOutputStream=new DataOutputStream(outputStreams);
            while((data=fileInputStream.read())!=-1){
                char c = (char)data;
                string=string+c;
            }
            dataOutputStream.writeUTF(string);
            System.out.println("The file "+fileNameNew +" file transfered to client machine");

        }
        catch (Exception e) {
            // TODO: handle exception
            System.out.println(" The server system got an exception : "+e.getMessage());
        }
        finally{
            try {
                socket.close();
                serverSocket.close();
                outputStreams.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                System.out.println(" Unable to send file (file transfer got the following exception ) : "+e.getMessage());
                e.printStackTrace();
            }

          
        }
      
    }

}


FTPClient.java

/**
 *
 */
package china;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

/**
 * @author java belazy
 *
 */
public class FTPClient {
  
    Socket socket =  null;
    int len = 0;
    int count = 0;
    InputStream inputStream = null;
    DataInputStream dataInputStream = null;
    DataInputStream newDataInputStream = null;
    String fileName = null;
    String fileData = null;

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        FTPClient ftpClient = new FTPClient();
        ftpClient.receiveFile();

    }

    private void receiveFile() {
        // receiving file sent by host system
        while(true){
        try{
            socket=new Socket("", 8025);
            inputStream = socket.getInputStream();
            newDataInputStream=new DataInputStream(inputStream);
            System.out.println(" Enter the file name to be saved ");
            dataInputStream = new DataInputStream(System.in);
            fileName = dataInputStream.readLine();
            File file = new File(fileName);
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            fileData =newDataInputStream.readUTF();
            len= fileData.length();
            for(count=0;count<len;count++){
                char c =fileData.charAt(count);
                fileOutputStream.write(c);
            }
            System.out.println("File copied to system ");

                   
        }catch (Exception e) {
            // TODO: handle exception
            System.out.println(" The file tranfer client got an exception : "+e.getMessage());
        }finally{
            try {
                socket.close();
                inputStream.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                System.out.println(" The file tranfer client got an exception : "+e.getMessage());
                e.printStackTrace();
            }
           
           
        }
       
        }
       
    }

}
 

file transfer protocol implementation in java

October 06, 2014

Bar code generator in java

How to generate bar code for each items in java

package com.proximotech.etrade.utils;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.Barcode;
import com.lowagie.text.pdf.Barcode128;
import com.lowagie.text.pdf.BarcodeEAN;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfWriter;

public class BarcodeCreator {

    public String barcodeToPdf() throws FileNotFoundException, DocumentException{

        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(
            "lumina730.pdf"));
        document.open();

        PdfContentByte cb = writer.getDirectContent();
        BarcodeEAN codeEAN = new BarcodeEAN();
        codeEAN.setCode("1439112001143");
        Paragraph p = new Paragraph();
       
       
        // CODE 128
        document.add(new Paragraph("Barcode 128"));
        Barcode128 code128 = new Barcode128();
        code128.setCode("9112001 Deepak");
        document.add(code128.createImageWithBarcode(cb, null, null));

        document.add(p);
        document.close();
     
        return null;
    }
   
  public static void main(String[] javacode) throws Exception {
     
  }
}

http://javabelazy.blogspot.in/

September 28, 2014

Develop a Regional language translator in java

Java source code to for english to malayalam language translator

     There are many online English to malayalam translator available in internet. If you are searching for a full java source code to convert english to malayalam then please dont go through this post, this only an idea how to start working on a english to malayalam language convertor. The code here is not a complete code. Copy the code paste it in your eclipse/Net bean ide and run it.

     You can download the English to malayalam convertor jar application from the link given below.
Please provide your feedback, you can comment for any post in this blog. Genuine comments will be appreciated !!! 

     Some guys sent me alternate code through face book and gmail (probably better code) after reading the post. thanks to those guys. and i have appended all those code with those posts. so share your knowledge !

Language Translator Image
Language Translator in java

Author : +belazy


/**
* Developing for office use
*/


import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;

import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.border.Border;
import java.awt.Rectangle;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
/**
* @author True caller java *
*/
public class Translator extends JFrame {

private static final long serialVersionUID = 1L;
private JPanel jContentPane = null;
private JTextArea typeArea = null;
private JTextArea viewArea = null;
private Translator thisClass = null;
private Mozhi mozhiObj = null;
/**
* This method initializes Typing area
*
* @return javax.swing.JButton
*/
private JTextArea getTypingArea() {
if (typeArea == null) {
typeArea = new JTextArea();
//typeArea.setBounds(new Rectangle(50, 50, 600, 600));
typeArea.setBounds(new Rectangle(30, 20, 200, 100));
Border border = BorderFactory.createLineBorder(Color.BLACK);
typeArea.setBorder(BorderFactory.createCompoundBorder(border,
BorderFactory.createEmptyBorder(10, 10, 10, 10)));
typeArea.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
//System.out.println(" Vipin C P");

}

public void keyTyped(KeyEvent e) {
//System.out.println(" Developing language Translator ");
//String engWord = typeArea.getText();
//viewArea.setText(mozhiObj.getMalayalam(engWord));
viewArea.setText(convertToMalayalam(typeArea.getText()));
}
public void keyPressed(KeyEvent e) {
//System.out.println(" English to south indian language translation ");
}
});
}
return typeArea;
}
protected String convertToMalayalam(String engWord) {
String englishWord = engWord;
String malWord = englishWord.replaceAll("A", "¦");
malWord = malWord.replaceAll("bi", "Ìß");
malWord = malWord.replaceAll("the", "çÄ");
malWord = malWord.replaceAll("sh", "×í");
return malWord;
}

/**
* This method initializes Typing area
*
* @return javax.swing.JButton
*/
private JTextArea getViewArea() {
if (viewArea == null) {
viewArea = new JTextArea();
Font malFont = new Font("Kerala", Font.PLAIN, 15);
Border border = BorderFactory.createLineBorder(Color.GRAY);
viewArea.setBorder(BorderFactory.createCompoundBorder(border,
BorderFactory.createEmptyBorder(10, 10, 10, 10)));
//viewArea.setBounds(new Rectangle(700, 50, 600, 600));
viewArea.setBounds(new Rectangle(250, 20, 200, 100));
viewArea.setEditable(false);
viewArea.setFont(malFont);
}
return viewArea;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Translator thisClass = new Translator();
thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
thisClass.setVisible(true);
}
});
}

/**
* This is the default constructor
*/
public Translator() {
super();
initialize();
}

/**
* This method initializes this
*
* @return void
*/
private void initialize() {
//this.setSize(1340, 720);
this.setSize(500, 200);
this.setContentPane(getJContentPane());
this.setTitle("CFED : English To Malayalam Translator");
mozhiObj = new Mozhi();
}

/**
* This method initializes jContentPane
*
* @return javax.swing.JPanel
*/
private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel();
jContentPane.setLayout(null);
//jContentPane.add(getLoginButton(), null);
jContentPane.add(getTypingArea(), null);
jContentPane.add(getViewArea(), null);
}
return jContentPane;
}

}






function : convertToMalayalam() is that converts english words to malayalam, work on it. you can use a separate class to do the job.


You can download the malayalam font from this link
FileName : Javabelazy72902
Pasword : independenceday

Please try this code and feedback...

here is an online malayalam editor link


Thanks to +deepajayaprakash payyanakkal


http://javabelazy.blogspot.in/

September 12, 2014

Traffic Light demo in visual basic

Demo for Traffic Light application in visual basic







Dim db As Database
Dim rs As Recordset

Private Sub Command1_Click()
Timer1.Enabled = True
Timer5.Enabled = False
Timer3.Enabled = False
Timer2.Enabled = False
Timer4.Enabled = False
End Sub

Private Sub Command2_Click()
End
End Sub

Private Sub Form_Load()
Set db = opendatabase("K:\WorldTradeCenter\Newyork\iphone\Moto.mdb")
Set rs = db.openrecordset("select * from traffic")
End Sub

Private Sub Timer1_Timer()
Shape1.FillStyle = 0
Shape6.FillStyle = 0
Shape2.FillStyle = 1
Shape3.FillStyle = 1
Shape4.FillStyle = 1
Shape5.FillStyle = 1
Timer2.Enabled = True
Timer1.Enabled = False
Timer3.Enabled = False
Timer4.Enabled = False
Timer5.Enabled = True
End Sub

Private Sub Timer2_Timer()
Shape1.FillStyle = 1
Shape6.FillStyle = 1
Shape2.FillStyle = 0
Shape3.FillStyle = 1
Shape4.FillStyle = 1
Shape5.FillStyle = 0
Timer3.Enabled = True
Timer1.Enabled = False
Timer2.Enabled = False
Timer4.Enabled = False
Timer5.Enabled = True
End Sub

Private Sub Timer3_Timer()
Shape1.FillStyle = 1
Shape6.FillStyle = 1
Shape2.FillStyle = 1
Shape3.FillStyle = 0
Shape4.FillStyle = 0
Shape5.FillStyle = 1
Timer3.Enabled = False
Timer1.Enabled = False
Timer2.Enabled = False
Timer4.Enabled = True
Timer5.Enabled = True
End Sub

Private Sub Timer4_Timer()
Shape1.FillStyle = 1
Shape6.FillStyle = 1
Shape2.FillStyle = 0
Shape3.FillStyle = 1
Shape4.FillStyle = 1
Shape5.FillStyle = 0
Timer3.Enabled = False
Timer1.Enabled = True
Timer2.Enabled = False
Timer4.Enabled = False
Timer5.Enabled = True
End Sub

Private Sub Timer5_Timer()
If rs.EOF = False Then
Label2(0).Caption = rs(0)
Label2(1).Caption = rs(0)
rs.MoveNext
Else
rs.MoveFirst
End If
End Sub
 



To download the microsoft access database file click here
filename : Javabelazy32510
password : iphone6


Happy Onam to all visitors

http://javabelazy.blogspot.in/

September 10, 2014

How to block browsing sites in your computer

How to block internet access in your computer



Yes you can block internet access to your computer !!!

you can override the DNS for a domain in your system by modifying the hosts file in system32 folder in windows. Actually these are used for testing purpose, but we used (we can use) to deny access to a particular site by using loop back ip ie 127.0.0.1 thus a big problem disturbing our IT Section ( assigned by +bithesh soubhagya  ) was solved.

We successfully blocked internet access in 100 branches under cfed kozhikode regional office.

The units under our regions are misusing internet for the past years, the old IT staff had blocked denied the access to internet explorer by a password. But it doesnt worked fine while mozilla firefox and google chrome came and peoples starts installing third party browser software. So now its necessity for any thing new that block their access to internet. For past few weeks i was working on it and found a solution.

How to block internet


Browse to  C:\Windows\System32\Drivers\etc\

you can find a hosts file in it, right click and edit and make following changes. Now try to access facebook, the site will redirect to your system itself. Access blocked !!!



consumerfed kozhikode region it section
you can download the hosts file from here

Other methods for blocking internet access to triveni computers link




Thanks to +Consumerfed  +Consumerfed IT Division  for assigning this task through our regional IT




http://javabelazy.blogspot.in/

August 17, 2014

Create a Digital clock in java script

java script example for how to use timer

Description : the program will help you to understand the working of timer and animation in html using javascript



<html>
<head>
<script type="text/javascript">
var c=0
var t
function timedCount()
{
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout("timedCount()",1000);

document.getElementById('clock').date=d;
var d= new Date();
}
</script>
</head>

<body>
<form>
<input type="button" value="Start count!" onClick="timedCount()" />
<input type="text" id="txt" />
<input type="text"  id="clock"/>
</form>
</body>

</html>



Java script animation example


<html>
<head>
<script type="text/javascript">
function mouseOver()
{
document.getElementById("b1").src ="asiangames.gif";
}
function mouseOut()
{
document.getElementById("b1").src ="olympics.gif";
}
</script>
</head>

<body>
<a href="
http://javabelazy.blogspot.in/" target="_blank">
<img border="0" alt="Java best blog" src="asiangames.gif" id="b1"
onmouseover="mouseOver()" onmouseout="mouseOut()" /></a>
</body>
</html>


http://javabelazy.blogspot.in/

August 05, 2014

How to write stored procedure in mysql

How to call MySql stored procedure form java application


There are 3 types of stored procedures
  • system stored procedures
  • extended stored procedure
  • user defined stored procedures
Stored procedure allow modular programing, faster execution, reduce traffic, security to your data

Create a table named states

/*Table structure for table `tbl_states` */

DROP TABLE IF EXISTS `tbl_states`;

CREATE TABLE `tbl_states` (
  `stateId` int(11) NOT NULL AUTO_INCREMENT,
  `state` varchar(25) NOT NULL,
  `status` varchar(10) NOT NULL DEFAULT 'Y',
  PRIMARY KEY (`stateId`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;


Stored procedure for inserting values to states

Procedure name : p_states_insertstates
Input : statename and status of state

/* Procedure structure for procedure `p_states_insertstates` */

/*!50003 DROP PROCEDURE IF EXISTS  `p_states_insertstates` */;

DELIMITER $$

/*!50003 CREATE DEFINER=`root`@`localhost` PROCEDURE `p_states_insertstates`(In i_state VARCHAR(25),in i_status varchar(10))
BEGIN
    insert into tbl_states(state,status) values (i_state,i_status);
    Select last_insert_id();
    END */$$
DELIMITER ;



insert query : insert  into `tbl_states`(`stateId`,`state`,`status`) values (1,'Sakha Republic','N');

Java Code : callable insertion


import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;


public class Main {
       public static Connection connections()
        {
            try
            {
                Class.forName("com.mysql.jdbc.Driver");
                Connection con=DriverManager.getConnection("jdbc:mysql://localhost/whatsAppdatabase","root","root");
                return con;
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            return null;
        }
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Main m = new Main();
        m.insert("SakhaRepublic","Y");
    }
    private void insert(String stateName, String stateStatus) {
        String state = stateName;
        String status = stateStatus;
        CallableStatement statement = null;
      
        Connection connect = Main.connections();
        System.out.println(" connecting .... ");
        String sql = "{call p_states_insertstates (?, ?)}";
        try {
            statement = connect.prepareCall(sql);
            statement.setString(1, state);
            statement.setString(2, stateStatus);
            //statement.registerOutParameter(3, java.sql.Types.VARCHAR);
            statement.execute();
            //int empName = statement.getInt(3);
            System.out.println(" id : ");
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally
        {
            try {
                statement.close();
                connect.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
          
        }
      
      
    }
}


Example of Mysql stored procedure with OUT parameter


DELIMITER $$
CREATE
    /*[DEFINER = { user | CURRENT_USER }]*/
    PROCEDURE `serviceinformata`.`test`(out id int)
    /*LANGUAGE SQL
    | [NOT] DETERMINISTIC
    | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
    | SQL SECURITY { DEFINER | INVOKER }
    | COMMENT 'string'*/
    BEGIN
    Select Max(stateId) into id from tbl_states;
    END$$
DELIMITER ;

replace the above function with this

    private void insert(String storedProcedure, String ,mysqlExample) {
        String state = stateName;
        String status = stateStatus;
        CallableStatement statement = null;
       
        Connection connect = Main.connections();
        System.out.println(" connecting .... ");
        String sql = "{call test (?)}";
        try {
            statement = connect.prepareCall(sql);

            statement.registerOutParameter(1, java.sql.Types.INTEGER);
            statement.execute();
            int stateId= statement.getInt(1);
            System.out.println(" id : "+stateId);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally
        {
            try {
                statement.close();
                connect.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
           
        }
      }

You have to download mysql connector.jar download link


This is a small example for insertion stored procedure in mysql and how to call it from your java application

Advantage of stored procedures

  1. performance
  2. productivity and ease of use
  3. scalability
  4. maintainability
  5. interoperability
  6. security
  7. replication

Possible Exceptions

Data too long for column 'column_name'

http://javabelazy.blogspot.in/

July 11, 2014

Commodity sales graph in excel

How to create a graph in microsoft office excel

Create a new excel

Rename the first sheet to DATA

Data for Graph
Excel Data
Enter the following data to sheet1 (named as DATA)

Choose the type of data from insert tab in excel sheet

Type of graph available in MS Excel
choose the type of graph in excel
choose select data
Select Data for graph
Select Data

A window will be open

type the following to the textbox  " =DATA!$B$1:$E$7 " (where data is the sheet name, no need of double quotes)

A graph will be created, click on switch row/column

sales graph image
Sales commodity wise graph

The chart properties will be available in Layout tab

excel graph properties
Excel graph properties

You can add title , data label , align it etc etc.....


Excel graph
Author : +Shimjith

Description

If you are looking for sales commodity wise graph , then micro soft office excel package is a good option. you can choose what ever types of graphs. In addition to bar graph many options are there. you can easily switch from one graph to other one. you can switch the axis too, you can even customize where you want to keep your data series.

Java Graph API Documentation /


Similar posts


http://javabelazy.blogspot.in/

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/

Facebook comments