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


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

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;
}
}

Tuesday, July 30, 2013

How to retrieve distinct pair of values from the given list of integers where the sum of each pair equals to given input value.

How to retrieve distinct pair of values from the given list of integers where the sum of each pair equals to given input value.


Example

Input : 9,2,5,4,6,-9
Output : 9,2 & 5,6



How to declare and initialize ArrayList in One line using Java


// Declare & Initilize Integer ArrayList in java
List<Integer> arr = new ArrayList<Integer>(Arrays.asList(9,2,5,4,6,-9))

// Using Arrays
int[] arr2 = new int[]{9,2,5,4,6,-9};


Wednesday, July 24, 2013

Tuesday, July 23, 2013

SQL Queries on Joins


// Get All deparments where corresponding employee first name is blank

SELECT dep.department_name,
  emp.first_name
FROM DEPARTMENTS dep
LEFT OUTER JOIN EMPLOYEES emp
ON dep.department_id  =emp.department_id where emp.first_name is null


// To get first column associated value in Oracle. Ir rownum =2, then returns first two values of first_name
select first_name from employees where rownum <=1


// Connect to database using sql command prompt

conn hr/hr;

// Below query substring the city column values from 1 to 4 characters and returns using MID() function
SELECT MID(City,1,4) AS ShortCity
FROM Customers;

// Returns length of each first_name column using LEN() function
SELECT LEN(first_name) FROM employees;

// Returns current system date using NOW() function
SELECT first_name,  Now() AS PerDate

FROM employees;

Different SQL JOINs

Before we continue with examples, we will list the types the different SQL JOINs you can use:
  • INNER JOIN: Returns all rows when there is at least one match in BOTH tables
  • LEFT JOIN: Return all rows from the left table, and the matched rows from the right table
  • RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table
  • FULL JOIN: Return all rows when there is a match in ONE of the tables

How to Sort List programatically without using any in built functions in Java


   // Sort list of integers in descending order.
    private static List<Integer> sortList(List<Integer> pList){
        int temp;
        if(pList != null && pList.size() > 0){
            for(int i=0;i<pList.size();i++){
                for(int j=i+1;j<pList.size();j++){
                    if(pList.get(j) > pList.get(i)){
                        temp = pList.get(i);
                        pList.set(i,pList.get(j));
                        pList.set(j,temp);
                    }
                }
            }
        }
        return pList;
    }

Test

// Initialize and assign values
List<Integer> list1 =Arrays.asList(2,5,23,-1,-5,0,4);
// Invoke above sortList() method.


- How to merge two lists in a sorted order ?

// Initialize & assign two lists
List<Integer> list1 =Arrays.asList(2,5,23,-1,-5,0,4);
List<Integer> list2 =Arrays.asList(23,15,323,-51,-65,0,47);
 
// Add the second list to first list
list1.addAll(list2);
// Invoke above sortList() method by passing merged list i.e list1.

Monday, July 22, 2013

Left outer join example with three tables along with case





SELECT tab1.tb1_a,
       CASE WHEN tab3.tb3_a IS NOT NULL THEN tb3_b
            ELSE 'No city for him yet'
       END AS City,
tab2.*, tab3.*
FROM tab1
LEFT OUTER JOIN tab2 ON    tab1.tb1_a = tab2.tb2_a
LEFT OUTER JOIN tab3 ON    tab2.tb2_b = tab3.tb3_a
where tb2_b = (select max(tb2_b)
                 from tab2 t22
                where t22.tb2_a = tb1_a)
or    tb2_b is null
order by 1

Sunday, July 21, 2013

Unix Useful commands in Fusion Development Environment.

How to Identify the access level to specific file/directory in UNIX ?

To identify what are the access permissions to specific file or directory for a logged in user in UNIX environment, Follow below steps

- Login to unix box
- Issue command : ls -la
- You will notice all the list of files/directories as shown below screenshot,

- First character specifies whether it is file or directory, If it is directory, it will show as 'd' otherwise just emply
- Next three characters represents access permissions to logged in user, r - read, w - write, x - execute
- Next three characters represents access permissions to the group (i.e appigroup)
- Last three characters represents access permissions to anybody, empty means no access.



-  Issue below commands to give access to Group(g), Owner(o) & Others (a) as below

chmod rw+o TMP - Give read write permissions to owner for 'TMP' directory/file name
chmod rwx-a TMP - Remove read,write, execute permissions on 'TMP' directory/file for others
chmod 700 TMP - Give read,write, execute permissions on 'TMP' directory/file to owner , and no access to others & group

Useful UNIX commands

- To convert dos based file to unix
   i. Create temporary file first eg : temp.xml
   ii. temp.xml << dos2unix build.xml
  This will convert build.xml ( which is based on window/dos OS) to temp.xml
- hostname - Print the host name
- ssh uxunt540 - connect to uxunt540 unix box
- To give a sudo access to specific user
                sudo su - <userName>
-To Copy a existing file
               cp <sourceFileName> <targetFileName>
- To Grep for specific content in a current directory
              ps -ef | grep 'Fortune Minds'       - This will search for 'Fortune Minds' string in all the directories and files in a current present working directory
- To know the present working directory
            pwd
- To find out specific file content or forlder
           whereis <FortuneMinds>    - This will find out files/folders which contains 'Fortune Minds' and list out all the findings.
-  To Edit a specific file
              vi FortuneMinds.txt
              Press 'I'
              Modify the file
              Esc,Shift+:, wq! 
- To backup a directory
             mv <source_folder_Name>  <target_folder_Name>
- To run any shell script
             ./startWebLogic.sh & - startWebLogic shell script will run in background.







Friday, July 19, 2013

How to perform search against Collect of Custom Objects in Java ?



How to perform search against Collect of Custom Objects in Java ?

Usecase : Identify whether the given EmploeeDTO associated last name exists in the List<EmployeDTO> or not.

- Create EmployeeDTO class and override equals() method as shown below.
- Invoke List.Contains() operation by passing the Custom DTO object, this will invoke internally equals() method and returns true if there are any matching EmployeeDTO matches with the given Object last name.

How to Import existing application in Eclipse ?



File -> Import -> General -> Existing Projects into workspace -> Browse -> <Choose Application folder> --> Finish

Wednesday, July 17, 2013

How to create Deployment Profiles (JAR, EAR & WAR) using Jdeveloper


Packaging Applications using Jdeveloper

How to create Deployment Profiles (JAR, EAR & WAR) using Jdeveloper

JAR files are Java Archives, JAR files are bundled with all java classes that end in .jar, If you want to allow other applications to access your java classes, then create JAR file and add them into class path.

WAR files are Web Application Archives. WAR files are JAR files that end in .war and are used to package and deploy web components into web containers. They can contain HTML documents, servlets, JSPs, or even applet class files. WAR archives also contain an XML file called a deployment descriptor that describes the components. This file is normally called web.xml.


An EAR file is an Enterprise Archive and is used to package modules of a J2EE application. An EAR file is a JAR file that ends in .ear and can contain JAR and WAR files in addition to any other file required by the module. EAR archives also contain a file describing their contents—called an application descriptor, typically, application.xml.

Jdeveloper allows to create these files very simple manner.

Creating JAR file using Jdeveloper

- Right click on any Java project, Project Properties, You will see below window.

- Choose 'Deployment' on left hand side menu, Click on 'New' button, Choose 'JAR File' from 'Archive Type' list of values , Give appropriate name for the JAR file, Click on Ok button

- Here give the JAR file path where you want to create, Click on 'Ok' in following steps.

- After creating Deployment profile, then next step is to create the JAR file using the above created deployment profile
- Right click on the Java project (where JAR deployment profile created) , Choose Deploy , Then select the deployment profile created in above step, then choose 'Ok' in following steps, After successful compilation Jeveloper will create JAR file at the specified location.. You will see a message as shown in below screen shot.

WAR Deployment Profile

Right click on the web project, Follow all the above steps, Choose 'WAR File' while creating deployment profile and rest of the steps are same as mentioned above.

EAR Deployment Profile

Right click on the application, Follow all the above steps, Choose 'EAR File' while creating deployment profile, rest of the steps are same as mentioned above.


Tuesday, July 9, 2013

How to translate from one language to another language


If you have a requirement to support internationalization (Multi Lingual ) support, You need to translate english to rest of the languages..Below google translator is much useful tool to translate from english to any other language.


http://translate.google.com/?tl=fr#auto/fr/Logout

Friday, July 5, 2013

Multi threading example using Java

Multi Threading example in java

It is very common requirement to implement multi threading in large scale applications to improve the throughput of response,

Below screenshot demonstrates how to crate a thread, and process the given List of values


Below java class demonstrates, how to perform multi threading.

Monday, July 1, 2013

How to use VarArgs in Java


Variable Arguments(Varargs) :  varargs allows a method to accept zero or more arguments, No need to specify how many number of arguments will be passed to a method.

Syntax : access_specifier return_type method_name(data_type... variable_name){}

Below example demonstrate two methods with varargs.


Thursday, June 27, 2013

Hello World Application using Struts 2.1


- Create a Java Project & Add Struts Capabilities to the project.

- Develop index.jsp as shown below, Ensure form action value will be used in struts.xml

- Ensure web.xml should be as shown below

- Define welcome.jsp with whatever you want to display.

- Develop a Customer.java POJO class as shown below, Ensure this should have a method called execute() , Struts framework will invoke execute() method internally.. This method can return any string value based on functional requirement.


- Modify struts.xml as shown below
  - Configure action element as shown below
  -  Add as many result elements as you want based on execute() method return values.. If execute() method returns "success" , "failure" depends on two conditions, then define two result elements as shown below.


- Run this application , Right click on project, Run As ->MyEclipse Server Application

- By default, it will launch index.jsp

- By clicking on 'Submit' button , this will invoke form action and navigate to based on execute() method return value.


Wednesday, June 26, 2013

Hello World Example With Spring Framework


- Create a Java Project in My Eclipse, Add 'Spring3.1' Capabilities, By right clicking on Project->MyEclipse->Project Facets(Capabilities)->Spriing Facet
This will load required libraries in the class path.

- Create a Customer POJO as shown below, with  one parameterized constructor and to data members


- Update applicationContext.xml as shown below by configuring the bean details.

- Write a simple Test class as shown below, Right click on this class and run as java application

- You should see below output by running above class

Monday, June 17, 2013

Deployment issue while deploying from Jdeveloper to Weblogic Console : Deployer:149140

Deployment issue while deploying from Jdeveloper to Weblogic Console : Deployer:149140


If you encounter below deployment issue while deploying from Jdev to Weblogic console,

Ensure you activated the changes in weblogic console.

[12:03:14 PM] [Deployer:149140]The task cannot be processed further until the current edit session is activated. When this occurs, task processing will continue. The user can exit the deployer tool without affecting the task.

Wednesday, June 12, 2013

How to Convert org.apache.myfaces.trinidad.model.UploadedFile to java.io.File



Convert org.apache.myfaces.trinidad.model.UploadedFile to java.io.File

// assume that you have the UploadedFile object named uploadFile
InputStreamReader reader = new InputStreamReader(uploadFile.getInputStream());
int partition = 1024;
int position = 0;
int length = 0;
char[] buffer = new char[partition];
FileWriter fstream = new FileWriter("test.tmp");
do{
    length = reader.read(buffer, position, partition)
    fstream.write(buffer, position, length);
}while(length > 0);
File file = new File("test.tmp");

    /**
     * Read the attached file content as a byte[] and convert to Datahandler
     * @param valueChangeEvent
     */
    public void onFileUpload(ValueChangeEvent valueChangeEvent) {
        String methodName = "onFileUpload(ValueChangeEvent)";
        _logger.entering(CLAZZ_NAME, methodName);
        try {
            UploadedFile file = (UploadedFile)valueChangeEvent.getNewValue();
            byte[] byteArray=org.apache.commons.io.IOUtils.toByteArray(file.getInputStream());
            DataHandler dataHandler = new DataHandler(byteArray,"application/octet-stream");

        } catch (Exception b64de) {
            _logger.logp(Level.SEVERE, CLAZZ_NAME, methodName,
                         " Exception Occured", b64de);

            b64de.printStackTrace();
        }
        _logger.exiting(CLAZZ_NAME, methodName);
    }

Tuesday, June 11, 2013

How to read, write, delete, update file content using Java

How to read, write, delete, update file content using Java


package com.fm.helloworld.customer.model.fileutil;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;

public class FileUtil {
    public FileUtil() {
        super();
      int a=34;
      Integer a1 = new Integer("34");
      System.out.println(a1);
    }

    /**
     * This method reads the contents of the given file
     * and returns the String
     * @param fileName
     * @return
     */
    public String readFileContent(String fileName) {
        StringBuilder sb = new StringBuilder();
        // Get the reference of given File
        File file = new File(fileName);
        int ch;
        // FileInputStream variable
        FileInputStream fin = null;
        try {
            fin = new FileInputStream(file);
            // Iterate through every character of given File
            while ((ch = fin.read()) != -1)
                sb.append((char)ch);
            fin.close();
        } catch (Exception e) {
            System.out.println(e);
        }
        return sb.toString();
    }

    /**
     * This method creates a new File
     * @param fileName
     * @param fileContent
     * @return
     */
    public boolean createFile(String fileName, String fileContent) {
        boolean isSuccess = true;
        try {
            File f1 = new File(fileName);
            BufferedWriter bw = new BufferedWriter(new FileWriter(f1));
            bw.write(fileContent);
            bw.close();
        } catch (Exception e) {
            System.out.println(e);
            isSuccess = false;
        }
        return isSuccess;
    }

    /**
     * This method reads the contents of the given file using Buffer Reader
     * and returns the String
     * @param fileName
     * @return
     */
    public String readFileContentUsingBufferReader(String fileName) {
        StringBuilder sb = new StringBuilder();
        // Get the reference of given File
        File file = new File(fileName);
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            while (true) {
                String str = br.readLine();
                if (str == null) {
                    break;
                } else {
                    sb.append(str);
                }
            }
            br.close();
        } catch (Exception e) {
            System.out.println(e);
        }
        return sb.toString();
    }
    /**
     * This method updated the given file with given content.
     * If everything goes fine, return true otherwise return false
     * @param fileName
     * @param fileContent
     * @return
     */
    public boolean updateFile(String fileName, String fileContent) {
        boolean isSuccess = true;
        StringBuilder sb = new StringBuilder();
        try {
            File f1 = new File(fileName);
            if (f1.canWrite()) {
                String existFileContent =
                    readFileContentUsingBufferReader(fileName);
                sb.append(existFileContent);
                BufferedWriter bw = new BufferedWriter(new FileWriter(f1));
                sb.append(fileContent);
                bw.write(sb.toString());
                bw.close();
            }

        } catch (Exception e) {
            System.out.println(e);
            isSuccess = false;
        }
        return isSuccess;
    }

    /**
     * This file copies data from srcFile to tgtFile
     * @param srcFile
     * @param tgtFile
     * @return
     */
    public boolean copyFile(String srcFile, String tgtFile) {
        boolean isSuccess = true;
        try {
            String existFileContent =
                readFileContentUsingBufferReader(srcFile);
            createFile(tgtFile, existFileContent);

        } catch (Exception e) {
            System.out.println(e);
            isSuccess = false;
        }
        return isSuccess;
    }

    /**
     *
     * @param fileName
     * @return
     */
    public boolean updateFileStatus(String fileName,boolean isReadOnly) {
        boolean isSuccess = true;
        StringBuilder sb = new StringBuilder();
        try {
            File file = new File(fileName);

            if(isReadOnly){
                file.setReadOnly();
            }else{
                file.setWritable(true);
            }
           
            boolean readOnly = file.canWrite();
            System.out.println("File Status : " + readOnly);

        } catch (Exception e) {
            System.out.println(e);
            isSuccess = false;
        }
        return isSuccess;
    }
    /**
     *
     * @param dirName
     * @return
     */
    public boolean createDirectory(String dirName){
        boolean isSuccess = true;
       
        try {
            File file = new File(dirName);
            file.mkdirs();

        } catch (Exception e) {
            System.out.println(e);
            isSuccess = false;
        }
        return isSuccess;
    }
    public static void main(String[] args) {
        FileUtil util = new FileUtil();
        //String fileContent=util.readFileContent("C:/RKP/emp.txt");
        //System.out.println(fileContent);
        String fileName = "C:/RKP/fmtest.txt";
        String tgtFileName = "C:/RKP/fmtest_copy.txt";
        String fileContent = null;
        boolean isSuccess = false;
        fileContent = " || Fortune Minds Inc - April 23";
        String dirName="C:/tmp/tmp1";
       
        //isSuccess= util.createDirectory(dirName);
         //isSuccess = util.createFile(fileName, fileContent);
        //fileContent = util.readFileContentUsingBufferReader(fileName);
        //isSuccess = util.updateFileStatus(fileName,true);
        //isSuccess = util.updateFile(fileName, fileContent);
        //isSuccess = util.updateFileStatus(fileName, false);
        //isSuccess = util.updateFile(fileName, fileContent);
        isSuccess=util.copyFile(fileName, tgtFileName);
        System.out.println(isSuccess);
        System.out.println(fileContent);
    }
}

Monday, June 3, 2013

How to get the logged in Host & User Details in Java

How to get the logged in Host Name & User Details in Java?

import java.net.InetAddress;

 String hostName = InetAddress.getLocalHost().getHostName();

To get logged in user name

String user = System.getProperty("user.name");

Friday, May 31, 2013

Date Conversions using XMLGregorianCalendar in Java

How to convert to different date data types using XMLGregorianCalendar in Java


/**
   * Returns XMLGregorianCalendar for Current Date and Time.
   */
  public XMLGregorianCalendar getCurrentDateTimeAsXMLGregorianCalendar()
  {
    GregorianCalendar gc = new GregorianCalendar();
    return new XMLGregorianCalendarImpl(gc);
  }

  /**
   * Convert supplied XMLGregorianCalendar to java util Date
   */
  public Date getJavaDateFromXMLGregorianCal(XMLGregorianCalendar pXCal)
  {
    if (pXCal != null)
    {
      return pXCal.toGregorianCalendar().getTime();
    }
    return null;
  }
   // Convert java.util.Date to XMLGregorianCalendar
  public XMLGregorianCalendar toXMLGregorianCalendar(Date pDate)
  {
    GregorianCalendar gc = new GregorianCalendar();
    gc.setTimeInMillis(pDate.getTime());
    return new XMLGregorianCalendarImpl(gc);
  }

Tuesday, May 28, 2013

How to retrieve data from Oracle Database using JSP

How to connect to Oracle Database in JSP ? How to query & Retrieve data from Database in JSP

- Below is the snippet about connecting to Oracle Database in JSP



Below is the snapshot to retrieve data from Result set and display it on to the screen using JSTL tab libraries in JSP


Thursday, May 23, 2013

How to Write JUnit Tests using Jdeveloper

JUnit is a simple, open source framework to write and run repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks. JUnit features include:
- Assertions for testing expected results
- Test fixtures for sharing common test data
- Test runners for running tests
File -> New -> Choose TestSuite as shown below




- Create a Test class as shown below


- Write the test methods as shown below, Ensure to have @Test annotation.
- Ensure to import below packages
                      import static org.junit.Assert.*;
                      import org.junit.Test;


- Open the test suite class, Structure Window -> Right click on class name -> Choose Run/Debug option



- Once you run all the tests, below is the screenshot how it looks like the results.

For More Info, visit : http://junit.sourceforge.net/doc/faq/faq.htm#running_15

Tuesday, May 7, 2013

Remote Desktop Share using Google Chrome browser

Google chrome has one of the best feature, I use frequently. i.e Remote Desktop Sharing. Very simple to access remote desktop.


Step1 : Open the below url in Google Chrome browser

https://chrome.google.com/webstore/detail/chrome-remote-desktop/gbchcmhmhahfdphkhkmpfmihenigjmpp/related

Step2 :  Click on 'Launch App' button

Step 3:  If you want to access remote machine, then click on 'Access' , Get the access code from other end , enter the access code when prompted, you are all set to access the remote machine.

Step4 : If someone want to access your machine, then click on 'Share' , Provide the generated access code to other end, The should able to access your machine.


Wednesday, May 1, 2013

How to convert Array to List and List to Array

Use case : How to convert java.util.List to Array & Array to java.util.List in Java

Implementation : 

List to Array conversion

List<String> nameList = new ArrayList<String>();
nameList.add("Steve");
nameList.add("Tom");

// Convert List to Array with Generics.
String[] nameArray = nameList.toArray(new String[nameList.size()]);

Array to List conversion

// Convert Arrays to List with Generics
List<String> lastNameList = new ArrayList<String>(Arrays.asList(nameArr));

Sunday, April 21, 2013

How to capture/Allow Program Input using Jdeveloper

Usecase : How to accept/capture/allow Program Input using Jdeveloper


Solution
 - Right click on project - Project Properties - Choose 'Run/Debug/Profile'  - Choose 'Default' and click on 'Edit' button - Choose 'Tool Settings' - Check 'Allow Program Input' - Click 'ok' button


Wednesday, April 17, 2013

Java/J2EE Workshop Assignments for Beginers



- Create a simple HelloWorld java class, Print ‘Hello World”.


- Create a MathUtil class to perform below operations

- add(int,int) ;

- multiply(int,int);

- divide(int,int);

- subtract(int,int);

- Override all the above methods for rest of data types (float,double,long)


- Create a CustomStringUtil class to perform below operations

- reverseString(String) - Reverste the given string and display

- determineLength(String) - Returns the length of the string

- characterAtIndex(String,int) - Returns the character at a specified index in a given String

- checkGivenCharExistsInString(String,char) - return true if the given character exists in a given String else false.

- convertToInteger(String) - if given input String is Numeric then only convert to Integer otherwise display a message saying “Invalid Input parameter”


- Max of four

- Write a method which accepts four values with different data types (int,float,double,long,String (Eg : “45”,”34.45”) for each method, and return the maximum value out of given two values.

Note : For string values, you have to typecast and apply mathematical operators


- Min of four

- Write a method which accepts five values with different data types (int,float,double,long,String (Eg : “45”,”34.45”) for each method, and return the minimum value out of given two values.

Note : For string values, you have to typecast and apply mathematical operators


- Max of five

- Write a method which accepts three values with different data types (int,float,double,long,String (Eg : “45”,”34.45”,”66”) for each method, and return the maximum value out of given five values.

Note : For string values, you have to typecast and apply mathematical operators


- Min of five

- Write a method which accepts five values with different data types (int,float,double,long,String (Eg : “45”,”34.45”,”343”) for each method, and return the minimum value out of given five values.


Note : For string values, you have to typecast and apply mathematical operators


- Random Number Generation

- Write a method, which accept an integer and return the number of random generated values between 1 to 1000 as an Array - Don't use any java provided api's such as Random class to generate , Use core java features and apply some logic.


- Greet Message - Using Switch & Case

- Write a method, which accept integers from 1- 10 , Based upon value print a message as shown below

10 -”Exceptional”

9 - “ Excellent”
8 - “ Very good”
7 - “ Good”
6 - “ Average”
5 - “ Work Hard”
4 - “  Poor”
3 - “ Very Poor”
2 - “ Rejected”
1 - “ Disqualified”
- Sum & Product of given number
-  Write two methods, which accept an integer value and perform as below
- Eg : if “5” is given then sum of the given number means : 5+4+3+2+1
- Eg : if “5” is given then product of the given number means : 5*4*3*2*1

- Factorial of given Number
- Write a method , which accept an integer and return the factorial value of given number

- Reverse a Number
- Write a method, which accepts an integer and return the ‘Reverse of the given Number”
- For eg : if “124” is given , then return 421

- Reverse a String
- Write a method , which accepts a String value then return the ‘Reverse of the Given String”
- Eg : if “ABC” is given, then return “CBA”

- Sum of all the integers between given two numbers, which are divisible by 3
- Write a method, which accept two integers ( Lower limit and upper limit) , and return the sum of all the integers between given range which are divisible by 3

- Concatenate
- Write a method, which accept an integer, and the result is String as shown below example
Eg : Input : 5 , Output : “5 - 4 - 3 - 2 - 1”

- Multiplication Table :
- Write a method, which accept an integer, print the Multiplication table for given input as shown below
Eg : If input is 7, Then result is : 7 X 1= 7
       7 X 2 = 14, etc... 7 X 10 = 70

-  Determine Year, Month, Days
- Write a method, accept an integer , then display a String with years, months and days as shown below
Eg : If input is 69 , then result should be : 69 days = 2 Month and 9 days

- Inverse Triangle
-  Write a method, which accepts an integer, and displays the result as shown below
Eg :   Input - 5
  Output :
 5 5 5 5 5
 4 4 4 4
 3 3 3
 2 2
 1

- Prime Number, Even, Odd
- Write three different methods, accepts an integer and return true corresponding to each method to check whether the given number is Prime Number or not , Even or not , Odd or not.

- Display Positions
- Write a method, which accepts an integer and returns the string as shown below example
Eg : Input : 125 , Result is : “ One Hundred Twenty Five”  - Similarly for any number which is less than or equal to 1 million.

- Print Triangle
- Write a method, which accepts an integer and return the output as shown below
Eg :
   1
   2 4
   3 6 9
   4 8 12 16 ... N (indicates no. of Rows) */
    

- Extract Number from a String
- Write a java method, which accepts a string and returns numeric value
- For eg : If input is " <=12" , then return only 12
If input is " >= 12.34" , then return only 12.34
---------------------------------------------------------------------------------------------------

- Arrays


     - Write a java utility method, which stores the numbers 1 to 100 into an int array and print these values

     - Write a java utility method, which stores the numbers 1.1,1.2,1.3 to 100.00 into an float array and print these values

     - Write a java utility method, which stores the 10 different names into String array and print these values

    

      - Create a PersonDTO class with name,age,sal,dob attributes with setter & getter methods, and implement below functionality

              - Write a utility method, which accepts an integer number(n) and returns Array of n ‘PersonDTO’ objects.

- Construct Array of ‘PersonDTO’  with different set of data for name,age,sal & dob fields (at least 5 different PersonDTO objects) , and implement below functionality

          -  Write a method, which accepts name, then iterate through the array, return the corresponding array of PersonDTO object which match with the given input Name.

          -  Write a method, which accepts age, then iterate through the array, return the corresponding array of PersonDTO objects where age <= given input age value.


- Write a method, which accepts three parameters, lower limit(integer), upper limit(integer)   , and numberType(String) , then returns the Array of numbers based on below conditions

     - Eg : If lower limit is 0, Upper limit is 100 , numberType is ‘Even’ then should return array of even numbers from 0 to 100

     - Eg : If lower limit is 0, Upper limit is 100 , numberType is Odd then should return array of odd numbers from 0 to 100

     - Eg : If lower limit is 0, Upper limit is 100 , numberType is ‘Prime’ then should return array of prime numbers from 0 to 100

     - Eg : If lower limit is 0, Upper limit is 100 , numberType is ‘Fibonacci’ then should return array of fibonacci numbers from 0 to 100

     - Eg : If lower limit is 0, Upper limit is 100 , numberType is null or blank then should return array of  numbers from 0 to 100


- Write a utility method, which accepts array of integers, returns the array of integers in ascending order

- Write a utility method, which accepts array of integers, returns the array of integers in descending order


- Write a utility method, which accepts array of float values, returns the array of float numbers in ascending order

- Write a utility method, which accepts array of float values, returns the array of float numbers in descending order


- Write a utility method, which accepts array of long numbers, returns the array of long numbers in ascending order

- Write a utility method, which accepts array of long numbers, returns the array of long numbers in descending order


- Write a utility method, which accepts array of String values, returns the array of String values in ascending order
- Write a utility method, which accepts array of String values, returns the array of String values in descending order


- Write a method, which accepts an integer array and return an integer array with below implementation

- Reverse the elements of given integer array and return the result array. For eg : If input is [0,1,2,3,4,5] , then result is {5,4,3,2,1,0]

- Write a method, which accepts an float array and return an integer array with below implementation

- Reverse the elements of given float array and return the result array.

- Write a method, which accepts and double array and return an integer array with below implementation

- Reverse the elements of given double array and return the result array.

- Write a method, which accepts an long array and return an integer array with below implementation

- Reverse the elements of given long array and return the result array.

- Write a method, which accepts an Integer array and return an integer array with below implementation

- Reverse the elements of given Integer array and return the result array.

- Write a method, which accepts an Float (Wrapper) array and return an integer array with below implementation

- Reverse the elements of given Float (Wrapper)array and return the result array.

- Write a method, which accepts an String array and return an integer array with below implementation

- Reverse the elements of given String array and return the result array.

- Write a method, which accepts Double array and return an integer array with below implementation
- Reverse the elements of given Double array and return the result array.


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

File API

-   Create a FileUtil class with below methods
- Write a method, which accepts directory path (String) as input, return true if it successfully creates the directory , otherwise return false (For eg : If “ \temp\office\employee” , then should create a directory under C:\temp\..

- Write a method, which accepts fileName, fileContent , Create the file as per given name and content , Return true upon successful creation of file, otherwise return false.

- Write a method, which accepts fileName as input parameter, delete the given file if exists and return true, otherwise return false.

- Write a method, which accepts two file names as srcFileName,tgtFileName, then copy the contents of srcFileName to tgtFileName, Return true upon successful copy otherwise return false.
- Write a method, which accepts fileName , fileContent, Append the fileContent to the existing file , return true upon successful update to the file otherwise return false.


- Create a employee.txt  file with at least 10 rows having below kind of data(FName,LName,Age,Dob,Company,Address)

      Steve||Jobs||23||12-12-1965||Apple||Address1||Address2||City||State||Country||Postal

- Create a EmployeeDTO class with fName,lName,age,dob,company,address1,address2,city,state,country and postal attributes & setter & getter method for each attribute

      Perform below implementation using above two steps.

- Write a method, Which accepts a first Name & last Name , Read the file content and if you find any match with the given first name and last name in file content, then read the line from the file, Delimit the line using ‘||’ pipe operator, populate first Name, lastName, age, date of birth and rest of the data to EmployeeDTO object and return the object.

- Write a method, which accepts ‘EmployeeDTO’ object, If this object is not null, then read each attribute, construct a String object with each attribute from EmployeeDTO object seperated by
||’ pipe operator, and append this string to employee.txt file.


-  Write a program which reads data stream from keyboard char by char.And read the data stream and exit the

  reading when it encounters the letter Q.

Hints: say the data stream is  abc1234Qefg

          While reading, it print will be  abcq123 only.



- Write a program which reads the directory,identifies whether its directory or a file.If it is a directory enter into the directory and count the number of directories and files available in that directory.



-  Write an example that counts the number of times a particular character, such as e, appears in a file.

Hints: say the file content is: “the java is oops launguage


-  Write an example that counts the number of times a particular word, such as “The”, appears in a file.

Hints: say the file content is: “The java is as good as the good programmer is ”


- Write a Program which opens a file,reads the file and counts the number of words available in that file.

- Write a method with below functionality - Prepare .txt file
- Accept table name as input parameter
- If the provided table exist in database, read the contents of the table, write the contents of the table into .txt file by comma separated.
- If table name doesn't exists, write a error message " Table doesn't exist" to console and return false.
- If successfully able to write into file and create, return true otherwise return false.

- Write a method with below functionality - PREPARE CSV file
- Accept table name as input parameter
- If the provided table exist in database, read the contents of the table, write the contents of the table into .csv file by comma separated.
- If table name doesn't exists, write a error message " Table doesn't exist" to console and return false.
- If successfully able to write into file and create, return true otherwise return false.

- Write a method with below functionality - - Return Array of file contents
- Accept table name as input parameter
- If the provided table exist in database, read the contents of the table, Prepare table content into two dimensional array and return
- If table name doesn't exists, write a error message " Table doesn't exist" to console and return null.
- If successfully able to write into file and create, return String[][] otherwise return null.
- Eg : If Employee table has two rows with content as Ravi,23 & Ron 24, output should be as below
[Ravi,23]
[Ron,24]

- Write a method with below functionality - - Return List of Array file content
- Accept table name as input parameter
- If the provided table exist in database, read the contents of the table, Prepare table content into List<String[]> and return it
- If table name doesn't exists, write a error message " Table doesn't exist" to console and return null.
- If successfully able to write into file and create, return List<String[]> otherwise return null.
- Eg : If Employee table has two rows with content as Ravi,23 & Ron 24, output should be as below
List<String[]>

------------------------------------------------------------------------------------------------------------------------------
JDBC related

- Write a SQL Script to below requirements

- Create a Student table with below attributes
- FName - 50 characters, required
- MName - 5 characters, optional
- LName - 50 char, required
- Age - Number, required
- DOB - Date - required
- Joining Date - Date - required
- GPA - Number(2,1) - Accepts a float value with only one value after decimal

-  Write a sql command to insert at least 5 students information into above table

-  Write a sql command to read all the students from Student table

- Write a sql command to read all the students whose name starts with ‘R’

- Write a sql command to read all the students whose LName ends with ‘i’

- Write a sql command to read only FName,LName from student table where age > 30 and FName contains a ‘i’

- Write a sql command to read all the students from Student table in descending order by age.

- Write a sql command to read all the students from Student table in ascending order by joining date.

- Write a sql command to alter Student table - Add a new column ‘StudentID - Number - Required - Unique’

- Write a sql command to update Student table, - Update all the records with a unique value for Student ID

- Write a sql command to delete the data from Student table where age <=12

- Write a sql command to read distinct First Names from Student table.

- Write a sql command to create a table called ‘Student_Backup’ exactly based on ‘Student’ table and copy the data from ‘Student’ table to ‘Student_Backup’

- Write a java program to read the contents of the ‘Student’ table and write the each row of Student table  into ‘Student.txt’ file , seperate the each column value by comma(‘,’)

- Write a java program to alter ‘Student’ table to add a new column ‘Email - varchar2(50), required’.

- Write a java program to read the data from ‘Student.txt’ and update the ‘Student_Backup’ database table.

- Create a Database Sequence to store the value of Student_ID

- Create a Database Trigger to set a new DB sequence value to ‘Student_ID’ column in Student table whenever new student record inserted.

- Write a java method deleteTable(), which accept a table name, Delete the contents of the given table name and return true if successfully deleted, otherwise return false.

- Write a java method , truncateTable() - Which accepts the table name , Remove the contents of the table as well as remove the table from the dataase. Return true if successfully removed db table otherwise return false.

- Write a java method, which accepts table name and return the String[][] as per below
        - Read the contents of the given table, Prepare String array for each row  , return all the data in a form of two dimensional array

- Write a java method as below
- public boolean createFileFromDBTable(String dbTableName,String fileName, String filePath)
- Based on given table name, Read the contents of the file
- Write each row of the table with a delimiter comma(,) to a text file
- Save the file as per given name and path.
- Return true upon successful creation of table, otherwise false.

- Write a java method as below
- public List<StudentDTO> readStudentData() throwsSQLException;
- Create a StudentDTO Pojo class with all the attributes as per Student table with setter/getter for every column in Student table.
- Read the contents of ‘Student’ table
- Iterate through each row of Student table, Create a new Object of StudentDTO for each row of Student table
- Set the corresponding Student database column values to corresponding StudentDTO
- Add the StudentDTO to ArrayList
- Return ArrayList
- Throw SQLException if any SQL related exception occurs.
-------------------------------------------------------------------------------------------------------------------

Date/Time l Related
- Write a method which returns a current java.util.Date object.
- Write a method, which accepts a Date Time in String format, convert String to java.util.Date
Eg : Input : “05/12/2012 12:12:12” Output: Corresponding java.util.Date object
Eg : Input : “20120528 12:12:12” Output: Corresponding java.util.Date object
Eg : Input : “MAR 28 2012  12:12:12” Output: Corresponding java.util.Date object
Eg : Input : “05/12/2012  23:56:54” Output: Corresponding java.util.Date object
- Write a method, which accepts timeZone and Date in String format, Convert the given String to a java.util.Date based on given time zone value.
public java.util.Date parseDate(String pDate, TimeZone pTimeZone);
- Write a method, which accepts java.util.Date object, Date Format, Convert the given java.util.Date to a String format and return it.
public String parseDateToString(java.util.Date pDate, String pDateFormat);
- Write a java method, which accepts two java.util.Date objects and perform whether first Date is after second date or not
public boolean after(java.util.Date pDate1,java.util.Date pDate2);
Eg : return true if pDate1 is after pDate2 , 12/12/2012 is after 12/12/2011 , Say return true.


- Write a java method, which accepts two java.util.Date objects and perform whether first Date is before second date or not

public boolean before(java.util.Date pDate1,java.util.Date pDate2);

Eg : return true if pDate1 is before pDate2 , 12/12/2012 is before 12/12/2013 , return true.

- Write a java method, which accepts two java.util.Date objects and perform whether first Date is on or after second date or not

public boolean onOrAfter(java.util.Date pDate1,java.util.Date pDate2);

Eg : return true if pDate1 is or or after pDate2 , 12/12/2012 12:23:45 is on or after 12/12/2012 12:23:45  , return true.

- Write a java method, which accepts two java.util.Date objects and perform whether first Date is on or before second date or not

public boolean onOrBefore(java.util.Date pDate1,java.util.Date pDate2);

Eg : return true if pDate1 is or or before pDate2 , 12/12/2012 12:23:45 is on or before12/12/2012 12:23:45  , return true.

- Write a java method, which accepts a java.util.Date object and int ,add given Days to Date and return the result Date

public java.util.Date addDays(java.util.Date pDate1,int pDays);

- Write a java method, which accepts a java.util.Date object and int ,add given yearsto Date and return the result Date

public java.util.Date addYears(java.util.Date pDate1,int pYears);

- Write a java method, which accepts a java.util.Date object and int ,add given Months to Date and return the result Date
public java.util.Date addMonths(java.util.Date pDate1,int pMonths);
- Write a java method, which accepts a java.util.Date object and int ,add given Hours to Date and return the result Date
public java.util.Date addHours(java.util.Date pDate1,int pHours);
- Write a java method, which accepts a java.util.Date object and int ,add given Minutes to Date and return the result Date
public java.util.Date addMinutes(java.util.Date pDate1,int pDays);
- Write a java method, which accepts a java.util.Date object, TimeZone , convert the given util.Date to oracle.jbo.domain.Date object based on given time zone value
public oracle.jbo.domain.Date parseToJboDate(java.util.Date pDate1,TimeZone pTimeZone);
- Write a java method, which accepts a java.util.Date object, TimeZone , convert the given util.Date to java.sql.Date object based on given time zone value
public java.sql.Date parseToSqlDate(java.util.Date pDate1,TimeZone pTimeZone);
- Write a java method, which accepts a java.util.Date object, Print Number of years, months,days,hours,minutes and seconds in a given Date object.
- Write a java method, which accepts java.util.Date , Return a Day of Week value
public String getDayOfWeek(java.util.Date pDate);
- Write a java method, which accepts java.util.Date, Return a Month for eg: JAN
public String getMonth(java.util.Date);
- Write a java method, which accepts two util.Date objects and perform whether those two dates are equal or not.
public boolean checkEquality(java.util.Date pDate1, java.util.Date pDate2);
- Write a java method, which accepts two util.Date objects and return the difference between two days in the format of String
public String findDateDifference(java.util.Date pDate1, java.util.Date pDate2);
Eg : 5/19/2013 12:23:45 , 5/19/2012 12:23:45 then output is : “ 1 Year 0 months 0 days 0 hours 0 minutes 0 seconds

- write a java method , which accepts java.util.Date object, returns Month for eg : JAN.MAR,SEP etc


- write a java method , which accepts java.util.Date object, returns Year for eg : 2013, 2011

- write a java method , which accepts java.util.Date object, returns Week for eg : 1.2,3etc

- write a java method , which accepts java.util.Date object, returns Day for eg : 1,2,3

- write a java method, which accepts Date in the form of String and returns Month, Year, Day, Week - Write separate methods for each , Hint : You need to convert from String to java.util.Date and re use above methods.
---------------------------------------------------------------------------------------------------------------------------------------------

Collection Framework Related

- Initialize ArrayList, Store 10 String values and display them
- Initialize ArrayList, Store 10 float numbers, print them in ascending order.
- Initialize ArrayList, store 10 employee names, sort them in descending order
- Initialize ArrayList, Store numbers from 1 to 1000 , Accept a number as a input parameter to the method, verify whether the given Number exists in the ArrayList or not.
- Write a method and implement below functionality
- Accept the DB table name
- Query the Database table, read the contents of the table, and store all the column1 values into List, Return the List

- Initialize ArrayList, load Employee Names into this by querying Employee table, Use java.util.Iterator , Iterate through the list and print the employee names

- Create Hash Map with below criteria
- Key is Id as Integer and value as EmployeeDTO
- Have empID and empName as attributes in EmployeeDTO class
- create 100 EmployeeDTO objects, each object will have id as 1,2,3,etcc and name as Name1,Name2,Name3,etcc
- store these objects into above map with key as employee ID
- Iterate Hash Map, Print all the key values(i.e Id)
- Iterate Hash Map, Print all the key values (i.e Id) and corresponding empName(EmployeeDTO->empName)
- Test by removing specific element from Hash map based on some key value.

- Create Hash Table with below critieria
- Key is employee ID of Integer data type
- Value is First Name
- Store 10 different employee ID's and corresponding names
- Iterate the Hash table, and print all the key values using java.util.Iterator
- Iterate Hash table, Print Key (i.e employee ID) and print corresponding value (i.e first Name)
- Test by removing specific element from Hash Table based on some key value.

- Create Hash Map with below criteria.
-> Key is Employee ID (Integer)
-> Value is List<String>
- Store 10 objects into Hash Map with distinct employee ID's and for each employee ID store 10 distinct String values into a List object and set it as a value
- Iterate Hash Map and print all the key values.
- Iterate Hash Map print all the key and corresponding list of values.



- Create a JUNIT test class for all the above functionality and verify.
------------------------------------------------------------------------------------------
JSP



- Develop a helloWorld.jsp , Display current Date/Time and IP Address

- Try below

- develop page1.jsp, Display “Welcome to page1” , Display a command button named as ‘Next’. By clicking on ‘Next’ button redirect the user to page2.jsp , Display message “ Welcome to Page2”

- Develop empHome.jsp with below buttons

- ‘CustomerMgmt’ button - By clicking on redirect the user to customerhome.jsp

- ‘VendorMgmt’ button - By clicking on redirect the user to vendorhome.jsp

               - ‘SearchEmployee’’ button - By clicking on redirect user to searchemp.jsp

- Develop ‘customerhome.jsp’ with below components

- ‘SearchCustomer’ button, By clicking on redirect to ‘searchcustomer.jsp’

- ‘AddCustomer’ button , By clicking on redirect to ‘addcustomer.jsp’
             
- Develop ‘vendorhome.jsp’ with below components
- ‘SearchVendor’ button, By clicking on redirect to ‘searchvendor.jsp’
- ‘AddCustomer’ button , By clicking on redirect to ‘addvendor.jsp’

 - Develop ‘searchcustomer.jsp’ with below components
- CustomerID - Input text
               - Customer First Name - Input text
               - Customer Last Name - Input text
               - Gender - Radio button with male/female options
               - Search - command button
               - Table component - By clicking on above search button, If any results matches with the database, then populate this table with list of matching customers

- Develop ‘addcustomer.jsp’ with below components and functionality
- Customer First Name - Input text - Required - Length should be <=50 char
- Customer Middle Name - Input text - Optional- Length should be <=5 char
- Customer Last Name - Input text - Required - Length should be <=50 char
               - Gender - Radio button with male/Female options.
               - DOB - Month - list of months/ Day - list of days from 1-31/Year - List of values from 1970 to 2013.
- Address , City, State,Postal,Country - Input text , all are required.
- Save - button - By clicking on this button perform below actions
- Validate the user entered data
              - If all the conditions matches, then save the data into database.

-----------------------------------------------------------------------------
XML/ XSD

- Understand difference between xsd and xml

- Create Address.xsd with below elements
  - Complex element - Address (City,State,Country,County,Postal - All are Strings)


- Create Employee.xsd with below elements
- Complex element : Name (FirstName,MiddleName,LastName)
- Age - Integer - Required
- Date of Birth - Date
- Qualification - String
- Salary - double 
- Phone - String - Optional
- Email,Fax - String

- Home Address - Reference to Address element, Reference to Address.xsd from above
- Work Address - Reference to Address element,Reference to Address.xsd from above


- Understand about name space, default name space, target name space
- Understand about what are all the available name spaces in XSD
- Add a condition in the EmployeeDetails.xsd that the EmpAge should be between 0 to 100 

-------------------------------------------------------------------
WebServices

- Create a webservice with below method
Accept a name and return "Hello " +name;

- Create a webservice with below methods
add, multiply,divide,subtract for int,long,float and double data types.

- Create a webservice, which accepts employee ID and return EmployeeDTO based on given employee ID

- Create a webservice, which accepts employee ID, if the given employee ID exists in database, delete the given employee information from the database, return true if successful deletion otherwise false.

- Create a web service, which perform as below
Input : Employee First Name, Last Name ,Date of Birth Start, Date of Birth End Date
Output : Return Array of EmployeeDTO objects based on matching given criteria against Employee database table
- Create a JUNIT test class for all the above functionality and verify.




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

Deployment Profiles

- Create a JAR file for any Model project
- Create a WAR file for any web project
- Create an EAR file for any Java EE application