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

Find word in dictionary

Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the dictionary
For example,
Given:
start = “hit”
end = “cog”
dict = [“hot”,”dot”,”dog”,”lot”,”log”]
Answer

public int ladderLength(String start, String end, HashSet<String> dict) {
    if (dict.size() == 0)
        return 0;
 
    dict.add(end);
 
    LinkedList<String> wordQueue = new LinkedList<String>();
    LinkedList<Integer> distanceQueue = new LinkedList<Integer>();
 
    wordQueue.add(start);
    distanceQueue.add(1);
 
    //track the shortest path
    int result = Integer.MAX_VALUE;
    while (!wordQueue.isEmpty()) {
        String currWord = wordQueue.pop();
        Integer currDistance = distanceQueue.pop();
 
        if (currWord.equals(end)) {
            result = Math.min(result, currDistance);
        }
 
        for (int i = 0; i < currWord.length(); i++) {
            char[] currCharArr = currWord.toCharArray();
            for (char c = 'a'; c <= 'z'; c++) {
                currCharArr[i] = c;
 
                String newWord = new String(currCharArr);
                if (dict.contains(newWord)) {
                    wordQueue.add(newWord);
                    distanceQueue.add(currDistance + 1);
                    dict.remove(newWord);
                }
            }
        }
    }
 
    if (result < Integer.MAX_VALUE)
        return result;
    else
        return 0;
}

FINDING NTH HIGHEST NUMBER

EmpID   Name    Salary
1   A   100
2   B   800
3   C   300
4   D   400
5   E   500
6   F   200
7   G   600

SELECT * FROM Employee E1
WHERE (N-1) = (
                SELECT COUNT(DISTINCT(E2.Salary))
                FROM Employee E2
                WHERE E2.Salary > E1.Salary
              )

Explanation

Suppose you want to find 5th highest salary, which means there are total 4 employees who have salary greater than 5th highest employee. So for each row from the outer query check the total number of salaries which are greater than current salary. Outer query will work for 100 first and check for number of salaries greater than 100. It will be 6, do not match (5-1) = 6 where clause of outerquery. Then for 800, and check for number of salaries greater than 800, 4=0 false then work for 300 and finally there are totally 4 records in the table which are greater than 300. Therefore 4=4 will meet the where clause and will return 3 C 300.

Another way

SELECT *
FROM(
SELECT BONUSMONTHID, dense_rank() over (ORDER BY BONUSMONTHID DESC) AS DenseRank
FROM REFERRALBONUS )
where DenseRank = 2

8 PEOPLE PUZZLE

There are 8 people, who need to cross a river in  single boat. People are 1 Cop, 1 Thief, 1 Man and his 2 Daughters, 1 Women and her 2 sons. As usual the conditions that has to be satisfied while crossing the River are given below:
•    When Police man is not on that river bank, Thief will beat all the people available on that river bank.
•    When Women is Not on that river bank, Man will beat her 2 sons.
•    When Man is Not on that river bank, Woman will beat his 2 daughters.
•    Only Two people can travel in the boat at any given time.
•    2 Sons and 2 daughters doesn’t know to drive the boat.
ANSWER
Please follow Step by Step process as defined below:
Initial stage Cop, Thief, Men, Daughters, Women, Sons are at River Bank – 1
1.    Pick up Cop-Thief pair and travel to River bank – 2
2.    Drop the Thief at River bank – 2 and cop only will reach back River bank – 1
3.    Cop will Pick up Daughter – 1 at river bank -1 and travels to River Bank -2
4.    Cop will drop the daughter – 1 at river bank – 2 and picks thief along with him and reaches back to River bank – 1
5.    Both Cop and thief pair will drop at River bank -1
6.    Now Man along with his Daughter – 2 travels from River bank -1 to River Bank -2
7.    Man will drop his Daughter -2 at river bank – 2 and reaches back River Bank – 1 single
8.    Now Man will pick up Women at River bank -1 and reaches to River bank – 2
9.    Man will get down at river bank-2 and Women alone will return back to River bank – 1
10.    Women will get down at River bank -1 . Cop and Thief pair will travel from River bank – 1 to River bank – 2
11.    Cop and Thief will get down at River bank – 2. Man alone will travel back to River bank -1
12.    Man picks up woman at River bank -1 and reaches back to River bank -2
13.    Man will get down at River bank – 2 and women alone will sail back to River bank -1
14.    Women will pick up her Son – 1 at River bank – 1 and travels back to River bank – 2
15.    Women along with her son – 1 will get down at River bank -2.
16.    Cop and Thief  pair will travel from River bank – 2 back to River bank – 1
17.    Cop will drop Thief at River bank -1 and picks Son -2 and reaches River bank -2
18.    Cop will drop son-2 at river bank -2 and sails back to River bank -1 to pick up thief
19.    Both Cop an Thief pair will reach back River bank – 2 safely.

Add numbers from a string

String str = "12 hi when 8 and 9";
str=str.replaceAll("[\\D]+"," "); // returns 12 8 9
    
String[] numbers=str.split(" ");
    int sum = 0;
    for(int i=0;i<numbers.length;i++){
            sum+=Integer.parseInt(numbers[i]);
        }

\\d* matches 0 or more digits, and so it even matches an empty string.
Use \\d+ to match only 1 and more digits

Greedy quantifiers
X?  X, once or not at all
X*  X, zero or more times
X+  X, one or more times

Egg Drop

Assume that we have m eggs, and n drops are allowed. Let us represent the height of the tallest building by g (m, n), for which we can find a solution with these constraints.

g (m, n) = g(m – 1, n – 1) + g (m, n – 1) (n > 0)
g (m, 0) = 1.

This is because if we drop the first egg from the g(m – 1, n – 1)-th step, if it breaks, we still have

(m – 1) eggs and (n – 1) steps, which are enough to detect in a building of height up to g (m – 1, n – 1).

On the other hand, if it does not break, we have m eggs and (n – 1) steps, which can give us extra

g (m, n – 1) height to be able to detect.

For fixed n, the expression of g(m, n) can be calculated explicitly., e.g..

g (2, n) = n * (n + 1)/2, (n >= 3 )

Explanation

n + (n-1) + (n-2) + (n-3) + (n-4) + … + 1 >= 100

n (n+1) / 2 >= 100

3 Eggs

h(3,m) = (m-1)m/2 +1 + (m-2)(m-1)/2+1 + … = SUM (1/2)j^2 – (1/2)j +1 for j from 1 to m and

we get (1/12)m(m+1)(2m+1) – (1/4)m(m+1) + m = (1/6)(m^3 -m) + m = (1/6)(m-1)m(m+1) + m.

(1/6)(m-1)m(m+1) + m < 100 which gives m =9

So 9 is enough.

CODE

When we drop an egg from a floor x, there can be two cases (1) The egg breaks (2) The egg doesn’t break.

1) If the egg breaks after dropping from xth floor, then we only need to check for floors lower than x with remaining eggs; so the problem reduces to x-1 floors and n-1 eggs
2) If the egg doesn’t break after dropping from the xth floor, then we only need to check for floors higher than x; so the problem reduces to k-x floors and n eggs.

/* Function to get minimum number of trails needed in worst
  case with n eggs and k floors */
int eggDrop(int n, int k)
{
    // If there are no floors, then no trials needed. OR if there is
    // one floor, one trial needed.
    if (k == 1 || k == 0)
        return k;
 
    // We need k trials for one egg and k floors
    if (n == 1)
        return k;
 
    int min = INT_MAX, x, res;
 
    // Consider all droppings from 1st floor to kth floor and
    // return the minimum of these values plus 1.
    for (x = 1; x <= k; x++)
    {
        res = max(eggDrop(n-1, x-1), eggDrop(n, k-x));
        if (res < min)
            min = res;
    }
 
    return min + 1;
}

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("");
}