Tuesday, October 20, 2015

DYNAMIC JDBC SELECT QUERY CODE



JAVA JDBC CODE THAT ACCEPTS ANY KIND OF SELECT QUERY WITH DIFFERENT ROWS AND COLUMN

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class SampleApp {
    public static void main(String[] args) throws ParseException, ClassNotFoundException, SQLException {
       Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost/SampleFileDb","root","root");
            Statement stm=con.createStatement();
           
            ResultSet rs=stm.executeQuery("select * from datas");
            ResultSetMetaData rsmd=rs.getMetaData();
            int colcount=rsmd.getColumnCount();
            System.out.println("columns: "+colcount); 
            for(int i=1;i<=colcount;i++)
            {
System.out.println("Column Name of "+i+" column: "+rsmd.getColumnName(i)); 
System.out.println("Column Type Name of "+i+" column: "+rsmd.getColumnTypeName(i));
            }
            int i=0;
            List<String> ls=new ArrayList<>();
            while(rs.next())
            {
                for(int y=1;y<=colcount;y++)
                {
                
                ls.add(rs.getString(y));
                   
               
                }
                System.out.println(ls);
                ls.clear();
                 
               
            }
          
           
       
    }
   

}

NEW LINE FILE CODING IN JAVA USING BUFFERED WRITER

DATABASE TO FILE WITH NEWLINE IN JAVA..


public class FileHandling {

    public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException {
           ArrayList<String> dataid = new ArrayList<String>(
    Arrays.asList("1","2","3","4","5"));
            FileStore(dataid,"File1","SampleFileDb","datas","DYNAMIC FILE HANDLER","id");
       
    }
     public static void FileStore(List<String> dataid,String filename,String databasename,String tablename,String title,String colidname) throws ClassNotFoundException, SQLException, FileNotFoundException, IOException
   {
       java.util.Date d=new java.util.Date();
         String time=d.toString();
         DateFormat dateFormat = new SimpleDateFormat("HH-mm-ss");
                 File fout = new File(filename+".doc");
                FileOutputStream fos = new FileOutputStream(fout);

                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
       
        String line="****************************************************************";
        bw.newLine();
        bw.write(title);
        bw.newLine();
        bw.write(line);
        bw.newLine();
         bw.write(time);
         bw.newLine();
         bw.write(line);
         bw.newLine();
        for(int i=0;i<dataid.size();i++)
        {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost/"+databasename+"","root","root");
            Statement stm=con.createStatement();
           ResultSet rs=stm.executeQuery("select * from "+tablename+" where "+colidname+"='"+dataid.get(i)+"'");
           
               bw.newLine();
             while(rs.next())
            {
                String data1=rs.getString(1);
              
             
               
                String data2=rs.getString(2);
               
                String data3=rs.getString(3);
                String data4=rs.getString(4);
               
                bw.write(data1+"__"+data2+"__"+data3+"__"+data4);
               bw.newLine();
               
             
               
            }
            
        }
     
         bw.write(line);
         bw.newLine();
        bw.newLine();
        bw.write(line);
         bw.close();
      

   }

TRANSFER FILE VIA LAN THROUGH JAVA SOCKET PROGRAMMING

FILE TRANSFER VIA LAN NETWORK.. SOCKET PROGRAMMING IN JAVA


CLIENT.JAVA

import java.net.*;
 import java.io.*;
 public class Client { public static void main (String [] args ) throws IOException
{
int filesize=1022386;
 int bytesRead;
int currentTot = 0;
Socket socket = new Socket("127.0.0.1",15123);
 byte [] bytearray = new byte [filesize];
 InputStream is = socket.getInputStream();
 FileOutputStream fos = new FileOutputStream("copy.doc");
 BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(bytearray,0,bytearray.length);
 currentTot = bytesRead;
do { bytesRead = is.read(bytearray, currentTot, (bytearray.length-currentTot));
if(bytesRead >= 0) currentTot += bytesRead;
}
 while(bytesRead > -1);
bos.write(bytearray, 0 , currentTot); bos.flush(); bos.close();
 socket.close();
}

}

SERVER.JAVA

import java.net.*;
 import java.io.*;
 public class Server
{
public static void main (String [] args ) throws IOException
{
ServerSocket serverSocket = new ServerSocket(15123);
 Socket socket = serverSocket.accept();
 System.out.println("Accepted connection : " + socket);
 File transferFile = new File ("Document.doc");
 byte [] bytearray = new byte [(int)transferFile.length()];
 FileInputStream fin = new FileInputStream(transferFile);
 BufferedInputStream bin = new BufferedInputStream(fin);
bin.read(bytearray,0,bytearray.length); OutputStream os = socket.getOutputStream();
 System.out.println("Sending Files...");
 os.write(bytearray,0,bytearray.length);
os.flush();
 socket.close();
System.out.println("File transfer complete");

}
 }

Tuesday, October 13, 2015

EXCEPTION HANDLING BY USING PAGE DIRECTIVE IN JSP


REFERENCE JSP ERROR TAG

<%@page errorPage="error.jsp" %>

ERROR PAGE IN JSP BY USING EXCEPTIO IMPLICIT OBJECT

error.jsp

  <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP ERROR</title>
    </head>
    <body>
        <h1>ERRORS</h1>
       
        <%@page isErrorPage="true" %>  <%-- MAKING JSP INTO ERROR PAGE --%>
       
        <h1><FONT COLOR="RED"<B><%= exception %></B> </FONT></</h1>
           
    </body>

</html>

USEBEAN IN JSP

JSP USEBEAN
<body>
        <jsp:useBean id="object" class="com.pack.maths.expression"/>
            <%
                int value = object.cube(5);
                out.print(value);
            %>
           
    </body>

Expression.java
public class expression {

    public int cube(int n) {
        return n * n * n;
    }

}


DATASOURCE SQL DATABASE IN JSP

WEB DATABASE USING DATSOURCE IN JSP

<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%@page import="javax.sql.DataSource"%>
<%@page import="javax.naming.InitialContext"%>
<%@page import="javax.naming.Context"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <%
          int  sno = 0;
          String name = request.getParameter("uname");
          String address = request.getParameter("uaddress");
       
          Context ctx = new InitialContext(); //CONTEXT CREATION
          DataSource ds = (DataSource)ctx.lookup("jdbc/myData"); //JNDI name
          Connection con = ds.getConnection();
          Statement st = con.createStatement();
          st.executeUpdate("insert into t1 values('"+sno+"','"+name+"', '"+address+"')");
          out.print("INSERTED SUCCESSFULLY");
        %>
    </body>
</html>

COOKIES IN JSP

SIMPLE COOKIES CREATION AND READING COOKIES

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <%
           
         
            Cookie cookie = null;
            String name = request.getParameter("uname");
       
            cookie = new Cookie("user", name);//creating cookie
            cookie.setMaxAge(60*60*24);
            response.addCookie(cookie);
            Cookie cook[]=request.getCookies();
            for(int i=0;i<cook.length;i++)  //reading cookies..
            {
                cookie=cook[i];
                out.println("COOKIE NAME.."+cookie.getName()+"</br>");
                out.println("COOKIE VALUE.."+cookie.getValue()+"</br>");
            }
            out.print(cookie);
            %>
    </body>
</html>

TABLE CREATION WITH COLSPAN AND ROWS SPAN IN PDF USING ITEXT


TABLE CREATION WITH COLSSPAN AND ROWS SPAN IN JAVA


import com.itextpdf.text.BadElementException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.draw.DottedLineSeparator;
import com.itextpdf.text.pdf.draw.LineSeparator;
import com.itextpdf.text.pdf.draw.VerticalPositionMark;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;


public class PdfGen {


    public static void main(String[] args) throws BadElementException, IOException, ParseException
    {
        //  text();
     
      String dt;
      dt=DateCreate("28-09-2015");
        System.out.println(dt);
     
    }
 
    public  static String DateCreate(String subdate) throws ParseException, BadElementException, IOException
    {
        String res;
           SimpleDateFormat fr=new SimpleDateFormat("dd-MM-yyyy");
        Date startdate=fr.parse(subdate);
        SimpleDateFormat di=new SimpleDateFormat("EEEE");
        String daych=di.format(startdate);
        if(daych.equals("Monday"))
        {
      SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yyyy");
      Calendar cal  = Calendar.getInstance();
                      cal.setTime(startdate);
                        cal.add(Calendar.DATE, 6);
                     
                        String enddatestr = sdf.format(cal.getTime());
                        Date enddate=fr.parse(enddatestr);
                     
                      List<String> dt=  getDaysBetweenDates(startdate,enddate);
                     
            String dt1=Pdf(dt);
            res=dt1;
        }
        else
        {
           res="Check Date,It is not Monday";
        }
        return res;
    }
    public static List<String> getDaysBetweenDates(Date startdate, Date enddate)
{
 
    List<String> dates = new ArrayList<>();
    Calendar calendar = new GregorianCalendar();
    calendar.setTime(startdate);

    while (calendar.getTime().before(enddate))
    {
        Date result = calendar.getTime();
     
        SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yyyy");
        String dt=sdf.format(result);
        dates.add(dt);
        calendar.add(Calendar.DATE, 1);
    }
    return dates;
}
    public static String Pdf(List<String> subdate) throws FileNotFoundException, BadElementException, IOException
    {
     
                     
      Document document = new Document();
      try
      {
         String Greetline="                                                       PROJECT TRACK SHEET";
         String Empname1="Employee Name :_______________________";
         String EmpId=   "Employee id        :_______________________";
         String EmpTL=   "Team Leader      :_______________________";
          String Empband="Band                   :_______________________";
         String EmpPLT=  "Platform              :_______________________";
         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("D:\\HelloWorld1.pdf"));
         document.open();
         Paragraph paragraph = new Paragraph();
           Chunk tab = new Chunk(new VerticalPositionMark(), 50f, false);
         // paragraph.setTabSettings(new TabSettings(tabList));
          Chunk CONNECT = new Chunk(
            new LineSeparator(0.5f, 95, BaseColor.BLUE, Element.ALIGN_CENTER, 3.5f));
        LineSeparator UNDERLINE =
            new LineSeparator(1, 100, null, Element.ALIGN_CENTER, -2);
        // creates tabs
        Chunk tab1 = new Chunk(new VerticalPositionMark(), 200, true);
        Chunk tab2 = new Chunk(new VerticalPositionMark(), 350, true);
          Chunk tab6 = new Chunk(new VerticalPositionMark(), 50f, false);
        Chunk tab3 = new Chunk(new DottedLineSeparator(), 450, true);
       Image image1 = Image.getInstance("imagevar.png");
          document.add(image1);
          document.add(new Paragraph(new Chunk(tab1)));
          document.add(new Paragraph(new Chunk(tab1)));
          document.add(new Paragraph(Greetline));
          document.add(new Paragraph(new Chunk(tab1)));
          document.add(new Paragraph(new Chunk(tab1)));
          document.add(new Paragraph(Empname1));
          document.add(new Paragraph(EmpId));
          document.add(new Paragraph(Empband));
          document.add(new Paragraph(EmpTL));
          document.add(new Paragraph(EmpPLT));
          Image image = Image.getInstance("D:\\images.jpg");
          image.setAbsolutePosition(390f, 500f);
          document.add(image);
          document.add(new Paragraph(new Chunk(tab1)));
          document.add(new Paragraph(new Chunk(tab1)));
           PdfPTable table = new PdfPTable(6); // 6 columns.
           table.setWidthPercentage(100);
           table.setWidths(new int[]{ 1, 1, 2, 1, 1,1});
            PdfPCell day = new PdfPCell(new Paragraph("  Day"));
            day.setRowspan(2);
            table.addCell(day);
            PdfPCell date = new PdfPCell(new Paragraph("  Date"));
            date.setRowspan(2);
            table.addCell(date);
            PdfPCell projass = new PdfPCell(new Paragraph("      Project Assigned"));
            projass.setRowspan(2);
            table.addCell(projass);
            PdfPCell workdone = new PdfPCell(new Paragraph("           Work Done"));
            workdone.setColspan(2);
            table.addCell(workdone);
            PdfPCell sign = new PdfPCell(new Paragraph("  Comments"));
            sign.setRowspan(2);
            table.addCell(sign);
            table.addCell("Fore noon");
            table.addCell("After noon");
            List<String> days= new ArrayList<>(
            Arrays.asList("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"));
            for(int i=0;i<days.size();i++)
            {
             
            table.addCell(" "+days.get(i));
            table.setSpacingBefore(10f);
            table.addCell(subdate.get(i));
            table.setSpacingBefore(10f);
            table.addCell(" ");
            table.setSpacingBefore(10f);
        table.addCell(" ");
         table.setSpacingBefore(10f);
         table.addCell(" ");
          table.setSpacingBefore(10f);
        table.addCell(" ");
            }
            document.add(new Paragraph(new Chunk(tab1)));
   
           document.add(table);
             document.add(new Paragraph(new Chunk(tab1)));
        document.add(new Paragraph(new Chunk(tab1)));
        document.add(new Paragraph(new Chunk(tab1)));
             document.add(new Paragraph("Total Working Days___________"));
             document.add(new Paragraph("Total Work in %     ___________"));
             document.add(new Paragraph(new Chunk(tab1)));
        document.add(new Paragraph(new Chunk(tab1)));
        document.add(new Paragraph(new Chunk(tab1)));
            document.add(new Paragraph("Employee Signature:                                                      HR Signature  :"));
            document.add(new Paragraph("                                                                                        Date          :"));
            //workdone.setColspan(2);
           //  table.setSpacingBefore(10f);
             //table.setSpacingBefore(10f);
            //float[] columnWidths = {2f, 1f, 1f};
         // table.setWidths(columnWidths);
         document.close();
     
         writer.close();
       
      }
      catch (DocumentException e)
      {
         e.printStackTrace();
       
      }
      return "success";
    }
 
}