Saturday 19 October 2013

Tomcat connection pooling

->This Tomcat connection pool Depends on Tomcat web server

->First configure database details and connection pool details in the context.xml file in META-INF folder of our web project

->Use ojdbc14.jar

Context.xml

<?xml version="1.0" encoding="UTF-8"?>
<Context path="/Client" docBase="ClientModule" crossContext="true" reloadable="false" debug="1">
    <Resource name="jdbcResource" auth="Container" type="javax.sql.DataSource"
       username="dbuser"
       password="dbpassword"
        driverClassName="oracle.jdbc.driver.OracleDriver"
        url="jdbc:oracle:thin:@192.168.0.178:1521:orcl"
        initialSize="25"
        maxActive="25"
        maxIdle="25"
        minIdle="10"
        maxWait="5000"
        removeAbandonedTimeout="50"
        removeAbandoned="true"
        testOnBorrow="true">
   </Resource>
</Context>

username:database username

password:database password

driverClassName:We are using oracle database so 
oracle.jdbc.driver.OracleDriver class

url: database url and database name

initialSize:That means at the time of pool creating it will create 25(we can give any number) connections,after that automatically pool creates new connections based on request.
maxActive:That means at the same time 25(we can give any number) connections only in active mode,so at the same time 26th person can’t get new connection from pool.

maxIdle:Idle means not used objects available in the pool,maximum the pool can have 25(we can give any number) idle objects

minIdle:Any time pool will have minimum of 10 idle objects.

maxWait:We are ready to getting new connection from pool,but pool don’t have connections,so we will wait for 5000 milliseconds(5 seconds),After that time also pool don’t have connections to give us then only displaying error like  org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot get a connection, pool error Timeout waiting for idle object.

removeAbandonedTimeout:50(we can give any number)means when the pool give the connection to us,and we didn’t return back the connection to pool,it will wait for 50 seconds for that connection,After 50 seconds this object is eligible for eviction.

romoveAbondoned: true means After removeAbondonedTime(50 seconds) pool forcefully get that object from us(from java program),If our program execution is not completed also pool will close the connection and get the connection.

testOnBorrow:true means at the time of getting connection from pool it will validate that connection.If validation fails,that connection will remove from the pool and create new connection.

testOnReturn:true means at the time of returning the connection to pool ,it will check that connection,
If validation fails,that connection will not return to pool.

minEvictableIdleTimeMillis:(int) The minimum amount of time an object may sit idle in the pool before it is eligible for eviction. The default value is 60000(60 seconds).This property uses pool internally for idle objects.

timeBetweenEvictionRunsMillis:(int) The number of milliseconds to sleep between runs of the idle connection validation/cleaner thread. This value should not be set under 1 second. It dictates how often we check for idle, abandoned connections, and how often we validate idle connections. The default value is 5000 (5 seconds).

->Create Web based Application

ConnectionPoolClass.java

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.sql.DataSource;


public class ConnectionPoolClass {
      
       public static InitialContext initialContext=null;
       public static DataSource datasource=null;
       Connection con=null;
      
        static {
                try{
                    initialContext = new InitialContext();
                    datasource = (DataSource)initialContext.lookup("java:/comp/env/jdbcResource");
                   
                }catch(Exception e)
                {
                e.printStackTrace();
                }
        }
        
        public boolean getConnection() {
               
                     try {
                           con=(Connection)datasource.getConnection();
                           System.out.println("connection is:"+con);
                     } catch (SQLException e) {
                           e.printStackTrace();
                     }
                      
               return true;
        }
        
        public void closeConnection() {
               try {
                     con.close();
              } catch (SQLException e) {
                     e.printStackTrace();
              }
        }
}

MyServlet.java

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyServlet extends HttpServlet {
      
       public void doGet(HttpServletRequest request,HttpServletResponse response) {
              PrintWriter out=null;
              try {
                     out=response.getWriter();
              } catch (IOException e) {
                     e.printStackTrace();
              }
              ConnectionPoolClass cp=new ConnectionPoolClass();
             
              cp.getConnection();
              cp.closeConnection();
      
       }
}


Web.xml
<servlet>
       <servlet-name>xxx</servlet-name>
       <servlet-class>com.iton.MyServlet</servlet-class>
  </servlet>
 
  <servlet-mapping>
       <servlet-name>xxx</servlet-name>
       <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app>


->This program only getting the connection from connection pool,If we get the connection remaining code is normal like perfoming CURD operations to create,update,retrieve,delete with database.

Maven 3rd party jar integration/Adding our own jar into maven and create own artifactId, groupId

Maven Command:

mvn install:install-file

-Dfile="C:\Ramakrishna\softwares\mysql-connector-java-5.1.6.jar"

-DgroupId=com.mysql

-DartifactId=connector

-Dversion=2.0              

-Dpackaging=jar

After run this command ,we can use mysql-connector-java-5.1.6.jar as maven dependency

<dependency>
<groupId>com.mysql </groupId>
<artifactId>connector</artifactId>
<version>2.0</version>

</dependency>

Sample:

Saturday 12 October 2013

File Download Using Servlets

HTML Code:

<html>
<body>
<form name="fileUploadForm" method="POST" action="sdd2">
<input type="submit" value="Download"/>
</form>
</body>

</html>

Web.xml:

<web-app>
 <servlet>
  <servlet-name>sdd2</servlet-name>
  <servlet-class>com.iton.DownloadServlet</servlet-class>

  </servlet>

<servlet-mapping>
  <servlet-name>sdd2</servlet-name>
  <url-pattern>/sdd2</url-pattern>
  </servlet-mapping>

</web-app>

Servlet Code:

import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadServlet extends HttpServlet
{
  public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    response.setContentType("text/html");
    
    PrintWriter out = response.getWriter();
    
    String filename = "Page1.jpg";
    
     //Give the path where the files are available in server
    //We can give our project folder in the Server
    String filepath = "C:/myfiles/";
    
    response.setContentType("APPLICATION/OCTET-STREAM");
    
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

    FileInputStream fis = new FileInputStream(filepath + filename);
    
    int i;
    
    while ((i = fis.read()) != -1)
    {
      out.write(i);
    }
    fis.close();
    out.close();
  }

}

Output:




File Upload Using Servlets

Here We are using orelly related jar(cos.jar) for uploading files

Maven pom.xml for cos.jar

<dependency>
<groupId>servlets.com</groupId>
<artifactId>cos</artifactId>
<version>05Nov2002</version>
</dependency>

Link for Direct jar Download:

http://www.servlets.com/cos/


Html Code:

<html>
<body>
<form name="fileUploadForm" method="POST" action="fu3" enctype="multipart/form-data">
<input type="file" name="fileUpload"/>
<input type="submit" value="Upload"/>
</form>
</body>
</html>

Web.xml:

<web-app>
<servlet>
  <servlet-name>fu3</servlet-name>
  <servlet-class>com.iton.FileUploadUsingOreilly</servlet-class>
  </servlet>

<servlet-mapping>
  <servlet-name>fu3</servlet-name>
  <url-pattern>/fu3</url-pattern>
  </servlet-mapping>

</web-app>

Servlet Code:

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oreilly.servlet.MultipartRequest;

public class FileUploadUsingOreilly extends HttpServlet {

public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException {

PrintWriter out=response.getWriter();

//We have to create the folder myfiles in c driver
MultipartRequest m=new MultipartRequest(request,"c:/myfiles");

out.write("Successfully Uploaded");
}
}

Output:


Thursday 10 October 2013

Write File Using FileOutputStream with new Jdk 1.7 try block feature

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

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

File file = new File("d:/java4.txt");
String content = "This is the text content";

//New jdk 1.7 feature
try (FileOutputStream fop = new FileOutputStream(file)) {

// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}

// Get the content in bytes
byte[] contentInBytes = content.getBytes();

fop.write(contentInBytes);
fop.flush();
fop.close();

System.out.println("Done");

} catch (IOException e) {
e.printStackTrace();
}
}
}

Write File Using FileOutputStream

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

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

FileOutputStream fop = null;
File file;
String content = "This is the text content";

try {

file = new File("d:/java3.txt");
fop = new FileOutputStream(file);

// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}

// Get the content in bytes
byte[] contentInBytes = content.getBytes();

fop.write(contentInBytes);
fop.flush();
fop.close();

System.out.println("Done");

} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fop != null) {
fop.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Write File Using FileWriter

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class WriteFileEx {

public static void main(String args[]) {

String data="THIS IS THE DATA TO WRITE IN THE FILE";

File file = new File("d:/java2.txt");
       FileWriter fr = null;
       try {
           fr = new FileWriter(file);
           fr.write(data);
       } catch (IOException e) {
           e.printStackTrace();
       }finally{
           try {
               fr.close();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
}

}

Write File Using Files Class

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

//Files class is available from 1.7
public class UsingFilesClass {

public static void main(String args[]) {

String data = "SOME DATA";
try {
           Files.write(Paths.get("d:/java1.txt"), data.getBytes());
           System.out.println("Done");
       } catch (IOException e) {
           e.printStackTrace();
       }
}
}

Write File Using BufferedWriter,FileWriter

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

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

String content = "This is the content to write into file";

File file = new File("d:/java.txt");

// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}

FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();

System.out.println("Done");

} catch (IOException e) {
e.printStackTrace();
}
}
}

How to make a button look like a Link

<html>
<head>
<title>Button Looks Like a Link</title>

<style type="text/css">
button {
background: none;
border: none;
display: inline;
font: inherit;
margin: 0;
padding: 0;
outline: none;
outline-offset: 0;
/* Additional styles to look like a link */
color: #4B0082;
cursor: pointer;
text-decoration: underline;
}
</style>

<script src="jquery.js"></script>
<script>
$(document).ready(function() {
alert("JQuery Loaded");
$("#ButtonId").click(function() {
alert("k fine");
});
$("#ButtonId").mouseup(function() {
$(this).css("color","#4B0082");
});
$("#ButtonId").mousedown(function() {
$(this).css("color","red");

});
});
</script>
</head>

<body>
<button id="ButtonId">Button</button></b>
<a href="#">Link</a>
</body>

</html>


Monday 7 October 2013

Read File Using InputStreamReader,FileInputStream



import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

public class InputStreamReaderExample {


public static void main(String[] args) {

InputStream inputStream=null;
Reader reader=null;
try {
inputStream = new FileInputStream("d:/ram.txt");

reader = new InputStreamReader(inputStream);

int data = reader.read();

while(data != -1){
   char out = (char) data;
   System.out.print(out);
   data = reader.read();
}

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Read File Using FileInputStream

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class ReadFileExample {

public static void main(String[] args) {

File file = new File("d:/ram.txt");
FileInputStream fis = null;

try {
fis = new FileInputStream(file);
 
  int content;
while ((content = fis.read()) != -1) {
// convert to char and display it
System.out.print((char) content);
}

} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}

Read File Using FileReader

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileEx {

public static void main(String[] args) {

File f = new File("d:/ram.txt");

FileReader fr = null;

try {
fr = new FileReader(f);

for (int val = fr.read(); val!= -1;val=fr.read()) {
System.out.print((char) val);
}

} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fr != null)
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}

Read File Using Files Class,BufferedReader



import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class BufferedReaderWithFilesExample {

public static void main(String args[]) {

Charset cs= StandardCharsets.UTF_8;
Path path = Paths.get("d:/ram.txt");
        BufferedReader br=null;
try {
br = Files.newBufferedReader(path,cs);
String line;
       while((line = br.readLine()) != null){
           //process the line
           System.out.println(line);
       }
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}

}

Read File Using FileReader,BufferedReader

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReaderExample {

public static void main(String[] args) {

BufferedReader br = null;

try {

String s;
br = new BufferedReader(new FileReader("d:/ram.txt"));

while ((s = br.readLine()) != null) {
System.out.println(s);
}

} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}

}
}