Tuesday, December 24, 2013

Java JTable Set Column's Read Only / Editable

{
    boolean[] canEdit = new boolean [] {
        false, true, false, false, false, false, false
    };
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return canEdit [columnIndex];
    }
}

Java JTable Hide / Off Table Column Header


jTable_sales_cotation.setTableHeader(null);

java JTable resize Table Column

 try {
           
      
            //get table model
            DefaultTableModel model = (DefaultTableModel) jTable_sales_cotation.getModel();
            model.addRow(new Object[]{
                item_code, item_description, quantity, unit, price,
                discount, line_total });
               jTable_sales_cotation.setAutoResizeMode(jTable_sales_cotation.AUTO_RESIZE_OFF);
              jTable_sales_cotation.getColumnModel().getColumn(0).setPreferredWidth(70);
              jTable_sales_cotation.getColumnModel().getColumn(1).setPreferredWidth(270);
              jTable_sales_cotation.getColumnModel().getColumn(2).setPreferredWidth(50);
              jTable_sales_cotation.getColumnModel().getColumn(3).setPreferredWidth(52);
              jTable_sales_cotation.getColumnModel().getColumn(4).setPreferredWidth(110);
              jTable_sales_cotation.getColumnModel().getColumn(5).setPreferredWidth(78);
              jTable_sales_cotation.getColumnModel().getColumn(6).setPreferredWidth(90);
   
            //DB operation

            //log.main(query);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Error: " + e, "Error in connectivity", JOptionPane.ERROR_MESSAGE);
        }
        update_total();
//        __Update_table();
//        __clear();

java Multiple DB Table Insert Statement and Rollback

  try {
                                    //DB OPERATION
                                    //TURN OFF AUTO COMMIT
                                    conn.setAutoCommit(false);
                                    //CREATE DB SAVEPOINT
                                    Savepoint save1 = conn.setSavepoint();
           
                              try{
                             
                          
                                        java.sql.Statement pst = conn.createStatement();
                                        pst.executeUpdate("INSERT INTO sales_dcl_orders ("
                                        + "order_no, trans_type, version, type,"
                                        + "debtor_no, branch_code, reference, customer_ref,"
                                        + "comments, ord_date, order_type, ship_via,"
                                        + "delivery_address, contact_phone, contact_email, deliver_to,"
                                        + "freight_cost, from_stk_loc, delivery_date, payment_terms,"
                                        + "total, insert_date,user_name) VALUES "
                                        + "('"+ max_id + "','"  + 32+ "','"  + 0 + "','"  + 0 + "'"
                                        + ",'"  + cus_id + "','"  + branch_id + "','"  + reference + "','"  + customer_ref + "'"
                                        + ",'"  + comments + "','"  + Ord_Date + "','"  + Order_Type_id + "','"  + Ship_Vaia_Id + "'"
                                        + ",'"  + Delv_Address + "','"  + Phone + "','"  + "" + "','"  + deliver_to + "'"
                                        + ",'"  + shipping_charge + "','"  + From_Loc_Id + "','"  + val_date + "','"  + Payment_tarm_id + "'"
                                        + ",'"  + inv_total + "','"  + u.todays_datetime() + "','"  + Dashboard.user_id + "')",Statement.RETURN_GENERATED_KEYS);
                
                               
                                   pst.executeUpdate("INSERT INTO audit_trail ("
                                        + "type, trans_no, user_id, description,"
                                        + "fiscal_year, gl_date, type_details ) VALUES "
                                        + "('"+ 32 + "','"  + max_id + "','"  + Dashboard.user_id  + "','"  + "" + "'"
                                        + ",'"  + fiscal_year_id + "','"  + u.todays_date() + "','"  + "Sales Quotation" + "')",Statement.RETURN_GENERATED_KEYS);
                             
                                  
                                 
                                  // get details from table and send to DB
                                 
                                int rowcount = jTable_sales_cotation.getRowCount();
                                   String item_code;
                                   String item_desc;
                                   String item_unit;
                                   String item_quentity;
                                   String item_price;
                                   String item_discount;
                                   while(rowcount > 0){
                                    rowcount--;
                                    item_code = jTable_sales_cotation.getModel().getValueAt(rowcount, 0).toString();
                                    item_desc = jTable_sales_cotation.getModel().getValueAt(rowcount, 1).toString();
                                    item_quentity = jTable_sales_cotation.getModel().getValueAt(rowcount, 2).toString();
                                    item_unit = jTable_sales_cotation.getModel().getValueAt(rowcount, 3).toString();
                                    item_price = jTable_sales_cotation.getModel().getValueAt(rowcount, 4).toString();
                                    item_discount = jTable_sales_cotation.getModel().getValueAt(rowcount, 5).toString();

                                      pst.executeUpdate("INSERT INTO sales_dcl_order_details ("
                                        + "order_no, trans_type, stk_code, description, unit,"
                                        + "unit_price, quantity, discount_percent, insert_date ) VALUES "
                                        + "('"+ max_id + "','"  + 32+ "','"  + item_code + "','"  + item_desc + "','"  + item_unit + "'"
                                        + ",'"  + item_price + "','"  + item_quentity + "','"  + item_discount + "','"  + u.todays_datetime() + "')",Statement.RETURN_GENERATED_KEYS);
                                     
                                }
                        //ALL DONE, COMMIT DB CHANGES
                                       conn.commit();
                                       JOptionPane.showMessageDialog(this, "Successful", "Successful", JOptionPane.PLAIN_MESSAGE);
                            } catch (Exception e) {
                                        pst.close();
                                        conn.rollback(save1);
                                        conn.setAutoCommit(true);
                                        JOptionPane.showMessageDialog(this, "Failed 3" +e, "Error in connectivity", JOptionPane.ERROR_MESSAGE);
                                        return;
                            }
                    } catch (Exception e) {
                        JOptionPane.showMessageDialog(this, e, "Invalid", JOptionPane.ERROR_MESSAGE);
                    }
            
                //TURN ON AUTO COMMIT
                       try {
                           conn.setAutoCommit(true);
                       } catch (SQLException ex) {
               //            Logger.getLogger(PurchaseOrder.class.getName()).log(Level.SEVERE, null, ex);
                       }
                    }

Java Hash Map Set and get Data

Set Hash Map

 private TreeMap <String, String> itemMap = new TreeMap<String, String>();
     private TreeMap <String, String> itemMap1 = new TreeMap<String, String>();
     private void FillCombo_Items(){
       
         //int row = jTable_Roles.getSelectedRow();
          // jCombo_Items.removeAllItems();
           itemMap.clear();
           itemMap1.clear();
          
           String S;
           String sql = "Select stock_id,description,units from inventory_dcl_stock_master ORDER BY description ASC";
        try {
                pst = conn.prepareStatement(sql);
               ResultSet rs_item = pst.executeQuery();
                jCombo_Items.addItem("");
                  
        while(rs_item.next()){
                 S = rs_item.getString("description");
                jCombo_Items.addItem(S);
                itemMap.put(rs_item.getString("stock_id"), S);
                itemMap1.put(S, rs_item.getString("units"));
              }
             
        }catch (Exception e) {
           
            JOptionPane.showMessageDialog(this, "Error in connecitivity " +e);
        }
       
        
    }

Get Data From  it

  stock_name = (String) jCombo_Items.getSelectedItem();
           stock_id = getKeyForValue(stock_name,itemMap);
           unit = getValueForKey(stock_name,itemMap1);
         

Java View Hashmap Data

Download Gson

https://code.google.com/p/google-gson/

Gson gson = new Gson();

System.out.println(gson.toJson(itemMap1));

Output:
{"17inch VGA Monitor":"ea","32MB VGA Card":"ea","52x CD Drive":"ea","Assembly Labour":"hrs","Black Fluid":"ea","Blue Fluid":"ea","Fluid 2":"ea","MK-Comx":"ea","P4 Business System":"ea","RX-35V":"ea","RX-55V":"ea","Red Fluid":"ea","s o d a":"ea"}

Sunday, September 15, 2013

Java Xml modify

package Utility;

/**
 *
 * @author Sakib
 */
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ModifyXMLFile {

    public static void main(String argv[]) {

       try {
        String filepath = "c:\\temp\\file.xml";
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(filepath);

        // Get the root element
        Node company = doc.getFirstChild();

        // Get the staff element , it may not working if tag has spaces, or
        // whatever weird characters in front...it's better to use
        // getElementsByTagName() to get it directly.
        // Node staff = company.getFirstChild();

        // Get the staff element by tag name directly
        Node staff = doc.getElementsByTagName("staff").item(1);

        // update staff attribute
        NamedNodeMap attr = staff.getAttributes();
        Node nodeAttr = attr.getNamedItem("id");
        nodeAttr.setTextContent("2");

        // append a new node to staff
        Element age = doc.createElement("age");
        age.appendChild(doc.createTextNode("28"));
        staff.appendChild(age);

        // loop the staff child node
        NodeList list = staff.getChildNodes();

        for (int i = 0; i < list.getLength(); i++) {

                   Node node = list.item(i);

           // get the salary element, and update the value
           if ("salary".equals(node.getNodeName())) {
            node.setTextContent("2000000");
           }

                   //remove firstname
        //   if ("firstname".equals(node.getNodeName())) {
        //    staff.removeChild(node);
        //   }

        }

        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(filepath));
        transformer.transform(source, result);

        System.out.println("Done");

       } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
       } catch (TransformerException tfe) {
        tfe.printStackTrace();
       } catch (IOException ioe) {
        ioe.printStackTrace();
       } catch (SAXException sae) {
        sae.printStackTrace();
       }
    }
}

Java XML Read


package Utility;

/**
 *
 * @author Sakib
 */


import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ReadXMLFile {

   public static void main(String argv[]) {

    try {

    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser saxParser = factory.newSAXParser();

    DefaultHandler handler = new DefaultHandler() {

    boolean bfname = false;
    boolean blname = false;
    boolean bnname = false;
    boolean bsalary = false;

    public void startElement(String uri, String localName,String qName,
                Attributes attributes) throws SAXException {

        System.out.println("Start Element :" + qName);

        if (qName.equalsIgnoreCase("FIRSTNAME")) {
            bfname = true;
        }

        if (qName.equalsIgnoreCase("LASTNAME")) {
            blname = true;
        }

        if (qName.equalsIgnoreCase("NICKNAME")) {
            bnname = true;
        }

        if (qName.equalsIgnoreCase("SALARY")) {
            bsalary = true;
        }

    }

    public void endElement(String uri, String localName,
        String qName) throws SAXException {

        System.out.println("End Element :" + qName);

    }

    public void characters(char ch[], int start, int length) throws SAXException {

        if (bfname) {
            System.out.println("First Name : " + new String(ch, start, length));
            bfname = false;
        }

        if (blname) {
            System.out.println("Last Name : " + new String(ch, start, length));
            blname = false;
        }

        if (bnname) {
            System.out.println("Nick Name : " + new String(ch, start, length));
            bnname = false;
        }

        if (bsalary) {
            System.out.println("Salary : " + new String(ch, start, length));
            bsalary = false;
        }

    }

     };

       saxParser.parse("c:\\temp\\file.xml", handler);

     } catch (Exception e) {
       e.printStackTrace();
     }

   }

}

Sunday, August 11, 2013

Java Check Number Value

public boolean checkIfNumber(String in) {

        try {

            Integer.parseInt(in);

        } catch (NumberFormatException ex) {
            return false;
        }

        return true;
    }

Friday, August 9, 2013

Java Data Log File Create

MyLogger log = new MyLogger();
lg = "Query....................."
log.main(lg);


Library Class

package dcl_payroll;

/**
 *
 * @author sakib
 */
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class MyLogger {
   
   // public static void main(String[] args) {
    public static void main(String s) {
       
        Logger logger = Logger.getLogger("MyLog");
        FileHandler fh;
       
        try {
           
            // This block configure the logger with handler and formatter
            int limit = 1000000; // 1 Mb
            fh = new FileHandler("C:\\temp\\test\\MyLogFile.log", limit,1,true);
         //   fh = new FileHandler("C:/temp/test/MyLogFile.log");
            logger.addHandler(fh);
            //logger.setLevel(Level.ALL);
            SimpleFormatter formatter = new SimpleFormatter();
            fh.setFormatter(formatter);
           
            // the following statement is used to log any messages
            logger.info(s);
           
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
       
      //  logger.info("Hi How r u?");
       
    }
   
}

Java Call System Notepad


 private void jMenuItem_NotepadActionPerformed(java.awt.event.ActionEvent evt) {                                                 
        runComponents("Notepad.exe");
    }

    protected void runComponents(String sComponents)
    {
        Runtime rt = Runtime.getRuntime();
        try{rt.exec(sComponents);}
        catch(IOException evt){JOptionPane.showMessageDialog(null,evt.getMessage(),"Error Found",JOptionPane.ERROR_MESSAGE);}
    }

Java Call System Calculator

private void jMenuItem_CalculatorActionPerformed(java.awt.event.ActionEvent evt) {                                                    
         runComponents("Calc.exe");
    } 



    protected void runComponents(String sComponents)
    {
        Runtime rt = Runtime.getRuntime();
        try{rt.exec(sComponents);}
        catch(IOException evt){JOptionPane.showMessageDialog(null,evt.getMessage(),"Error Found",JOptionPane.ERROR_MESSAGE);}
    }

Java SearchKeyTyped

private void jTextField_SearchKeyTyped(java.awt.event.KeyEvent evt) {                                          
         clear();
                
                ax = jTextField_Search.getText().trim();
                String sql = "Select * from dclemployee where EmpId like ? or DclFirstname like ? or DclLastname like ? or DclPhoneC like ? or DclEmail like ?";
              
            //JOptionPane.showMessageDialog(this, jTable_Roles.getModel().getValueAt(row, 0).toString());
          
        try {
             
              pst = conn.prepareStatement(sql);
              pst.setString(1,  "%" + ax );
              pst.setString(2, ax + "%");
              pst.setString(3, ax + "%");
              pst.setString(4, ax + "%");
              pst.setString(5, ax );
              rs = pst.executeQuery();

}

Java Image Upload with Crop And Bolb Creation

private void jButton_Image_UploadActionPerformed(java.awt.event.ActionEvent evt) {                                                    
        JFileChooser chooser = new JFileChooser();
        chooser.showOpenDialog(null);
        File f = chooser.getSelectedFile();

        filename = f.getAbsolutePath();

        String fileName1 = f.getName();
        String filePath = filename.substring(0, filename.lastIndexOf(File.separator));

        //  JOptionPane.showMessageDialog(null, filePath);
        JOptionPane.showMessageDialog(null, fileName1);

        jTextField_Path.setText(filename);
        //JOptionPane.showMessageDialog(null, filename);

        try {
            imagex = new File(filename);
            fis = new FileInputStream(imagex);

            // image scale down method

            BufferedImage originalImage = ImageIO.read(new File(filename));//change path to where file is located
            int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();

            BufferedImage resizeImageJpg = resizeImage(originalImage, type, 100, 100);
            ImageIO.write(resizeImageJpg, "jpg", new File("d:\\test\\Dcl" + fileName1));

            // image scale down method

            // send to DB start
            image2 = new File("d:\\test\\Dcl" + fileName1);
            inputStream = new FileInputStream(image2);
            // send to DB End


            //  JOptionPane.showMessageDialog(null, os);

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                bos.write(buf, 0, readNum);

            }
            upload_image = bos.toByteArray();
            // view uploaded image
            ImageIcon tinyPicture = new ImageIcon(upload_image);
            Image imagexx = tinyPicture.getImage();
            //  JOptionPane.showMessageDialog(null, imagexx);
            imagexx = imagexx.getScaledInstance(105, -1, imagexx.SCALE_SMOOTH);
            tinyPicture.setImage(imagexx);
            jLabel_Image.setIcon(tinyPicture);

        } catch (Exception e) {
            System.out.println("Exception Occured:" + e);
        }
    }             

   private static BufferedImage resizeImage(BufferedImage originalImage, int type, int IMG_WIDTH, int IMG_HEIGHT) {
                        BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
                        Graphics2D g = resizedImage.createGraphics();
                        g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
                        g.dispose();

                        return resizedImage;
        }                                     

Java View Bolb Image Form Database

  if( rs.getBlob("DclImage") == null  ){
                           
                            jLabel_Image.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/datacraft.jpg")));
                       
                        }else{
                           
                            java.sql.Blob imageBlob = rs.getBlob("DclImage");

                            byte[] imageBytes = imageBlob.getBytes(1, (int) imageBlob.length());

                                // for scalling image code
                            ImageIcon tinyPicture= new ImageIcon(imageBytes);
                            Image image= tinyPicture.getImage();
                            image = image.getScaledInstance(105, -1, image.SCALE_SMOOTH);
                            tinyPicture.setImage(image);
                            jLabel_Image.setIcon(tinyPicture);
                        }

Java Close Window With Confirmation Dialog

   public void close(){
              int p = JOptionPane.showConfirmDialog(null, "Do you really want to Exit","Exit",JOptionPane.YES_NO_OPTION);
                if(p == 0){
                try{
                        WindowEvent winClosingEvent = new WindowEvent(this,WindowEvent.WINDOW_CLOSING);
                        Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(winClosingEvent);
                }catch(Exception e){
                       
                   JOptionPane.showMessageDialog(this, e, "Invalid", JOptionPane.ERROR_MESSAGE);
        }
           
       }
    }

Java Clear Text Box And Combo Box

 public void clear(){
       
             try{

                 jText_Allowence.setText("");
                 jTextArea_Details.setText("");
                 jText_Deduction.setText("");
                  jCombo_EmpList.removeAllItems();
                  jCombo_Month.removeAllItems();
                  // set one blank
                  FillCombo();
                  // call dropdown
              
              }catch (Exception e) {
           
                       JOptionPane.showMessageDialog(this, e, "Invalid", JOptionPane.ERROR_MESSAGE);
        }
        }

Java Combo Box

  private void FillCombo(){

                 try {
                        jCombo_EmpList.addItem("");
                        rs = u.getAll_Active_Emp();
                        while(rs.next()){
                            jCombo_EmpList.addItem(rs.getString("EmpId"));
                        }
                  
                            
                     }catch (Exception e) {

                    JOptionPane.showMessageDialog(this, e);
                }
            }

Thursday, August 1, 2013

Java Given Number To Words


package dcl_payroll;

import java.io.*;


public class Words
{
 long num;
 private Words()
 {
  num=0;
 }
 private Words(long num)
 {
  this.num=num;
 }
 public void setNumber(long num)
 {
  this.num=num;
 }
 public long getNumber()
 {
  return num;
 }
 public static Words getInstance(long num)
 {
  return new Words(num);
 }
 public static String leftChars(String str,int n)
 {
  if(str.length()<=n)
   return str;
  else
   return str.substring(0,n);
 }
 public static String rightChars(String str,int n)
 {
  if(str.length()<=n)
   return str;
  else
   return str.substring(str.length()-n,str.length());
 }
 public long leftChars(int n)
 {
  return new Long(leftChars(new Long(num).toString(),n)).longValue();
 }
 public long rightChars(int n)
 {
  return new Long(rightChars(new Long(num).toString(),n)).longValue();
 }
 public long leftChars(long num,int n)
 {
  return new Long(leftChars(new Long(num).toString(),n)).longValue();
 }
 public long rightChars(long num,int n)
 {
  return new Long(rightChars(new Long(num).toString(),n)).longValue();
 }
 public int length(long num)
 {
  return new Long(num).toString().length();
 }
 private String belowTen(long x)
 {
  switch((int)x)
  {
   case 1:
    return "One ";
   case 2:
    return "Two ";
   case 3:
    return "Three ";
   case 4:
    return "Four ";
   case 5:
    return "Five ";
   case 6:
    return "Six ";
   case 7:
    return "Seven ";
   case 8:
    return "Eight ";
   case 9:
    return "Nine ";
  }
  return "";
 }
 private String belowTwenty(long x)
 {
  if(x<10)
   return belowTen(x);
  switch((int)x)
  {
   case 10:
    return "Ten ";
   case 11:
    return "Eleven ";
   case 12:
    return "Twelve ";
   case 13:
    return "Thirteen ";
   case 14:
    return "Fourteen ";
   case 15:
    return "Fifteen ";
   case 16:
    return "Sixteen ";
   case 17:
    return "Seventeen ";
   case 18:
    return "Eighteen ";
   case 19:
    return "Nineteen ";
  }
  return "";
 }
 private String belowHundred(long x)
 {
  if(x<10)
   return belowTen(x);
  else if(x<20)
   return belowTwenty(x);
  switch((int)leftChars(x,1))
  {
   case 2:
    return "Twenty "+belowTen(rightChars(x,1));
   case 3:
    return "Thirty "+belowTen(rightChars(x,1));
   case 4:
    return "Fourty "+belowTen(rightChars(x,1));
   case 5:
    return "Fifty "+belowTen(rightChars(x,1));
   case 6:
    return "Sixty "+belowTen(rightChars(x,1));
   case 7:
    return "Seventy "+belowTen(rightChars(x,1));
   case 8:
    return "Eighty "+belowTen(rightChars(x,1));
   case 9:
    return "Ninety "+belowTen(rightChars(x,1));
  }
  return "";
 }
 private String belowThousand(long x)
 {
  if(x<10)
   return belowTen(x);
  else if(x<20)
   return belowTwenty(x);
  else if(x<100)
   return belowHundred(x);
  return belowTen(leftChars(x,1))+"Hundred "+belowHundred(rightChars(x,2));
 }
 private String belowLakh(long x)
 {
  if(x<10)
   return belowTen(x);
  else if(x<20)
   return belowTwenty(x);
  else if(x<100)
   return belowHundred(x);
  else if(x<1000)
   return belowThousand(x);
  if(length(x)==4)
   return belowTen(leftChars(x,1))+"Thousand "+belowThousand(rightChars(x,3));
  else
   return belowHundred(leftChars(x,2))+"Thousand "+belowThousand(rightChars(x,3));
 }
 public String belowCrore(long x)
 {
  if(x<10)
   return belowTen(x);
  else if(x<20)
   return belowTwenty(x);
  else if(x<100)
   return belowHundred(x);
  else if(x<1000)
   return belowThousand(x);
  else if(x<100000)
   return belowLakh(x);
  if(length(x)==6)
   return belowTen(leftChars(x,1))+"Lakh "+belowLakh(rightChars(x,5));
  else
   return belowHundred(leftChars(x,2))+"Lakh "+belowLakh(rightChars(x,5));
 }
 public String belowBilion(long x)
 {
  if(x<10)
   return belowTen(x);
  else if(x<20)
   return belowTwenty(x);
  else if(x<100)
   return belowHundred(x);
  else if(x<1000)
   return belowThousand(x);
  else if(x<100000)
   return belowLakh(x);
  else if(x<100000000)
   return belowCrore(x);
 
  if(length(x)==8)
   return belowTen(leftChars(x,1))+"Bilion "+belowCrore(rightChars(x,7));
  else
   return belowHundred(leftChars(x,2))+"Bilion "+belowCrore(rightChars(x,7));
 }
 public String getNumberInWords()
 {
  if(num<10)
   return belowTen(num);
  else if(num<20)
   return belowTwenty(num);
  else if(num<100)
   return belowHundred(num);
  else if(num<1000)
   return belowThousand(num);
  else if(num<100000)
   return belowLakh(num);
  else if(num<10000000)
   return belowCrore(num);
  else if(num<1000000000)
   return belowBilion(num);
  return "";
 }
 public static void main(String[] args) throws Exception
 {
  System.out.println("Enter one number:");
  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  Words w=Words.getInstance(Integer.parseInt(br.readLine()));
  System.out.println(w.getNumberInWords());
 }
}

Wednesday, July 31, 2013

Java Date Time Format

String str = "12/9/2010 4:39:38 PM";
Formatter formatter = new SimpleDateFormat("M/dd/yyyy H:m:s a");
Date date =(Date)formatter.parse(str);
Formatter formatterOutput = new SimpleDateFormat("MM/dd/yyyy HH:m:ss a");
String s = formatterOutput.format(date);


Format formatter;

// The year
formatter = new SimpleDateFormat("yy");    // 02
formatter = new SimpleDateFormat("yyyy");  // 2002
ime
// The month
formatter = new SimpleDateFormat("M");     // 1
formatter = new SimpleDateFormat("MM");    // 01
formatter = new SimpleDateFormat("MMM");   // Jan
formatter = new SimpleDateFormat("MMMM");  // January

// The day
formatter = new SimpleDateFormat("d");     // 9
formatter = new SimpleDateFormat("dd");    // 09

// The day in week
formatter = new SimpleDateFormat("E");     // Wed
formatter = new SimpleDateFormat("EEEE");  // Wednesday

// Get today's date
Date date = new Date();

// Some examples
formatter = new SimpleDateFormat("MM/dd/yy");
String s = formatter.format(date);
// 01/09/02

formatter = new SimpleDateFormat("dd-MMM-yy");
s = formatter.format(date);
// 29-Jan-02

// Examples with date and time; see also
// Formatting the Time Using a Custom Format
formatter = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
s = formatter.format(date);
// 2002.01.29.08.36.33

formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
s = formatter.format(date);
// Tue, 09 Jan 2002 22:14:02 -0500

Java Age Calculate

 public static String getAge(String dateOfBirth) {
       int age;
       int age_m;
       int age_d;
      // String dob = "1984-09-20";
       String dob = dateOfBirth;

            //TAKE SUBSTRINGS OF THE DOB SO SPLIT OUT YEAR, MONTH AND DAY
            //INTO SEPERATE VARIABLES
            int yearDOB = Integer.parseInt(dob.substring(0, 4));
            int monthDOB = Integer.parseInt(dob.substring(5, 7));
            int dayDOB = Integer.parseInt(dob.substring(8, 10));

            //CALCULATE THE CURRENT YEAR, MONTH AND DAY
            //INTO SEPERATE VARIABLES
            DateFormat dateFormat = new SimpleDateFormat("yyyy");
            java.util.Date date = new java.util.Date();
            int thisYear = Integer.parseInt(dateFormat.format(date));

            dateFormat = new SimpleDateFormat("MM");
            date = new java.util.Date();
            int thisMonth = Integer.parseInt(dateFormat.format(date));

            dateFormat = new SimpleDateFormat("dd");
            date = new java.util.Date();
            int thisDay = Integer.parseInt(dateFormat.format(date));

            //CREATE AN AGE VARIABLE TO HOLD THE CALCULATED AGE
            //TO START WILL – SET THE AGE EQUEL TO THE CURRENT YEAR MINUS THE YEAR
            //OF THE DOB
            age = thisYear - yearDOB;

            //IF THE CURRENT MONTH IS LESS THAN THE DOB MONTH
            //THEN REDUCE THE DOB BY 1 AS THEY HAVE NOT HAD THEIR
            //BIRTHDAY YET THIS YEAR
            if(thisMonth < monthDOB){
                age_m = monthDOB-thisMonth;
            }else{
            age_m = thisMonth-monthDOB;
            }
            if(thisMonth == monthDOB){
                age_m = 0;
            }
            //IF THE MONTH IN THE DOB IS EQUEL TO THE CURRENT MONTH
            //THEN CHECK THE DAY TO FIND OUT IF THEY HAVE HAD THEIR
            //BIRTHDAY YET. IF THE CURRENT DAY IS LESS THAN THE DAY OF THE DOB
            //THEN REDUCE THE DOB BY 1 AS THEY HAVE NOT HAD THEIR
            //BIRTHDAY YET THIS YEAR
            if(thisDay < dayDOB){
            age_d = dayDOB - thisDay;
            }else{
            age_d =  thisDay - dayDOB;  
            }

            if(thisDay == dayDOB){
            age_d = 0;
            }

            //THE AGE VARIBALE WILL NOW CONTAIN THE CORRECT AGE
            //DERIVED FROMTHE GIVEN DOB
            System.out.println(age);
            String p = age + " Year " + age_m + " Month " + age_d + " Days ";
            return p;
    }

Monday, July 29, 2013

Java Get Date Time

 /**
  * @author Nazmus Sakib
 */

  //  Print Today's Date time

public String todays_datetime()
    {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                java.util.Date date = new java.util.Date();
                // System.out.println(dateFormat.format(date));
                return (dateFormat.format(date));

        }

Output is : 2013-07-30 10:55:05


// Print Next Month
public String next_month_year()
    {
            Calendar cal = GregorianCalendar.getInstance();
            SimpleDateFormat df = new SimpleDateFormat("MMMM yyyy");

            Date currentMonth = new Date();
            cal.setTime(currentMonth);

            // current month
            String currentMonthAsSting = df.format(cal.getTime());

            // Add next month
            cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)+1);
            //cal.add(Calendar.MONTH, 1);
            String nextMonthAsString = df.format(cal.getTime());

            System.out.println(nextMonthAsString);     
                return (nextMonthAsString);

        }

Java HTML Alert


/**
 *   Java HTML Alert Box
 * @author Nazmus Sakib
 */



private String msg_access = "<HTML> Access Denied <br>"
                                    + "Already Count This Figure In Salary</HTML>";


  JOptionPane.showMessageDialog(null,msg_access, "Already Count", OptionPane.ERROR_MESSAGE);

Friday, July 26, 2013

Java to Oracle Database Connection with net beans IDE

package Utility;

/**
 *
 * @author Sakib
 * Datacraft LTD
 */

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.*;
public class OracleJDBC {
  
    public static void main(String[] argv) {

        System.out.println("** ------ Oracle JDBC Connection Testing ------ **");

        try {

            Class.forName("oracle.jdbc.driver.OracleDriver");

        } catch (ClassNotFoundException e) {

            System.out.println("Where is your Oracle JDBC Driver?");
            e.printStackTrace();
            return;

        }

        System.out.println("Oracle driver registered");
        Connection conn=null;

        try {

            conn = DriverManager.getConnection( "jdbc:oracle:thin:@127.0.0.1:1521:xe", "sakib","Abc999");

            Statement stmt= conn.createStatement();
            ResultSet r=stmt.executeQuery("Select * from employees");
            while(r.next()){
            String str= r.getString("FIRSTNAME");
            System.out.println (str);
           
            }

        } catch (SQLException e) {

            System.out.println("Connection Failed! Check output console");
            e.printStackTrace();
            return;

        }
    }
}

Thursday, July 25, 2013

Java to MySQL Database Connection with net beans IDE

Java to MySQL Database Connection with net beans IDE


package Utility;
/**
 *
 * @author Nazmus Sakib
 */

import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;


public class javaconnect {
   
    Connection conn = null;
    public static Connection ConnecrDb(){
       
        try {
             Class.forName("com.mysql.jdbc.Driver");
             Connection conn = (Connection)DriverManager.getConnection("jdbc:mysql://localhost/dcl_payrole","root","123456");
             return conn;
        }catch (Exception e) {
           
            JOptionPane.showMessageDialog(null, e);
            return null;
            
        }
      
    }
   
}