Visualization: Line Chart

Visualization: Line Chart

 

How to Use Line Chart in Project ?

Just Copy this code and customize  yourself  then paste it in html page or jsp,php

 

 <html>
  <head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Year', 'Sales', 'Expenses'],
          ['2004',  1000,      400],
          ['2005',  1170,      460],
          ['2006',  660,       1120],
          ['2007',  1030,      540]
        ]);

        var options = {
          title: 'Company Performance'
        };

        var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="chart_div" style="width: 900px; height: 500px;"></div>
  </body>
</html>


 

 

Sending Email using JavaMail API

Sending Email using JavaMail API

You can use one of the following techniques to get the SMTP server:There are various ways to send email using JavaMail API. For this purpose, you must have SMTP server that is responsible to send mails.

  • Install and use any SMTP server such as Postcast server, Apache James server, cmail server etc. (or)
  • Use the SMTP server provided by the host provider e.g. my SMTP server is mail.javatpoint.com (or)
  • Use the SMTP Server provided by other companies e.g. gmail etc.
Here, we are going to learn above three aproches to send email using javamail API. But we should learn the basic steps to send email from java application.

Steps to send email using JavaMail API

There are following three steps to send email using JavaMail. They are as follows:
  1. Get the session object that stores all the informations of host like host name, username, password etc.
  2. compose the message
  3. send the message

1) Get the session object

The javax.mail.Session class provides two methods to get the object of session, Session.getDefaultInstance() method and Session.getInstance() method. You can use anyone method to get the session object. Examples of these methods are as follows:

Syntax of getDefaultInstance() method

There are two methods to get the session object by using the getDefaultInstance() method. It returns the default session.
  1. public static Session getDefaultInstance(Properties props)  
  2. public static Session getDefaultInstance(Properties props,Authenticator auth)  

Example of getDefaultInstance() method

  1. Properties properties=new Properties();  
  2. //fill all the informations like host name etc.  
  3. Session session=Session.getDefaultInstance(properties,null);  

Syntax of getInstance() method

There are two methods to get the session object by using the getInstance() method. It returns the new session.
  1. public static Session getInstance(Properties props)  
  2. public static Session getInstance(Properties props,Authenticator auth)  
  3.   
  4. </pre></div>  
  5. <h4 class="h4">Example of getDefaultInstance() method</h4>  
  6. <div class="codeblock"><pre name="code" class="java" >  
  7.   
  8. Properties properties=new Properties();  
  9. //fill all the informations like host name etc.  
  10. Session session=Session.getInstance(properties,null);  

2) Compose the message

The javax.mail.Message class provides methods to compose the message. But it is an abstract class so its subclass javax.mail.internet.MimeMessage class is mostly used.
To create the message, you need to pass session object in MimeMessage class constructor. For example:
  1. MimeMessage message=new MimeMessage(session);  
Now message object has been created but to store information in this object MimeMessage class provides many methods. Let's see methods provided by the MimeMessage class:

Commonly used methods of MimeMessage class

1) public void setFrom(Address address): is used to set the from header field.
2) public void addRecipients(Message.RecipientType type, String addresses): is used to add the given address to the recipient type.
3) public void setSubject(String subject): is used to set the subject header field.
4) public void setText(String textmessage) is used to set the text as the message content using text/plain MIME type.

Example to compose the message:

  1. MimeMessage message=new MimeMessage(session);  
  2. message.setFrom(new InternetAddress("pankaj@java.com"));  
  3. message.addRecipient(Message.RecipientType.To,   
  4. new InternetAddress("kamlesh@java.com"));  
  5. message.setHeader("Hi, everyone");  
  6. message.setText("Hi, This mail is to inform you...");  

3) Send the message

The javax.mail.Transport class provides method to send the message.

Commonly used methods of Transport class

1) public static void send(Message message): is used send the message.
2) public static void send(Message message, Address[] address): is used send the message to the given addresses.

Example to send the message:

  1. Transport.send(message);  

Simple example of sending email using JavaMail API

In this example, we are going to learn how to send email by SMTP server installed on the machine e.g. Postcast server, Apache James server, Cmail server etc. If you want to send email by using your SMTP server provided by the host provider, see the example after this one.
For sending the email using JavaMail API, you need to load the two jar files:
  • mail.jar
  • activation.jar
Dowanload jar file go to the Oracle site to download the latest version.
  1. import java.util.*;  
  2. import javax.mail.*;  
  3. import javax.mail.internet.*;  
  4. import javax.activation.*;  
  5.   
  6. public class SendEmail  
  7. {  
  8.  public static void main(String [] args){  
  9.       String to = "pnkjtiwari446@gmail.com";//change accordingly  
  10.       String from = "pankaj0590@gmail.com";change accordingly  
  11.       String host = "localhost";//or IP address  
  12.   
  13.      //Get the session object  
  14.       Properties properties = System.getProperties();  
  15.       properties.setProperty("mail.smtp.host", host);  
  16.       Session session = Session.getDefaultInstance(properties);  
  17.   
  18.      //compose the message  
  19.       try{  
  20.          MimeMessage message = new MimeMessage(session);  
  21.          message.setFrom(new InternetAddress(from));  
  22.          message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));  
  23.          message.setSubject("Ping");  
  24.          message.setText("Hello, this is example of sending email  ");  
  25.   
  26.          // Send message  
  27.          Transport.send(message);  
  28.          System.out.println("message sent successfully....");  
  29.   
  30.       }catch (MessagingException mex) {mex.printStackTrace();}  
  31.    }  
  32. }  

In this example, we are going to learn how to send email by SMTP server installed on the machine e.g. Postcast server, Apache James server, Cmail server etc. If you want to send email by using your SMTP server provided by the host provider, see the example after this one.
To run this example, you need to load two jar files. There are 4 ways to load the jar file. One of the way is set classpath. Let's see how to run this example:
Load the jar filec:\> set classpath=mail.jar;activation.jar;.;
compile the source filec:\> javac SendEmail.java
run byc:\> java SendEmail

Example of sending email using JavaMail API through the SMTP server provided by the host provider

If you are using the SMTP server provided by the host provider e.g. mail.java.com , you need to authenticate the username and password. The javax.mail.PasswordAuthentication class is used to authenticate the password.
If you are sending the email using JavaMail API, load the two jar files:
  • mail.jar
  • activation.jar
 Dowanload jar file go to the Oracle site to download the latest version.
  1. import java.util.Properties;  
  2. import javax.mail.*;  
  3. import javax.mail.internet.*;  
  4.   
  5. public class SendMailBySite {  
  6.  public static void main(String[] args) {  
  7.   
  8.   String host="mail.javatpoint.com";  
  9.   final String user="pankajl@java.com";//change accordingly  
  10.   final String password="xxxxx";//change accordingly  
  11.     
  12.   String to="pankaj0590@gmail.com";//change accordingly  
  13.   
  14.    //Get the session object  
  15.    Properties props = new Properties();  
  16.    props.put("mail.smtp.host",host);  
  17.    props.put("mail.smtp.auth""true");  
  18.      
  19.    Session session = Session.getDefaultInstance(props,  
  20.     new javax.mail.Authenticator() {  
  21.       protected PasswordAuthentication getPasswordAuthentication() {  
  22.     return new PasswordAuthentication(user,password);  
  23.       }  
  24.     });  
  25.   
  26.    //Compose the message  
  27.     try {  
  28.      MimeMessage message = new MimeMessage(session);  
  29.      message.setFrom(new InternetAddress(user));  
  30.      message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));  
  31.      message.setSubject("java");  
  32.      message.setText("This is simple program of sending email using JavaMail API");  
  33.        
  34.     //send the message  
  35.      Transport.send(message);  
  36.   
  37.      System.out.println("message sent successfully...");  
  38.    
  39.      } catch (MessagingException e) {e.printStackTrace();}  
  40.  }  
  41. }  

As you can see in the above example, userid and password need to be authenticated. As, this program illustrates, you can send email easily. Change the username and password accordingly. Let's see how to run it once again by simple technique:

Load the jar filec:\> set classpath=mail.jar;activation.jar;.;
compile the source filec:\> javac SendMailBySite.java
run byc:\> java SendMailBySite

JavaMail Architecture

Java Mail API Tutorial


The JavaMail API provides protocol-independent and plateform-independent framework for sending and receiving mails.The JavaMail is an API that is used to compose, write and read electronic messages (emails).
The javax.mail and javax.mail.activation packages contains the core classes of JavaMail API.
The JavaMail facility can be applied to many events. It can be used at the time of registering the user (sending notification such as thanks for your interest to my site), forgot password (sending password to the users email id), sending notifications for important updates etc. So there can be various usage of java mail api.

Protocols used in JavaMail API

There are some protocols that are used in JavaMail API.
  • SMTP
  • POP
  • IMAP
  • MIME
  • NNTP and others

SMTP

SMTP is an acronym for Simple Mail Transfer Protocol. It provides a mechanism to deliver the email. We can use Apache James server, Postcast server, cmail server etc. as an SMTP server. But if we purchase the host space, an SMTP server is bydefault provided by the host provider. For example, my smtp server is mail.javatpoint.com. If we use the SMTP server provided by the host provider, authentication is required for sending and receiving emails.

POP

POP is an acronym for Post Office Protocol, also known as POP3. It provides a mechanism to receive the email. It provides support for single mail box for each user. We can use Apache James server, cmail server etc. as an POP server. But if we purchase the host space, an POP server is bydefault provided by the host provider. For example, the pop server provided by the host prvider for my site is mail.javatpoint.com. This protocol is defined in RFC 1939.

IMAP

IMAP is an acronym for Internet Message Access Protocol. IMAP is an advanced protocol for receiving messages. It provides support for multiple mail box for each user ,in addition to, mailbox can be shared by multiple users. It is defined in RFC 2060.

MIME

Multiple Internet Mail Extension (MIME) tells the browser what is being sent e.g. attachment, format of the messages etc. It is not known as mail transfer protocol but it is used by your mail program.

NNTP and Others

There are many protocols that are provided by third-party providers. Some of them are Network News Transfer Protocol (NNTP), Secure Multipurpose Internet Mail Extensions (S/MIME) etc.

JavaMail Architecture

The java application uses JavaMail API to compose, send and receive emails. The JavaMail API uses SPI (Service Provider Interfaces) that provides the intermediatory services to the java application to deal with the different protocols. Let's understand it with the figure given below:
JavaMail API Architecture

JavaMail API Core Classes

There are two packages that are used in Java Mail API: javax.mail and javax.mail.internet package. These packages contains many classes for Java Mail API. They are:
  • javax.mail.Session class
  • javax.mail.Message class
  • javax.mail.internet.MimeMessage class
  • javax.mail.Address class
  • javax.mail.internet.InternetAddress class
  • javax.mail.Authenticator class
  • javax.mail.PasswordAuthentication class
  • javax.mail.Transport class
  • javax.mail.Store class
  • javax.mail.Folder class etc.

We will know about these class one by one when it is getting used.

How to upload and download file from desire folder using struts2.0

Let see the Simple Example for upload and download file from desire folder


/****** Action Class for saving file from desire folder ***/
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.tomcat.util.http.fileupload.FileUtils;

import com.opensymphony.xwork2.ActionSupport;
public class WebAction extends ActionSupport {

    private File myfile;
    private String myfileFileName;
    private String myfileContentType;
    private String filePathToSaveInDB;

    public String openHome() {
        return "open";
    }

    public String uploadFileToMyFolder() {
        try {
            ServletContext servletContext = ServletActionContext.getServletContext();
            String path = "MyFolder/";
            //getting the path to where the images will be uploaded
            String filePath = servletContext.getRealPath(path);

            File uploadDir = new File(filePath);
            //if the folder does not exits, creating it
            if (uploadDir.exists() == false) {
                uploadDir.mkdirs();
            }
            setFilePathToSaveInDB(path + "/" + myfileFileName);
            FileUtils.copyFile(myfile, new File(uploadDir, myfileFileName));
         
        } catch (Exception e) {
            System.out.println("Exception : " + e);
            addActionError(e.getMessage());
            return "failure";
        }
        return "success";
    }

// GETTER AND SETTER GOES HERE


Struts.xml file

<action name="uploadFileToMyFolder" method="uploadFileToMyFolder" class="com.debraj.WebAction">
            <interceptor-ref name="fileUpload">
                <param name="maximumSize">2097152</param>
                <param name="allowedTypes">
                              image/png,image/gif,image/jpeg,image/jpg
                </param>
            </interceptor-ref>
            <interceptor-ref name="defaultStack"></interceptor-ref>
            <result name="success">/pages/web/Success.jsp</result>
            <result name="failure">/pages/web/failure.jsp</result>
</action>



Home.jsp for fire Action



<!DOCTYPE HTML>

<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
    <head>
        <title><s:text name="Struts2 File Upload" /></title>
    </head>
    <body>
        <div>
            <s:form id="uploadFileToMyFolder" name="uploadFileToMyFolder" action="uploadFileToMyFolder" enctype="multipart/form-data">
                <s:text name="Upload Image : " />
                <s:file name="myfile" id="myfile"/>
                <s:submit name="submit"/>
            </s:form>
        </div>
    </body>
</html>


Success.jsp


<!DOCTYPE HTML>

<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
    <head>
        <title><s:text name="Struts2 File Upload Success" /></title>
    </head>
    <body>
        <div>
            <s:actionmessage />
            <s:property value="myfile"/><br />
            <s:property value="myfileFileName"/><br />
            <s:property value="myfileContentType"/><br />
            <img src="<s:text name='%{filePathToSaveInDB}'/>"/><br />
           
        </div>
    </body>
</html>


fail.jsp


<!DOCTYPE HTML>

<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
    <head>
        <title><s:text name="Struts2 File Upload Failure" /></title>
    </head>
    <body>
        <div>
            <s:actionerror />
        </div>
    </body>
</html>


For Downloading File form desire Folder



package pankaj;
import java.sql.*;
import java.io.*;
import java.util.*;
public class Download {

static ArrayList arr=new ArrayList();


private static String assign_name,submit_date,attach1,reg_no;

public ArrayList getArr() {
return arr;
}

public void setArr(ArrayList arr) {
this.arr = arr;
}

public String getReg_no() {
return reg_no;
}

public void setReg_no(String reg_no) {
this.reg_no = reg_no;
}

public String getAssign_name() {
return assign_name;
}

public void setAssign_name(String assign_name) {
this.assign_name = assign_name;
}

public String getSubmit_date() {
return submit_date;
}

public void setSubmit_date(String submit_date) {
this.submit_date = submit_date;
}

public static String getAttach1() {
return attach1;
}

public static void setAttach1(String attach1) {
Download.attach1 = attach1;
}

public static ArrayList dd(String n)throws Exception
{
System.out.println("NAME"+n);
Class.forName("oracle.jdbc.OracleDriver");
     Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","oracle");
     Statement st=con.createStatement();
     //ResultSet rs=st.executeQuery("select assign.attach1,assign.assign_name,assign.submitdate from stureg inner join assign on  assign.classname  = stureg.classname and assign.sectionname=stureg.section where stureg.username='"+n+"'");
    ResultSet rs1=st.executeQuery("SELECT * FROM STUREG WHERE USERNAME='"+n+"'");
    String classname=null;
    String section=null;
    while(rs1.next())
    {
    classname=rs1.getString("CLASSNAME");
    section=rs1.getString("SECTION");
    }
    ResultSet rs=st.executeQuery("SELECT * FROM ASSIGN WHERE CLASSNAME='"+classname+"' AND SECTIONNAME='"+section+"'");
     while(rs.next())
     {

       arr.add(rs.getString("ASSIGN_NAME")+"@@"+rs.getString("SUBMITDATE")+"@@"+rs.getString("ATTACH1")+"@@"+rs.getString("SUBJECT"));
   
     }
     return arr;
}



}


download.jsp



<%@page import="java.sql.*"%>
<%@page import="pankaj.Download,java.util.*" %>
<%@taglib uri="/struts-tags" prefix="s" %>

<%
String n=(String)session.getAttribute("user");
out.println("NAme:"+n);
          ArrayList arr;
          arr=Download.dd(n);
        /* arr=Download.dd(request.getParameter("ver"));
         
           //out.println(request.getParameter("ver"));
         
         
           Class.forName("oracle.jdbc.OracleDriver");
     Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","oracle");
     Statement st=con.createStatement();
     Download d=new Download();
     ResultSet rs1=st.executeQuery("SELECT * FROM STUREG WHERE USERNAME='"+n+"'");
    String classname=null;
    String section=null;
    while(rs1.next())
    {
    classname=rs1.getString("CLASSNAME");
    section=rs1.getString("SECTION");
    }
          //String s=d.getReg_no();
           //out.println("NAME:"+s);
     ResultSet rs=st.executeQuery("select Attach1 from assign where SECTIONNAME='"+section+"' and CLASSNAME='"+classname+"'");
   
     rs.next();*/
   
   
           
   %>
 
 
 
 
   <table class="normal-table m-bot-30" cellspacing='0'>
        <thead>
          <tr>
            <th width="20%" class="first">Assignment Name</th>
            <th width="23%">Submit Date</th>
            <th width="20%">Subject</th>
            <th colspan="2"></th>
           
          </tr>
        </thead>
       
         <tbody>
       
         <%
        for(Object obj:arr)
        {
        String newlst1[]=obj.toString().split("@@");
       
         %>
         <tr>
         <td><%=newlst1[0] %></td>
         <td><%=newlst1[1] %></td>
         <td><%=newlst1[3] %></td>
          <td width="20%" ><a href="down.jsp?file=<%=newlst1[2] %>">Download</a></td>
       
         <%}
         arr.clear();
          %>
         
         
         
       
        </tbody>
       
        </table>
         

            </div>


Read file from desire folder

down.jsp


<%
String filename = request.getParameter("file");
out.println("File"+filename);
  String filepath = "C:/Server/webapps/School/UploadFile/";
  response.setContentType("APPLICATION/OCTET-STREAM");
  response.setHeader("Content-Disposition","attachment; filename"+filename);

  java.io.FileInputStream fileInputStream=new java.io.FileInputStream(filepath+filename);

  int i;
  while ((i=fileInputStream.read()) != -1) {
    out.write(i);
  }
  fileInputStream.close();
%>













© Copyright 2013 Java EveryThing About Java (PANKAJ TIWARI) - All Rights Reserved - Powered by Blogger.com