Tuesday, December 10, 2013

How to find Date Difference in Months using Java ?



       

      public static int getMonthsDiffArray(Date startDate, Date endDate) {
        int[] months = null;
        Calendar startCalendar = new GregorianCalendar();
        startCalendar.setTime(startDate);
        Calendar endCalendar = new GregorianCalendar();
        endCalendar.setTime(endDate);
        int diffInMonths =
            endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH);     
        return diffInMonths;
 }

    //HH converts hour in 24 hours format (0-23), day calculation
            SimpleDateFormat format =
                new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
            Date startDate = format.parse("04/14/2012 09:29:58");
            Date endDate = format.parse("08/15/2012 10:31:48");

    
       
 


Wednesday, November 20, 2013

How to Marshall and UnMarshall POJO using Java

This blog explains about converting POJO(Plain Old Java Object) to XML and XML to POJO

- Below is the EmployeeDTO, Ensure to specify @XMLRootElement
       

  package com.fm.xmlutil.dto;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class EmployeeDTO {
    public EmployeeDTO() {
        super();
    }
    private String fName;
    private String lName;
    private String address1;

    public void setFName(String fName) {
        this.fName = fName;
    }

    public String getFName() {
        return fName;
    }

    public void setLName(String lName) {
        this.lName = lName;
    }

    public String getLName() {
        return lName;
    }

    public void setAddress1(String address1) {
        this.address1 = address1;
    }

    public String getAddress1() {
        return address1;
    }
}

       
 

- Below is the XMLUtil class

       

  package com.fm.xmlutil;

import com.fm.xmlutil.dto.EmployeeDTO;

import java.io.StringReader;
import java.io.StringWriter;

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 * This class has the util methods to convert the POJOs to XML and vice versa using JAXB API.
 *
 * @author Fortune Minds
 */
public class XMLUtil {
   /**
     *This methodd converts Java Object to XML String
     * @param rootObject
     * @return
     * @throws Exception
     */
    public static String javaToXml(Object rootObject) throws Exception {
        StringWriter writer = new StringWriter();
        JAXBContext jaxbContext =
            JAXBContext.newInstance(rootObject.getClass());
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshaller.marshal(rootObject, writer);
        return writer.toString();
    }



    /**
     * This method converts XML to Java Object
     * @param rootObject
     * @param xmlString
     * @return
     * @throws Exception
     */
    public static Object xmlToJava(Object rootObject,
                                   String xmlString) throws Exception {
        JAXBContext jaxbContext =
            JAXBContext.newInstance(rootObject.getClass());
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        return jaxbUnmarshaller.unmarshal(new StringReader(xmlString));
    }
    
    public static void main(String args[]){
        EmployeeDTO dto = new EmployeeDTO();
        dto.setFName("FortuneMinds");
        dto.setLName("Inc");
        dto.setAddress1("8000 Corporatecenter Drive");
        try {
            String r =javaToXml(dto);
            System.out.println(r);
        } catch (Exception e) {
            // TODO: Add catch code
            e.printStackTrace();
        }
        
    }
}

       
 

Note :  Have jaxb-api-2.2.jar on class path

Thursday, November 14, 2013

How to split String using String Tokenizer



    String test ="Hello||FortuneMinds";
    StringTokenizer StrTkn = new StringTokenizer(test, "||");
    while(StrTkn.hasMoreTokens())
    {
      System.out.println(StrTkn.nextToken());
    }

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