Thursday, 29 December 2011

WebCam Integration in java using jmf

public class OfflineVisitorRegistration extends JFrame
{

    private static final long serialVersionUID = 1L;
    // ----------------------------Variables declaration-----------------------//
    public JLabel header, firstNameL, lastNameL, ContactInformationL, companyNameL, address1L, address2L, entryTypeL, lblmsg, barCodeL, hitex;
    public JTextField firstNameT, lastNameT, companyNameT, address1T, address2T, emptySpace;
    public JCheckBox barCodeT;
    public JButton save, print, newVisitor;
    public JComboBox entrySelector;
    public Font SansSerif;
    public String[] entryList;
    Calendar cal;
    int month;
    int year;
    int day;
    public DefaultTableModel dt1;
    public JTable jt1;
    Image img, webCamImg;
    ImageIcon barCodeicon = null;
    String ID;

    private PageFormat mPageFormat;
   
    JPanel contentPane = new JPanel();
    // ----------------------- ----End of variables
    // declaration------------------//

    public Container webContainer = getContentPane();
    public Player _player = null;
    public Image webImage = null;
    public Buffer buffer = null;
    public BufferToImage btoi = null;
    public ImageIcon webCamImageicon = null;

    // ----------------------- Constructor---------------------------------//

    public OfflineVisitorRegistration()
    {
        super();
        createForm();
        PrinterJob pj = PrinterJob.getPrinterJob();
        mPageFormat = pj.defaultPage();
       
        addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent e)
            {
                try
                {
                    _player.stop();
                    _player.deallocate();
                    _player.close();
                }
                catch (Exception e1)
                {
                    e1.printStackTrace();
                }

                System.exit(0);
            }
        });

        this.setVisible(true);
    }

    public void createForm()
    {
        SansSerif = new Font("SansSerif", Font.BOLD, 12);
        setLayout(new FlowLayout(FlowLayout.CENTER));

        Dimension left = new Dimension(120, 25);
        Dimension right = new Dimension(120, 25);
        Dimension stream = new Dimension(50, 300);

        header = new JLabel("<HTML><H1>VISITOR REGISTRATION FORM</H1></HTML>");
        hitex = new JLabel("<HTML><H1>HITEX</H1></HTML>");

        firstNameL = new JLabel("FirstName:");
        firstNameL.setPreferredSize(left);
        firstNameT = new JTextField();
        firstNameT.setPreferredSize(right);

        lastNameL = new JLabel("Service:");
        lastNameL.setPreferredSize(left);
        lastNameT = new JTextField();
        lastNameT.setPreferredSize(right);

        ContactInformationL = new JLabel("ContactInformation");
        ContactInformationL.setPreferredSize(left);

        companyNameL = new JLabel("Company:");
        companyNameL.setPreferredSize(left);
        companyNameT = new JTextField();
        companyNameT.setPreferredSize(right);

        address1L = new JLabel("Address1:");
        address1L.setPreferredSize(left);
        address1T = new JTextField();
        address1T.setPreferredSize(right);

        address2L = new JLabel("Address2:");
        address2L.setPreferredSize(left);
        address2T = new JTextField();
        address2T.setPreferredSize(right);

        emptySpace = new JTextField();

        entryTypeL = new JLabel("Entry Type:");
        entryTypeL.setPreferredSize(left);

        entryList = new String[3];
        entryList[0] = "Single";
        entryList[1] = "Multi";
        entryList[2] = "Pass";

        entrySelector = new JComboBox(entryList);
        entrySelector.setFont(SansSerif);

        barCodeT = new JCheckBox();
        barCodeL = new JLabel();
        barCodeL.setText("Generate BarCode:");

        lblmsg = new JLabel("", JLabel.CENTER);

        // --------------------------------------------buttons with action
        // listeners--------------------------------------------------------------//
        newVisitor = new JButton("New");
        newVisitor.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                newVisitor_actionPerformed(e);
            }

        });
        save = new JButton("Save");
        save.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                save_actionPerformed(e);
            }

        });
        print = new JButton("Print Preview");
        print.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                print();
            }
        });
        // -------------------------------------------------image path choose
        // code----------------------------------------------//
        JButton browse = new JButton("Browse");
        browse.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                browseImage(e);
            }
        });

        // --------------------------------------------image capture buttons
        // with action listeners---------------------------------------//
        JPanel panel = new JPanel();
        panel.setPreferredSize(stream);

        contentPane = new JPanel(new BorderLayout());
        JLabel contentPaneLabel = null;
        if (webCamImageicon == null)
        {
            contentPaneLabel = new JLabel(new ImageIcon("D:/image1.jpg"));
        }
        else
        {
            contentPaneLabel = new JLabel(webCamImageicon);
        }

        contentPaneLabel.setHorizontalAlignment(JLabel.CENTER);
        contentPane.add(contentPaneLabel);

        JButton start = new JButton("Start");
        start.setMnemonic('S');
        start.setCursor(new Cursor(Cursor.HAND_CURSOR));
        // ****************************Action listener for start
        // streaming***************************//
        start.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                _player.start();
            }
        });

        JButton stop = new JButton("Stop");
        stop.setMnemonic('S');
        stop.setCursor(new Cursor(Cursor.WAIT_CURSOR));
        // ****************************Action listener for Stop
        // streaming***************************//
        stop.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                _player.stop();
            }
        });

        JButton snap = new JButton("Take photo");
        snap.setMnemonic('T');
        snap.setCursor(new Cursor(Cursor.HAND_CURSOR));

        // ********************Action listener for Take Snap from video
        // streaming***************************//
        snap.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                String mlcoation = "vfw:Micrsoft WDM Image Capture (Win32):0";
                FrameGrabbingControl fgc = (FrameGrabbingControl) _player.getControl("javax.media.control.FrameGrabbingControl");
                buffer = fgc.grabFrame();
                btoi = new BufferToImage((VideoFormat) buffer.getFormat());
                img = btoi.createImage(buffer);
                Image image1 = img.getScaledInstance(75, 75, java.awt.Image.SCALE_SMOOTH);
                webCamImageicon = new ImageIcon(image1);
                try {
                    _player.stop();
                } catch (Exception e1) {
                    e1.printStackTrace();
                }

            }
        });

        // --------------------------media
        // locater------------------------------------------//

        String mediaFile = "vfw:Micrsoft WDM Image Capture (Win32):0";
        try
        {
            MediaLocator mlr = new MediaLocator(mediaFile);
            _player = Manager.createRealizedPlayer(mlr);

            if (_player.getVisualComponent() != null)
            {
                panel.add(_player.getVisualComponent());
            }
        }
        catch (Exception e)
        {
            System.err.println("media stream exception " + e);
        }

        // =====================form fields
        // allignMent=================================//

        Box firstNameBox = new Box(BoxLayout.X_AXIS);

        firstNameBox.add(firstNameL);
        firstNameBox.add(Box.createHorizontalStrut(15));
        firstNameBox.add(firstNameT);

        Box lastNameBox = new Box(BoxLayout.X_AXIS);
        lastNameBox.add(lastNameL);
        lastNameBox.add(Box.createHorizontalStrut(15));
        lastNameBox.add(lastNameT);

        Box companyNamBox = new Box(BoxLayout.X_AXIS);
        companyNamBox.add(companyNameL);
        companyNamBox.add(Box.createHorizontalStrut(15));
        companyNamBox.add(companyNameT);

        Box addressLine1Box = new Box(BoxLayout.X_AXIS);
        addressLine1Box.add(address1L);
        addressLine1Box.add(Box.createHorizontalStrut(15));
        addressLine1Box.add(address1T);

        Box addressLine2Box = new Box(BoxLayout.X_AXIS);
        addressLine2Box.add(address2L);
        addressLine2Box.add(Box.createHorizontalStrut(15));
        addressLine2Box.add(address2T);

        Box entryTypeBox = new Box(BoxLayout.X_AXIS);
        entryTypeBox.add(entryTypeL);
        entryTypeBox.add(Box.createHorizontalStrut(15));
        entryTypeBox.add(entrySelector);

        Box fieldSet1Box = new Box(BoxLayout.Y_AXIS);
        fieldSet1Box.add(firstNameBox);
        fieldSet1Box.add(Box.createVerticalStrut(15));
        fieldSet1Box.add(lastNameBox);
        fieldSet1Box.add(Box.createVerticalStrut(15));
        fieldSet1Box.add(companyNamBox);

        Box fieldSet2Box = new Box(BoxLayout.Y_AXIS);
        fieldSet2Box.add(addressLine1Box);
        fieldSet2Box.add(Box.createVerticalStrut(15));
        fieldSet2Box.add(addressLine2Box);
        fieldSet2Box.add(Box.createVerticalStrut(15));
        fieldSet2Box.add(entryTypeBox);

        Box visitorFormBox = new Box(BoxLayout.X_AXIS);
        visitorFormBox.add(fieldSet1Box);
        visitorFormBox.add(Box.createHorizontalStrut(15));
        visitorFormBox.add(fieldSet2Box);

        Box formButtonsBox = new Box(BoxLayout.X_AXIS);
        formButtonsBox.add(newVisitor);
        formButtonsBox.add(Box.createHorizontalStrut(15));
        formButtonsBox.add(save);
        formButtonsBox.add(Box.createHorizontalStrut(15));
        formButtonsBox.add(print);

        Box formWithButtonsBox = new Box(BoxLayout.Y_AXIS);
        formWithButtonsBox.add(visitorFormBox);
        formWithButtonsBox.add(Box.createVerticalStrut(30));
        formWithButtonsBox.add(formButtonsBox);

        Box formLayoutBox = new Box(BoxLayout.X_AXIS);
        formLayoutBox.add(formWithButtonsBox);
        // ================End of form fields
        // allignMent=================================//

        // ===============Media Component==========================//
        Box mediaButtonBox = new Box(BoxLayout.X_AXIS);
        mediaButtonBox.add(start);
        mediaButtonBox.add(Box.createHorizontalStrut(15));
        mediaButtonBox.add(stop);
        mediaButtonBox.add(Box.createHorizontalStrut(15));
        mediaButtonBox.add(snap);
        mediaButtonBox.add(Box.createHorizontalStrut(15));
        mediaButtonBox.add(browse);

        Box mediaStreamWithButtons = new Box(BoxLayout.Y_AXIS);
        mediaStreamWithButtons.add(panel);
        mediaStreamWithButtons.add(Box.createHorizontalStrut(30));
        mediaStreamWithButtons.add(mediaButtonBox);

        Box b14 = new Box(BoxLayout.Y_AXIS);
        b14.add(mediaStreamWithButtons);
        b14.add(Box.createVerticalStrut(15));
        b14.add(formLayoutBox);

        add(hitex);
        add(header);
        // add(contentPane);
        add(mediaStreamWithButtons);
        add(formLayoutBox);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocation(00, 00);
        setBackground(new Color(193,247,245));
        setSize(750, 1000);
        setVisible(true);
    }

    // ---------------------------------------------------------------------------------------//
    // -------------------------------Save
    // functionality--------------------------------------//
    // ---------------------------------------------------------------------------------------//
    private void save_actionPerformed(ActionEvent e)
    {
        System.out.println("\nSave_actionPerformed(ActionEvent e) called.");
        save.setEnabled(false);
        print.setEnabled(true);

        cal = Calendar.getInstance();
        month = cal.get(Calendar.MONTH);
        year = cal.get(Calendar.YEAR);
        day = cal.get(Calendar.DAY_OF_MONTH);

        String firstName = new String(firstNameT.getText());
        String LastName = new String(lastNameT.getText());
        String companyName = new String(companyNameT.getText());
        String address1 = new String(address1T.getText());
        String address2 = new String(address2T.getText());
        String entryType = "";

        int selection = entrySelector.getSelectedIndex();
        switch (selection)
        {
        case 0:
            entryType = "Single";
            break;

        case 1:
            entryType = "Multi";
            break;

        case 2:
            entryType = "Pass";
            break;
        }

        ID = (firstName + day + "." + (month + 1) + "." + year + entryType);

        PreparedStatement pstm;
        try
        {
            // --------------------loading the
            // driver------------------------------------//
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            Connection connect = DriverManager.getConnection("jdbc:odbc:Visitor_Registration");

            pstm = connect.prepareStatement("insert into Visitor_Registration(firstName,service,company) values(?,?,?)");

            pstm.setString(1, firstName);
            pstm.setString(2, LastName);
            pstm.setString(3, companyName);

            // -----------------execute method to execute the
            // query-----------------------------------------------//
            pstm.executeUpdate();
            lblmsg.setText("<HTML><FONT COLOR = Blue>Details have been added to database</FONT></HTML>");
            JOptionPane.showMessageDialog(null, lblmsg);
            // -----------------closing the prepared statement and connection
            // object-------------------------------//
            pstm.close();
            connect.close();
        }
        catch (SQLException sqe)
        {
            System.out.println("SQl error" + sqe.getMessage());
        }
        catch (ClassNotFoundException cnf)
        {
            System.out.println("Class not found error");
        }
    }

    // ---------------------------------------------------------------------------------------//
    // -------------------------------Refresh Form -------------------------------------------//
    // ---------------------------------------------------------------------------------------//

    public void newVisitor_actionPerformed(ActionEvent e)
    {
        firstNameT.setText("");
        lastNameT.setText("");
        companyNameT.setText("");
        address1T.setText("");
        address2T.setText("");
        barCodeT.setSelected(false);
        ID = "";
        save.setEnabled(true);
        print.setEnabled(false);
        webCamImageicon = null;
    }

    // ---------------------------------------------------------------------------------------//
    // -------------------------------Printfunctionality-------------------------------------//
    // ---------------------------------------------------------------------------------------//
    public void print()
    {
        String firstName = "";
        String LastName = "";
        String companyName = "";
        String entryType = "";
        firstName = new String(firstNameT.getText());
        LastName = new String(lastNameT.getText());
        companyName = new String(companyNameT.getText());

        int selection = entrySelector.getSelectedIndex();
        switch (selection)
        {
        case 0:
            entryType = "Single";
            break;
        case 1:
            entryType = "Multi";
            break;
        case 2:
            entryType = "Pass";
            break;
        }

        JFrame frame = new JFrame("ID Printing");
//        if (barCodeT.isSelected() == true)
//        {
//            // Barcode39 codeEAN = new Barcode39();
//            Barcode128 codabar = new Barcode128();
//            codabar.setBarHeight(40);
//            codabar.setSize(500);
//            codabar.setCode("4./s44");
//            img = codabar.createAwtImage(Color.BLACK, Color.WHITE);
//            barCodeicon = new ImageIcon(img);
//        }

        //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        String[] columnNames =    { "", "" };
        ImageIcon hitexIcon = new ImageIcon(getClass().getResource("logo.jpg"));
        JLabel lbl = new JLabel();
        lbl.setIcon(hitexIcon);
       
        Object[][] data =
        {
                { hitexIcon,"<HTML><H4><FONT COLOR = Blue >HITEX BITE ON-2012 </FONT></H4></HTML>" }
                ,{webCamImageicon,"<HTML><B><FONT> " + firstName + "<br>" + companyName + "<br>" + LastName+ "</FONT></B></HTML>"}
        };

        DefaultTableModel model = new DefaultTableModel(data, columnNames);
       
        final JTable table = new JTable(model)
        {
            private static final long serialVersionUID = 2332482825563749721L;

            public Class getColumnClass(int column)
            {
                if (column == 0)
                {
                    return Icon.class;
                }
                if (column == 1)
                {
                    return String.class;
                }
                return String.class;
            }
        };
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.setRowHeight(100);
       
        table.getColumnModel().getColumn(0).setPreferredWidth(100);
        table.getColumnModel().getColumn(1).setPreferredWidth(200);
        //table.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED,Color.BLUE, Color.GRAY));
        table.setShowHorizontalLines(false);
        table.setShowVerticalLines(false);
       
       
        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setBorder(BorderFactory.createEmptyBorder());
        frame.add(scrollPane, BorderLayout.LINE_START);
        JButton button = new JButton("Print");
       
        //==================================================================//
       
        ActionListener printAction = new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                PrinterJob pj = PrinterJob.getPrinterJob();
                ComponentPrintable cp = new ComponentPrintable(table);
               
                Paper paper= mPageFormat.getPaper();
                paper.setSize(100, 90);
                paper.setImageableArea(1, 1, 1270, 1000);
                mPageFormat.setPaper(paper);
                mPageFormat.setOrientation(PageFormat.PORTRAIT);
               
                pj.setPrintable(cp, mPageFormat);
                if (pj.printDialog())
                {
                    try
                    {
                        pj.print();
                    }
                    catch (PrinterException e1)
                    {
                        System.out.println(e1);
                    }
                }
            }
        };
        button.addActionListener(printAction);
        frame.add(button, BorderLayout.SOUTH);
        frame.setVisible(true);
        frame.setLocation(new Point(76, 182));
        frame.setSize(new Dimension(400, 300));
    }

    // ---------------------------------------browseImage------------------------------------------------//
    public void browseImage(ActionEvent e)
    {
        FileSelect fileSelect = new FileSelect();
        String fileContent = fileSelect.getImagePath();
        if (fileContent != null)
        {
            ImageIcon browsedIcon = new ImageIcon(fileContent);
            Image browsedImage = browsedIcon.getImage();
            webCamImageicon = new ImageIcon(browsedImage.getScaledInstance(75, 75, java.awt.Image.SCALE_SMOOTH));
        }
    }

    // ---------------------------------------------------------------------------------------//
    // -------------------------------Main---------------------------------------------------//
    // ---------------------------------------------------------------------------------------//
    public static void main(String[] args)
    {
        JFrame.setDefaultLookAndFeelDecorated(true);
        JDialog.setDefaultLookAndFeelDecorated(true);
        try
        {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        }
        catch (Exception ex)
        {
            System.out.println("Failed loading L&F: ");
            System.out.println(ex);
        }
        new OfflineVisitorRegistration();
    };
   
   
    class ComponentPrintable implements Printable
    {
          private Component mComponent;

          public ComponentPrintable(Component c)
          {
            mComponent = c;
          }

          public int print(Graphics g, PageFormat pageFormat, int pageIndex)
          {
            if (pageIndex > 0)
              return NO_SUCH_PAGE;
           
            Graphics2D g2 = (Graphics2D) g;
            g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
            boolean wasBuffered = disableDoubleBuffering(mComponent);
            mComponent.paint(g2);
            restoreDoubleBuffering(mComponent, wasBuffered);
            return PAGE_EXISTS;
          }

          private boolean disableDoubleBuffering(Component c)
          {
            if (c instanceof JComponent == false)
              return false;
            JComponent jc = (JComponent) c;
            boolean wasBuffered = jc.isDoubleBuffered();
            jc.setDoubleBuffered(false);
            return wasBuffered;
          }

          private void restoreDoubleBuffering(Component c, boolean wasBuffered)
          {
            if (c instanceof JComponent)
              ((JComponent) c).setDoubleBuffered(wasBuffered);
          }
    }

    }