Monday, April 22, 2013

Upload .csv file in struts1

fileupload.jsp



<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@page import="java.util.Iterator"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"  session="false"%>
     <%!
       String Path=null;
        HttpSession session;
       String basePath =null;
   
     
     %> <%
       Path = request.getContextPath();
      basePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+Path+"/";
     %>
      <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <title>Stats Section </title>
 
 
  </head>

<body>
   
     <html:form action="/FileUploadControl" method="post" enctype="multipart/form-data" styleId="stateformid">
            <html:file property="statsfile">Upload</html:file>
            <html:submit>Add</html:submit>
     
      </html:form>
     
</body>
</html>

FileUploadControl.java



package action;

import java.io.File;
import java.io.FileOutputStream;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import bean.AddFileBean;
import dao.DaoFactory;
import dao.SqlDao;

public class FileUploadControl extends Action
{
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
 {
HttpSession session = request.getSession(false);
ServletContext context =   getServlet().getServletContext();
String excel_location =context.getInitParameter("excelpath");
excel_location =request.getRealPath(excel_location);
excel_location =excel_location+"/";
DaoFactory sql = new SqlDao();
AddFileBean addfile = new AddFileBean();

int i = 0;
int id = 0;
AddFileBean addfile1 =   (AddFileBean)form;
FormFile statsfile = addfile1.getStatsfile();
String fileName1   =   statsfile.getFileName();
if(!fileName1.equals(""))
{
 
    File fileToCreate = null;
   
   
    if(fileName1.equals(""))
    {
    fileName1 = "";
    }
    else
    {
      fileToCreate = new File(excel_location, statsfile.getFileName());
    FileOutputStream fileOutStream = new FileOutputStream(fileToCreate);
    fileOutStream.write(statsfile.getFileData());
    fileOutStream.flush();
          fileOutStream.close();
    }
           excel_location=excel_location+statsfile.getFileName();
           String  excel_location1 =  excel_location.replace("\\","/");
          sql.AddData(excel_location1);
 }
else
{
i = 1 ;
}

if(i!=1)
   return mapping.findForward("success");
else
return mapping.findForward("error");
}}



AddFileBean.java


package bean;

import org.apache.struts.upload.FormFile;

public class AddFileBean extends org.apache.struts.validator.ValidatorForm
{

private FormFile statsfile;



public FormFile getStatsfile()
{
return statsfile;
}
public void setStatsfile(FormFile statsfile)
{
this.statsfile = statsfile;
}

}



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:jsp="http://java.sun.com/xml/ns/javaee/jsp" 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_2_5.xsd" id="WebApp_ID" version="2.5">
  <context-param>
    <param-name>excelpath</param-name>
    <param-value>/Excel</param-value>
  </context-param>
  <display-name>nccp</display-name>
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
      <param-name>config</param-name>
      <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <init-param>
      <param-name>debug</param-name>
      <param-value>2</param-value>
    </init-param>
    <init-param>
      <param-name>detail</param-name>
      <param-value>2</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
  </servlet>
  <servlet>
    <description></description>
    <display-name>FileUploadControl</display-name>
    <servlet-name>FileUploadControl</servlet-name>
    <servlet-class>Action.FileUploadControl</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>FileUploadControl</servlet-name>
    <url-pattern>/FileUploadControl</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <session-config>
    <session-timeout>30</session-timeout>
  </session-config>
  <welcome-file-list>
    <welcome-file>/fileupload.jsp</welcome-file>
  </welcome-file-list>
  <jsp-config>
    <taglib>
      <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
      <taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
    </taglib>
    <taglib>
      <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
      <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
    </taglib>
    <taglib>
      <taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
      <taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
    </taglib>
    <taglib>
      <taglib-uri>/WEB-INF/struts-nested.tld</taglib-uri>
      <taglib-location>/WEB-INF/struts-nested.tld</taglib-location>
    </taglib>
    <taglib>
      <taglib-uri>/WEB-INF/struts-tiles.tld</taglib-uri>
      <taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
    </taglib>
  </jsp-config>
 
</web-app>

struts-config.xml


<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
          "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">

<struts-config>
    <form-beans>
<form-bean name="AddFileBean" type="bean.AddFileBean"/>
    </form-beans>

    <global-exceptions>

    </global-exceptions>

    <global-forwards>
        <forward name="welcome"  path="/Welcome.do"/>
    </global-forwards>

    <action-mappings>
<action input="fileupload.jsp" name="AddFileBean" path="/FileUploadControl" scope="request" type="action.FileUploadControl">
            <forward name="success" path="/success.jsp" />
            <forward name="error" path="/error.jsp" />
        </action>
       <action path="/Welcome" forward="/welcomeStruts.jsp"/>
    </action-mappings>

    <controller processorClass="org.apache.struts.tiles.TilesRequestProcessor"/>

    <message-resources parameter="action/ApplicationResource"> </message-resources>

    <!-- ========================= Tiles plugin ===============================-->
    <!--
    This plugin initialize Tiles definitio n factory. This later can takes some
    parameters explained here after. The plugin first read parameters from
    web.xml, thenoverload them with parameters defined here. All parameters
    are optional.
    The plugin should be declared in each struts-config file.
    - definitions-config: (optional)
    Specify configuration file names. There can be several comma
    separated file names (default: ?? )
    - moduleAware: (optional - struts1.1)
    Specify if the Tiles definition factory is module aware. If true
    (default), there will be one factory for each Struts module.
    If false, there will be one common factory for all module. In this
    later case, it is still needed to declare one plugin per module.
    The factory will be initialized with parameters found in the first
    initialized plugin (generally the one associated with the default
    module).
    true : One factory per module. (default)
    false : one single shared factory for all modules
    - definitions-parser-validate: (optional)
    Specify if xml parser should validate the Tiles configuration file.
    true : validate. DTD should be specified in file header (default)
    false : no validation

    Paths found in Tiles definitions are relative to the main context.
    -->
    <plug-in className="org.apache.struts.tiles.TilesPlugin" >
        <set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml" />
        <set-property property="moduleAware" value="true" />
    </plug-in>

    <!-- ========================= Validator plugin ================================= -->
    <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
        <set-property
            property="pathnames"
            value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
    </plug-in>
</struts-config>










Upload .csv file in struts2

fileupload.jsp



<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" session="false"%>
<html>
<head>
 <s:head />
   <title>File Upload Page</title>
</head>
 <s:actionerror/>
 <body>
   <table border="0" align="center" bordercolor="red">
    <s:form action="uploadAction" method="POST" enctype="multipart/form-data">
 <tr>
      <td style="color: red;">
    Chose File:    <s:file name="uploadFile"  size="40" cssStyle="color:green"/>
        <s:iterator value="fieldErrors.uploadFile"><s:property/></s:iterator>
      </td>
 </tr>
  <tr>
       <td>
          <s:submit value="Upload" name="submit" cssStyle="color:green"/>
      </td>
 </tr>
    </s:form>
    </table>
 </body>
 </html>


FileUploadAction.java



package action;
import java.io.File;

import javax.servlet.ServletContext;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import sqldao.DaoFactory;
import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport{
private static final long serialVersionUID = 1L;


private File uploadFile;
private String uploadFileContentType;
private String uploadFileFileName;

public File getUploadFile() {
return uploadFile;
}
public void setUploadFile(File uploadFile) {
this.uploadFile = uploadFile;
}

public String getUploadFileContentType() {
return uploadFileContentType;
}
public void setUploadFileContentType(String uploadFileContentType) {
this.uploadFileContentType = uploadFileContentType;
}

public String getUploadFileFileName() {
return uploadFileFileName;
}
public void setUploadFileFileName(String uploadFileFileName) {
this.uploadFileFileName = uploadFileFileName;
}
DaoFactory dao = DaoFactory.getDao("sql");

public String execute()
{
try{
if(uploadFileFileName==null){
addFieldError("uploadFile", "file is required");
return INPUT;
}
String name = getUploadFileFileName();
        String []fileext = name.split("\\.");
        String ext = fileext[1];
if(ext.equals("csv")){
ServletContext context = ServletActionContext.getServletContext();
        String filePath = context.getRealPath("csvfile");
        String csv_location  = filePath+"/";
                 File fileToCreate = new File(csv_location, uploadFileFileName);
                 FileUtils.copyFile(uploadFile, fileToCreate);
                 String filePathname = csv_location+uploadFileFileName;
                 String filerealpath  = filePathname.replace("\\", "/");
        dao.insertdata(filerealpath);
}else{
  addFieldError("uploadFile", "Upload only csv file");
  return INPUT;
        }
}catch(Exception e)
{
e.printStackTrace();
            addActionError(e.getMessage());
            return INPUT;
}
return SUCCESS;
}

public Object getModel(){

return null;
}

}


struts.xml


<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
     <constant name="struts.multipart.maxSize" value="164703120" />
     <constant name="struts.ui.theme" value="simple"/>
    <include file="struts-default.xml"/>
    <package name="a" extends="struts-default">
   
        <action name="uploadAction" class="action.FileUploadAction"> 
        
            <interceptor-ref name="exception" />
<interceptor-ref name="alias" />
<interceptor-ref name="servletConfig" />
<interceptor-ref name="prepare" />
<interceptor-ref name="i18n" />
<interceptor-ref name="chain" />
<interceptor-ref name="debugging" />
<interceptor-ref name="profiling" />
<interceptor-ref name="scopedModelDriven" />
<interceptor-ref name="modelDriven" />
<interceptor-ref name="fileUpload">
</interceptor-ref>
<interceptor-ref name="basicStack"/>
<interceptor-ref name="checkbox" />
<interceptor-ref name="staticParams" />
<interceptor-ref name="actionMappingParams"/>
<interceptor-ref name="params">
<param name="excludeParams"> dojo\..*,^struts\..*</param>
</interceptor-ref>
<interceptor-ref name="conversionError" />
<interceptor-ref name="validation">
<param name="excludeMethods"> input,back,cancel,browse</param>
</interceptor-ref>
<interceptor-ref name="workflow">
<param name="excludeMethods"> input,back,cancel,browse</param>
</interceptor-ref>
            <result name="success">/success.jsp</result>
            <result name="input">/index.jsp</result>
        </action>
    </package>
</struts>


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_2_5.xsd" id="WebApp_ID" version="2.5">
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>







Struts2 Framework Interceptors


Struts 2 framework provides a good list of out-of-the-box interceptors that come preconfigured and ready to use. Few of the important interceptors are listed below:
SNInterceptor & Description
1alias
Allows parameters to have different name aliases across requests.
2checkbox
Assists in managing check boxes by adding a parameter value of false for check boxes that are not checked.
3conversionError
Places error information from converting strings to parameter types into the action's field errors.
4createSession
Automatically creates an HTTP session if one does not already exist.
5debugging
Provides several different debugging screens to the developer.
6execAndWait
Sends the user to an intermediary waiting page while the action executes in the background.
7exception
Maps exceptions that are thrown from an action to a result, allowing automatic exception handling via redirection.
8fileUpload
Facilitates easy file uploading.
9i18n
Keeps track of the selected locale during a user's session.
10logger
Provides simple logging by outputting the name of the action being executed.
11params
Sets the request parameters on the action.
12prepare
This is typically used to do pre-processing work, such as setup database connections.
13profile
Allows simple profiling information to be logged for actions.
14scope
Stores and retrieves the action's state in the session or application scope.
15ServletConfig
Provides the action with access to various servlet-based information.
16timer
Provides simple profiling information in the form of how long the action takes to execute.
17token
Checks the action for a valid token to prevent duplicate formsubmission.
18validation
Provides validation support for actions

Tuesday, April 2, 2013

Multithreading in java

Multithreading is a  process of executing multiple threads simultaneously. Thread is basically a lightweight subprocess , a smallest  unit of processing .

Multithreading is  mostly  used games, animation etc.



Extending the Thread Class
The steps for creating a thread by using the fi rst mechanism are:
 1. Create a class by extending the Thread class and override the run() method:
class MyThread extends Thread {
 public void run() {
 // thread body of execution
 }
 }
 2. Create a thread object:
MyThread thr1 = new MyThread();
 3. Start Execution of created thread:
thr1.start();



THREAD LIFE CYCLE
The life cycle of threads in Java is very similar to the life cycle of processes running in an operating system.
During its life cycle the thread moves from one state to another depending on the operation performed by it
or performed on it as illustrated in Fig. 14.4. A Java thread can be in one of the following states:
∑ NEW
 A thread that is just instantiated is in new state. When a start() method is invoked, the thread
moves to the ready state from which it is automatically moved to runnable state by the thread
scheduler.
∑ RUNNABLE (ready running)
 A thread executing in the JVM is in running state.
∑ BLOCKED
 A thread that is blocked waiting for a monitor lock is in this state. This can also occur when a thread
performs an I/O operation and moves to next (runnable) state.
∑ WAITING
 A thread that is waiting indefi nitely for another thread to perform a particular action is in this state.
∑ TIMED_WAITING (sleeping)
 A thread that is waiting for another thread to perform an action for up to a specifi ed waiting time is in
this state.

Monday, April 1, 2013

Variable and Datatype in java


Variable  : -   Variable is name of memory location .

 There are three  types of  variables in java.

 1. local
2.  instance
3.  static


1. local

    variable declare inside the meth

StringBuffer Class in java

The StringBuffer class  is used to created mutable string.The StringBuffer class is same as string except. It is mutable.

Counstructor:-

StringBuffer();
StringBuffer(String str);
StringBuffer(int capacity);

 Example:-


class A{

 public static void main(String args[]){

  StringBuffer buffer  =  new StringBuffer("Hello");

     buffer.append("Java");
  System.out.println(sb);
}

Saturday, March 30, 2013

What is difference between JDK,JRE and JVM

JVM is acronym for  Java Virtual machine,it is an  abstract machine which  provides the runtime environment in  which java bytecode can be executed.

JVMs are available  for many hardware and software platform (so JVM is platforms dependent).



JRE  is  java runtime environment . it is used to  provide  runtime environment. it is  the implementation of JVM.  it is physically exists.



JDK  is acronym of java development kit. it is physically exist.

ServletOutputStream Class in java

It is  an abstract class . which is provide stream to write binary data into the response

  ServletOutputStream fout = response.getOutputStream()



Example :   to down load video in jsp page


String url = request.getParameter("url");
    String title = request.getParameter("title");
    URL tU = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) tU.openConnection();
    String type = conn.getContentType();
    InputStream ins = conn.getInputStream();
    ServletOutputStream fout = response.getOutputStream();
    response.setContentType("mime/flv");
    response.setHeader("Content-disposition","attachment; filename=\""+title+".flv\"");
    byte[] outputByte = new byte[conn.getContentLength()];
    int bytesRead;
    int length = conn.getContentLength();
    int read = 0;
    while((bytesRead = ins.read(outputByte, 0, length)) != -1){
         //read += bytesRead;
         //System.out.println(read + " out of " + length);
         fout.write(outputByte, 0, bytesRead);
    }
     fout.flush();
     fout.close();
     out.clear(); // where out is a JspWriter
     out = pageContext.pushBody();
     response.getOutputStream().flush();



Friday, March 29, 2013

Create a 3D bar chart in JSP page using JFreeChart

This Example shows you how to create a 3D bar chart in jsp page using JFreeChart. Code given below creates a bar chart of scores of two teams in matches.
In the code given below we have extended class ApplicationFrame to create a frame and also pass a string value to the constructor of ApplicationFrame class by using super keyword that will be name of the created frame.

Methods used in this example are described below:
pack(): This method invokes the layout manager.

centerFrameOnScreen(): This method is used for the position of the frame in the middle of the screen.

setVisible(): This method is used for display frame on the screen.

createCategoryDataset(): This method is used to create the instance of CategoryDataset Interface and that contains a copy of the data in an array.

saveChartAsPNG(): This method is used to save chart in to png format.

jsp3Dbarchart.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">
 
 
<%page  import="java.awt.*" %>
<%page  import="java.io.*" %>
<%page  import="org.jfree.chart.*" %>
<%page  import="org.jfree.chart.axis.*" %>
<%page  import="org.jfree.chart.entity.*" %>
<%page  import="org.jfree.chart.labels.*" %>
<%page  import="org.jfree.chart.plot.*" %>
<%page  import="org.jfree.chart.renderer.category.*" %>
<%page  import="org.jfree.chart.urls.*" %>
<%page  import="org.jfree.data.category.*" %>
<%page  import="org.jfree.data.general.*" %>

<%
  final double[][] data = new double[][]{
 {210300320265299},
 {200304201201340}
 };

 final CategoryDataset dataset =
   DatasetUtilities.createCategoryDataset
("Team """, data);

 JFreeChart chart = null;
 BarRenderer renderer3D = null;
 CategoryPlot plot = null;


 final CategoryAxis3D categoryAxis = new CategoryAxis3D("Match");
 final ValueAxis valueAxis = new NumberAxis3D("Run");
 renderer3D = new BarRenderer3D();

 plot = new CategoryPlot(dataset, categoryAxis, valueAxis, renderer3D);
 plot.setOrientation(PlotOrientation.VERTICAL);
 chart = new JFreeChart("Srore Bord", JFreeChart.DEFAULT_TITLE_FONT,
  plot, 
true);

 chart.setBackgroundPaint(new Color(249231236));

  try {
 final ChartRenderingInfo info = new ChartRenderingInfo
 (
new StandardEntityCollection());
 
final File file1 = new File("../webapps/jspchart/web/3dbarchart.png");
 ChartUtilities.saveChartAsPNG(file1, chart, 600400, info);
  catch (Exception e) {
 out.println(e);
 }
%>

<html>
  <head>
  <meta http-equiv="Content-Type"
  
content="text/html; charset=UTF-8">
  <title>JSP Page</title>
  </head>
  <body>
  <IMG SRC="3dbarchart.png"
  
WIDTH="600" HEIGHT="400" BORDER="0" USEMAP="#chart">
  </body>
</html>

Create area chart in JSP page using JFreeChart

This Example shows you how to create a area chart in JSP page using JFreeChart. Code given below creates a area chart of runs of two teams in different matches. In the code given below we have extended class ApplicationFrame to create a frame and also pass a string value to the constructor of ApplicationFrame class by using super keyword that will be name of the created frame.

Methods used in this example are described below:
pack(): This method invokes the layout manager.

centerFrameOnScreen(): This method is used for the position of the frame in the middle of the screen.

setVisible(): This method is used for display frame on the screen.

createCategoryDataset(): This method is used to create the instance of CategoryDataset Interface and that contains a copy of the data in an array.

createAreaChart(): This method is used to create bar chart for given values. It takes title, category axis label, value axis label, dataset, Plot Orientation, legend, tool tips and urls as parameters.

saveChartAsPNG(): This method is used to save chart in to png format.

jspareachart.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<%page  import="java.awt.*" %>
<%page  import="java.io.*" %>
<%page  import="org.jfree.chart.*" %>
<%page  import="org.jfree.chart.axis.*" %>
<%page  import="org.jfree.chart.entity.*" %>
<%page  import="org.jfree.chart.labels.*" %>
<%page  import="org.jfree.chart.plot.*" %>
<%page  import="org.jfree.chart.renderer.category.*" %>
<%page  import="org.jfree.chart.urls.*" %>
<%page  import="org.jfree.data.category.*" %>
<%page  import="org.jfree.data.general.*" %>

<%
  final double[][] data = new double[][]{
  {210300320265299},
  {200304201201340}
  };

 final CategoryDataset dataset =
  DatasetUtilities.createCategoryDataset
(
  "Team """, data);

 final JFreeChart chart = ChartFactory.createAreaChart(
  "Area Chart""""Value", dataset,
   PlotOrientation.VERTICAL,

  true, true, false);

 final CategoryPlot plot = chart.getCategoryPlot();
 plot.setForegroundAlpha(0.5f);

 chart.setBackgroundPaint(new Color(249231236));

 try {
  final ChartRenderingInfo info = new ChartRenderingInfo
   (
new StandardEntityCollection());



final File file1 = new File("../webapps/jspchart/web/
  areachart.png"
);
 ChartUtilities.saveChartAsPNG(file1, chart, 600400, info);
  catch (Exception e) {
  out.println(e);
  }

%>

<html>
  <head>
  <meta http-equiv="Content-Type" 
   content=
"text/html; charset=UTF-8">
  <title>JSP Page</title>
  </head>
  <body>
  <IMG SRC="areachart.png" WIDTH="600" HEIGHT="400" BORDER="0"
   
USEMAP="#chart">
  </body>
</html>




Thursday, March 28, 2013

Introduction to POJO (Plain Old Java Object) Programming Model


One of the new features of added by Sun Microsystems in EJB 3.0 is POJO (Plain Old Java Object). It is a Java object that doesn't extend or implement some specialized classes and interfaces respectively require by the EJB framework. Therefore, all normal Java objects are POJO?s only. The following classes are not POJO classes shown as:
class MyServlet extends HttpServlet {} 
class MyRemote implements SessionBean {}
In POJO model, it is recommended that, interfaces should be explicitly implemented whenever you want to pick and choose the methods of the interface. The interfaces are optional for entity beans but required for session beans and message-driven beans. In this model, both the interface and the bean class do not have to throw unnecessary exceptions such as RemoteException.

The interface class in POJO model is a Plain Old Java Interface (POJI).
 The Benefits of POJOs: 
Decoupling: It decouples the application components from the infrastructure of the EJB framework that lets you construct an application from loosely coupled components. There are no longer need to write the tedious JNDI framework-specific lookup code. You can design and implement the business logic. Once that's working, and then you can deal with persistence and transactions.
Easier testing: You can test or run your business logic outside of the application server in a few seconds.
Flexible:
 A Java POJO code can be implemented with any type of enterprise bean such as Message Driven Bean and Entity Bean.  The POJO technology can be used with any type of Enterprise Java Beans(e.g Session Bean, Message Driven Bean or Entity Bean).

Let?s understand the POJO with Message Driven Bean:
Message Driven POJOs:
Message-driven POJOs offer the functionality like MDB to make a simple JavaBeans for the developers. Similar to a MDB in EJB, it acts as a receiver for JMS messages.
Writing a message-driven POJO is not much different than writing a message-driven EJB. The major difference between both is that, an message-driven POJO (MDP) must implement thejavax.jms.MessageListener interface. Like an MDB, you don't have to implementjavax.ejb.MessageDrivenBean and the EJB lifecycle methods defined by the interface.
The EJB 3.0 uses annotations to build completely POJO-based messaging applications.

 In EJB 3.0?s container application server, there is an easier way to implement message driven RPCs. You can use POJOs as message end-points (message driven POJO). The RPC caller retrieves an automatically generated stub of the POJO and makes regular calls against the POJO methods. The message driven POJO works much like a session bean of EJB3, except that all calls are tunneled via a message queue.


 Let?s see the structure of Message Driven POJO given below:
  




Overview of Threads


Process
process is an instance of a computer program that is executed sequentially. It is a collection of instructions which are executed simultaneously at the rum time. Thus several processes may be associated with the same program. For example, to check the spellingis a single process in the Word Processor program and you can also use other processes likeprinting, formatting, drawing, etc. associated with this program.
Thread
A thread is a lightweight process which exist within a program and executed to perform a special task.Several threads of execution may be associated with a single process. Thus a process that has only one thread is referred to as a single-threaded process, while a process with multiple threads is referred to as a multi-threaded process.
In Java Programming language,  thread is a sequential path of code execution within a program. Each thread has its own local variables, program counter and lifetime. In single threaded runtime environment, operations are executes sequentially i.e. next operation can execute only when the previous one is complete. It exists in a common memory space and can share both data and code of a program.Threading concept is very important in Java through which we can increase the speed of any application. You can see diagram shown below in which a thread is executed along with its several operations with in a single process. 

To make bar chart from excel sheet in java?


import java.io.*;
import java.util.*;
import org.jfree.data.*;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.plot.PlotOrientation;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.jfree.data.category.DefaultCategoryDataset;

    public class ReadExcel{
        public static void main(String[]args){
    short a=0;  
    short b=1;  
     int i=0;   
    ArrayList<Integer> list1=new ArrayList<Integer>();
    ArrayList<Integer> list2=new ArrayList<Integer>();
        int   x=0, y=0;  
       String filename ="C:/data.xls";     
        if(filename != null && !filename.equals("")){
        try{    
        FileInputStream fs =new FileInputStream(filename);    
        HSSFWorkbook wb = new HSSFWorkbook(fs);   
        for(int k = 0; k < wb.getNumberOfSheets(); k++){    
         int j=i+1;    
         HSSFSheet sheet = wb.getSheetAt(k);    
         int rows  = sheet.getPhysicalNumberOfRows();    
         for(int r =     1; r < rows; r++){    
         HSSFRow row   = sheet.getRow(r);    
         int cells = row.getPhysicalNumberOfCells();    
            HSSFCell cell1  = row.getCell(a);      
            x =(int) cell1.getNumericCellValue();    
            HSSFCell cell2  = row.getCell(b);     
            y =(int) cell2.getNumericCellValue();     

            list1.add(new Integer(x));
            list2.add(new Integer(y));   
          }       
          i++;   
        }    }catch(Exception e){ 
    System.out.println(e);

 }

 }
 DefaultCategoryDataset dataset = new DefaultCategoryDataset();
  for(int j=0;j<list1.size();j++){
        dataset.setValue((double)list2.get(j), "Marks", list1.get(j).toString());
  }
        JFreeChart chart = ChartFactory.createBarChart("BarChart using JFreeChart","ID", "Marks", dataset, 
        PlotOrientation.VERTICAL, false,true, false);
               try {
               ChartUtilities.saveChartAsJPEG(new File("C:/chart.jpg"), chart,400, 300);
               } catch (IOException e) {
               System.out.println("Problem in creating chart.");
  }
 }
}