Pages

Friday 17 January 2014

Sending Email with java

It is quite important to send email in normal use. So to do it with java is quite simple task firstly we need to have a API file  or jar file which means Java Archive Resource file which consist of special functions and classes which are needed. There are varieties of jars like sendmail, JavaMail and many more. So choice is ours.Below is example of JavaMail jar file. 

To send an e-mail using your Java Application is simple enough but to start with you should have JavaMail API and Java Activation Framework (JAF) installed on your machine.

Send a Simple E-mail:
Here is an example to send a simple e-mail from your machine. Here it is assumed that your localhost is connected to the internet and capable enough to send an email.


import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendEmail
{
   public static void main(String [] args)
   {    
      // Recipient's email ID needs to be mentioned.
      String to = "abcd@gmail.com";

      // Sender's email ID needs to be mentioned
      String from = "web@gmail.com";

      // Assuming you are sending email from localhost
      String host = "localhost";

      // Get system properties
      Properties properties = System.getProperties();

      // Setup mail server
      properties.setProperty("mail.smtp.host", host);

      // Get the default Session object.
      Session session = Session.getDefaultInstance(properties);

      try{
         // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);

         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));

         // Set To: header field of the header.
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));

         // Set Subject: header field
         message.setSubject("This is the Subject Line!");

         // Now set the actual message
         message.setText("This is actual message");

         // Send message
         Transport.send(message);
         System.out.println("Sent message successfully....");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }

}

Uploading and Downloading Files In JAVA

Below is Code for uploading and downloading file or attachment using java!!!!
upload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Example</title>
</head>
<body>
<form id="form1" enctype="multipart/form-data" action="../upload" method="post">
            <table>
            <tr>
            <td> File Name </td>
            <td><input type="text" name="filename"/>
            </tr>
            <tr>
                    <td>Select File  </td>
                    <td><input type="file"  name="file" />
                 
                </tr>
               
            <tr><td><input type="submit" value="submit"/></td></tr>
            </table>
         
        </form>
           
</body>
</html>


upload.java
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

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

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
 * Servlet implementation class up
 */
public class up extends HttpServlet {
private static final long serialVersionUID = 1L;
     
    /**
     * @see HttpServlet#HttpServlet()
     */
    public up() {
        super();
        // TODO Auto-generated constructor stub
    }

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub

}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try {
/* String f1=request.getParameter("file");
f1.
if(f1.endsWith(".txt"))
{
System.out.println(f1);
}
else
{
System.out.println("not a txt file");
}*/
            // Apache Commons-Fileupload library classes
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload sfu  = new ServletFileUpload(factory);
 
            if (! ServletFileUpload.isMultipartContent(request)) {
                System.out.println("sorry. No file uploaded");
                return;
            }
             Connection con=null;
            java.util.List items = sfu.parseRequest(request);
         
            FileItem FirstName = (FileItem) items.get(0);
            String fn = FirstName.getString();
              System.out.println(fn);
              FileItem Image = (FileItem) items.get(1);
         String type=  Image.getContentType();
         if(type=="image/jpeg"){
         response.setContentType("image/jpeg");
         }
              Class.forName("com.mysql.jdbc.Driver");
    con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
           System.out.println("get connection");
             
           PreparedStatement ps = (PreparedStatement) con.prepareStatement("insert into files_upload(file_name,file_data,file_type) values (?,?,?)");
           
           System.out.println("prepared statement");
           ps.setString(1,fn);
           ps.setBinaryStream(2, Image.getInputStream(), (int) Image.getSize());
           ps.setString(3, type);
           ps.executeUpdate();
           System.out.println("File Uploaded Successfully.");
}
        catch(Exception ex) {
       
           System.out.println(ex);
        }
}
}

download.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ page import="java.io.*,java.util.*,java.sql.*" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>view</title>
</head>
<body>

    <br><br>

    <table width="200px" style="border:1px solid #ff0000;background-color:f7f7f7" align="center">

    <tr style="font-weight:bold;">

    <td align="center" align="center" colspan=2 style="border-bottom: 2px solid #000000;">Download Files</td>

    </tr>

 <tr style="font-weight:bold;">

       <td align="center" style="border-bottom: 2px solid #000000;">Id</td>

       <td align="center" style="border-bottom: 2px solid #000000;">File</td>

    </tr>

    

    <%

    

         String connectionURL = "jdbc:mysql://localhost:3306/test";

        //  String url=request.getParameter("WEB_URL");

        //  String Content=new String("");

          Statement stmt=null;

      Connection con=null;

    try

    {

        Class.forName("com.mysql.jdbc.Driver");

        con=DriverManager.getConnection(connectionURL,"root","root"); 

        stmt=con.createStatement();

        String qry = "select * from files_upload";

        ResultSet rst= stmt.executeQuery(qry);
        
    
        
        while(rst.next())

        {

    %>

         <tr>

      <td  align="center"><%=rst.getInt(1)%></td>

      <td align="center">

      <a href="../DBFileDownloadServlet?id=<%=rst.getInt(1)%>"><%=rst.getString(2)%></a>

       </td>

    </tr>

    <%

        }
        
    }

    catch(Exception e){

        e.printStackTrace();

    }

    %>

    </table>

    

</body>
</html>

download.java 


import java.io.*;
import java.util.*;
import java.sql.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class file_download
 */
public class file_download extends HttpServlet {
private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public file_download() {
        super();
        // TODO Auto-generated constructor stub
    }

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub

   

   int id=0;

   if(request.getParameter("id")!=null && request.getParameter("id")!="")

   {

 id = Integer.parseInt(request.getParameter("id").toString());

   }

        String connectionURL = "jdbc:mysql://localhost/test";

         String url=request.getParameter("WEB_URL");

         String Content=new String("");

         Statement stmt=null;

     Connection con=null;

   try

   {

       String filename="data"+id+".docx";

        Class.forName("com.mysql.jdbc.Driver").newInstance();

     con=DriverManager.getConnection(connectionURL,"root","root"); 

     stmt=con.createStatement();

         String qry = "select * from file where id='"+id+"'";

         ResultSet rst= stmt.executeQuery(qry);

                       if(rst.next())

                       {

   

                               Content=rst.getString("file_data");

                       }

                       

               byte requestBytes[] = Content.getBytes();

               ByteArrayInputStream bis = new ByteArrayInputStream(requestBytes);

               response.reset();

               response.setContentType("application/*");

               response.setHeader("Content-disposition","attachment; filename=" +filename);

               byte[] buf = new byte[1024];

                 int len;

                 while ((len = bis.read(buf)) > 0){

                                 response.getOutputStream().write(buf, 0, len);

                                }

               bis.close();

               response.getOutputStream().flush(); 

   }

   catch(Exception e){

       e.printStackTrace();

   }

   
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}

}


Wednesday 15 January 2014

Java Beans

A Java Bean is a reusable software component (actually, a Java class) that can be manipulated visually in a builder tool
Java Beans are just ordinary Java classes that follow certain conventions - you don't need special tools to create them
It is useful to have some tools to help assemble and configure a Bean-based application

Examples of "builder tools":
1.BeanBox (part of Sun's basic Beans Development Kit (BDK) - available free from java.sun.com)
2.Sun Java Workshop
3.IBM VisualAge for Java
4,Symantec Visual Cafe
5.Borland JBuilder
6.Java Bean conventions

There are two primary conventions that must be followed in creating Java Bean classes:
each "property" of the Java Bean class is implemented by defining two public functions (a "get" function and a "set" function)
the "operations" of the Java Bean class are the other public functions defined in the class
/* file Thermometer.java */
public class Thermometer {
  /* these two functions define the "currentTemperature" property */
  public int getCurrentTemperature() { return temp; }
  public void setCurrentTemperature(int aTemp) { temp = aTemp; }

  private int temp;

  public void temperatureChanged(TempChangedEvent ev) { ... }
  ... other implementation details ...
}

Reflection in Java

The "builder" programs can use special functions in Java 1.1 to discover which operations are part of each class
the special Java functions are called the Java Reflection API
they are used in many places in the builders
Java builders can display a "property sheet" for each Java Bean

More Java Bean configuration

The reflection interface may also be used by the builder tool to help the "programmer" tie user interface events to particular operations:
Java code is generated by the Builder tools

Java applications can use the "set" operations to initialize properties
Builder tools can also create the code for new objects that can be "registered" to receive events from the appropriate user interface objects
this means: a Java Bean doesn't have to be modified by the builder tools
all of the tailoring code can be put into newly-created classes
this is almost like "callbacks" in C and C++-based framework software
Creating a Java Bean

Design an ordinary Java class:
decide what properties and public operations it will support
Make sure that each property has a "get" and "set" operation in the public interface of the Java Bean class
Make sure that the class conforms to the Java 1.1 event model
If the class is a "visual Bean", then it should probably be a derived class of one of the AWT classes (probably Component or Container)
A Java Bean may also use some other helper classes
You can bundle the ".class" files for the main Java Bean class and all of the helper classes into a "Java Archive" file (JAR file)
Java Beans make good interfaces

Java Beans can be used to provide an interface to other non-Java applications that use Microsoft's ActiveX component technology
there is a "bridge" between Java Beans and ActiveX
Java Beans can be used to encapsulate the interface to an external database
the "get" and "set" operations in a Java Bean might actually use the Java database interface classes (the JDBC classes) to interact with a relational database
Not all Java Beans are graphical - but they can still be used to assemble applications using an application builder tool
Alternative ways to make a Java Bean

It isn't necessary to make changes to an existing class to convert it to a Java Bean
instead, you can create a "BeanInfo" class that defines the properties and public operations
for example, the BeanInfo class for the Temperature class would be called TemperatureBeanInfo
this class can define functions that permit the builder tools to access the characteristics of the Java Bean
public class TemperatureBeanInfo extends java.beans.SimpleBeanInfo {
 /* the following function will return an array of PropertyDescriptor
    objects, one object per Java Bean property */
  public PropertyDescriptor[] getPropertyDescriptors() {
   ...
  }
}


Using Java Beans for Web programs

Java applets are programs designed to run within a Web browser
An applet is a Java class that is derived from the java.applet.Applet class
Applets usually define the following functions:
init() - this function will define what will be done when the applet is first downloaded (it will usually create some user interface objects and set them up to be displayed, but it might also connect to a database or set up some other resources)
paint() - this function will be used to draw fixed strings and images, which might need to be redrawn any time the window is moved or becomes visible
Under standard conditions, applets can access files on the Web server, but not on the local "client" machine


Conclusion

Java Beans is a technology that makes it possible to build flexible Java applications
Applications can be built by non-programmers (using a builder tool)

Creating new Java Bean classes requires certain skills:
1.the developer needs to understand and use the Java 1.1 event model
2.the developer must follow certain "naming conventions" when creating the operation names in a Java Bean class
3.extra information for the builder tools can be added in a BeanInfo class
4.Java Beans is supported by many of the new Java development tools
5.Java Beans can be used in tandem with many other technologies
ActiveX
relational databases

Tuesday 14 January 2014

Attributes Of Servlets

An attribute in servlet is an object that can be set, get or removed from one of the following scopes:

request scope
session scope
application scope
The servlet programmer can pass information from one servlet to another using attributes. It is just like passing object from one class to another so that we can reuse the same object again and again.

Attribute specific methods of ServletRequest, HttpSession and ServletContext interface

There are following 4 attribute specific methods. They are as follows:
public void setAttribute(String name,Object object):sets the given object in the application scope.
public Object getAttribute(String name):Returns the attribute for the specified name.
public Enumeration getInitParameterNames():Returns the names of the context's initialization parameters as an Enumeration of String objects.
public void removeAttribute(String name):Removes the attribute with the given name from the servlet context.

Model View and Controller

MVC stands for Model View and Controller. It is a design pattern that separates the business logic, presentation logic and data.

Controller acts as an interface between View and Model. Controller intercepts all the incoming requests.

Model represents the state of the application i.e. data. It can also have business logic.

View represents the presentaion i.e. UI(User Interface).





Example of following MVC in JSP

In this example, we are using servlet as a controller, jsp as a view component, Java Bean class as a model.

In this example, we have created 5 pages:

index.jsp a page that gets input from the user.
ControllerServlet.java a servlet that acts as a controller.
login-success.jsp and login-error.jsp files acts as view components.
web.xml file for mapping the servlet.
File: index.jsp
<form action="ControllerServlet" method="post">  
Name:<input type="text" name="name"><br>  
Password:<input type="password" name="password"><br>  
<input type="submit" value="login">  
</form>  
File: ControllerServlet
package com.javatpoint;  
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;  
public class ControllerServlet extends HttpServlet {  
    protected void doPost(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        response.setContentType("text/html");  
        PrintWriter out=response.getWriter();  
          
        String name=request.getParameter("name");  
        String password=request.getParameter("password");  
          
        LoginBean bean=new LoginBean();  
        bean.setName(name);  
        bean.setPassword(password);  
        request.setAttribute("bean",bean);  
          
        boolean status=bean.validate();  
          
        if(status){  
            RequestDispatcher rd=request.getRequestDispatcher("login-success.jsp");  
            rd.forward(request, response);  
        }  
        else{  
            RequestDispatcher rd=request.getRequestDispatcher("login-error.jsp");  
            rd.forward(request, response);  
        }  
      
    }  
  
    @Override  
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
            throws ServletException, IOException {  
        doPost(req, resp);  
    }  
}  
File: LoginBean.java
package com.javatpoint;  
public class LoginBean {  
private String name,password;  
  
public String getName() {  
    return name;  
}  
public void setName(String name) {  
    this.name = name;  
}  
public String getPassword() {  
    return password;  
}  
public void setPassword(String password) {  
    this.password = password;  
}  
public boolean validate(){  
    if(password.equals("admin")){  
        return true;  
    }  
    else{  
        return false;  
    }  
}  
}  
File: login-success.jsp
<%@page import="com.javatpoint.LoginBean"%>  
  
<p>You are successfully logged in!</p>  
<%  
LoginBean bean=(LoginBean)request.getAttribute("bean");  
out.print("Welcome, "+bean.getName());  
%>  
File: login-error.jsp
<p>Sorry! username or password error</p>  
<%@ include file="index.jsp" %>  
File: 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"   
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"   
id="WebApp_ID" version="3.0">  
    
  <servlet>  
  <servlet-name>s1</servlet-name>  
  <servlet-class>com.javatpoint.ControllerServlet</servlet-class>  
  </servlet>  
  <servlet-mapping>  
  <servlet-name>s1</servlet-name>  
  <url-pattern>/ControllerServlet</url-pattern>  
  </servlet-mapping>  
</web-app>  




JSP VS SERVLETS

Following Points are noted for Java Server Pages:-

1. JSP is a webpage scripting language that can generate dynamic content.
2. JSP run slower compared to Servlet as it takes compilation time to convert into Java Servlets.
3. It’s easier to code in JSP than in Java Servlets.
4. In MVC, jsp act as a view.
5. JSP are generally preferred when there is not much processing of data required.
6.The advantage of JSP programming over servlets is that we can build custom tags which can directly call Java beans.
7.We can achieve functionality of JSP at client side by running JavaScript at client side.


Following Points are noted for Java Servlets:-

1. Servlets are Java programs that are already compiled which also creates dynamic web content.
2. Servlets run faster compared to JSP.
3. Its little much code to write here.
4. In MVC, servlet act as a controller.
5. Servlets are best for use when there is more processing and manipulation involved.
6. There is no such custom tag facility in servlets.

7. There are no such methods for servlets.


Sunday 6 October 2013

Scans and Counter Measures

Before Starting scanning and its methodology we must start with discussing types of scans.
First of all there are 3 types of scans possible based on their operation performed.
These are Port Scanning, Network Scanning and vulnerability scanning.
1.Port Scanning is used to determine open ports and services.
2.Network Scanning is used to locate working IP Addresses from a list and find out which are more      useful.
3.Vulnerability Scanning is for knowing the weaknesses in a network computers.

Know,Let us know about some popular services and ports used by them.FTP uses port no 21, Telnet uses port no 23, HTTP uses port 80, SMTP-25,POP3-110,HTTPS-443.

Scanning Methodology:-

1.Check for Live Systems.
we can check for live systems by performing Ping Sweep of IP Addresses.The systems responding to PING are active or live others might be Inactive or possibility of firewalls.

2.Check Open Ports.
3.Service Identification.
4.banner Grabbing or OS FingerPrinting.
5.Vulnerability Scanning.

NOTE:-
ICMP Scanning or Ping Sweep :-
Sending ICMP requests to all hosts on network to determine which are up and responding.It runs parallel on all systems because it can be run on all Systems simultaneously.

CounterMeasures to Port Scanning:-
Following steps could be followed:-
1.Implementation Of Intrusion Detection Systems or firewalls, should be followed.
2.After implementation of IDS or firewalls perform port scanning using tools such as Pinger, Friendly Pinger, WS_PING_PRO and many more so as to know whether firewall correctly works or not.
3.Check whether firewall able to detect probes set up by Port scanning tool.
It is to be noted that firewall must scan both data and packet not only TCP Header to determine whether traffic is allowed to pass through Firewall.
4.Network IDS should be used to hold on Operating System Detection Methods.
5.Onlu Needed Ports should be opened and rest closed.