generate PDF in Java

public String generateLeaversReport(ArrayList<UserReportBean> leaversAList,String leaversFromDate,String leaversToDate,String filteredLocation) throws Exception
{
    Document document = null;
    File f= null;
    try
    {
        document = new Document(PageSize.A4,10,10,10,10);
        f = new File("Leavers.pdf");
        FileOutputStream fos = new FileOutputStream(f);
        PdfWriter.getInstance(document, fos );
        document.open();
        Table table=new Table(29);
        table.setBorder(0);
        table.setWidth(100f);
        table.setWidths(new float[]{0.5f,1.2f,1.0f,0.6f,1.25f,1.25f,1.5f,1.25f,1.20f,0.75f,1f,1.20f,0.75f,0.75f,0.75f,1.5f,0.8f,1.10f,0.8f,0.8f,0.8f,0.8f,0.9f,0.6f,0.6f,0.6f,0.6f,0.6f,0.6f});
        table.setCellsFitPage(true);
        table.setPadding(2);
        table.setSpacing(0);

        Cell hdrCell = new Cell(new Chunk(StringUtils.trimToEmpty("Leavers Report For the Period :  "+leaversFromDate+" To "+leaversToDate+" For "+filteredLocation),
                FontFactory.getFont(FontFactory.HELVETICA_BOLD, 8, Font.BOLD, new Color(0, 0, 0))));
     
        hdrCell.setColspan(29);
        hdrCell.setHeader(true);
        hdrCell.setBorder(Rectangle.NO_BORDER);
        hdrCell.setHorizontalAlignment(Cell.ALIGN_CENTER);
        table.addCell(hdrCell);
        
        table.addCell(getHeaderCell_New("S.No.",1));
        table.addCell(getHeaderCell_New("AssociateID",1));
        table.addCell(getHeaderCell_New("First Name",1));
        table.addCell(getHeaderCell_New("Middle Name",1));
        table.addCell(getHeaderCell_New("Last Name",1));
        
        for(int i=0;i<leaversAList.size();i++)
        {
            UserReportBean bean=leaversAList.get(i);
            table.addCell(getCell_New(String.valueOf(i+1),1));
            table.addCell(getCell_New(bean.getAssociateID(),1));
            table.addCell(getCell_New(bean.getFirstName(),1));
            table.addCell(getCell_New(bean.getMiddleName(),1));
            table.addCell(getCell_New(bean.getLastName(),1));
        }
        document.add(table);
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }
    finally
    {
        if(document!=null)
        {
            document.close();
        }
    }
    return f!=null?f.getAbsolutePath():null;
}

break vs return

break is used to exit (escape) the for-loop, while-loop, switch-statement that you are currently executing.
return will exit the entire method you are currently executing (and possibly return a value to the caller, optional).

you cannot use either break nor return to escape an if-else-statement. They are used to escape other scopes.

The value of x inside the while-loop will determine if the code below the loop will be executed or not:

void f()
{
   int x = -1;
   while(true)
   {
     if(x == 0)
        break;         // escape while() and jump to execute code after the the loop 
     else if(x == 1)
        return;        // will end the function f() immediately,
                       // no further code inside this method will be executed.

     do stuff and eventually set variable x to either 0 or 1
     ...
   }

   code that will be executed on break (but not with return).
   ....
}

break leaves a loop, continue jumps to the next iteration.

    class BreakContinue {
        public static void main( String [] args ) {
               for( int i = 0 ; i < 10 ; i++ ) {
                     if( i % 2 == 0) { // if pair, will jump
                         continue; // don't go to "System.out.print" below.
                     }
                     System.out.println("The number is " + i );

                     if( i == 7 ) {
                         break; // will end the execution, 8,9 wont be processed
                      }
               }
        }
    }

Ans
The number is 1
The number is 3
The number is 5
The number is 7

Struts MVC Architecture

The model contains the business logic and interact with the persistance storage to store, retrive and manipulate data.

The view is responsible for dispalying the results back to the user. In Struts the view layer is implemented using JSP.

The controller handles all the request from the user and selects the appropriate view to return. In Sruts the controller’s job is done by the ActionServlet.

abcd

The following events happen when the Client browser issues an HTTP request.

  • The ActionServlet receives the request.
  • The struts-config.xml file contains the details regarding the Actions, ActionForms, ActionMappings and ActionForwards.
  • During the startup the ActionServelet reads the struts-config.xml file and creates a database of configuration objects. Later while processing the request the ActionServlet makes decision by refering to this object.

When the ActionServlet receives the request it does the following tasks.

  • Bundles all the request values into a JavaBean class which extends Struts ActionForm class.
  • Decides which action class to invoke to process the request.
  • Validate the data entered by the user.
  • The action class process the request with the help of the model component. The model interacts with the database and process the request.
  • After completing the request processing the Action class returns an ActionForward to the controller.
  • Based on the ActionForward the controller will invoke the appropriate view.
  • The HTTP response is rendered back to the user by the view component.

abcd1

  1. User clicks on a link in an HTML page.
  2. Servlet controller receives the request, looks up mapping information in struts-config.xml, and routes to an action.
  3. Action makes a call to a Model layer service.
  4. Service makes a call to the Data layer (database) and the requested data is returned.
  5. Service returns to the action.
  6. Action forwards to a View resource (JSP page)
  7. Servlet looks up the mapping for the requested resource and forwards to the appropriate JSP page.
  8. JSP file is invoked and sent to the browser as HTML.
  9. User is presented with a new HTML page in a web browser.

web.xml Servlet Configuration

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

    <servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>   

Struts-config.xml

<struts-config>

<form-beans>
<form-bean name="HelloWorldActionForm"

type="com.vaannila.HelloWorldActionForm"/>

<action-mappings>
<action input="/index.jsp" name="HelloWorldActionForm" path="/HelloWorld"  scope="session" type="com.vaannila.HelloWorldAction">
<forward name="success" path="/helloWorld.jsp" />
</action>
</action-mappings>

Struts-config.xml is used for making connection between view & controller whereas web.xml is used for making connection between web container & web application.

web.xml will be read by container when we start the container.struts-config.xml will be read by init() method of ActionServlet.

JDBC

connection conn = connectionpool.getconnection(); 
          // drivermanager.getconenction(url,username, pass) get from property file

preparedstatement pstmt;
resultset rs;

StringBuilder query = new String Builder();
query.append ("SELECT * FROM USERS");

pstmt = conn.preparedstatement(query.toString());
pstmt.set(1, bean.getvalue())'

rs = pstmt.executeQuery();

while(rs.next()){
    rs.getInt("");
}

Regex

regex

CODE SNIPET

String regex “\s”;
String input = "Testing the text for regex";
String replace = ”Text to be replaced”;

Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);

if(matcher.find()){
   ...
}

Other Functions
Matcher.matches() – returns true or false
Input  = m.replaceAll(replace);

CODE

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexTestPatternMatcher {
  public static final String EXAMPLE_TEST = "This is my small example string which I'm going to use for pattern matching.";

  public static void main(String[] args) {
    Pattern pattern = Pattern.compile("\\w+");
    Matcher matcher = pattern.matcher(EXAMPLE_TEST);
    // check all occurance
    while (matcher.find()) {
      System.out.print("Start index: " + matcher.start());
      System.out.print(" End index: " + matcher.end() + " ");
    }
  }
}

OR

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMatches
{
    public static void main( String args[] ){

      // String to be scanned to find the pattern.
      String line = "This order was placed for QT3000! OK?";
      String pattern = "(.*)(\\d+)(.*)";

      // Create a Pattern object
      Pattern r = Pattern.compile(pattern);

      // Now create matcher object.
      Matcher m = r.matcher(line);
      if (m.find( )) {
         System.out.println("Found value: " + m.group(0) );
         System.out.println("Found value: " + m.group(1) );
         System.out.println("Found value: " + m.group(2) );
      } else {
         System.out.println("NO MATCH");
      }
   }
}

Java Concepts – 2

Difference between an Interface and an Abstract class

  • All methods in an interface are implicitly abstract. On the other hand, an abstract class may contain both abstract and non-abstract methods.
  • A class may implement a number of Interfaces, but can extend only one abstract class.
  • In order for a class to implement an interface, it must implement all its declared methods. However, a class may not implement all declared methods of an abstract class. Though, in this case, the sub-class must also be declared as abstract.
  • Abstract classes can implement interfaces without even providing the implementation of interface methods.
  • Variables declared in a Java interface is by default final. An abstract class may contain non-final variables.
  • Members of a Java interface are public by default. A member of an abstract class can either be private, protected or public.
  • An interface is absolutely abstract and cannot be instantiated. An abstract class also cannot be instantiated, but can be invoked if it contains a main method.

How do you ensure that N threads can access N resources without deadlock ?

  • A very simple way to avoid deadlock while using N threads is to impose an ordering on the locks and force each thread to follow that ordering. Thus, if all threads lock and unlock the threads in the same order, no deadlocks can arise.

Differences exist between Iterator and ListIterator

  • An Iterator can be used to traverse the Set and List collections, while the ListIterator can be used to iterate only over Lists.
  • The Iterator can traverse a collection only in forward direction, while the ListIterator can traverse a List in both directions.
  • The ListIterator implements the Iterator interface and contains extra functionality, such as adding an element, replacing an element, getting the index position for previous and next elements, etc.

Differences exist between HashMap and Hashtable

  • A HashMap allows the existence of null keys and values, while a Hashtable doesn’t allow neither null keys, nor null values.
  • A Hashtable is synchronized, while a HashMap is not. Thus, HashMap is preferred in single-threaded environments, while aHashtable is suitable for multi-threaded environments.
  • A HashMap provides its set of keys and a Java application can iterate over them. Thus, a HashMap is fail-fast. On the other hand, a Hashtable provides an Enumeration of its keys.

Difference between ArrayList and LinkedList

  • An ArrayList is an index based data structure backed by an Array. It provides random access to its elements with a performance equal to O(1). On the other hand, a LinkedList stores its data as list of elements and every element is linked to its previous and next element. In this case, the search operation for an element has execution time equal to O(n).
  • The Insertion, addition and removal operations of an element are faster in a LinkedList compared to an ArrayList, because there is no need of resizing an array or updating the index when an element is added in some arbitrary position inside the collection.
  • A LinkedList consumes more memory than an ArrayList, because every node in a LinkedList stores two references, one for its previous element and one for its next element.

HASHSET

HashSet does not guarantee any insertion orders of the set but it allows null elements. HashSet can be used in place of ArrayList to store the object if you require no duplicate and don’t care about insertion order.

Method Overloading Rules

  • change method signature. Method signature is made of number of arguments, type of arguments and order of arguments
  • only changing the return type of method does not amount to method overloading.
  • So your overloaded method throws the same exception, a different exception or it simply does no throw any exception; no effect at all on method loading.

Method Overriding Rules

  • argument list in overridden and overriding methods must be exactly same
  • return type of overriding method can be child class of return type declared in overridden method.
    public class SuperClass {
       //Overriden method
       public Number sum(Integer a, Integer b) {
           return a + b;
       }
    }
    
    class SubClass extends SuperClass {
       //Overriding method
       @Override
       public Integer sum(Integer a, Integer b) {
                       //Integer extends Number; so it's valid
           return a + b;
       }
    }

private, static and final methods can not be overridden

Overriding method can not throw checked Exception higher in hierarchy than thrown by overridden method. Let’s say for example overridden method in parent class throws FileNotFoundException, the overriding method in child class can throw FileNotFoundException; but it is not allowed to throw IOException or Exception, because IOException or Exception are higher in hierarchy i.e. super classes of FileNotFoundException.

Java Concepts

THROWS VS THROW

1. Throws clause in used to declare an exception and throw keyword is used to throw an exception explicitly.
2. If we see syntax wise, throw is followed by an instance variable and throws is followed by exception class names.
3. The keyword throw is used inside method body to invoke an exception and throws clause is used in method declaration (signature).

Throw:

static{
try {
throw new Exception("Something went wrong!!");
} catch (Exception exp) {
System.out.println("Error: "+exp.getMessage());
}
}

Throws:
public void sample() throws ArithmeticException{
 //Statements

.....

 //if (Condition : There is an error)
ArithmeticException exp = new ArithmeticException();
 throw exp;
...
}

Cloning

By default, java cloning is ‘field by field copy’ i.e. as the Object class does not have idea about the structure of class on which clone() method will be invoked. So, JVM when called for cloning, do following things:

1) If the class has only primitive data type members then a completely new copy of the object will be created and the reference to the new object copy will be returned.

2) If the class contains members of any class type then only the object references to those members are copied and hence the member references in both the original object as well as the cloned object refer to the same object.

In java, if a class needs to support cloning it has to do following things:

           A) You must implement Cloneable
B) You must override clone() method from Object class.

EXAMPLE

Employee cloned = (Employee) original.clone();
System.out.println(cloned.getEmpoyeeId());

Finally 

Finally block will execute even if you put return statement in try block or catch block but finally block won’t run if you call System.exit form try or catch.

Static

non-static variable cannot be referenced from a static context. Static variable belongs to Java class while non-static variable belongs to object. Static variable will keep same value for every object while value of non static variable varies from object to object.

Static fields are initialized at the time of class loading in Java, opposite to instance variable which is initialised when you create instance of a particular class.Static method can not be overridden in Java as they belong to class and not to object. If you try to override a static method with a non-static method in sub class you will get compilation error.

How to access non static variable inside static method or block

public class StaticTest {
    private int count=0;
    public static void main(String args[]) throws IOException {
        StaticTest test = new StaticTest(); //accessing static variable by creating an instance of class
        test.count++;
    }  
}

Yes, we can overload static method in Java.

Reverse words

public static String reverseWords2(String sentence) {
    StringBuilder sb = new StringBuilder(sentence.length() + 1);
    String[] words = sentence.split(" ");
    for (int i = words.length - 1; i >= 0; i--) {
        sb.append(words[i]).append(' ');
    }
    sb.setLength(sb.length() - 1);  // Strip trailing space
    return sb.toString();
}

ODBC

conn = ConnectionPool.getConnection();
connection = getClientConnection();

public static Connection getClientConnection() throws SQLException
    {
        Connection conn = null;
        try
        {
            if(!propertiesRead)
            {
                propertiesRead = true;
                Properties props = new Properties();
                props.load(new FileInputStream(new File("ClientDBConnection.properties")));
                DB_URL = props.getProperty("DB_URL");
                DB_USER = props.getProperty("DB_USER");
                DB_PASSWORD = props.getProperty("DB_PASSWORD");
            }
        
            Class.forName("oracle.jdbc.driver.OracleDriver");
            conn = DriverManager.getConnection(DB_URL,DB_USER,DB_PASSWORD);
        }
        catch(Exception ex)
        {
            throw new SQLException("Unable to create Client Connection "+ex);
        }
        return conn;

query = new StringBuilder();
query.append(" SELECT JOINEESCOUNT FROM USERS  ");

//any conditions
if("YTD".equals(bean.getTypeOfReport())){
        query.append(" '01-Jul-"+bean.getFiscalYear()+"' AND SYSDATE ");
}

pstmt = conn.prepareStatement(query.toString());
pstmt.setInt(1,bean.getId());
rs = pstmt.executeQuery();
while(rs.next()){
      newBean.setNumOfJoinees(rs.getInt("JOINEESCOUNT"));
}

Why String is Immutable or Final in Java

  • It is mainly for security reasons. String is used as parameter in network connection, database url etc. It can be easily attacked if it is mutable
  • Immutability of String solves some synchronization issues, it makes the String thread safe
  • To support StringPool facility. Design Strings are created in a special memory area in java heap known as “String Intern pool”. When ever you create new string variable it search for the pool to check wether it is already exist. It exist then return reference of the existing string object. If string is not immutable, changing the string with one reference will lead to the wrong value for the other references.
  • To cache the hashcode of String
  • To support class loading mechanism in which String is used as arguments. String being mutable results in wrong class being loaded
  • when compiler optimizes your String objects, it sees that if two objects have same value (a=”test”, and b=”test”) and thus you need only one string object