Tuesday, September 1, 2015

SETTING ICON IMAGE TO SWING APPLICATION IN JAVA

SETTING ICON IMAGE:


Image i = new ImageIcon(ClassLoader.getSystemResource("world.png")).getImage();
setIconImage(i);

NOTE:

Image file should be placed in project source directory(src) and it should not be very large size...

SOCKET PROGRAMMING IN JAVA

SIMPLE CLIENT AND SERVER PROGRAMMING USING SOCKETS IN JAVA

         Server socket:
    import java.net.ServerSocket;
   import java.net.Socket;

                      ServerSocket ss=new ServerSocket(6655);
                       jLabel1.setText("SERVER STARTED....");
                        Socket s=ss.accept(); //WAIT TILL CONNECTION RECEIVED FROM CLIENT..
                        jLabel1.setText("SERVER CONNTECTED WITH CLIENT....");
                        DataInputStream dis=Input();
                        DataOutputStream dout=output();
                       String type=dis.readUTF();
                    System.out.Println(type);
      public  DataInputStream Input() throws IOException
    {
        DataInputStream dis=new DataInputStream(s.getInputStream());
        return dis;
       
    }
    public  DataOutputStream output() throws IOException
    {
        DataOutputStream dout=new DataOutputStream(s.getOutputStream());
        return dout;
       
    }




CLIENT SOCKET:-

Streams.java

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class Streams
{
    //Socket s;
    public DataInputStream Input(Socket s) throws IOException
    {
        DataInputStream dis=new DataInputStream(s.getInputStream());
        return dis;
       
    }
    public DataOutputStream output(Socket s) throws IOException
    {
        DataOutputStream dout=new DataOutputStream(s.getOutputStream());
        return dout;
       
    }
}
USING STREAMS IN NATIVE CODE:

NativecodecLIENT.java
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

String host=”localhost”;
   Socket s =new Socket(host,6655);//ESTABLISH CONNECTION TO SERVER WITH IP 127.0.0.0.1
     DataInputStream    dis=new Streams().Input(s);
        DataOutputStream    dout=new Streams().output(s);

          dout.writeUTF("data variable 1");

DYNAMICALLY ADDING DATA TO JTABLE IN JAVA SWING

ADDING STRING ARRAY OBJECT ELEMENTS IN JTABLE IN JAVA:-

         String col[] = {"FOOD ID","FOOD NAME","FOOD CATEGORY", "COST"};

 tableModel = new DefaultTableModel(col, 0);
jTable1.setModel(tableModel);
        try {
            String fid=”1”;
           String fname=”Data 1”;
           String fcateg=”data 2”;
          String cost=”20”;
              
            Object[] objs1 = {fid, fname, fcateg, cost};
            tableModel.addRow(objs1);

            }
             }
        catch (IOException | NumberFormatException ex)
        {
            Logger.getLogger(FoodHome.class.getName()).log(Level.SEVERE, null, ex);
        }


SIMPLE PDF CREATION IN JAVA

PDF CREATION IN JAVA USING ITEXT JAR:

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;


public class Pdfcreation
{
    public static void main(String[] args) throws FileNotFoundException
   {
      Document document = new Document();
      try
      {
         
         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("D:\\HelloWorld.pdf"));
         document.open();
         document.add(new Paragraph("OM GANAPATHAYAE NAMAHA..."));
           document.add(new Paragraph("OM GANAPATHAYAE NAMAHA..."));
         document.close();
         writer.close();
      }
      catch (DocumentException e)
      {
         e.printStackTrace();
      }
     
   }
   
}

SIMPLE  PDF BILL GENERATION IN JAVA:-

public void calc() throws IOException, ClassNotFoundException, SQLException, DocumentException
     {
       Date d=new Date();
         String line="***************************************************";
         DateFormat dateFormat = new SimpleDateFormat("HH-mm-ss");
          filename=dateFormat.format(d);
         Document document = new Document();
         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename+".pdf"));
         document.open();
         document.add(new Paragraph("BILL TIME:- "+d.toString()));
         document.add(new Paragraph("BILL NO:- "+max));
         document.add(new Paragraph(line));
         document.add(new Paragraph("HOTEL MANAGEMENT SYSTEM"));
         document.add(new Paragraph("**your food destination**"));
         document.add(new Paragraph(line));
        
         document.add(new Paragraph("FOOD   QTY  RATE  TOTAL-AMT"));
         document.add(new Paragraph(line));
        
        for (String l11 : l1)
        {
            Statement stm=new DataBase_Connection().ConnectionGet().createStatement();
            ResultSet rs = stm.executeQuery("select * from fooditems where fid='" + l11 + "'");
            while(rs.next())
            {
                
                document.open();
                fcost=rs.getString("cost");
                fname=rs.getString("fname");
                String qty=m1.get(l11);
               
                String tota=tot.get(l11);
                String cont=fname+"___"+qty+"___"+tota+"___"+fcost;
                document.add(new Paragraph(cont));
                 //str.add(cont);
                
            
            }
               
           
        }
        document.add(new Paragraph(line));
        document.add(new Paragraph("GRAND TOTAL:.."+grand));
        document.add(new Paragraph(line));
        document.add(new Paragraph("THANK YOU! VISIT AGAIN.."));
        document.close();
         writer.close();
        String gran=Double.toString(grand);
      
       
        dout.writeUTF(gran);
      
       
     }

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

RUNNING EXE FILE FROM JAVA ..

RUNNING EXE FILE FROM JAVA AND READ ITS EXE RESULT VALUES:
public void commonProcess() throws IOException, InterruptedException, ClassNotFoundException, SQLException
{
    dt=dateChooserCombo1.getText();
       Impvar vr=dbDate();
    int maxid=vr.max+1;
    String max=String.valueOf(maxid);
            ProcessBuilder pb = new ProcessBuilder("C:\\Users\\user\\Documents\\Visual Studio 2010\\Projects\\Nutri\\Nutri\\bin\\Debug\\Nutri","o",max,dt);
            Process ps = pb.start();
            int exitValue=ps.waitFor();
                BufferedReader reader;
                // System.out.println("Exit Value" + exitValue);
                if (exitValue == 0) {
                                reader = new BufferedReader(new InputStreamReader(ps
                                                                .getInputStream()));
                } else {
                                reader = new BufferedReader(new InputStreamReader(ps
                                                                .getErrorStream()));
                }
                StringBuilder sb = new StringBuilder();
      
                String temp = reader.readLine();
        
                while (temp != null)
        {
              
                          
                                sb.append(temp);
                                temp = reader.readLine();
         }
         reader.close();
               
        String stat=sb.toString().trim();
        if(stat.equalsIgnoreCase("Opened"))
        {
         JOptionPane.showMessageDialog(rootPane, "SECTION OPENED FOR DATE..."+dt);
        }
        else
        {
             JOptionPane.showMessageDialog(rootPane, "Execution ERROR...");
             System.out.println(stat);
            
        }
      
}
DISPLAY ANY DOCUMENTS IN JAVA(.txt,.pdf,.doc,.docx..etc)
 private static void display_File(String filename)
    {
        try {

            if ((new File(filename+".pdf")).exists()) {

                Process p = Runtime
                        .getRuntime()
                         .exec("rundll32 url.dll,FileProtocolHandler "+filename+".pdf");
                p.waitFor();

            } else {

              //  System.out.println("File does not exist");
                JOptionPane.showMessageDialog(null,"File does not exist" );

            }

        }
        catch (Exception ex)
        {
            ex.printStackTrace();
           
        }
    }
NOTE:-CHANGE EXTENSION ACCORDING TO USAGE TYPE

JDBC CONNECTION IN JAVA


DataBase_Connection.java

USING DATABASE COONECTION AS GLOBAL TO ALL PACKAGE:

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


public class DataBase_Connection
{
    private static final String USERNAME="root",PASSWORD="root",DRIVER="com.mysql.jdbc.Driver",
                          URL="jdbc:mysql://localhost/hotel";
    public Connection ConnectionGet() throws ClassNotFoundException, SQLException
    {
        Class.forName((DRIVER));
        Connection con=DriverManager.getConnection(URL, USERNAME,PASSWORD);
        return con;
        
        
    }
    
}

CALLING  DataBase_Connection.java IN NATIVE CODE:

INSERT QUERY:

Statement stm=new DatabaseConnection().ConnectionGet().createStatement();
stm.executeUpdate("insert into nutri(id,date) values("+maxid+",'"+dt+"')");

UPDATE QUERY:

Statement stm=new DatabaseConnection().ConnectionGet().createStatement();
 stm.executeUpdate("update nutri set "+colu+"='"+foodt+"' where id="+id+"");
JOptionPane.showMessageDialog(rootPane, colu+".. INSERTED FOR DATE...."+dt);

SELECT QUERY:
Statement stm=new DatabaseConnection().ConnectionGet().createStatement();
        ResultSet rs=stm.executeQuery("select * from nutri where id=(select max(id) from nutri)");
        while(rs.next())
                {
                    id=rs.getInt("id");
                    date=rs.getString("DATE").trim();
                          
                }

----------------------------------------------------------------------------------------------------
SIMPLE JDBC CONNECTION WITHOUT SEPERATE CLASS USING MY SQL:

SIMPLE DATA INSERTION WITH STRING STARTS WITH CHAR “-“:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public void datainsert() throws IOException
{
     Date dt=new Date();
       int maxid=0;
        try {
               String pattern = "dd/MM/yyyy";
               String pattern2="HH:mm:ss";
    SimpleDateFormat format = new SimpleDateFormat(pattern);
       String da=format.format(dt);
         SimpleDateFormat format2 = new SimpleDateFormat(pattern2);
         String tm=format2.format(dt);
        Class.forName("com.mysql.jdbc.Driver");
         Connection con= DriverManager.getConnection("Jdbc:mysql://localhost/stat","root","root");
        Statement stm=con.createStatement();
       ResultSet rs= stm.executeQuery("select max(id) from status");
       while(rs.next())
       {
          
            maxid=rs.getInt(1);
           
           
       }
       maxid+=1;
       String data=jPasswordField1.getText().trim();
       if(data.startsWith("-"))
       {
       stm.executeUpdate("insert into status values('"+maxid+"','"+da+"','"+tm+"','"+categ+data+"')");
      // JOptionPane.showMessageDialog(rootPane, "DATA ADDED");
      
       jPasswordField1.setText("");
       }
       else
       {
           throw new IOException("SYSTEM ERROR");
       }
        jButton1.setVisible(false);
       
        con.close();
        categ="$";
       
        }
       catch (SQLException | IOException |ClassNotFoundException e)
       {
           JOptionPane.showMessageDialog(rootPane, e.getMessage());
        }
      


}

ADDING JAVA APPLICATION IN SYSTEM TRAY


import java.awt.AWTException;
import java.awt.Image;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public void notify1(String stat) throws AWTException
{
   
   String icoPath = "D://world.png";

        if (SystemTray.isSupported()) {
            final SystemTray systemTray = SystemTray.getSystemTray();
            final TrayIcon trayIcon = new TrayIcon(new ImageIcon(icoPath, "omt").getImage(), "Aware");
            trayIcon.setImageAutoSize(true);// Autosize icon base on space
             

            MouseAdapter mouseAdapter = new MouseAdapter() {

                @Override
                public void mouseClicked(MouseEvent e) {
                    showframe();
                 
                }
            };
            //ADDING APP TO SYSTEM TRAY AT SPECIFIC CONDITION
            if(stat.equals("AWARE STARTED"))
            {
             trayIcon.addMouseListener(mouseAdapter);
              systemTray.add(trayIcon);
            }
       
            try
            {
               
              //DISPLAYING MESSAGE IN SYAYTEM TRAY..
                trayIcon.displayMessage("STATUS",stat,TrayIcon.MessageType.INFO);
            }
            catch (Exception e) {
                e.printStackTrace();
            }
           
        }
       
}

RMI-REMOTE METHOD INVOCATION: IN JAVA

RMI SERVER:-

import java.rmi.*;
import java.rmi.server.*;
import java.rmi.registry.*;
import java.util.Scanner;

public class RmiServe
{
    public static void main(String args[])
    {
        try
        {
            RmiImpl stub=new RmiImpl();
             Registry reg=LocateRegistry.createRegistry(1099);
            reg.rebind("server", stub);
            System.out.println("SERVER STARTED...");
            while(true)
            {
                Scanner in=new Scanner(System.in);
               
                String msg=in.nextLine().trim();
                if(stub.getClient()!=null)
                {
                    RmiInterc cli=stub.getClient();
                    cli.send(msg);
                   
                }
               
               
            }
           
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
}
}
RMI CLIENT:-

import java.rmi.*;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Scanner;

public class RmiClients
{
   public static void main(String args[]) throws RemoteException, NotBoundException
   {
     RmiImpl rm=new RmiImpl();
     Registry reg=LocateRegistry.getRegistry("127.0.0.1",1099);
       RmiInterc rmi=(RmiInterc)reg.lookup("server");
        System.out.println("CONNECTED TO SERVER");
        rmi.setClient(rm);
        while(true)
            {
                Scanner in=new Scanner(System.in);
            System.out.println("ENTER VALUE");
            String msg=in.nextLine().trim();
            rmi.send(msg);
            }
      
   }
}
RMI INTERFACE:

public interface RmiInterc extends Remote
{
 public void send(String msg) throws RemoteException;
  public void setClient(RmiInterc c)throws RemoteException;
  public RmiInterc getClient() throws RemoteException;

}
RMI IMPLEMENTING CLASS:

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class RmiImpl extends UnicastRemoteObject implements RmiInterc
{
         String dat;
    public RmiInterc client=null;
     RmiImpl() throws RemoteException
    {
        super();
    }
   
    public void send(String s) throws RemoteException
        {
                                System.out.println(s);
               
        }
      public void setClient(RmiInterc c)throws RemoteException
    {
        client=c;
       
    }
                public RmiInterc getClient() throws RemoteException
        {
            return client;
        }
   

}

RECEIVING MAIL IN JAVA

import java.util.Properties;
import javax.mail.Address;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import java.util.*;
import javax.mail.*;


public class ReceiveMailing {

 
    public static void main(String[] args) throws MessagingException
    {
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "imaps");
        try {
            Session session = Session.getInstance(props, null);
            Store store = session.getStore();
            store.connect("imap.gmail.com", "complaintszero@gmail.com", "your password");
            Folder inbox = store.getFolder("INBOX");
            inbox.open(Folder.READ_ONLY);
            Message msg = inbox.getMessage(inbox.getMessageCount());
            Address[] in = msg.getFrom();
            for (Address address : in) {
                System.out.println("FROM:" + address.toString());
            }
            Multipart mp = (Multipart) msg.getContent();
            BodyPart bp = mp.getBodyPart(0);
            System.out.println("SENT DATE:" + msg.getSentDate());
            System.out.println("SUBJECT:" + msg.getSubject());
            System.out.println("CONTENT:" + bp.getContent());
        } catch (Exception mex) {
            mex.printStackTrace();
        }

    }
   
}
NOTE: FOR BOTH MAIL SEND AND RECEIVE NEED JAR FILES MAIL.JAR AND  ACTIVATION.JAR

SENDING MAIL IN JAVA

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.*
public void sendmail(String sndmail,String name,String pwd)
    {
        //change accordingly

  //Get the session object
  Properties props = new Properties();
  props.put("mail.smtp.host", "smtp.gmail.com");
  props.put("mail.smtp.socketFactory.port", "465");

  props.put("mail.smtp.starttls.enable", "true");
 props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.port", "587");
 
   Session session = Session.getDefaultInstance(props,
   new javax.mail.Authenticator() {

   protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
   return new javax.mail.PasswordAuthentication("ragava08@gmail.com","YOUR PASSWORD");//change accordingly
 
   }
  });
 
  //compose message
  try
  {
   MimeMessage message = new MimeMessage(session);
   message.setFrom(new InternetAddress("ragava08@gmail.com"));//change accordingly
   message.addRecipient(Message.RecipientType.TO,new InternetAddress(sndmail.trim()));
   message.setSubject("sending maill java");
   message.setText("TEST MAIL THROUGH JAVA");
   
   //send message
   Transport.send(message);
  JOptionPane.showMessageDialog(rootPane, "MAIL SENT SUCCESSFULLY");

   //System.out.println("message sent successfully");
 
  }
  catch (MessagingException e)
  {
      throw new RuntimeException(e);
  }

    }


NOTE:
IF ABOVE CODE THROWS EXCEPTION..
CHANGE THE SESSION INSTANCE(BOLD WORDS) ... To BELOW CODE

Session s = Session.getInstance(props,new javax.mail.Authenticator()