Wednesday, November 6, 2013

Java Best Practices & Naming Standards


Java Best Practices

- Avoid creating unnecessary objects and always prefer to do Lazy Initialization, Create object only if needed.

- Never make an instance/object fields of class public, Ensure to give right access specifier based on requirement.

- Try to make classes immutable, This can be achieved by having private constructor and have public static method to get the instance of the class.
- Try to prefer Interfaces instead of Abstract classes

- Always try to limit the scope of Local variable, This can be achieved by declaring variable just before use.

- Use existing libraries instead of writing your own framework from scrach.

- Wherever possible user primitive data types and avoid unnecessary usage of wrapper class .
 For eg : use 'int' data type rather than 'Integer' just to hold    some integer values.


- Never use String constructor, For eg : String name ="Fortune Minds" is best practice , String name = new String("Fortune Minds") is not a best practice.  

Standard Java Naming Conventions



The below list outlines the standard Java naming conventions for each identifier type, Give meaningful name for every identifier you define/create in Java.

Packages: Names should be in lowercase. With small projects that only have a few packages it's okay to just give them simple (but meaningful!) names:
              package com.fm.employee
              package mathutil 
In software companies and large projects where the packages might be imported into other classes, the names will normally be subdivided. Typically this will start with the company domain before being split into layers or features:
         package com.mycompany.utilities
         package org.bobscompany.application.userinterface 

 Classes: Names should be in CamelCase. Try to use nouns because a class is normally representing something in the real world:
                 class Customer
                 class Account 

 Interfaces: Starts with Upper case and follows CamelCase. They tend to have a name that describes an operation that a class can do:
                interface Comparable
                interface Enumerable 
Note that some programmers like to distinguish interfaces by beginning the name with an "I":
            interface IComparable
           interface IEnumerable 

Methods: Names should be in mixed case. Use verbs to describe what the method does:
               void calculateTax()
               string getSurname() 

Variables: Names should be in mixed case. The names should represent what the value of the variable represents: Make sure to give meaningful names
         string firstName
         int orderNumber 
Only use very short names when the variables are short lived, such as in for loops:
 for (int i=0; i<20;i++)
 {
    //i only lives in here
 } 

Constants: Names should be in uppercase.
         static final int DEFAULT_WIDTH
         static final int MAX_HEIGHT 

Monday, October 14, 2013

How to send an email using Java API & Gmail account


Below blog explains about sending an email using Gmail email address as from email and Java API

Below is the sample code snippet to send email using Java Mail API.

Download the Java Mail Jar and set in class path
Here is the link to download java-mail.jar  http://www.oracle.com/technetwork/java/index-138643.html

       
import com.sun.mail.util.MailSSLSocketFactory;

import java.util.Properties;

import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.internet.MimeMessage;

import java.net.URL;

import java.security.GeneralSecurityException;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import javax.mail.Session;
    /**
   * De limit the toEmail List
   * Authenticate
   * @param msg
   * @param subject
   * @param toEmail
   * @param fromEmail
   * @return
   * @throws Exception
   */
  public static String sendEmail(String msg, String subject, String toEmail, String fromEmail)
    throws Exception
  {
    String toEmails[] = toEmail.split(",");
    System.out.println("TO:::FROM:::SUBJ:::BODY:::" + toEmail + "-" + fromEmail + "-" + subject + "-" + msg);

    Session session = setSessionAuthentication();
    InternetAddress from = new InternetAddress(fromEmail);
    InternetAddress to[] = new InternetAddress[toEmails.length];
    for (int c = 0; c < toEmails.length; c++)
    {
      to[c] = new InternetAddress(toEmails[c]);
    }
    MimeMessage message = new MimeMessage(session);
    message.setFrom(from);
    message.addRecipients(Message.RecipientType.TO, to);
    message.setSubject(subject);
    message.setText(msg);
    Transport.send(message);
    // msg="OK Msg Posted Successfully";
    return "EMail Sent Successfully";
  }

  /**
   *
   * @return
   * @throws Exception
   */
  public static Session setSessionAuthentication()
    throws Exception
  {
    final String username = "FM@gmail.com";
    final String password = "GMAIL PASSWORD";
    //Using SSL
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");
    // USING TLS
    //        Properties props = new Properties();
    //        props.put("mail.smtp.auth", "true");
    //        props.put("mail.smtp.starttls.enable", "true");
    //        props.put("mail.smtp.host", "smtp.gmail.com");
    //        props.put("mail.smtp.port", "587");
    props.put("mail.debug", "true");
    MailSSLSocketFactory sf = null;
    try
    {
      sf = new MailSSLSocketFactory();
    }
    catch (GeneralSecurityException e1)
    {
      e1.printStackTrace();
    }
    sf.setTrustAllHosts(true);
    props.put("mail.smtp.ssl.socketFactory", sf);
    Session session = Session.getInstance(props, new javax.mail.Authenticator()
      {
        protected PasswordAuthentication getPasswordAuthentication()
        {
          return new PasswordAuthentication(username, password);
        }
      });
    return session;
  }
       
 

Monday, October 7, 2013

How to find Fiscal Month Start & End Date , Fiscal Week Start & End Date for a given Date using Java

This blog explains about getting Fiscal Month Start & End date , Fiscal Week start & end date based on given date using Java API

From the below diagram,

 For October 2013, 9/29/2013 is Fiscal Month Start Date , 11/9/2013 is Fiscal Month End Date
Similarly - 9/29/2013 is fiscal week start date , 10/5/2013 is fiscal week end date for any date b/w 1st to 5th in October.


Implementation
       
    private static GregorianCalendar gregorianCalendar;
    private static final int MAX_WEEKS = 6;

      private static void init(Date date) {
        gregorianCalendar = new GregorianCalendar();
        gregorianCalendar.clear();
        gregorianCalendar.setTime(date);
    }

    /**
     * Returns the Start date of fiscal week based on given input Date
     * @param date
     * @return
     * @throws Exception
     */

    public static Date getFiscalWeekStartDate(Date date) throws Exception {
        if (date != null) {
            init(date);
            return getFiscalWeekStartDate(gregorianCalendar);
        }
        return null;

    }

    private static Date getFiscalWeekStartDate(GregorianCalendar gregorianCalendar) {
        int correction = 1 - gregorianCalendar.get(GregorianCalendar.DAY_OF_WEEK);
        gregorianCalendar.add(Calendar.DATE, correction);
        return gregorianCalendar.getTime();
    }

    /**
     * Returns the Start date of fiscal week based on given input Date
     * @param date
     * @return
     * @throws Exception
     */

    public static Date getFiscalWeekEndDate(Date date) throws Exception {
        if (date != null) {
            init(date);
            return getFiscalWeekEndDate(gregorianCalendar);
        }
        return null;
    }

    private static Date getFiscalWeekEndDate(GregorianCalendar gregorianCalendar) {
        int correction = 7 - gregorianCalendar.get(GregorianCalendar.DAY_OF_WEEK);
        gregorianCalendar.add(Calendar.DATE, correction);
        return gregorianCalendar.getTime();
    }

    /**
     * Returns the Start date of fiscal month based on given input Date
     * @param date
     * @return
     * @throws Exception
     */

    public static Date getFiscalMonthStartDate(Date date) throws Exception {
        if (date != null) {
            init(date);
            int correction = 1 - gregorianCalendar.get(GregorianCalendar.DAY_OF_MONTH);
            gregorianCalendar.add(Calendar.DATE, correction);
            return getFiscalWeekStartDate(gregorianCalendar);
        }
        return null;

    }

    /**
     * Returns the End date of fiscal month based on given input Date
     * @param date
     * @return
     * @throws Exception
     */

    public static Date getFiscalMonthEndDate(Date date) throws Exception {
        if (date != null) {
            int correction = 0;
            init(date);
            int num_of_weeks = gregorianCalendar.getActualMaximum(Calendar.WEEK_OF_MONTH);
            int cur_week = gregorianCalendar.get(Calendar.WEEK_OF_MONTH);
            if (num_of_weeks < MAX_WEEKS) {
                correction = num_of_weeks - cur_week + 1;
            } else {
                correction = num_of_weeks - cur_week;
            }
            gregorianCalendar.add(Calendar.WEEK_OF_MONTH, correction);
            return getFiscalWeekEndDate(gregorianCalendar);
        }

        return null;
    }
       
 


Wednesday, September 25, 2013

How to download content from HTTPS (Secured) website using Java

I spent lot of time to accomplish downloading a content from HTTPS(secured) website, I couldn't find right place to get enough information to resolve certificate related errors/exceptions while trying to connecting to https website, I thought of documenting all my findings so that others no need to spend time on researching root cause for certificates related information


       

import java.io.BufferedInputStream;
import java.io.FileOutputStream;

import java.net.URL;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;


public class HTTPSFileDownload {
    public HTTPSFileDownload() {
        super();
    }

    /**
     *  This method trust all the certificates.
     */
    private void trustAllCertificates() {

        //Manager to trust all certificates
        TrustManager[] trustAllCerts =
            new TrustManager[] { new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(java.security.cert.X509Certificate[] certs,
                                               String authType) {
                }

                public void checkServerTrusted(java.security.cert.X509Certificate[] certs,
                                               String authType) {
                }
            } };

        // Activate the new trust manager
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        HTTPSFileDownload s = new HTTPSFileDownload();
        s.trustAllCertificates();
        String https_url = "https://google.com";
        URL url;
        try{
            url = new URL(https_url);
            HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
            BufferedInputStream in = null;
            FileOutputStream fout = null;
            if (con != null) {
                in = new BufferedInputStream(con.getInputStream());
                fout = new FileOutputStream("C:/RKP/httpsFile.csv");

                byte data[] = new byte[1024];
                int count;
                while ((count = in.read(data, 0, 1024)) != -1) {
                    fout.write(data, 0, count);
                }
            }
            
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
}
       
 

I hope this would helpful


Friday, September 20, 2013

How to read from CSV file and Writes into Oracle Database using Java

This blog explains about reading content from CSV file and writes into Oracle database table using Java

- Below code reads the data from CSV file, Ensure to give absolute path for the fileName
       

     /**
     * This method reads the file content based on given file name
     * File Name should be absolute path.
     * @param fileName
     * @return
     */
    public List readCSVFile(String fileName) {
        List content = new ArrayList();
        try {
            BufferedReader br = new BufferedReader(new FileReader(fileName));
            String strLine = "";
            StringTokenizer st = null;
            int lineNumber = 0, tokenNumber = 0;
            while ((strLine = br.readLine()) != null) {
                content.add(strLine.split(","));
            }
        } catch (Exception fnfe) {
            fnfe.printStackTrace();
        }

        return content;
    }
       
 

- Below code translates the String array to POJO
       

    /**
     * This method convert given String array to CustomerDTO
     * @param fileContent
     * @return
     */
    public List convertArryToDTO(List fileContent) {
        List custList = null;
        CustomerDTO dto = null;
        if (fileContent != null && fileContent.size() > 0) {
            custList = new ArrayList();
            for (String[] row : fileContent) {
                if (row != null) {
                    dto = new CustomerDTO();
                    dto.setFirstName(row[0]);
                    dto.setMiddleName(row[1]);
                    dto.setLastName(row[2]);
                    dto.setCity(row[4]);
                    custList.add(dto);
                }
            }
        }

        return custList;
    }
       
 
- Below code writes to Database
       

      /**
     * dbURL =jdbc:oracle:thin:@server:port:serviceID
     * @return
     */
    private Connection getDBConnection(String dbURL) {
        Connection conn=null;
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            conn =
                DriverManager.getConnection(dbURL, "hr", "hr");
        } catch (Exception cnfe) {
            cnfe.printStackTrace();
        }
        return conn;
    }

    /**
     *
     * @param custList
     * @return
     */
    public String saveCustomersToDB(List custList) {
        String result = null;
        Connection conn=null;
        String dbURL = "jdbc:oracle:thin:@localhost:1521:XE";
        PreparedStatement stmt=null;
        try {
            conn = getDBConnection(dbURL);
            String query = "INSERT INTO CUSTOMER(ID,FNAME,LNAME,CITY) VALUES (?,?,?,?)";
            stmt = conn.prepareStatement(query);
            Random random = new Random();
            for (CustomerDTO customerDTO : custList) {
                stmt.setInt(1, random.nextInt(3400));
                stmt.setString(2, customerDTO.getFirstName());
                stmt.setString(3, customerDTO.getLastName());
                stmt.setString(4, customerDTO.getCity());
                stmt.execute();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(stmt != null){
                try {
                    stmt.close();
                } catch (SQLException sqle) {
                    sqle.printStackTrace();
                }
            }
            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException sqle) {
                    sqle.printStackTrace();
                }
            }

        }
        return result;
    }
       
 

- Below method retrieves employee information from database based on given employee ID
       

   public List getCustomerList()
  {
  /**
   * This method retrieves employee information based on employee ID
   * @param empID
   * @return
   */
  public EmployeeDTO readEmployeeDetailsFromDB(int empID)
  {
    EmployeeDTO dto = null;
    Connection conn = null;
    PreparedStatement stmt = null;
    String dbURL = "jdbc:oracle:thin:@localhost:1521:XE";
    try
    {
      conn = getDBConnection(dbURL);
      String query = "SELECT EMP_ID,FNAME,LNAME,DESCRIPTION FROM SRC_EMP WHERE EMP_ID= " + empID;
      stmt = conn.prepareStatement(query);
      stmt.execute();
      ResultSet rs = stmt.executeQuery(query);
      while (rs.next())
      {
        dto = new EmployeeDTO();
        String fName = rs.getString("FNAME");
        int supplierID = rs.getInt("EMP_ID");
        String lName= rs.getString("LNAME");
        String desc = rs.getString("DESCRIPTION");
        dto.setId(supplierID);
        dto.setFName(fName);
        dto.setLName(lName);
        dto.setDesc(desc);
      }
    }
    catch (Exception ex)
    {
      ex.printStackTrace();
    }
    return dto;
  }
       
 

Tuesday, August 13, 2013

JXplorer To Access LDAP Information


Below is the nice tool to access LDAP to see users, groups and their permissions.

JXplorer

http://jxplorer.org/index.html

Thursday, August 1, 2013

How to implement Singleton design pattern in Java ?

Singleton design pattern is most commonly used design pattern across all  Java/J2EE applications. This design pattern is used for controlling the creation of number of instances for a specific class. Remember controlling instances is per 'Class Loader' and not for JVM. As you know JVM can have more than one class loader.

Version 1 :


public class DateTimeUtil{
// Declare static instance, that means one for a class (Not for instance )
public static DateTimeUtil singleton=null;
// Create a method , first time creates the instance, for every next subsequent calls, will not create a new instance.
public DateTimeUtil getInstance(){
// Create instance for very first time.
if(singleton==null){
singleton = new DateTimeUtil();
}
return singleton;
}
}

Versiont 2

public class DateTimeUtil{
// Declare and create  instance when class loaded itself.
public static final DateTimeUtil singleton=new DateTimeUtil();
public DateTimeUtil getInstance(){
return singleton;
}
}