Monday, 20 January 2014

Delete duplicate numbers from the file




Program:


import java.io.*;
class FileWriterDemo1 
{
  public static void main(String[] args)throws IOException
  {
    BufferedReader br1=
     new BufferedReader(new FileReader("input.txt"));
    PrintWriter out=new PrintWriter("output.txt");
    String target=br1.readLine();
    while(target!=null)
    {
 boolean available=false;
 BufferedReader br2=
          new BufferedReader(new FileReader("output.txt"));
 String line=br2.readLine();
 while(line!=null)
 {
          if(target.equals(line))
   {
     available=true;
     break;
   }
     line=br2.readLine();
 }
 if(available==false)
 {
   out.println(target);
   out.flush();
 }
 target=br1.readLine();
     }
}
}

Thursday, 16 January 2014

Compress Jpeg Images Through JAVA

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;


/**
 * 
 * @author alekhya
 *
 */
public class CompressJpegImages {

 public static String inputFolder =
       "C:\\Users\\akondam\\Desktop\\images";
 public static String outputFolder = 
       "C:\\Users\\akondam\\Desktop\\CompressedFolderimages";
 public static void main(String[] args) {
  CompressJpegImages cji = new CompressJpegImages();
  cji.listFiles(inputFolder);
 }
  public void listFiles(String directoryName){
   File directory = new File(directoryName);
   //get all the files from a directory
   File[] fList = directory.listFiles();
   for (File file : fList){
   if (file.isFile()){
   compressImageFile(file);
   }
   }
 }
    public void compressImageFile(File file){
    try {
     File compressedImageFile 
      = new File(outputFolder+"//"+file.getName());
     InputStream is = new FileInputStream(file);
     OutputStream os = new FileOutputStream(compressedImageFile);
     float quality = 0.5f;
     // create a BufferedImage as the result of decoding the
     supplied InputStream
     BufferedImage image = ImageIO.read(is);
    // get all image writers for JPG format
    Iterator<ImageWriter> writers =
     ImageIO.getImageWritersByFormatName("jpg");
    if (!writers.hasNext())
 throw new IllegalStateException("No writers found");
 ImageWriter writer = (ImageWriter) writers.next();
 ImageOutputStream ios = ImageIO.createImageOutputStream(os);
 writer.setOutput(ios);
 ImageWriteParam param = writer.getDefaultWriteParam();
        // compress to a given quality
 param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
 param.setCompressionQuality(quality);
 // appends a complete image stream containing a 
        //single image and associated stream and image metadata 
       //and thumbnails to the output 
       writer.write(null, new IIOImage(image, null, null), param);
       // close all streams
       is.close();
       os.close();
       ios.close();
       writer.dispose();
     } catch (FileNotFoundException e) {
 e.printStackTrace();
     } catch (IOException e) {
 e.printStackTrace();
     }
 }

Wednesday, 8 January 2014

Increase heap size in JVM( Permgen space error in Tomcat).

To read JVM heap size. 
The maximum theoretical heap limit for the 32-bit JVM is 4G. Due to 
various additional constraints such as available swap, kernel address 
space usage, memory fragmentation, and VM overhead, in practice the 
limit can be much lower. On most modern 32-bit Windows systems the 
maximum heap size will range from 1.4G to 1.6G. On 32-bit Solaris 
kernels the address space is limited to 2G. On 64-bit operating systems 
running the 32-bit VM, the max heap size can be higher, approaching 4G 
on many Solaris systems.
 
public class GetHeapSize {
 public static void main(String[]args){
  
  //Get the jvm heap size.
  long heapSize = Runtime.getRuntime().totalMemory();
  
  //Print the jvm heap size.
  System.out.println("Heap Size = " + heapSize);
 }
}
 
 
Good url to gain knowledge on memory 
http://www.oracle.com/technetwork/java/hotspotfaq-138619.html#gc_heap_32bit 
 
Update the tomcat\bin\catalina.bat file.
SET JAVA_OPTS="-Dfile.encoding=UTF-8 -server -Xms512m -Xmx1024m 
-XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m 
-XX:MaxPermSize=256m -XX:+DisableExplicitGC”
  

Tuesday, 7 January 2014

Sample Onlinetest Project using Servlet and JSP

Online test consist of three screens
1. LoginPage.jsp
2. Exam.jsp
3. scoreDisplay.jsp

After successfull Login Questions will be displayed 5 questions atlast we can submit the exam.The scoreDisplay screen is shown with correct answers.

Database Screen shots:onlinetest
users
question

answer
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 >
  <welcome-file-list>
    <welcome-file>LoginPage.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>Sample</servlet-name>
    <servlet-class>com.DAO.LohinServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Sample</servlet-name>
    <url-pattern>/loginverify</url-pattern>
  </servlet-mapping>
   <servlet>
    <servlet-name>Sample1</servlet-name>
    <servlet-class>com.DAO.AnsServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Sample1</servlet-name>
    <url-pattern>/arrverify</url-pattern>
  </servlet-mapping>
</web-app>
 
LoginPage.jsp 
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <title>Login Page</title>
  <script type="text/javascript" src="js/jquery.min.js"></script>
  <script type="text/javascript"> 
  $(document).ready(function(){
 localStorage.clear();
 })
 </script>
</head>

<body bgcolor="#E6E6FF">
<h3>
<center>
<h2>Login</h2>
<form action="loginverify" method="get">
<br/> Username:<input type="text"  name="uname"/>
<br/>Password:<input type="password"  name="pswd"/>
<br/><input type="submit" value="submit" />
<br/><a href="register.jsp" >Register Here</a>
</form>
</center>
</h3>
</body>
</html>
 
LohinServlet.java 
package com.DAO;

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

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.Beans.Users;

public class LohinServlet extends HttpServlet {

/**
 * 
 */
 private static final long serialVersionUID = -6423051009614465001L;
   /**
   * Constructor of the object.
   */
   public LohinServlet() {
 super();
   }
   /**
   * Destruction of the servlet. <br>
   */
   public void destroy() {
 super.destroy(); // Just puts "destroy" string in log
 // Put your code here
   }
   /**
   * The doGet method of the servlet. <br>
   *
   * This method is called when a form has its tag value method equals to get.
   * 
   * @param request the request send by the client to the server
   * @param response the response send by the server to the client
   * @throws ServletException if an error occurred
   * @throws IOException if an error occurred
   */
   public void doGet(HttpServletRequest request, 
  HttpServletResponse response)
   throws ServletException, IOException {
   response.setContentType("text/html");  
         PrintWriter out = response.getWriter();  
  Users users=new Users();
  users.setUsername(request.getParameter("uname"));
  users.setPassword(request.getParameter("pswd"));
  Integer bvalue=0;
 try {
   bvalue = LoginDAO.validateLogin(users);
 } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
 }
 if(bvalue!=0){
  users.setUserId(bvalue);
  Integer uidVal=users.getUserId();
  HttpSession session=request.getSession();
  session.setAttribute("CurrentSessionUser", users);
  response.sendRedirect("Exam.jsp?i=0&uidVal="+uidVal); 
 }else{
   out.print("<center>");  
          out.print("Sorry UserName or Password Error!");  
   RequestDispatcher rd=
          request.getRequestDispatcher("/LoginPage.jsp");  
   rd.include(request, response);  
   //response.sendRedirect("LoginPage.jsp?");
 }
 }
 /**
  * Initialization of the servlet. <br>
  *
  * @throws ServletException if an error occurs
  */
 public void init() throws ServletException {
  // Put your code here
  System.out.println("In Inits");
 }

}


LoginDAO.java 

package com.DAO;

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

import com.Beans.Users;
import com.Connection.ConnectionProvider;


public class LoginDAO {

 public static Integer validateLogin(Users users) throws Exception{
  Connection con=ConnectionProvider.getConn();
  Boolean exist;
  int uid=0;
  try {
    java.sql.PreparedStatement ps=
     con.prepareStatement(
     "select * from Users where username=? and password=?");
    ps.setString(1,users.getUsername());
    ps.setString(2,users.getPassword());
    ResultSet rs=ps.executeQuery();
    while(rs.next()){
    uid=rs.getInt("USER_ID");
    }
    return uid;
  }catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   throw e;
  }
}
}
 
 Exam.jsp
<%@ page language="java"
  contentType="text/html; 
  charset=windows-1256" 
  pageEncoding="UTF-8"
  import="com.DAO.QuestionDAO" 
  import="com.Beans.Users" %>
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <title>Exam</title>
 <script type="text/javascript" src="js/jquery.min.js"></script>
 <script type="text/javascript"> 
 var myAns = new Array();
var ival="<%= request.getParameter ("i") %>";
var uidVal="<%= request.getParameter ("uidVal") %>";
$(document).ready(function(){

if(ival=="0")
   document.getElementById('butPrevious').disabled = true; 
else if(ival=="4")
  document.getElementById('butNext').disabled = true; 
if(ival>=0 && ival<5){
    var cell = document.getElementById(localStorage.getItem(ival));
    cell.style.background = "green";
 }
    var selectedOpt="selectedOpt";
    var val=localStorage.getItem(ival);
    document.getElementById(selectedOpt+val.charAt(3)).checked = true;
})

function openPrevoius()
 {
 if(ival>0){
   ival--;
   window.location.href = 
   "http://localhost:8400/OLTest/Exam.jsp?i="+ival+"&uidVal="+uidVal;
  }
 }
 function openNext()
 {
   if(ival<5){
   ival++;
   }
   if(ival!=null){
     if(ival<5)
     window.location.href = 
    "http://localhost:8400/OLTest/Exam.jsp?i="+ival+"&uidVal="+uidVal;
    }
}

function openSubmit(id)
{
   var theOpts = document.getElementsByName("selectedOpt");
   for(var i=0;i<theOpts.length;i++){
   if(theOpts[i].checked){
     theOpts[i].value;
     var cell = document.getElementById(id);
     cell.style.background = "green";
     if(ival=="0"){
       localStorage.clear();
     }
     localStorage.setItem(  ival,id );
     if(ival=="4"){
     for(var i=0;i<5;i++){
       myAns[i]=localStorage.getItem(i);
     }
  }
  }else{
     theOpts[i].value;
     var opt="opt";
     var cell = document.getElementById(opt+i);
     cell.style.background = "#E6E6FF";
  }
 }
}
function clickSubmit(){


var uidVal="<%= request.getParameter ("uidVal") %>";
var arr=new Array();

for(var i=0;i<5;i++){
arr[i]=localStorage.getItem(i);
}
    arr;
    var json = arr;
$.ajax({
            url:"arrverify",
            type:"POST",
            dataType:'json',
            data: {json:json,uid:uidVal},
            success: function(data){
             window.location.href = "scoreDisplay.jsp";
            } 


        });
  
}

</script>

</head>

<body bgcolor="#E6E6FF">
<center>
 
 <% Users currentUser =
 (Users)(session.getAttribute("CurrentSessionUser"));%> 
 <br/>Welcome <%= currentUser.getUsername() %>
 <%= currentUser.getUserId() %>

<form method="post" id="frm">
  <center>
  <table border="1" width="30%" cellpadding="5" id="tableId">
  <jsp:useBean id="Quest" class="com.Beans.Question" scope="application"/>
  <jsp:useBean id="QuestDAO" class="com.DAO.QuestionDAO" scope="application" />
  <jsp:useBean id="AnswerDAO" class="com.DAO.AnswerDAO" scope="application" />
   <% java.util.List<com.Beans.Question> list =  
   new java.util.ArrayList<com.Beans.Question>(); %>
   <%  int i= Integer.parseInt(request.getParameter("i"));
   if(i==0){
 list=QuestDAO.getQuestions();
 session.setAttribute("list",list);
   }else{
  list= (java.util.List<com.Beans.Question>)session.getAttribute("list");
    }
    %>
         
  <thead>
  <tr>
      <th id="ram"  ><%= request.getParameter("i") %></th>
      <th ><%=  list.get(i).getQuestion() %></th>
  </tr>
  </thead>
  <tbody>
  <tr>
      <td id="opt0" onclick="openSubmit('opt0')">
      <input type="radio" id="selectedOpt0" name="selectedOpt" > 
      <%=  list.get(i).getOpt1() %>
      </td>
      <td id="opt1" onclick="openSubmit('opt1')">
      <input type="radio" id="selectedOpt1" name="selectedOpt" > 
      <%=  list.get(i).getOpt2() %>
      </td>
   </tr>
   <tr>
      <td id="opt2" onclick="openSubmit('opt2')">
     <input type="radio" id="selectedOpt2" name="selectedOpt" > 
      <%=  list.get(i).getOpt3() %>
      </td>
      <td id="opt3" onclick="openSubmit('opt3')">
     <input type="radio" id="selectedOpt3" name="selectedOpt" > 
     <%=  list.get(i).getOpt4() %>
     </td>
   </tr>
   </tbody>
   </table>
   </center>
</form>
    <input type="button" value="Previous" name="Previous" 
          id="butPrevious" onclick="openPrevoius()" >
               &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <input type="button" value="Submit" name="Submit" 
         id="butSubmit" onclick="clickSubmit()" >
  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <input type="button" value="Next" id="butNext" name="Next" 
           onclick="openNext()" />
        
</center>

</body>
</html>
  
 
 
AnsServlet:
package com.DAO;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONException;
import org.json.JSONObject;

import com.Beans.ResultDisplay;

/**
 * Servlet implementation class AnsServlet
 */

public class AnsServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
 /**
  * @see HttpServlet#HttpServlet()
  */
  public AnsServlet() {
     super();
     // TODO Auto-generated constructor stub
  }
  /**
   * @see HttpServlet#doPost(HttpServletRequest request, 
     HttpServletResponse response)
   */
   protected void doPost(HttpServletRequest request, 
    HttpServletResponse response) throws ServletException,IOException{
 // TODO Auto-generated method stub
     PrintWriter out=response.getWriter();
     String uid=request.getParameter("uid");
     String[] answers = request.getParameterValues("json[]");
     List<ResultDisplay> lisResult=new ArrayList<ResultDisplay>();
     try {
         lisResult=AnswerDAO.insertAns(answers,Integer.parseInt(uid));
     }catch (Exception e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
     }
     if(lisResult.size()>1){
 HttpSession session=request.getSession();
 session.setAttribute("resultOfUser", lisResult);
     try {
 JSONObject jobj = new JSONObject();
 String urlToRedirect = "scoreDisplay.jsp";
 jobj.put("url",urlToRedirect);
 response.getWriter().write(jobj.toString());
     }catch (JSONException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
     }
     }else{
 out.print("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");  
        out.print("Sorry some error occured we will recover soon");  
 RequestDispatcher rd=request.getRequestDispatcher("/Exam.jsp");  
 rd.include(request, response);  
     }
     }
}
AnswerDAO.java 
package com.DAO; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.Beans.ResultDisplay; import com.Beans.Users; import com.Connection.ConnectionProvider; import com.mysql.jdbc.PreparedStatement; public class AnswerDAO { public static List<ResultDisplay> insertAns(String[] answers,int uid) throws Exception{ Connection con=ConnectionProvider.getConn(); String[] ans=new String[]{}; ans=answers; int result=0; String resultVal=""; List<ResultDisplay> lis=new ArrayList<ResultDisplay>(); try { for(int i=0;i<ans.length;i++){ String selectTableSQL = "SELECT "+ans[i]+" FROM question where QUESTION_ID=?"; java.sql.PreparedStatement preparedStatement1 = con.prepareStatement(selectTableSQL); preparedStatement1.setInt(1,(i+1)); ResultSet rs = preparedStatement1.executeQuery(); while (rs.next()) { resultVal = rs.getString(ans[i]); if(i==0){ String deleteTableSQL = "DELETE FROM answer where USER_ID=?"; java.sql.PreparedStatement preparedStatement2 = con.prepareStatement(deleteTableSQL); preparedStatement2.setInt(1,uid); int rs1 = preparedStatement2.executeUpdate(); } } String insertTableSQL = "INSERT INTO answer(ANSWER, QUESTION_ID, USER_ID) VALUES(?,?,?)"; java.sql.PreparedStatement preparedStatement = con.prepareStatement(insertTableSQL); preparedStatement.setString(1,resultVal); preparedStatement.setInt(2,(i+1)); preparedStatement.setInt(3,uid); result +=preparedStatement.executeUpdate(); System.out.println("Result"+result); if(result==5){ lis=AnswerDAO.result(uid); } } return lis; } catch (Exception e) { // TODO Auto-generated catch block throw e; } } public static List<ResultDisplay> result(int uid) throws Exception{ Connection con=ConnectionProvider.getConn(); List<ResultDisplay> resD=new ArrayList(); try { String qry= "select q.question,q.correctanswer,a.answer,a.user_id"+ "from question q,answer a where q.question_id=a.question_id and a.user_id=?"; java.sql.PreparedStatement preparedStatement=con.prepareStatement(qry); preparedStatement.setInt(1,uid); ResultSet rs = preparedStatement.executeQuery(); while(rs.next()){ ResultDisplay rd= new ResultDisplay(); rd.setQuestion(rs.getString("question")); rd.setCorrectanswer(rs.getString("correctanswer")); rd.setAnswer(rs.getString("answer")); rd.setUsers(rs.getInt("user_id")); resD.add(rd); } return resD; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); throw e; } } } 
 
 scoreDisplay.jsp
 
<%@page import="java.util.List"%>
<%@ page language="java"
  contentType="text/html; 
  charset=windows-1256" 
  pageEncoding="UTF-8"
  import="com.Beans.ResultDisplay" %>
<html>
<body bgcolor="#E6E6FF">
<center>
<% java.util.List<com.Beans.ResultDisplay> list = 
new java.util.ArrayList<com.Beans.ResultDisplay>(); %>
<%  list = (List<ResultDisplay>)(session.getAttribute("resultOfUser"));%> 
<table border="1" width="30%" cellpadding="5" id="tableId">
<thead>
   <tr>
   <th id="ram"  >Question</th>
   <th >Correct Answer</th>
   <th >Your Answer</th>
   </tr>
</thead>
<tbody>
  <tr>
  <td id="q0" ><%=  list.get(0).getQuestion() %></td>
  <td id="ca0" ><%=  list.get(0).getCorrectanswer()%></td>
  <td id="a0" ><%=  list.get(0).getAnswer() %></td>
  </tr>
  <tr>
  <td id="q1" ><%=  list.get(1).getQuestion() %></td>
  <td id="ca1" ><%=  list.get(1).getCorrectanswer() %></td>
  <td id="a1" ><%=  list.get(1).getAnswer() %></td>
  </tr>
  <tr>
  <td id="q2" ><%=  list.get(2).getQuestion()%></td>
  <td id="ca2" ><%=  list.get(2).getCorrectanswer() %></td>
  <td id="a2" ><%=  list.get(2).getAnswer()  %></td>
  </tr>
  <tr>
  <td id="q3" ><%=  list.get(3).getQuestion() %></td>
  <td id="ca3" ><%=  list.get(3).getCorrectanswer() %></td>
  <td id="a3" ><%=  list.get(3).getAnswer()  %></td>
  </tr>
  <tr>
  <td id="q4" ><%=  list.get(4).getQuestion() %></td>
  <td id="ca4" ><%=  list.get(4).getCorrectanswer() %></td>
  <td id="a4" ><%=  list.get(4).getAnswer()  %></td>
  </tr>
 </tbody>
</table>
</center>
</body>
</html>