Tuesday, April 19, 2016

Servlet example to perform Edit, Add operation on File

Requirement :- User has a course and can add course in it dependend on other. User can edit also the same course. Text file can have commented code like starting with # in the text file, So neglect such tile
Following are the servlet code
1:- ReadTextFileServlet
package com.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Vector;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ReadTextFileServlet extends HttpServlet {
//Vector av = new Vector();
HtmlUtils hu = new HtmlUtils();
PrintWriter out;
ServletContext context;
String filename = "/WEB-INF/Course1.txt";
/* protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
// We are going to read a file called configuration.properties. This
// file is placed under the WEB-INF directory.
String filename = "/WEB-INF/Course.txt";
ServletContext context = getServletContext();
// First get the file InputStream using ServletContext.getResourceAsStream()
// method.
InputStream is = context.getResourceAsStream(filename);
if (is != null) {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);
PrintWriter writer = response.getWriter();
String text;
// We read the file line by line and later will be displayed on the
// browser page.
while ((text = reader.readLine()) != null) {
writer.println(text + "");
}
}
}*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
printTable(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
printTable(request, response);
}
public void printTable(HttpServletRequest request,
HttpServletResponse response) throws IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
Vector av = new Vector();
out.print(hu.createHtmlHeader("Print Table"));
out.print(hu.getTableHead("center", 1));
out.print(hu.getTH("center", "Code"));
out.print(hu.getTH("center", "Title"));
out.print(hu.getTH("center", "Prerequisites"));
out.print(hu.getTH("center", "Operation"));
ServletContext context = getServletContext();
InputStream is = context.getResourceAsStream(filename);
if (is != null) {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);
//PrintWriter writer = response.getWriter();
String text;
while ((text = reader.readLine()) != null) {
if(text.length() > 0 && text.trim().indexOf('#') != 0) {
//writer.println(text + "");
String[] sArray = text.split(",",0);
if(sArray.length==1)
{
String parameter = "";
for(int i=0;iav.addElement(sArray[0]);
parameter = sArray[0];
}
av.addElement("");
av.addElement("");
av.addElement("Edit");
}else if (sArray.length==2)
{
String parameter1 = "";
for(int i=0;iav.addElement(sArray[i]);
parameter1 = parameter1 + "-" + sArray[i];
}
av.addElement("");
av.addElement("Edit");
}else
{
String parameter2 = "";
for(int i=0;iav.addElement(sArray[i]);
parameter2 = parameter2 + "-" +sArray[i];
}
av.addElement("Edit");
}
}
}
}
out.print(hu.getTableContents("center", av, 4));
out.print(hu.getTR());
out.print(hu.getTD());
out.println("Add Course");
out.print(hu.getClosedTD());
out.print(hu.getClosedTR());
out.print(hu.getHtmlFooter());

}

class HtmlUtils {
public String createHtmlHeader(String title) {
String htmlHeader = null;
htmlHeader = " " + title + " ";
return htmlHeader;
}
public String getHtmlFooter() {
String htmlFooter = "
";
return htmlFooter;
}
public String getHead(int level, String heading) {
return " " + heading + "";
}
public String getTableHead(String align, int border) {
String tableHeader = null;
tableHeader = "";
return tableHeader;
}
public String getTR(String align) {
String TRCell = null;
TRCell = " ";
return TRCell;
}
public String getTR() {
String TRCell = null;
TRCell = " ";
return TRCell;
}
public String getTD(String align, String value) {
String TDCell = null;
TDCell = "

" + value + "
";
return TDCell;
}
public String getTD() {
String TDCell = null;
TDCell = "

";
return TDCell;
}
public String getTD(int width) {
String TDCell = null;
TDCell = "

";
return TDCell;
}
public String getTH(String align, String value) {
String THCell = null;
THCell = "

" + value + "
";
return THCell;
}
public String getTableContents(String align, Vector values, int elementCounter) throws IOException {
StringWriter Cells = new StringWriter();
String contents = new String();
int vsize = values.size();
Cells.write(" ");
for (int i = 0; i < vsize; i++) {
String value = values.elementAt(i).toString();
if (i != 0) {
if (i >= elementCounter) {
if (i % elementCounter == 0) {
Cells.write("
\n\n ");
}
}
}
Cells.write("
" + value + "
\n");
}
Cells.write("
");
contents = Cells.toString();
Cells.flush();
Cells.close();
return contents;
}
public String getClosedTR() {
String TRCell = null;
TRCell = "
";
return TRCell;
}
public String getClosedTD() {
String TDCell = null;
TDCell = "
";
return TDCell;
}
public String getBR(int lines) {
StringWriter lineBR = new StringWriter();
String lineBRs = new String();
for (int i = 0; i <= lines; i++) {
lineBR.write("
\n");
}
lineBRs = lineBR.toString();
return lineBRs;
}
public String getLI(String item) {
String li = new String("


  • ");
    li += item;
    return li;
  • }
    }
    }

    2:- AddCourseTextFileServlet
    package com.test;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.util.Vector;
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    public class AddCourseTextFileServlet extends HttpServlet {
    /**
    *
    */
    private static final long serialVersionUID = 1L;
    Vector av = new Vector();
    ServletContext context;
    String filename = "/WEB-INF/Course1.txt";
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    context = getServletContext();
    printTable(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    //printTable(request, response);
    String finalCheckBox="";
    PrintWriter out = response.getWriter();
    String button1Click = request.getParameter("Submit");
    System.out.println("button1Click"+button1Click);
    File outputFile = new File(getServletContext().getRealPath("/WEB-INF/")
    + "/Course1.txt");
    FileWriter fout = new FileWriter(outputFile,true);

    try {
    InputStream is = context.getResourceAsStream(filename);
    if (is != null) {
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader reader = new BufferedReader(isr);

    String text;
    int k=0;
    while ((text = reader.readLine()) != null) {
    if(text.length() > 0 && text.trim().indexOf('#') != 0) {
    k = k +1 ;
    String[] sArray = text.split(",",2);
    String [] checkboxNamesList = new String[sArray.length];

    for(int i=0;i{
    checkboxNamesList= request.getParameterValues(sArray[i]);
    if(null != checkboxNamesList)
    {
    finalCheckBox = finalCheckBox + sArray[i].toString() + " ";
    }
    else
    {
    finalCheckBox = finalCheckBox;
    }

    }
    }
    }
    System.out.println("Value of record is:"+k);
    }
    } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    String finalString = request.getParameter("Code") + "," + request.getParameter("Title") + "," + finalCheckBox;
    fout.write("\n");
    fout.write(finalString);
    fout.close();
    RequestDispatcher rd = request.getRequestDispatcher("readTextFileServlet");
    rd.forward(request,response);

    }

    public void printTable(HttpServletRequest request,
    HttpServletResponse response) throws IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("");
    out.println("");
    out.println(" Add Course ");
    out.println("");
    out.println("");
    out.println("
    ");
    out.println("");
    out.println("
    Code:
    ");
    out.println("
    ");
    out.println(" ");
    out.println("
    Title:
    ");
    out.println("
    ");
    out.println(" ");
    out.println("
    Prerequisite(s):
    ");
    try {
    InputStream is = context.getResourceAsStream(filename);
    if (is != null) {
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader reader = new BufferedReader(isr);
    String text;
    int k=0;
    while ((text = reader.readLine()) != null) {
    if(text.length() > 0 && text.trim().indexOf('#') != 0) {
    //writer.println(text + "");
    k = k +1 ;
    String[] sArray = text.split(",",2);
    out.print("
    ");
    for(int i=0;i{
    out.print("");
    out.print(" ");
    //out.print(" ");


    out.print("
    ");
    out.print("
    ");
    out.println("
    ");
    out.print(sArray[i].toString());
    out.print("
    ");
    }
    out.print("

    ");

    }
    }
    System.out.println("Value of record is:"+k);
    }
    out.println("


    ");
    out.println("
    ");
    } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    out.println("
    ");
    out.println("
    ");

    }
    }

    3:- EditCourseTextFileServlet
    package com.test;
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.util.Vector;
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    public class EditCourseTextFileServlet extends HttpServlet {
    /**
    *
    */
    private static final long serialVersionUID = 1L;
    Vector av = new Vector();
    ServletContext context;
    String filename = "/WEB-INF/Course1.txt";
    String sUrlParam="";

    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    context = getServletContext();
    printTable(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    //printTable(request, response); //To Lead the table as per the data available from URL
    request.setAttribute("param",sUrlParam);
    RequestDispatcher rd = request.getRequestDispatcher("editSaveCourseTextFileServlet");
    rd.forward(request,response);
    }

    public void printTable(HttpServletRequest request,
    HttpServletResponse response) throws IOException {
    response.setContentType("text/html");
    sUrlParam = request.getParameter("param");
    PrintWriter out = response.getWriter();
    out.println("");
    out.println("");
    out.println(" Edit Course ");
    out.println("");
    out.println("");
    out.println("
    ");
    out.println("");
    String[] urlArray = sUrlParam.split("-",0);
    //for(int i=0;iif(urlArray.length > 0)
    {
    //System.out.println(urlArray[i]);
    if((urlArray.length == 2 || urlArray.length == 3) && urlArray[0] != null)
    {
    out.println("

    Code:
    ");
    out.println("
    ");
    out.println(" ");
    }
    if((urlArray.length == 2 || urlArray.length == 3) && urlArray[1] != null)
    {
    out.println(" Title:
    ");
    String textValue = urlArray[1].trim();//.toString().replaceAll(" ", " ");
    out.println("
    ");
    out.println(" ");
    }
    if(urlArray.length == 3 && urlArray[2]!= null)
    {
    //Showing all Check Box
    InputStream is = context.getResourceAsStream(filename);
    if (is != null) {
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader reader = new BufferedReader(isr);
    String text;
    out.println("

    Prerequisite(s):
    ");
    out.print("");
    String checkBoxString = urlArray[2].trim().toString();
    String[] sArray1 = checkBoxString.split(" ",0);
    out.print("
    ");
    while ((text = reader.readLine()) != null) {
    if(text.length() > 0 && text.trim().indexOf('#') != 0) {
    //writer.println(text + "");
    String[] sArray = text.split(",",2);
    for(int i=0;i{
    out.print(" ");
    //cheking if the check box need to clicked start[
    boolean flag = false;
    for(int m=0;mif(sArray[i].toString().equals(sArray1[m].toString()))
    {
    out.println("

    ");
    out.print(sArray[i].toString());
    flag = true;
    }
    }
    //cheking if the check box need to clicked end]
    if(!flag)
    {
    out.println("
    ");
    out.print(sArray[i].toString());
    flag= false;

    }
    out.print("
    ");
    out.print("");
    }
    }
    }
    out.print("");
    out.print("");
    }
    }
    else
    {
    try {
    InputStream is = context.getResourceAsStream(filename);
    if (is != null) {
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader reader = new BufferedReader(isr);
    String text;
    int k=0;
    out.println("

    Prerequisite(s):
    ");
    while ((text = reader.readLine()) != null) {
    if(text.length() > 0 && text.trim().indexOf('#') != 0) {
    //writer.println(text + "");
    k = k +1 ;
    String[] sArray = text.split(",",2);
    out.print("
    ");
    for(int i=0;i{
    out.print("");
    out.print(" ");
    //out.print(" ");


    out.print("
    ");
    out.print("
    ");
    out.println("
    ");
    out.print(sArray[i].toString());
    out.print("
    ");
    }
    out.print("

    ");
    }
    }
    out.print("
    ");
    System.out.println("Value of record is:"+k);
    }
    } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    out.println("


    ");
    out.println("
    ");
    out.println("");
    out.println("
    ");
    }
    }
    }
    4:- EditSaveCourseTextFileServlet
    package com.test;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.util.Vector;
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    public class EditSaveCourseTextFileServlet extends HttpServlet {
    /**
    *
    */
    private static final long serialVersionUID = 1L;
    Vector av = new Vector();
    ServletContext context;
    String filename = "/WEB-INF/Course1.txt";
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    context = getServletContext();
    }

    private void updateLine(String toUpdate, String updated) throws IOException {
    InputStream is = context.getResourceAsStream(filename);
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader file = new BufferedReader(isr);
    String my_new_str = toUpdate.replaceAll("-", ",");
    String line;
    String input = "";
    while ((line = file.readLine()) != null)
    input += line + "\n";
    input = input.replace(my_new_str, updated);
    File outputFile = new File(getServletContext().getRealPath("/WEB-INF/")
    + "/Course1.txt");
    //FileWriter fout = new FileWriter(outputFile,true);
    FileOutputStream os = new FileOutputStream(outputFile);
    os.write(input.getBytes());
    file.close();
    os.close();
    }

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

    String sOldValue = ""+request.getAttribute("param");

    //printTable(request, response);
    String finalCheckBox="";
    PrintWriter out = response.getWriter();
    String button1Click = request.getParameter("Submit");
    System.out.println("button1Click"+button1Click);
    File outputFile = new File(getServletContext().getRealPath("/WEB-INF/")
    + "/Course1.txt");
    FileWriter fout = new FileWriter(outputFile,true);

    try {
    context = getServletContext();
    InputStream is = context.getResourceAsStream(filename);
    if (is != null) {
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader reader = new BufferedReader(isr);

    String text;
    int k=0;
    while ((text = reader.readLine()) != null) {
    if(text.length() > 0 && text.trim().indexOf('#') != 0) {
    k = k +1 ;
    String[] sArray = text.split(",",2);
    String [] checkboxNamesList = new String[sArray.length];

    for(int i=0;i{
    checkboxNamesList= request.getParameterValues(sArray[i]);
    if(null != checkboxNamesList)
    {
    finalCheckBox = finalCheckBox + sArray[i].toString() + " ";
    }
    else
    {
    finalCheckBox = finalCheckBox;
    }

    }
    }
    }
    System.out.println("Value of record is:"+k);
    }
    } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    String finalString = request.getParameter("Code") + "," + request.getParameter("Title") + "," + finalCheckBox;
    this.updateLine(sOldValue, finalString);
    RequestDispatcher rd = request.getRequestDispatcher("readTextFileServlet");
    rd.forward(request,response);
    }
    }

    5- web.xml


       



    6:- Course1.txt
    # This is commented line no need to read it

    Siddhu120,Comment 1
    Siddhu122,Comment 2
    Siddhu201,Comment 3
    Siddhu202,Comment 4,Siddhu120 Siddhu201
    Siddhu203,Comment 6,Siddhu202
    Siddhu320,Comment ,Siddhu120 Siddhu122 Siddhu203




    Image_2

    Image_3

    Image_4

    No comments: