Sunday, September 22, 2013

Thinking in Java, Exercise Questions on Concurrency- I


/*Exercise 1:  Implement a Runnable.
 *  Inside run( ), print a message, and then call yield( ).
 *   Repeat this three times, and then return from run( ).
 *    Put a startup message in the constructor and a shutdown message when the task terminates.
 *    Create a number of these tasks and drive them using threads.
*/

import java.util.concurrent.*;
public class concurrency_ex1 {

public static void main(String[] args){
thRunnable1 r = new thRunnable1();
Thread a = new Thread(r);
Thread b = new Thread(r);

a.setName("Thread_a");
b.setName("Thread_b");
a.start();
b.start();
        }
}

public class thRunnable1 implements Runnable {

thRunnable1(){
System.out.println("Initialising the constructor...");
}

public void run(){
for(int i=0; i<3; i++) {
System.out.println("Inside run ..."+ i + "times" + " " + Thread.currentThread().getName());
Thread.yield();
}
System.out.println("Finishing the task : " + Thread.currentThread().getName());
}

}


/*Exercise 2: Following the form of generics/Fibonacci.java, create a task that produces a sequence of n Fibonacci numbers, 
 * where n is provided to the constructor of the task. Create a number of these tasks and drive them using threads.
 * 
 * */

import java.util.concurrent.*;
import java.util.*;

public class concurrency_ex2 {

public static void main(String args[]){
Thread a = new Thread(new thRunnable2(9));
Thread b = new Thread(new thRunnable2(19));
a.start();
b.start();
        }
}

public class thRunnable2 implements Runnable{
private int fib;
thRunnable2(int fib){
this.fib = fib;
}
public void run(){
int i=0, res = 1, j =0;
System.out.println("Thread is " + Thread.currentThread().getName());
while(res <= fib){
System.out.println(res);
j = res;
res = i + res;
i = j;
}
}
}

/*Exercise 3: Implement a Runnable.
 *  Inside run( ), print a message, and then call yield( ).
 *   Repeat this three times, and then return from run( ).
 *    Put a startup message in the constructor and a shutdown message when the task terminates. 
 *    Create using the different types of executors.
*/
import java.util.concurrent.*;

public class concurrency_ex1 {
public static void main(String[] args){
ExecutorService exec = Executors.newSingleThreadExecutor();
for(int i=0; i<10; i++)
exec.execute(new thRunnable1());
exec.shutdown();
}
}

public class thRunnable1 implements Runnable {
thRunnable1(){
System.out.println("Initialising the constructor...");
}
public void run(){
for(int i=0; i<3; i++) {
System.out.println("Inside run ..."+ i + "times" + " " + Thread.currentThread().getName());
Thread.yield();
}
System.out.println("Finishing the task : " + Thread.currentThread().getName());
}
}

/*Exercise 4: Following the form of generics/Fibonacci.java, create a task that produces a sequence of n Fibonacci numbers, 
 * where n is provided to the constructor of the task. Create using the different types of executors.
 * 
 * */

import java.util.concurrent.*;
import java.util.*;

public class concurrency_ex2 {

public static void main(String args[]){
ExecutorService exec = Executors.newFixedThreadPool(2);
exec.execute(new thRunnable2(9));
exec.execute((Runnable) new thRunnable2(16));
exec.execute((Runnable) new thRunnable2(7));
exec.shutdown(); 
}
}

public class thRunnable2 implements Runnable{
private int fib;
thRunnable2(int fib){
this.fib = fib;
}
public void run(){
int i=0, res = 1, j =0;
System.out.println("Thread is " + Thread.currentThread().getName());
while(res <= fib){
System.out.println(res);
j = res;
res = i + res;
i = j;
}
}
}

/* Exercise 5: Modify Exercise 2 so that the task is a Callable that sums the values of all the Fibonacci numbers.
 *  Create several tasks and display the results.
 * */

import java.util.concurrent.*;
import java.util.*;

public class concurrency_ex2 {

public static void main(String args[]){

                ExecutorService exec = Executors.newFixedThreadPool(2);
ArrayList<Future<Integer>> a = new ArrayList<Future<Integer>>();
a.add(exec.submit(new thCallable5(5)));
a.add(exec.submit(new thCallable5(8)));
a.add(exec.submit(new thCallable5(19)));
for(Future<Integer> fs: a){
try{
System.out.println("Sum is " +fs.get());
}catch(InterruptedException e){}
catch(ExecutionException ex){}
finally{
exec.shutdown();
}
}
}


import java.util.concurrent.*;

public class thCallable5 implements Callable<Integer>{
private int fib;
thCallable5(int fib){
this.fib = fib;
}
public Integer call(){
int i=0, res = 1, j =0, sum=0;
System.out.println("Thread is " + Thread.currentThread().getName());
while(res <= fib){
sum = sum + res;
System.out.println(res);
j = res;
res = i + res;
i = j;
}
return sum;
}
}


/* Exercise 6 : Create a task that sleeps for a random amount of time between 1 and 10 seconds, 
 * then displays its sleep time and exits.
 *  Create and run a quantity (given on the command line) of these tasks.*/

import java.util.concurrent.*;
import java.util.*;


public class concurrency_ex6 {
public static void main(String args[]){
ExecutorService exec = Executors.newCachedThreadPool();
Scanner sc = new Scanner(System.in);
int task = sc.nextInt();
 
for(int i=0; i<task; i++){
Future<Integer> sleep_t = exec.submit(new thCallable6());
try{
System.out.println(sleep_t.get());
}catch(InterruptedException e){}
catch(ExecutionException ex){}
}
}
}

import java.util.concurrent.*;
import java.util.Random;
public class thCallable6 implements Callable<Integer>{
public Random r = new Random();
public Integer call(){
int sleep_t = r.nextInt(10);
try{
Thread.sleep(sleep_t * 1000);
}catch(InterruptedException e) {
System.out.println(e);
}
return sleep_t;
}




Tuesday, March 19, 2013

Small Factorial


Tried two approach for the problem below:
You are asked to calculate factorials of some small positive integers.
Input
An integer t, 1<=t<=100, denoting the number of testcases, followed by t lines, each containing a single integer n, 1<=n<=100.
Output
For each integer n given at input, display a line with the value of n!

Time limit 2 sec(s)
Memory limit 256 MB
Source limit 1024 KB
(http://www.hackerearth.com/problem/small-factorials/)

/*Without recurrsion*/

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;


public class factorial {
    public static void main(String args[] ) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int t = Integer.parseInt(br.readLine());
        int arr[] = new int[t];
        for (int i = 0; i < t; i++) {
            arr[i] = Integer.parseInt(br.readLine());        
        }
        
        for(int i=0; i<t; i++){
            BigInteger res= BigInteger.valueOf(1);
            while(arr[i]>1){
                res = res.multiply(BigInteger.valueOf(arr[i]--));
            }
            System.out.println(res);        
        }        
    }
}
Statistics:
ResultTime (Sec)Memory (KiB)
1003.322211790732
/*With recurrsion*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;

public class recurrsion_fact {
    public static void main(String args[] ) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
int arr[] = new int[t];
for (int i = 0; i < t; i++) {
    arr[i] = Integer.parseInt(br.readLine());        
}
for(int i=0; i<t; i++){
    System.out.println(factorial(arr[i]));
}
    }
   
    private static BigInteger  factorial(int num){
BigInteger  res= BigInteger.valueOf(num);
if(num == 0){
    return BigInteger.valueOf(1);
}
else{
    res = res.multiply(factorial(--num));
}         
return res;
    }        
}

Statistics:
Result Time (Sec)Memory (KiB)
100          2.4186               12053904
Recurrsion is a trade off between speed and memory useage. :)


Thursday, February 7, 2013

Admission Form


School admission form to accept value from user and returns the form if any of the field is blank.
The value of the fields which are filled already, are retained.

http Address: http://localhost:8080/Excercise/form1.html

web.xml(To be stored in folder called apache tomcat/webapps/Excercise/WEB-INF in webapps):


<servlet>
<servlet-name>SchoolForm</servlet-name>
<servlet-class>Prog.Problem.School_Admission</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>SchoolForm</servlet-name>
<url-pattern>/Admission.do </url-pattern>
</servlet-mapping>

form1.html (School Admission form to be stored in apache tomcat/webapps/Excercise )

<html>
<body>

Fill in the form below for school admission for class I.

<form method="POST" action="Admission.do" >

Child's Name = <input name = "Name"></br>

DOB = <input name ="DOB"></br>

Father name = <input name = "Father"></br>

Residence Address = <input name = "Adress"> </br>

Previous School name = <input name = "School"></br>

<input type="Submit" value="Submit Form" >

<form>
</body>
</html>


School_Admission.java (.class to be stored in folder apache tomcat/webapps/Excercise/WEB-INF/classes/Prog/Problem)
package Prog.Problem;


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class School_Admission extends HttpServlet{

public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException{

res.setContentType("text/html");
PrintWriter out = res.getWriter();


if((req.getParameter("Name")=="") || (req.getParameter("DOB")=="") || (req.getParameter("Adress")=="") || (req.getParameter("Father")=="") || (req.getParameter("School")=="") ){
/*Any of above field is unfilled, return the form to user.*/
RequestDispatcher view = req.getRequestDispatcher("Incomplete_Form.jsp");
view.forward(req, res);
}

             /*If all fields are filled, show the summary of the form to user. */
else{
out.println("Form filled is </br>");
out.println("Child's Name : " + req.getParameter("Name")+ "</br>");
out.println("DOB : " + req.getParameter("DOB")+ "</br>");
out.println("Father's Name : " + req.getParameter("Father")+ "</br>");
out.println("Address : "+req.getParameter("Adress") + "</br>");
out.println("Previous School Name : " + req.getParameter("School")+ "</br></br>");
out.println("Thank you, we will get in touch asap");
}
}
}

Incomplete_Form.jsp(To be store din apache tomcat/webapps/Excercise)
This form is dispalyed till all the fields are filled by user
<html>
<body>

Enter all the fields:

<form method="POST" action="Admission.do" >

Child's Name = <input name = "Name" value="<%= request.getParameter("Name")%>"/></br>

DOB = <input name ="DOB" value="<%= request.getParameter("DOB")%>"></br>

Father name = <input name = "Father" value="<%= request.getParameter("Father")%>"/></br>

Residence Address = <input name = "Adress" value="<%= request.getParameter("Adress")%>"/> </br>

Previous School name = <input name = "School" value="<%= request.getParameter("School")%>"/></br>

<input type="Submit" value="Submit Form" >

<form>


</html>
</body>

Wednesday, January 23, 2013

ServletContextListener

Program to demonstrate use of ServletContextListener

1. Open Link:  http://localhost:8080/Excercise/MailContext

The context parameter "adminMail" is made as an attribute and database connection is made when the context is initialized. The listener which checks for context initialization is MailContextListener. 

web.xml(To be stored in folder called apache tomcat/webapps/Excercise/WEB-INF in webapps):


<web-app....>

<context-param>

<param-name>adminMail</param-name>
<param-value>java123@oracle.com</param-value>
</context-param>

<listener>

<listener-class>pack1.work.Controller.MailContextListener</listener-class>
</listener>

<servlet>

<servlet-name>ContextL</servlet-name>
<servlet-class>pack1.work.Controller.ContextListenerTester</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>ContextL</servlet-name>
<url-pattern>/MailContext</url-pattern>
</servlet-mapping>
</web-app>

/* This Listener gets the init parameter from DD, passes to Mail class constructor to make a object, set it as an attribute */
MailContextListener (.class to be stored in folder apache tomcat/webapps/Excercise/WEB-INF/classes/pack1/work/Controller )

package pack1.work.Controller;


import javax.servlet.*;

public class MailContextListener implements ServletContextListener{
public void contextInitialized(ServletContextEvent event){
ServletContext context = event.getServletContext();
String mail = (String)context.getInitParameter("adminMail");
Mail mail_id = new Mail(mail);
context.setAttribute("admin", mail_id);
}
public void contextDestroyed(ServletContextEvent event){
             /*The attributes get released when context is destroyed, so no memory release functionality to be added*/

}
}

/*Simple method which gets the string through constructor*/
Mail.java (.class to be stored in folder apache tomcat/webapps/Excercise/WEB-INF/classes/pack1/work/Controller )
package pack1.work.Controller;

public class Mail {
public String mail_id;
public Mail(String mail){
mail_id=mail;
}

}

/*Servlet to display the attribute set by Listener when context is initialized.*/
ContextListenerTester(.class to be stored in folder apache tomcat/webapps/Excercise/WEB-INF/classes/pack1/work/Controller )

package pack1.work.Controller;


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ContextListenerTester extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse res)throws IOException, ServletException{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
Mail mail = (Mail)getServletContext().getAttribute("admin");
pw.println("The admin id is " + mail.mail_id);
}
}

Wednesday, January 16, 2013

Cookie useage

Program to demonstrate data stored in cookies being shared across web-app.

1. Open Link:  http://localhost:8080/Excercise/view.html
2. Fill in user name and password.
3. Select the  items to shop.
4. 3rd page displays the uesr name and password(though unlikely in real world) stored from cookies and List of items to be shopped.

 web.xml(To be stored in folder called apache-tomcat/webapps/Excercise/WEB-INF in webapps):
<web-app ...>
<servlet>
<servlet-name>cookie1</servlet-name>
<servlet-class>pack1.work.Controller.NameStore</servlet-class>
</servlet>

<servlet>
<servlet-name>cookie2</servlet-name>
<servlet-class>pack1.work.Controller.ItemStore</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>cookie1</servlet-name>
<url-pattern>/Namedisplay</url-pattern>
</servlet-mapping>
    
<servlet-mapping>
<servlet-name>cookie2</servlet-name>
<url-pattern>/Itemdisplay</url-pattern>
</servlet-mapping>
</web-app>

view.html (To be stored in folder webapps/Excercise )


<html>
<body>

Enter user name and password for detail display of shopping List:

  <form method = "POST" action = "Namedisplay">
User name: <input name="username" type="text">
Password: <input name="pwd" type="password"></br>


<input value ="Submit" type="SUBMIT">

  </form>

</body>
</html>

NameStore,java( .class to be stored in folder apache-tomcat/webapps/Excercise/WEB-INF/classes/pack1/work/Controller )
/* File to store username and password in cookies*/

package pack1.work.Controller;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;


public class NameStore extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException{
response.setContentType("text/html");

String usrname =  request.getParameter("username");
String password =  request.getParameter("pwd");
HttpSession session = request.getSession();

session.setMaxInactiveInterval(20*60);
Cookie cookie1 = new Cookie("Name", usrname);
Cookie cookie2 = new Cookie("Cryptic", password);

response.addCookie(cookie1);
response.addCookie(cookie2);

cookie1.setMaxAge(20*60);
cookie2.setMaxAge(20*60);

RequestDispatcher view = request.getRequestDispatcher("ShopCart.jsp");
view.forward(request, response);
}

}

ShopCart.jsp((To be stored in folder apache-tomcat/webapps/webapps/Excercise ))
/*Jsp file that  takes you to other servlet*/
<html>
<body>
Welcome to Shopping World!!  Shop unlimited on following items!!</br>

Hi

<form method="Post" action="Itemdisplay">
<input type="checkbox" name="Shop" value = "Dress" >Dresses</br>
<input type="checkbox" name="Shop" value = "Acessories">Acessories</br>
<input type="checkbox" name = "Shop" value = "Sandals">Sandals</br>
<input type="checkbox" name = "Shop" value = "Electronics">Electronic Items</br>
<input type="checkbox" name = "Shop" value = "Vehicle">Vehicles</br>

<input type = "submit" value = "Items selected!!!">
</form>

</body>
</html>



ItemStore.java( .class to be stored in folder apache-tomcat/webapps/Excercise/WEB-INF/classes/pack1/work/Controller)

/*Program retrieves the username and password cookie.*/

package pack1.work.Controller;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ItemStore extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie cookies[] = request.getCookies();
String user="", password="";
for(int i=0; i<cookies.length; i++){

if(cookies[i].getName().equals("Name")){
user = cookies[i].getValue();

}

else if(cookies[i].getName().equals("Cryptic")){
password = cookies[i].getValue();
}

}

String[] options = request.getParameterValues("Shop");

out.println("</br>");
out.println("Hi, Your login id is: " + user + "Your password is : " + password);
out.println("</br> Above info is brought to u by COOKIES!!!");
out.println("</br> You want ");
for(int i=0; i<options.length; i++){
out.println(options[i] + " ");
}
out.println("from this site");


}
}