Pages

Sunday, February 24, 2019

Java Example to check if Number is Odd or Even

Java Example to check if the entered number is Odd or Even. This example is for the beginners who just started learning programming.



import java.util.Scanner;

public class OddOrEven {

    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);

        System.out.print("Enter the number: ");
        int num = reader.nextInt();

        if(num % 2 == 0)
            System.out.println(num + " is even.");
        else
            System.out.println(num + " is odd.");
    }
}
Watch video here
https://youtu.be/sX0XAROhuiQ

Java Example to check if entered Number is Prime or not

This Java Example if for beginners to check if entered number is prime i.e. number which is divisible by only two numbers first 1 and second itself. If any number is divisible by 3 or more numbers, it is not a prime number.

Play Free Online Games and Win Big Prize Money 

import java.util.Scanner;
public class Prime {

    public static void main(String[] args) {
        
        
        Scanner keyboard = new Scanner(System.in);

        int number = keyboard.nextInt();
        boolean flag = false;
        for(int i = 2; i <= number/2; ++i)
        {
            // condition for nonprime number
            if(number % i == 0)
            {
                flag = true;
                break;
            }
        }

        if (!flag)
            System.out.println(number + " is a prime number.");
        else
            System.out.println(number + " is not a prime number.");
    }
}

Watch video here
https://youtu.be/sX0XAROhuiQ

Wednesday, August 30, 2017

Java example for generating a table of a number and for loop

This example is for Java beginners to let them learn two basic concepts of the language
1. for loop
2. Using Scanner class to get input from keyboard

 
import java.util.Scanner;

public class TableOfInteger {

     // start of main() function

        public static void main(String[] args) {

        Scanner keyboard = new Scanner(System.in);

        // get an object of Scanner class for getting input from keyboard

        System.out.println("enter an integer for generate table ");

        int table = keyboard.nextInt();

        // for loop

        for(int i=1;i<=10;i++)

                                System.out.println(table + "X" + i +"=" +table*i);

}

//end of main function()

}
Watch video here
https://youtu.be/sX0XAROhuiQ

Monday, August 28, 2017

If-else statement, read input from keyboard (by java.util.Scanner) and Find if a number is Even Or Odd example in Java

this example explains three important topics of Java
1. read input from keyboard
2. if-else statement
3. calculate if the number is even or odd


import java.util.Scanner;

public class FindEvenOrOddNumber {

        public static void main(String[] args) {

        // main() function

        Scanner keyboard = new Scanner(System.in);

        // Scanner object to read input from keyboard

        System.out.println("enter an integer");

        int even_odd = keyboard.nextInt();

         if(even_odd%2 == 0) //check if number is odd or even

                                System.out.println(even_odd + " is even number.");

                         else

                                System.out.println(even_odd + " is odd number.");

}

}
Watch video here
https://youtu.be/sX0XAROhuiQ

Sunday, August 27, 2017

Hello world example in Java

This Example is for the beginners to start programming in Java

Play Free Online Games and Win Big Prize Money 

public class Hello{

//main() function start

  public static void main(String args[]){

    System.out.println("Hello World !");

//command to print on the console 

  }

// main function finish

}

Watch video here
https://youtu.be/sX0XAROhuiQ

Saturday, November 15, 2014

Uploading Image in jsp, java, Netbeans

i had spent a lot of time for uploading an image in jsp page.so to help you guys i am writing this blog.
the way to upload the desired image is as below(neteans project)



1. Put the image file in web folder(where all the web pages are placed.)
2. Wright the code

 <%String s=request.getContextPath() + "/abc.JPG";%>

<img src="<%=s%>" width = "500" hight = "600" aligh = "center" />
3. Mention the extensions of image carefully i.e(.jpeg, jpg are not treated as same)

for any other query keep posting.
Good Luck!!!

Watch video
https://youtu.be/sX0XAROhuiQ

Monday, November 10, 2014

Create and display dynamic Chart in JSP using Database inputs(jFreeChart Library)

 JSP code that generates chart of database(Time-Speed  which was my application requirement) and returns chart image whenever called

Play Free Online Games and Win Big Prize Money 

-Watch video
https://youtu.be/sX0XAROhuiQ
<%// required packages  %>

<%@ page import="java.awt.Image" %>

<%@ page import="java.awt.*"%>

<%@ page import="java.text.SimpleDateFormat"%>

<%@ page import="java.awt.BasicStroke"%>

<%@ page import ="org.jfree.ui.ApplicationFrame"%>

<%@ page import="java.io.*" %>

<%@ page import="java.io.File"%>

<%@ page import="org.jfree.chart.*" %>

<%@ page import="org.jfree.chart.axis.*" %>

<%@ page import="org.jfree.chart.entity.*" %>

<%@ page import="org.jfree.chart.labels.*" %>

<%@ page import="org.jfree.chart.plot.*" %>

<%@ page import="org.jfree.chart.renderer.category.*" %>

<%@ page import="org.jfree.chart.urls.*" %>

<%@ page import="org.jfree.data.category.*" %>

<%@ page import="org.jfree.data.general.*" %>

<%@ page import="org.jfree.data.time.Minute"%>

<%@ page import="org.jfree.data.time.Hour"%>

<%@ page import="org.jfree.data.time.TimeSeries"%>

<%@ page import="org.jfree.data.time.TimeSeriesCollection"%>

<%@ page import="org.jfree.data.xy.XYDataset"%>

<%@ page import="org.jfree.chart.plot.XYPlot"%>

<%@ page import="org.jfree.chart.renderer.xy.StandardXYItemRenderer"%>

<%@ page import="org.jfree.chart.renderer.xy.XYItemRenderer"%>

 <%@ page import=  "java.sql.Connection" %>

<%@ page import  ="java.sql.DriverManager" %>

<%@ page import = "java.sql.SQLException" %>

<%@ page import = "java.sql.PreparedStatement" %>

<%@ page import = "java.sql.ResultSet" %>

<%@ page import = "java.sql.Statement" %>

 <%@ page import=  "javax.servlet.*" %>

<%@ page import  ="javax.servlet.http.*" %>



<%@ page import="java.awt.image.BufferedImage"%>

<%

 try

 {

 File image = File.createTempFile("image", "tmp");



 //chart class instance

Fms fm = new Fms("Graph");



JFreeChart chart = fm.createChart(fm.dataset);

 ChartUtilities.saveChartAsPNG(image, chart, 500, 400);

//get input stream

 FileInputStream fileInStream = new FileInputStream(image);

//output stream foe returning chart as image

 OutputStream outStream = response.getOutputStream(); 

 long fileLength;

 byte[] byteStream;

 fileLength = image.length();

 byteStream = new byte[(int)fileLength];

//read chart image

 fileInStream.read(byteStream, 0, (int)fileLength);

//returns chart image whenever called

 response.setContentType("image/png");

 response.setContentLength((int)fileLength);

 response.setHeader("Cache-Control","no-store,no-cache, must-revalidate, post-check=0, pre-check=0");

 response.setHeader("Pragma", "no-cache");

 fileInStream.close();

 outStream.write(byteStream);

 outStream.flush();

 outStream.close();

 }

 catch (IOException e)

 {

 System.err.println("Problem occurred creating chart.");

 }

%>

<%! public class Fms extends ApplicationFrame {   

//Main class

   XYDataset dataset= null;

   public Fms(final String title) {

        super(title);

      dataset= createDataset();

        final JFreeChart chart = createChart(dataset);

        final ChartPanel chartPanel = new ChartPanel(chart);

        chartPanel.setPreferredSize(new java.awt.Dimension(700, 570));

        chartPanel.setMouseZoomable(true, false);

        setContentPane(chartPanel);

    } 

//chart creation method

   JFreeChart createChart(final XYDataset dataset) {

        final JFreeChart chart = ChartFactory.createTimeSeriesChart(

            "Speed Chart",

            "Time",

            "Speed",

            dataset,

            true,

            true,

            false

        );

        chart.setBackgroundPaint(Color.white);

       final XYPlot plot = chart.getXYPlot();

        plot.setBackgroundPaint(Color.lightGray);

        plot.setDomainGridlinePaint(Color.white);

        plot.setRangeGridlinePaint(Color.white);

        plot.setDomainCrosshairVisible(true);

        plot.setRangeCrosshairVisible(false);

        final XYItemRenderer renderer = plot.getRenderer();

        if (renderer instanceof StandardXYItemRenderer) {

            final StandardXYItemRenderer rr = (StandardXYItemRenderer) renderer;

            rr.setShapesFilled(true);

            renderer.setSeriesStroke(0, new BasicStroke(1.0f));

            renderer.setSeriesStroke(1, new BasicStroke(1.0f));

           }       

        final DateAxis axis = (DateAxis) plot.getDomainAxis();

        axis.setDateFormatOverride(new SimpleDateFormat("dd:MM")); 

        try{

        final ChartRenderingInfo info = new ChartRenderingInfo

(new StandardEntityCollection());

final File file1 = new File("c:/Documents and Settings/accounts/WebApplication2/web/barchart.png");

ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);

        }catch(Exception e){}

        return chart;

    }   

//data set generation method

    private XYDataset createDataset() {

        final TimeSeriesCollection dataset = new TimeSeriesCollection();

        dataset.setDomainIsPointsInTime(true);       

        final TimeSeries s1 = new TimeSeries("Series 1", Minute.class);

         int str = 0;

         int i =0,j= 0 ;

         String str1 = null;

        try{             

      Class.forName("sun.jdbc.odbc.JdbcOdbc"); 

      Connection con=DriverManager.getConnection("jdbc:odbc:FMSDB",null,null);

      PreparedStatement st;   

      Statement stmt = con.createStatement(); 

      String query = "Select * from Job_Status";

      stmt.executeQuery(query);

       ResultSet rs = stmt.executeQuery(query);       

           while( rs.next() )

        {                 

         str1= rs.getString("Time");

         String sa = str1.substring(11,13);

         String ha = str1.substring(14,16);

        str= rs.getInt("Speed"); 

        j=Integer.parseInt(sa);

        i=Integer.parseInt(ha);

        String date = rs.getString("Date");

        String y = date.substring(0,4);

         String m = date.substring(5,7);

          String d = date.substring(8,10);

         s1.add(new Minute(i, j, Integer.parseInt(d), Integer.parseInt(m), Integer.parseInt(y)), str);

          }

          }

          catch(Exception e)

          {             

          }

         System.out.println(str1.substring(11,13));

          System.out.println(str1.substring(14,16)+"\t"+str1);                 

        dataset.addSeries(s1);   

        return dataset;

    }

    }

%>
HTML Code for calling this JSP file
exp.jsp is the name of above jsp code file in my application
<html>

<body>

<img src="exp.jsp" alt="Progress chart" />

</body>

</html>
Note: To implement this code you will need jFreeChart Library from jFree Org.

Watch video
https://youtu.be/sX0XAROhuiQ

Tuesday, November 4, 2014

Reading Data from comm port in Java

This code first write 0x80 to COM port () then it reads 0x32 from COM port and then sends 6 more bytes and to terminate the packet it receives  0x70 form COM port.



This code can be very helpful to communicate with embedded devices which communicate with PC through COM port.

-Watch video
https://youtu.be/sX0XAROhuiQ
// library import

import java.io.*;
import java.util.*;
import javax.comm.*;
import java.sql.Connection;
import  java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class Fms implements Runnable{ 
static Enumeration portList;
static CommPortIdentifier portId;
static SerialPort serialPort;
static OutputStream outputStream;
static InputStream inputStream;
static Thread readThread,dataBase;
static int crf;
static int cwf;
static byte cxc[] = new byte[4];
static int cxm = 128;//0x80
static byte[] creadBuffer;//1byte read
static int creadBuff[]; 
write rt=new write();
static read rd;   
public void run() {
    };
    public static void main(String[] args) {
        int a=10;
        write wr = new write();
        read rd = new read(1);
         int b = 0;
        int speed=0,tcount=0,jcount=0,status=0;
      while(b!=10){      
       for(int j =0 ; j<=1;j++){
            try{
        wr.cwritemain(a); 
         rd.cmainx(a);          
         readThread.sleep(1000);
            }
            catch(Exception e){}
            if(j==0){
                status =creadBuff[1];
                jcount =creadBuff[5];
          System.out.println("results : "+status +"\t"+jcount); 
            }
            if(j==1){
                speed =creadBuff[1]*256+creadBuff[2];//to convert received data in decimal
                tcount =creadBuff[6];
          System.out.println("results : "+speed +"\t"+tcount); 
            }
             }    
    }            
       }
 static class write{        
         public void cwritemain(int m)
{       
             cwf = m;
             cxc[0] = 0x26;
             portList = CommPortIdentifier.getPortIdentifiers();
             System.out.println(portList.hasMoreElements());
while (portList.hasMoreElements()) {                                   
                                        portId = (CommPortIdentifier) portList.nextElement();
                                        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                                    
if (portId.getName().equals("COM1"))
{                                  
try {
serialPort = (SerialPort) portId.open("SimpleWriteApp32", 2000);
                                                  } catch (PortInUseException e) {
}
try {
outputStream = serialPort.getOutputStream();
} catch (Exception e) {
}
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (Exception e) {
}
                                               if(cwf==10){
try {
outputStream.write(cxm);// 0x80 written
serialPort.close();
                                                                outputStream.close();
} catch (Exception e) {
}
                                               }
                                        }
                                }
                        }
         }        
    }   
   static class read implements SerialPortEventListener{
      public read(int s) {}
      public void cmainx(int cp) {
crf = 10;
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals("COM1")) {
try {
                                                    serialPort = (SerialPort) portId.open("readapp32",
2000);
} catch (PortInUseException e) {
System.out.println(e.getMessage());
}
try {
inputStream = serialPort.getInputStream();
} catch (Exception e) {
System.out.println(e);
}
try {
serialPort.addEventListener(this);
} catch (Exception e) {
System.out.println(e);
}
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);                                                
} catch (Exception e) {
System.out.println(e);
}
}
}
}                       
}
        public void serialEvent(SerialPortEvent event) {            
            switch (event.getEventType()) {
case SerialPortEvent.DATA_AVAILABLE:
creadBuffer = new byte[8];
                                creadBuff= new int[8];
try {
                                   int i = 0;                               
while (inputStream.available() > 0) { 
                                          creadBuff[i]=inputStream.read();
                                          System.out.println("Data available is: "+creadBuff[i]);                                                  
                                               i++;
}
                                      inputStream.close();
} catch (IOException e) {
}
                                System.out.println("event");
System.out.println("recieved \t"+creadBuffer[0] );
if (creadBuffer[0] == 0x70) {
                                    System.out.println("Got 0x70"+creadBuffer[0] );
serialPort.close();
rd = new read(5);
rd.cmainx(1);// ag
                                }
                                if (creadBuffer[0] == 0x32) {
                                    System.out.println("Got"+creadBuffer[0] );
serialPort.close();                                
                                }
                                serialPort.close();
            }
        }
   }  

   }

Watch video

Tuesday, May 29, 2012

Datagram Client in Java

This Example is implementation of Datagram Client or UDP client purpose of this example is to provide a fare idea about the working of UDP client server this client example works with server example and link to server example is given at the end of this code example works on the concept of UDP protocol (simple transmission model without implicit handshaking)



-Watch video
https://youtu.be/sX0XAROhuiQ
import java.io.*;

import java.net.*;

public class Client {

    public static void main(String[] args) {

      DatagramSocket clientSkt = null;

      InetAddress IPAdd = null;

      String text =null;

      DatagramPacket receivePkt= null;

      BufferedReader inFromUser =

         new BufferedReader(new InputStreamReader(System.in));

      try{

      clientSkt = new DatagramSocket();

      IPAdd = InetAddress.getByName("localhost");

      }

      catch(SocketException exp){

          System.out.println(exp);

      }

      catch(UnknownHostException exp){

          System.out.println(exp);

      }      

      byte[] sendData = new byte[1024];

      byte[] receiveData = new byte[1024];

      try{

      text = inFromUser.readLine();

      sendData = text.getBytes();

      DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAdd, 3030);

      clientSkt.send(sendPacket);

      receivePkt = new DatagramPacket(receiveData, receiveData.length);

      clientSkt.receive(receivePkt);

      }

      catch(IOException exp){

          System.out.println(exp);

      }

      String modifiedSentence = new String(receivePkt.getData());

      System.out.println("FROM SERVER:" + modifiedSentence);

      clientSkt.close();

    }

}
Watch video
Datagram Server Source

Datagram Server in Java

This example is about Datagram Server or UDP server purpose of this example is to provide a fare idea about the working of UDP client server this server example works with client example and link to the client example is given at the end of this code example works on the concept of UDP protocol (simple transmission model without implicit handshaking)

Play Free Online Games and Win Big Prize Money 

-Watch video
https://youtu.be/sX0XAROhuiQ
import java.io.*;

import java.net.*;

public class Server {

    public static void main(String[] args) {

        DatagramSocket serverSkt= null;

        try{

            serverSkt = new DatagramSocket(3030);

        }

        catch(SocketException exp)

        {

            System.out.println(exp);

        }

        byte[] receiveData = new byte[1024];

        byte[] sendData = new byte[1024];

        while(true)

          {

            DatagramPacket receivePkt = new DatagramPacket(receiveData, receiveData.length);

            try{

                serverSkt.receive(receivePkt);

            }

            catch(IOException exp)

            {

                System.out.println(exp);

            }

            String sentence = new String( receivePkt.getData());

            System.out.println("RECEIVED: " + sentence);

            InetAddress IPAddress = receivePkt.getAddress();

            int port = receivePkt.getPort();

            String capitalizedSentence = sentence.toUpperCase();

            sendData = capitalizedSentence.getBytes();

            DatagramPacket sendPkt =

            new DatagramPacket(sendData, sendData.length, IPAddress, port);

            try{

            serverSkt.send(sendPkt);

            }

            catch(IOException exp)

            {

                System.out.println(exp);

            }   

        }

      }        

  }
Watch video
Datagram Client Source

Friday, February 10, 2012

Get Your PC's IP Address in Java

This example returns IP address of your PC.

Play Free Online Games and Win Big Prize Money 

-Watch video
https://youtu.be/sX0XAROhuiQ
import java.net.*;

public class TellMyIP {

public static void main(String[] args) {

 InetAddress localHostIP= null;

   //creates instance of InetAddress

  try{

  localHostIP=InetAddress.getLocalHost();

  //initializes localHostIP

  System.out.println("IP ADDRESS OF MY PC IS = "+localHostIP.getHostAddress());

  //gets IP address and prints it

  }catch (Exception exception){

  System.out.println("Something that went wrong is :"+exception.getMessage());

  }

   }

}
Watch video

Wednesday, March 30, 2011

Send email in Java with attachment

Java Mail API is required to work with this code to send email in Java from your email account with attachments .

       
import java.util.Properties;

import javax.activation.DataHandler;

import javax.activation.DataSource;

import javax.activation.FileDataSource;

import javax.mail.*;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeBodyPart;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeMultipart;

public class MailWithAttachment

{

public static void main(String args[]) throws Exception

{

    String host = "smtp.gmail.com";//host name

    String from = "abc@gmail.com";//sender id

    String to = "xyz@yahoo.com";//reciever id

    String pass = "***";//sender's password 

    String fileAttachment = "test.txt";//file name for attachment 

    //system properties

    Properties prop = System.getProperties();

    // Setup mail server properties

    prop.put("mail.smtp.gmail", host);

    prop.put("mail.smtp.starttls.enable", "true");

    prop.put("mail.smtp.host", host);

    prop.put("mail.smtp.user", from);

    prop.put("mail.smtp.password", pass);

    prop.put("mail.smtp.port", "587");

    prop.put("mail.smtp.auth", "true");

    //session 

    Session session = Session.getInstance(prop, null);

    // Define message

    MimeMessage message = new MimeMessage(session);

    message.setFrom(new InternetAddress(from));

    message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));

    message.setSubject("Hello Java Mail Attachment");

    // create the message part 

    MimeBodyPart messageBodyPart = new MimeBodyPart();

    //message body

    messageBodyPart.setText("Hi");

    Multipart multipart = new MimeMultipart();

    multipart.addBodyPart(messageBodyPart);

    //attachment

    messageBodyPart = new MimeBodyPart();

    DataSource source = new FileDataSource(fileAttachment);

    messageBodyPart.setDataHandler(new DataHandler(source));

    messageBodyPart.setFileName(fileAttachment);

    multipart.addBodyPart(messageBodyPart);

    message.setContent(multipart);

    //send message to reciever

    Transport transport = session.getTransport("smtp");

    transport.connect(host, from, pass);

    transport.sendMessage(message, message.getAllRecipients());

    transport.close();

}

}
Watch video

Monday, March 28, 2011

Database Connctions in Java

This example Works with MS Access to explain DB concepts and can be changed accordingly to any other database for that you will need to configure their respective JAR libraries to your project i.e. for MY-SQL you will need MySQL-Connector JAR.

       
import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

public class dbConnections

{

public static void main(String args[])

{

     try{  

      Class.forName("sun.jdbc.odbc.JdbcOdbc");  //load DB drivers

      Connection con=DriverManager.getConnection("jdbc:odbc:DBName",username,pwd);

      //create db connections

      Statement stmt = con.createStatement(); // creates statement for db access

      String query = "SELECT * FROM Job"; // sql query

      ResultSet rs = stmt.executeQuery(query);

      //execute sql query and stores the result in the result set rs

      while( rs.next() ) {

       System.out.println("Job  "+rs.getString("Job_Id"));

      }

      rs.close(); //close resultset

      stmt.close(); // close statement 

      con.close();  // close connection   

     }

    catch(SQLException e)

    {

     System.out.println(e);

    }

    catch(ClassNotFoundException e)

    {

     System.out.println(e);

   }

}

}
Watch video

Wednesday, March 16, 2011

Read emails from Gmail Account

This code reads emails from a Gmail account to work with this code you will need javax.mail API
-Watch video


https://youtu.be/sX0XAROhuiQ
import java.io.BufferedInputStream;

import java.io.IOException;

import java.io.FileWriter;

import java.io.InputStream;

import java.security.*;

import java.util.Properties;

import javax.mail.*;

public class ReadMail {

  public static void main(String args[]) throws IOException {

         Properties properties = System.getProperties();

         properties.setProperty("mail.store.protocol", "imaps");

             try {

                 Session session = Session.getDefaultInstance(properties, null);

                 //create session instance

                 Store store = session.getStore("imaps");//create store instance

                 store.connect("pop.gmail.com", "abc@gmail.com", "****");

                 //set your user_name and password

                 System.out.println(store); 

                 Folder inbox = store.getFolder("inbox");

                 //set folder from where u wants to read mails

                 inbox.open(Folder.READ_ONLY);//set access type of Inbox

                 Message messages[] = inbox.getMessages();// gets inbox messages

                 for (int i = 0; i < messages.length; i++) {

                System.out.println("------------ Message " + (i + 1) + " ------------");

                System.out.println("SentDate : " + messages[i].getSentDate()); //print sent date

                System.out.println("From : " + messages[i].getFrom()[0]); //print email id of sender

                System.out.println("Sub : " + messages[i].getSubject()); //print subject of email

                try

                {

                      Multipart mulpart = (Multipart) messages[i].getContent();

                      int count = mulpart.getCount();

                      for (int j = 0; j+1 < count; j++)

                     {

                          storePart(mulpart.getBodyPart(j));

                     }

                }

                catch (Exception ex)

                {

                     System.out.println("Exception arise at get Content");

                     ex.printStackTrace();

                }

           }

           store.close();

      }

catch (Exception e) {

System.out.println(e);  

}  

}

  public static void storePart(Part part) throws Exception

     {    

          InputStream input = part.getInputStream();

          if (!(input instanceof BufferedInputStream))

         {

              input = new BufferedInputStream(input);

          }

          int i;

         System.out.println("msg : ");

          while ((i = input.read()) != -1)

         {

         System.out.write(i);

         }

     }

}
Watch video
Send email using javax.mail source

Wednesday, January 19, 2011

Telnet Client with Java

This example implements Telnet with help of Telnet server. The code connects to the Telnet server and receives data whenever command "1" is entered


Watch video
https://youtu.be/sX0XAROhuiQ
import java.net.*;

import java.io.*;

class TelnetClient

{

    public static void main(String args[]) throws Exception

    {

        //Create object of Socket

        Socket soc=new Socket("localhost",8088);

        String Command;

        //Create object of Input Stream to read from socket

        DataInputStream din=new DataInputStream(soc.getInputStream());    

        //Create object of Output Stream   to write on socket 

        DataOutputStream dout=new DataOutputStream(soc.getOutputStream());

        // Object of Buffered Reader to read command from terminal

        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

        System.out.println("Welcome to Telnet Client");

        System.out.println("< Telnet Prompt >");

        Command=br.readLine();//reads the command 

        dout.writeUTF(Command);//sends command to server

        System.out.println(din.readLine()); //gets the response of server        

        soc.close();  //close port  

        din.close();  //close input stream     

        dout.close();  //close output stream      

        br.close();   //close buffered Reader    

    }

}
Watch video
Telnet Server Source

Telnet Server with Java

This code sends a string to a client whenever client connects it and sends the response to client when command "1" is received.


-Watch video
https://youtu.be/sX0XAROhuiQ
import java.lang.*;

import java.io.*;

import java.net.*;

class TelnetServer {

   public static void main(String args[]) {

      String data = "Hello Client!! ";

      try {

          // Create object of Server Socket 

         ServerSocket srvr = new ServerSocket(8088);

          // Socket object that listens the port (8088) and accepts the incoming connection

          //requests 

         Socket skt = srvr.accept();

         System.out.println("Client Connected!");

         // gets output stream object  

         PrintWriter out = new PrintWriter(skt.getOutputStream(), true);

         //gets input stream object    

         DataInputStream din=new DataInputStream(skt.getInputStream());        

         if(din.readUTF().equals("1")){ 

         // sends response to incoming request if command is '1'    



         System.out.println("String: '" + data);

         out.print(data);

         }

         out.close();// clos out

         skt.close();// close skt

         srvr.close();// close srvr

         din.close(); // close din

      }

      catch(Exception e) {

         System.out.print(e);

      }

   }

}
Watch video
Telnet Client Source

Thursday, January 13, 2011

Reading and Writhing Data from comm port in Java

This code first write 0x80 to COM port then it reads 0x32 from COM port and then sends 6 more bytes and to terminate the packet it sends 0x70.

import java.io.*;
import java.util.*;
import javax.comm.*;
import java.sql.Connection;
import  java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class Fms implements Runnable{ 
    static Enumeration portList;
    static CommPortIdentifier portId;
    static SerialPort serialPort;
    static OutputStream outputStream;
    static InputStream inputStream;
    static Thread readThread,dataBase;
    static int crf;
    static int cwf;
    static byte cxc[] = new byte[4];
    static int cxm = 128;//0x80
    static byte[] creadBuffer;//1byte read
    static int creadBuff[]; 
    write rt=new write();
    static read rd;   
     public void run() {
     };
    public static void main(String[] args) {
        int a=10;
        write wr = new write();
        read rd = new read(1);
         int b = 0;
        int speed=0,tcount=0,jcount=0,status=0;
      while(b!=10){      
       for(int j =0 ; j<=1;j++){
            try{
        wr.cwritemain(a); 
         rd.cmainx(a);          
         readThread.sleep(1000);
            }
            catch(Exception e){}
            if(j==0){
                status =creadBuff[1];
                jcount =creadBuff[5];
          System.out.println("results : "+status +"\t"+jcount); 
            }
            if(j==1){
                speed =creadBuff[1]*256+creadBuff[2];//to convert received data in decimal
                tcount =creadBuff[6];
          System.out.println("results : "+speed +"\t"+tcount); 
            }
             }    
    }            
       }
 static class write{        
         public void cwritemain(int m)
{       
             cwf = m;
             cxc[0] = 0x26;
             portList = CommPortIdentifier.getPortIdentifiers();
             System.out.println(portList.hasMoreElements());
while (portList.hasMoreElements()) {                                   
                                        portId = (CommPortIdentifier) portList.nextElement();
                                        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                                    
if (portId.getName().equals("COM1"))
{                                  
try {
serialPort = (SerialPort) portId.open("SimpleWriteApp32", 2000);
                                                  } catch (PortInUseException e) {
}
try {
outputStream = serialPort.getOutputStream();
} catch (Exception e) {
}
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (Exception e) {
}
                                               if(cwf==10){
try {
outputStream.write(cxm);// 0x80 written
serialPort.close();
                                                                outputStream.close();
} catch (Exception e) {
}
                                               }
                                        }
                                }
                        }
         }        
    }   
   static class read implements SerialPortEventListener{
      public read(int s) {}
      public void cmainx(int cp) {
crf = 10;
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals("COM1")) {
try {
                                                    serialPort = (SerialPort) portId.open("readapp32",
2000);
} catch (PortInUseException e) {
System.out.println(e.getMessage());
}
try {
inputStream = serialPort.getInputStream();
} catch (Exception e) {
System.out.println(e);
}
try {
serialPort.addEventListener(this);
} catch (Exception e) {
System.out.println(e);
}
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);                                                
} catch (Exception e) {
System.out.println(e);
}
}
}
}                       
}
        public void serialEvent(SerialPortEvent event) {            
            switch (event.getEventType()) {
case SerialPortEvent.DATA_AVAILABLE:
creadBuffer = new byte[8];
                                creadBuff= new int[8];
try {
                                   int i = 0;                               
while (inputStream.available() > 0) { 
                                          creadBuff[i]=inputStream.read();
                                          System.out.println("Data available is: "+creadBuff[i]);                                                  
                                               i++;
}
                                      inputStream.close();
} catch (IOException e) {
}
                                System.out.println("event");
System.out.println("recieved \t"+creadBuffer[0] );
if (creadBuffer[0] == 0x70) {
                                    System.out.println("Got 0x70"+creadBuffer[0] );
serialPort.close();
rd = new read(5);
rd.cmainx(1);// ag
                                }
                                if (creadBuffer[0] == 0x32) {
                                    System.out.println("Got"+creadBuffer[0] );
serialPort.close();                                
                                }
                                serialPort.close();
            }
        }
   }  
   }
Watch video

Saturday, January 8, 2011

Send email in Java

//javax.mail
This code sends mail using gmail smtp you may need javax.mail api to implement this code.


-Watch video
https://youtu.be/sX0XAROhuiQ
import java.util.Properties;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.Message.RecipientType;

import javax.mail.internet.AddressException;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;

import javax.mail.Store;

public class Main {

        public static void main(String[] args) {

try{

                    String host = "smtp.gmail.com";

                    String from = "abc@gmail.com";//your gmail account

                    String pass = "****";//your password of gmail account

                    Properties props = System.getProperties();

                    props.put("mail.smtp.starttls.enable", "true");

                    props.put("mail.smtp.host", host);

                    props.put("mail.smtp.user", from);

                    props.put("mail.smtp.password", pass);

                    props.put("mail.smtp.port", "587");

                    props.put("mail.smtp.auth", "true");

                    String[] to = {"xyz@gmail.com"};

                    // receiver mail address can be other then gmail

                    Session session = Session.getDefaultInstance(props, null);

                    MimeMessage message = new MimeMessage(session);

                    message.setFrom(new InternetAddress(from));

                    InternetAddress[] toAddress = new InternetAddress[to.length];

                    for( int i=0; i < to.length; i++ ) {

                        toAddress[i] = new InternetAddress(to[i]);

                    }

                    System.out.println(Message.RecipientType.TO);

                    for( int i=0; i < toAddress.length; i++) {

                        message.addRecipient(Message.RecipientType.TO, toAddress[i]);

                    }

                    message.setSubject("Java Mail!!!");//set subject of mail

                    message.setText("Hey!!! This is mail from your friend Java!!");//set mail content

                    Transport transport = session.getTransport("smtp");

                    transport.connect(host, from, pass);

                    transport.sendMessage(message, message.getAllRecipients());

                    transport.close();

                    }

                        catch(Exception e)

                    {

                        System.out.println(e);

                    }   

 }        

}
Watch video