Java code to write in a TEXT FILE


This java program,creates a text file in the address specified if is not present and writes the content in this text file.If the text file is already present in the specified address, the content will be appended to the previously existing content.This program requires two class file,one is the java main class file(WriteText.java) and other is the java class file(WriteFile.java) which wites the content into the text file.Steps are given below.
Steps
  1. Select Java form the categories and Java Application  from the projects, click Next.
  2. Set the Project name as  writeText  and set the Create Main Class, click Finish.
  3. Under the  project "writeText", you can see two files, double click the Source Packages,you can see a package by name " writetext " ,double click it you will find the Java Main Class FileWriteText.java.
  4. Right click the   package  by name " writetext " and select New -> Other 
  5. From Categories select Java and from File Types select Java Class, click Next
  6. Set the Class Name as "WriteFile.java" and ensure the package name is  " writetext".
Now open the  WriteText.java, remove the existing code and paste the following code :

Java code to read the content of a TEXT FILE

Steps
  1. Select Java form the categories and Java Application  from the projects, click Next.
  2. Set the Project name as  readText  and set the Create Main Class, click Finish.
  3. Under the  project "readText", you can see two files, double click the Source Packages,you can see a package by name "readtext " ,double click it you will find the Java Main Class FileReadText.java.
  4. Right click the   package  by name "readtext " and select New -> Other 
  5. From Categories select Java and from File Types select Java Class, click Next
  6. Set the Class Name as "ReadFile.java" and ensure the package name is  "readtext ".
Now open the ReadText.java, remove the existing and paste the following code :

Implementation of POLYALPHABETIC SUBSTITUTION CIPHER usin java(Encryption technique)


Steps

  1. Select Java form the categories and Java Application  from the projects, click Next.
  2. Set the Project name as  PolyCiipher  and set the Create Main Class, click Finish.
  3. Under the  project "polyciipher", you can see two files, double click the Source Packages,you can see a package by name polyciipher " ,double click it you will find the Java Main Class FilePolyCiipher.java.
  4. Open this file, remove the existing code and paste the following code.
------------------------------------------PolyCiipher.java.---------------------------------------------------------

Java code to convert the individual character of a string into its ascii value


Steps

  1. Select Java form the categories and Java Application  from the projects, click Next.
  2. Set the Project name as  ascii  and set the Create Main Class, click Finish.
  3. Under the  project "ascii", you can see two files, double click the Source Packages,you can see a package by name " ascii " ,double click it you will find the Java Main Class File Ascii .java.
  4. Open this file, remove the existing code and  paste the following code.
------------------------------------------------Ascii.java-----------------------------------------------------------

java code to reverse a string


Steps

  1. Select Java form the categories and Java Application  from the projects, click Next.
  2. Set the Project name as reverseString and set the Create Main Class, click Finish.
  3. Under the  project "reverseString", you can see two files, double click the Source Packages,you can see a package by name "reversestring" ,double click it you will find the Java Main Class FileReverseString.java.
  4. Open this file, remove the existing code and  paste the following code.
----------------------------------------------ReverseString.java-------------------------------------------------

Java code to generate a PDF

Steps
  1. From category directory, select  Java and from project directory, select Java Application, click Next.
  2. Set the project name as PDFWriter and deselect the Create Main Class option, so to name the class and package by your own choice, click Finish.
  3. Now you can see two files,Source Package and Libraries under the project name  PDFWriter.
  4. For this you need to have one Java Main Class and one jar file,itextpdf-5.2.0.jar(Download it).
  5. Right click the  Source Package, select New->Other->Java->Java Main Class.
  6. Set the name of the Java Main Class File as FirstPDF and set the package name as pdfJava, click Finish.
  7. Right click the Libraries,select Add Jar/Folder and then  add itextpdf-5.2.0.jar  the downloaded location.
  8. Now double click the  FirstPDF.java, remove the existing code and  paste the following code.
--------------------------------------------- FirstPDF.java--------------------------------------------------------

/*

 * To change this template, choose Tools | Templates

 * and open the template in the editor.

 */

package pdfJava;

/**
 *
 * @author ZISSAN
 */
import java.io.FileOutputStream;
import java.io.IOException;

//import com.lowagie.text.Document;
//import com.lowagie.text.DocumentException;
//import com.lowagie.text.Paragraph;
//import com.lowagie.text.pdf.PdfWriter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class   FirstPDF{
 /**
* Generates a PDF file with the text 'Hello World'
*/
public static void main(String[] args) {

System.out.println("Hello World");

// Step1:  A document-object is created
Document document = new Document();
try {
// Step2:A writer is created that listens to the document and directs a  PDF-stream to a file.
PdfWriter.getInstance(document, new FileOutputStream("C:/PDF/FirstPdf.pdf"));
//"C:/PDF/FirstPdf.pdf" is the location at which pdf by name FirstPdf.pdf will be created,PDF is the folder //name in "C" drive.
// Step3: Open the document
document.open();
// Step4: Add a paragraph to the document
document.add(new Paragraph("Hello world"));
} catch (DocumentException dex) {
System.err.println(dex.getMessage());
} catch (IOException ioex) {
System.err.println(ioex.getMessage());
}

// Step 5: Close the document
document.close();
System.out.println("PDF is created sussecefully ");
}   
}
---------------------------------------------- FirstPDF.java----------------------------------------------------------------
For using this code in jsp,you can contact me through mail.

Java mail program

Steps


  1. Select java web from the categories list and select web-application from the project list and set the project name as SendingEmail and set all other properties as defaults.
  2. For this you need to have two jar files, mail.jar and activation-1.1.1.jar. Download these files and right click the libraries in the Netbeans 7.0.1 and select ADD JAR/FOLDER. Select these two jar files.
  3. Once this done, you need two have 3 jsp pages, index.jsp, success.jsp and error .jsp and one  servlet file, EmailServlet.java, to handle the request posted by the user from index.jsp
index.jsp---------------------------------------------------------------------------------------------------

In index.jsp, you need to have 5 text box for sender email address set by name="from", receiver email address set by name="to", subject set by name="subject", login set by name="login" and password set by name="password" in the index.jsp.It also requires one textarea for message set by name="message" in the index.jsp.These parameters are received by servlet file EmailServlet.java and process the required operation,i.e if no exceptions occurs then it will redirect to the success.jsp page else it will redirect to the error.jsp page.

Remove the existing code and paste following code in the index.jsp

-------------------------------------------------index.jsp-----------------------------------------------------
<%-- 
    Document   : index
    Created on : 24 Jan, 2012, 3:52:40 PM
    Author     : ZISSAN
    Email-id   :ziszrcks@gmail.com
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        
        <title>Sending email</title>
        
    </head>
    <body>
    <center>
        <form action="EmailServlet" method="post">   
            <table>
                <tr>
                    <td>From</td>
                    <td><input type="text" name="from"></td>
                </tr>
                <tr>
                <tr>
                    <td>To</td>
                    <td><input type="text" name="to"></td>
                </tr>
                <tr>
                    <td>Subject</td>
                    <td><input type="text" name="subject"></td>
                </tr>    
                <tr>
                    <td>Message</td>
                    <td><textarea cols="25" rows="8" name="message"></textarea></td>
                </tr>
                <tr>
                    <td>Login</td>
                    <td><input type="text" name="login"></td>
                </tr>
                <tr>
                    <td>Password</td>
                    <td><input type="password" name="password"></td>
                </tr>
               
            </table>
            
            <input type="submit" value="submit">
        </form>
        <br><br>
        

    </center>
</body>
</html>
------------------------------------------end of index.jsp--------------------------------------------------
After index.jsp, to compute the request or to handle the request we need a servlet file.This is done by writing the code in EmailServlet.java.For this right click the SourcePackage and select New-->Servlet-->
then set the class name as "EmailServlet.java" and set the package name as "email".Once this has been done you can see under SourcePackage, package name "email".Then you need to set this servlet and its url pattern in web.xml. For this right click the SendingEmail project node and select New-->Other-->Web-->
Standard Deployment Descriptor (web.xml).Once selected,set properties as default.This file you will find  under the WEB-INF.
Remove the existing code and paste the following the code in web.xml

web.xml----------------------------------------------------------------------------------------------------
-----------------------------------------------web.xml-----------------------------------------------------

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>EmailServlet</servlet-name>
        <servlet-class>email.EmailServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>EmailServlet</servlet-name>
        <url-pattern>/EmailServlet</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>
-----------------------------------------end of web.xml----------------------------------------------------

Once servlet name, class and its url is set, then  remove the existing code and paste the following the code  in EmailServlet.java

EmailServlet.java-------------------------------------------------------------------------------------------
For this you need to have an account in gmail, therefore you need to set the following properties,i.e host name,port number,enabling authenticaton and enabling encryption.

-----------------------------------------EmailServlet.java--------------------------------------------------
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package email;

import java.io.*;
import java.net.*;

import java.util.Properties;
import javax.mail.AuthenticationFailedException;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 *
 * @author ZISSAN
 */
public class EmailServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

//response.setContentType("text/html;charset=UTF-8");
//PrintWriter out = response.getWriter();
        final String err = "/error.jsp";
        final String succ = "/success.jsp";
     
        

        String from = request.getParameter("from");
        String to = request.getParameter("to");
        String subject = request.getParameter("subject");
        String message = request.getParameter("message");
        String login = request.getParameter("login");
        String password = request.getParameter("password");
       
        
       
        try {
            Properties props = new Properties();
            
                props.setProperty("mail.host", "smtp.gmail.com");
                props.setProperty("mail.smtp.port", "587");
                props.setProperty("mail.smtp.auth", "true");
                props.setProperty("mail.smtp.starttls.enable", "true");
             

            
           
            Authenticator auth = new SMTPAuthenticator(login, password);

            Session session = Session.getInstance(props, auth);

            MimeMessage msg = new MimeMessage(session);
            msg.setText(message);
            msg.setSubject(subject);
            msg.setFrom(new InternetAddress(from));
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            Transport.send(msg);

        } catch (AuthenticationFailedException ex) {

            request.setAttribute("ErrorMessage", "Authentication failed");

            RequestDispatcher dispatcher = request.getRequestDispatcher(err);
            dispatcher.forward(request, response);

        } catch (AddressException ex) {
            request.setAttribute("ErrorMessage", "Wrong email address");

            RequestDispatcher dispatcher = request.getRequestDispatcher(err);
            dispatcher.forward(request, response);

        } catch (MessagingException ex) {

            request.setAttribute("ErrorMessage", ex.getMessage());

            RequestDispatcher dispatcher = request.getRequestDispatcher(err);
            dispatcher.forward(request, response);

        }
        RequestDispatcher dispatcher = request.getRequestDispatcher(succ);
        dispatcher.forward(request, response);
    }

    private class SMTPAuthenticator extends Authenticator {

        private PasswordAuthentication authentication;

        public SMTPAuthenticator(String login, String password) {
            authentication = new PasswordAuthentication(login, password);
        }

        protected PasswordAuthentication getPasswordAuthentication() {
            return authentication;
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}

----------------------------------------end of EmailServlet.java-------------------------------------------
  success.jsp -----------------------------------------------------------------------------------------------
Remove the existing code and paste the following the code
----------------------------------------------success.jsp--------------------------------------------------
<%-- 
    Document   : success
    Created on : 24 Jan, 2012, 4:03:33 PM
    Author     : ZISSAN
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
  <head>
    <title>Message</title>
    <link rel="stylesheet" href="style.css" type="text/css">
  </head>
  <body>
    <center>
      <div class="msg">
        <h2>Message</h2>
          <p>
               Email sent
          </p>
      </div>
   </center>
  </body>
</html>

---------------------------------------end of  success.jsp--------------------------------------------------

error.jsp --------------------------------------------------------------------------------------------------
Remove the existing code and paste the following the code

-----------------------------------------------error.jsp----------------------------------------------------
<%-- 
    Document   : error
    Created on : 24 Jan, 2012, 4:02:53 PM
    Author     : ZISSAN
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Error</title>
      <link rel="stylesheet" href="style.css" type="text/css">
    </head>
    <body>
      <center>
        <div class="error">
          <h2>Error</h2>
            <p>
               Message: <%= request.getAttribute("ErrorMessage") %>    
            </p>
        </div>
      </center>
    </body>
</html>
-------------------------------------end of error.jsp-------------------------------------------------------



Ajax autocomplete source code in jsp retrieving data from database



This project is done in netbeans7.0.1

Steps for setting up the project
1.Select Java Web in categories directory in the left
2.Select Web Application in the project directory
3.Set the project name as "autocomplete"
4.Then click next
5.Set the JavaEE version: Java EE 6 Web and click finish

For this two javascript files and two jsp pages (index.jsp and list.jsp) and one css( style.css )

1.jquery-1.4.2.min.js

2.jquery.autocomplete.js


Place the above js file in a single folder by name "JS" under Web Pages(right click Web Pages and New         ->  Other  ->  Other -> folder and name it JS) directory of the project by name "autocomplete" in netbeans


3.In the index.jsp, index.jsp will be present in Web Pages folder by default,dont delete it, remove the existing code and paste the following the code :
-----------------------------------------------index.jsp-----------------------------------------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd"
>
<!--author: zissan     emailid:ziszrcks@gmail.com-->
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script type="text/javascript" src="JS/jquery-1.4.2.min.js"></script>
<script src="JS/jquery.autocomplete.js"></script>
</head>
<body>
<div style="width: 300px; margin: 50px auto;">
<b>Country</b>   : <input type="text" id="country" name="country" class="input_text"/>
</div>

</body>
<script>
jQuery(function(){
$("#country").autocomplete("list.jsp");
});
</script>
</html>
--------------------------------------end of index.jsp------------------------------------------------------

4.In the list.jsp ,remove the existing code and paste the following the code:

-------------------------------------------list.jsp-----------------------------------------------------------

<!--author: zissan  emailId: ziszrcks@gmail.com
.this page handles the request of id=country(in index.jsp)
-->
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>


<%
      try{
          Connection con;
    Statement stmt;
    ResultSet rs;
    String host="jdbc:mysql://localhost:3306/books";
//books is the database name
            String uName="root";
            String uPass="enter your password";
            con=DriverManager.getConnection(host,uName,uPass);
            stmt=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
         
         
         
         
     
         
/* copy the countries name in the table "country" with a field name countries
            countrieslist               =
"Afghanistan",
"Albania",
"Algeria",
"Andorra",
"Angola",
"Antigua and Barbuda",
"Argentina",
"Armenia",
"Australia",
"Austria",
"Azerbaijan",
"Bahamas",
"Bahrain",
"Bangladesh",
"Barbados",
"Belarus",
"Belgium",
"Belize",
"Benin",
"Bhutan",
"Bolivia",
"Bosnia and Herzegovina",
"Botswana",
"Brazil",
"Brunei",
"Bulgaria",
"Burkina Faso",
"Burundi",
"Cambodia",
"Cameroon",
"Canada",
"Cape Verde",
"Central African Republic",
"Chad",
"Chile",
"China",
"Colombi",
"Comoros",
"Congo (Brazzaville)",
"Congo",
"Costa Rica",
"Cote d'Ivoire",
"Croatia",
"Cuba",
"Cyprus",
"Czech Republic",
"Denmark",
"Djibouti",
"Dominica",
"Dominican Republic",
"East Timor (Timor Timur)",
"Ecuador",
"Egypt",
"El Salvador",
"Equatorial Guinea",
"Eritrea",
"Estonia",
"Ethiopia",
"Fiji",
"Finland",
"France",
"Gabon",
"Gambia, The",
"Georgia",
"Germany",
"Ghana",
"Greece",
"Grenada",
"Guatemala",
"Guinea",
"Guinea-Bissau",
"Guyana",
"Haiti",
"Honduras",
"Hungary",
"Iceland",
"India",
"Indonesia",
"Iran",
"Iraq",
"Ireland",
"Israel",
"Italy",
"Jamaica",
"Japan",
"Jordan",
"Kazakhstan",
"Kenya",
"Kiribati",
"Korea, North",
"Korea, South",
"Kuwait",
"Kyrgyzstan",
"Laos",
"Latvia",
"Lebanon",
"Lesotho",
"Liberia",
"Libya",
"Liechtenstein",
"Lithuania",
"Luxembourg",
"Macedonia",
"Madagascar",
"Malawi",
"Malaysia",
"Maldives",
"Mali",
"Malta",
"Marshall Islands",
"Mauritania",
"Mauritius",
"Mexico",
"Micronesia",
"Moldova",
"Monaco",
"Mongolia",
"Morocco",
"Mozambique",
"Myanmar",
"Namibia",
"Nauru",
"Nepal",
"Netherlands",
"New Zealand",
"Nicaragua",
"Niger",
"Nigeria",
"Norway",
"Oman",
"Pakistan",
"Palau",
"Panama",
"Papua New Guinea",
"Paraguay",
"Peru",
"Philippines",
"Poland",
"Portugal",
"Qatar",
"Romania",
"Russia",
"Rwanda",
"Saint Kitts and Nevis",
"Saint Lucia",
"Saint Vincent",
"Samoa",
"San Marino",
"Sao Tome and Principe",
"Saudi Arabia",
"Senegal",
"Serbia and Montenegro",
"Seychelles",
"Sierra Leone",
"Singapore",
"Slovakia",
"Slovenia",
"Solomon Islands",
"Somalia",
"South Africa",
"Spain",
"Sri Lanka",
"Sudan",
"Suriname",
"Swaziland",
"Sweden",
"Switzerland",
"Syria",
"Taiwan",
"Tajikistan",
"Tanzania",
"Thailand",
"Togo",
"Tonga",
"Trinidad and Tobago",
"Tunisia",
"Turkey",
"Turkmenistan",
"Tuvalu",
"Uganda",
"Ukraine",
"United Arab Emirates",
"United Kingdom",
"United States",
"Uruguay",
"Uzbekistan",
"Vanuatu",
"Vatican City",
"Venezuela",
"Vietnam",
"Yemen",
"Zambia",
"Zimbabwe"
};*/
         
            String query = (String)request.getParameter("q");
            String sql="select countries from country where countries like '"+query+"%'";
            rs=stmt.executeQuery(sql);
            rs.last();
            int length=rs.getRow();
response.setHeader("Content-Type", "text/html");
int cnt=1;
     
if(rs.first()){
        for(int i=0;i<length;i++)
{
if(rs.getString(1).toUpperCase().startsWith(query.toUpperCase()))
{
out.print(rs.getString(1)+"\n");
if(cnt>=10)
break;
cnt++;
                        rs.next();
}
                           
             
}
               }
          else{
                               out.println("country name not in the database");
                               }
   

             
           
%>
<%
      }
      catch(Exception e1){
      out.println("cannot display the records");
      }
%>

---------------------------------------------end of list.jsp---------------------------------------------------
place the two jsp in Web Pages foler directly

5. For the style.css right click the Web Pages directory (New -> Other -> Other -> folder ) and name it "css"
and then right click the css folder (New -> Other -> Other -> CascadingStyleSheet ) and name it "style.css"
    In the "style.css", remove the existing code and paste the following the code:
----------------------------------------------style.css-------------------------------------------------------
 .ac_results {
padding: 0px;
border: 1px solid #ff7c08;
background-color: white;
overflow: hidden;
}

.ac_results ul {
width: 100%;
list-style-position: outside;
list-style: none;
padding: 0;
margin: 0;
}

.ac_results li {
margin: 0px;
padding: 2px 5px;
cursor: default;
display: block;
color: #972800;
font-family:Arial, Helvetica, sans-serif;
/*
if width will be 100% horizontal scrollbar will apear
when scroll mode will be used
*/
/*width: 100%;*/
font-size: 12px;
/*
it is very important, if line-height not setted or setted
in relative units scroll will be broken in firefox
*/
line-height: 16px;
overflow: hidden;

}

.ac_loading {
background: white url('../images/indicator.gif') right center no-repeat;
}

.ac_odd {
background-color: #fef2d8;
}

.ac_over {
background-color: #febb80;
color: white;
}


.input_text{
font-family:Arial, Helvetica, sans-serif;
font-size:12px;
border:1px solid #FF7C08;
padding:2px;
width:150px;
color:#802900;
background:white url(../images/search.png) no-repeat 3px 2px;
padding-left:17px;
}

-------------------------------------------end of style.css---------------------------------------------------
For this two images are required:
1. indicator.gif

2. search.png

--------------------------------------------screenshot-------------------------------------------------------


Srcreenshots

------------------------------------------------sql command------------------------------------------------
databsename : books

  • CREATE TABLE country (countries VARCHAR(20) NOT NULL, PRIMARY KEY (countries));
  • INSERT INTO books.country (countries) VALUES ('Angola');