Wednesday, April 25, 2012

download the csv file using servlets


Csv.java
-----------

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {



File                f        = new File("d:\\csv.txt");
       int                 length   = 0;
       ServletOutputStream op       = response.getOutputStream();
       ServletContext      context  = getServletConfig().getServletContext();
       String              mimetype = context.getMimeType( "text" );
       FileWriter writer = new FileWriter("d:\\csv1.text");

       //
       //  Set the response and go!
       //
       //
       response.setContentType( (mimetype != null) ? mimetype : "application/octet-stream" );
       response.setContentLength( (int)f.length() );
       response.setHeader( "Content-Disposition", "attachment; filename=\"" + writer + "\"" );

       //
       //  Stream to the requester.
       //
       byte[] bbuf = new byte[1024];
DataInputStream in = new DataInputStream(new FileInputStream(f));

       while ((in != null) && ((length = in.read(bbuf)) != -1))
       {
           op.write(bbuf,0,length);
       }

       in.close();
       op.flush();
       op.close();
// 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
}

}


web.xml
----------
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>Csv</servlet-class>

</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/csvv</url-pattern>

</servlet-mapping>


</web-app>

Monday, April 23, 2012

mp3 player creation in java


required JMF s/w and related jars


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;

import javax.media.ControllerEvent;
import javax.media.ControllerListener;
import javax.media.Manager;
import javax.media.Player;
import javax.media.RealizeCompleteEvent;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class MediaPlayerDemo extends JFrame {
    /**
*
*/
private static final long serialVersionUID = 1L;

private Player player;

    private File file;

    public MediaPlayerDemo() {
        super("Demonstrating the Java Media Player");

        JButton openFile = new JButton("Open file to play");
        openFile.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                openFile();
                createPlayer();
            }
        });
        getContentPane().add(openFile, BorderLayout.NORTH);

        setSize(300, 300);
        show();
    }

    private void openFile() {
        JFileChooser fileChooser = new JFileChooser();

        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        int result = fileChooser.showOpenDialog(this);

        // user clicked Cancel button on dialog
        if (result == JFileChooser.CANCEL_OPTION)
            file = null;
        else
            file = fileChooser.getSelectedFile();
    }

    private void createPlayer() {
        if (file == null)
            return;

        removePreviousPlayer();

        try {
            // create a new player and add listener
            player = Manager.createPlayer(file.toURL());
            player.addControllerListener(new EventHandler());
            player.start(); // start player
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Invalid file or location",
                    "Error loading file", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void removePreviousPlayer() {
        if (player == null)
            return;

        player.close();

        Component visual = player.getVisualComponent();
        Component control = player.getControlPanelComponent();

        Container c = getContentPane();

        if (visual != null)
            c.remove(visual);

        if (control != null)
            c.remove(control);
    }

    public static void main(String args[]) {
        MediaPlayerDemo app = new MediaPlayerDemo();

        app.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    // inner class to handler events from media player
    private class EventHandler implements ControllerListener {
        public void controllerUpdate(ControllerEvent e) {
            if (e instanceof RealizeCompleteEvent) {
                Container c = getContentPane();
                c.setBackground(new Color(255, 255, 204));

                // load Visual and Control components if they exist
                Component visualComponent = player.getVisualComponent();

                if (visualComponent != null)
                    c.add(visualComponent, BorderLayout.CENTER);
                c.setBackground(new Color(255, 255, 204));
                Component controlsComponent = player.getControlPanelComponent();

                if (controlsComponent != null)
                    c.add(controlsComponent, BorderLayout.SOUTH);

                c.doLayout();
            }
        }
    }
}

Saturday, April 21, 2012

Playing video in java using JMF

required:
----------


and add the jar files to classpath

MediaPanel.java:
------------------

import java.awt.BorderLayout;
  import java.awt.Component;
    import java.io.IOException;
    import java.net.URL;
    import javax.media.CannotRealizeException;
    import javax.media.Manager;
    import javax.media.NoPlayerException;
  import javax.media.Player;
    import javax.swing.JPanel;
   
  public class MediaPanel extends JPanel
  {
      /**
*/
private static final long serialVersionUID = 1L;

public MediaPanel( URL mediaURL )
      {
        setLayout( new BorderLayout() ); // use a BorderLayout
  
          // Use lightweight components for Swing compatibility
  Manager.setHint( Manager.LIGHTWEIGHT_RENDERER, true );
        
        try
        {
            // create a player to play the media specified in the URL
            Player mediaPlayer = Manager.createRealizedPlayer( mediaURL );
  
            // get the components for the video and the playback controls
            Component video = mediaPlayer.getVisualComponent();
            Component controls = mediaPlayer.getControlPanelComponent();
            
            if ( video != null )
              add( video, BorderLayout.CENTER ); // add video component
  
          if ( controls != null )
              add( controls, BorderLayout.SOUTH ); // add controls
   
            mediaPlayer.start(); // start playing the media clip
          } // end try
          catch ( NoPlayerException noPlayerException )
          {
            System.err.println( "No media player found" );
        } // end catch
          catch ( CannotRealizeException cannotRealizeException )
  {
            System.err.println( "Could not realize media player" );
          } // end catch
          catch ( IOException iOException )
   {
            System.err.println( "Error reading from the source" );
          } // end catch
      } // end MediaPanel constructor
  } // end class MediaPanel
MediaTest.java:
----------------
import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.JFileChooser;
import javax.swing.JFrame;


  public class MediaTest
  {
    // launch the application
  public static void main( String args[] )
  {
        // create a file chooser
        JFileChooser fileChooser = new JFileChooser();
  
        // show open file dialog
          int result = fileChooser.showOpenDialog( null );
   
        if ( result == JFileChooser.APPROVE_OPTION ) // user chose a file
        {
          URL mediaURL = null;
  
            try
            {
              // get the file as URL
                mediaURL = fileChooser.getSelectedFile().toURL();
             } // end try
            catch ( MalformedURLException malformedURLException )
            {
              System.err.println( "Could not create URL for the file" );
            } // end catch
   
            if ( mediaURL != null ) // only display if there is a valid URL
            {
                JFrame mediaTest = new JFrame( "Media Tester" );
              mediaTest.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
   
                MediaPanel mediaPanel = new MediaPanel( mediaURL );
              mediaTest.add( mediaPanel );
  
                mediaTest.setSize( 300, 300 );
              mediaTest.setVisible( true );
             
          } // end inner if
        } // end outer if
      }
  }
note :choose any mpg file

Friday, April 20, 2012

open browser through ant script


<macrodef name="openInBrowser">

  <attribute name="url"/>


  <sequential>

     <exec dir="${basedir}" executable="rundll32.exe">

        <arg line="url.dll, FileProtocolHandler"/>

        <arg line="@{url}"/>

     </exec>

  </sequential>  

</macrodef>
<target name="openTestResults" depends="tomcat-start">

  <echo message="Opening test results in default browser" />

  <openInBrowser url="http://localhost:2020/TrackingGadget-0.1-dev/gvHome"/>

</target>

Java Class return Xml file with Bean class data


package com.asman;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
class Student{
  private String gender;

  private String name;

  private int age;

  public String getGender() {
    return gender;
  }

  public void setGender(String gender) {
    this.gender= gender;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age= age;
  }
}



package com.asman;

import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
public class BeanToXMLExp {
public static void main(String[] args) throws Exception {
   JAXBContext contextObj = JAXBContext.newInstance(Student.class);

   Marshaller marshallerObj = contextObj.createMarshaller();
   marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

   Student myStudent = new Student();
   myStudent.setGender("M");
   myStudent.setName("Amar");
   myStudent.setAge(20);
//our xml file store d: directory
   marshallerObj .marshal(myStudent, new FileOutputStream("d:\\Student.xml"));


 }
}

output:
--------
student.xml
-----------

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<student>
    <age>20</age>
    <gender>M</gender>
    <name>Amar</name>
</student>



Thursday, April 19, 2012

Execute the query with time slot


DELIMITER //
CREATE DEFINER = 'jack@example.com'
EVENT pax_day
ON SCHEDULE EVERY 1 DAY
STARTS '2009-01-14 22:45:00' ENABLE
DO
BEGIN
INSERT INTO paxarchive
SELECT * FROM pax -> WHERE FlightDate <= DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY);
DELETE FROM pax
WHERE FlightDate <=DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY);
END//


DELIMITER $$
alter EVENT employee_hour1
 ON SCHEDULE EVERY 2 minute
 STARTS '2012-04-19 18:20:00' ENABLE
 DO
   BEGIN
     INSERT INTO employees_audit
            set lastname = (SELECT lastname FROM employees
       WHERE employeeNumber = 121),action='mydata',employeeNumber='1265',changedon = NOW();
   END
$$
DELIMITER ;


DELIMITER $$
alter EVENT employee_hour
 ON SCHEDULE EVERY 2 hour
 STARTS '2012-04-19 16:09:00' ENABLE
 DO
   BEGIN
     INSERT INTO employees_audit
            set lastname = (SELECT lastname FROM employees
       WHERE employeeNumber = 120),action='mydata',employeeNumber='1265',changedon = NOW();
   END
$$
DELIMITER ;

MySQL Tiggers

MySQL Tiggers
Introduction to SQL Triggers
SQL trigger is an SQL statements or a set of SQL statements which is stored to be activated or fired when an event associating with a database table occurs. The event can be any event including INSERT, UPDATE  and DELETE.
The difference between a trigger and a stored procedure is that a trigger is activated or called when an event happens in a database table, a stored procedure must be called explicitly. 
Advantages:
SQL trigger provides an alternative way to run scheduled tasks. With SQL trigger, you don’t have to wait to run the scheduled tasks. You can handle those tasks before or after changes being made to database tables
Disadvantages:
SQL trigger only can provide extended validation and cannot replace all the validations. Some simple validations can be done in the application level.  For example, you can validate input check in the client side by using javascript or in the server side by server script using PHP or ASP.NET.

Trigger Implementation in MySQL

While trigger is implemented in MySQL has all features in standard SQL but there are some restrictions you should be aware of like following:
§  It is not allowed to call a stored procedure in a trigger.
§  It is not allowed to create a trigger for views or temporary table.
§  It is not allowed to use transaction in a trigger.
§  Return statement is disallowed in a trigger.
§  Creating a trigger for a database table causes the query cache invalidated. Query cache allows you to store the result of query and corresponding select statement. In the next time, when the same select statement comes to the database server, the database server will use the result which stored in the memory instead of parsing and executing the query again.
§  All trigger for a database table must have unique name. It is allowed that triggers for different tables having the same name but it is recommended that trigger should have unique name in a specific database.  To create the trigger, you can use the following naming convention: (BEFORE | AFTER)_tableName_(INSERT| UPDATE | DELETE)

Creating the first trigger in MySQL

-------- employees------------
CREATE TABLE `employees` (
  `employeeNumber` int(11) NOT NULL,
  `lastName` varchar(50) NOT NULL,
  `firstName` varchar(50) NOT NULL,
  `extension` varchar(10) NOT NULL,
  `email` varchar(100) NOT NULL,
  `officeCode` varchar(10) NOT NULL,
  `reportsTo` int(11) default NULL,
  `jobTitle` varchar(50) NOT NULL,
  PRIMARY KEY  (`employeeNumber`)
)

--------------------- employees_audit--------------
CREATE TABLE employees_audit ( 
id int(11) NOT NULL AUTO_INCREMENT, 
employeeNumber int(11) NOT NULL, 
lastname varchar(50) NOT NULL, 
 
changedon datetime DEFAULT NULL, 
action varchar(50) DEFAULT NULL, 
PRIMARY KEY (id) 
) 
In order to keep track the changes of last name of employee we can create a trigger that is fired before we make any update on the employees table. 
DELIMITER $$
CREATE TRIGGER before_employee_update 
BEFORE UPDATE ON employees
FOR EACH ROW BEGIN
INSERT INTO employees_audit
SET action = 'update',
employeeNumber = OLD.employeeNumber,
lastname = OLD.lastname,
changedon = NOW(); END$$
DELIMITER ;



webservice read the data from xml based on given id

file.xml
-----------

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


<train id="1">
<name>yong</name>
<from>mook kim</from>
<to>mkyong</to>
<arr>100000</arr>
                <dep>324</dep>
</train>
<train id="2">
<name>low</name>
<from>yin fong</from>
<to>fong fong</to>
<arr>200000</arr>
                <dep>525</dep>
</train>
</company>


Train.java:
----------


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.asman;

/**
 *
 * @author laxman
 */
public class Train {
    public String id;
    public String name;
    public String from;
    public String to;
    public String arr;
    public String dep;

}


Trainservice.java

-----------------
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.asman;

import java.io.File;
import java.io.IOException;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author laxman
 */
@WebService()
public class Trainservice {

   
    

    /**
     * Web service operation
     */
    @WebMethod(operationName = "getTraindetails")
    public Train getTraindetails(@WebParam(name = "id")
    String id) throws IOException {
         String name="null";
          String from="null";
          String to="null";
          String arr="null";
          String dep="null";
          Train train=new Train();


File fXmlFile = new File("C:\\Users\\Home\\webservicewithxml\\src\\java\\com\\asman\\file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = null;
        try {
            dBuilder = dbFactory.newDocumentBuilder();
        } catch (ParserConfigurationException ex) {
        }
Document doc = null;
        try {
            doc = dBuilder.parse(fXmlFile);
        } catch (SAXException ex) {
        } catch (IOException ex) {
        }
doc.getDocumentElement().normalize();

System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("train");

for (int temp = 0; temp < nList.getLength(); temp++) {

  Node nNode = nList.item(temp);
  if (nNode.getNodeType() == Node.ELEMENT_NODE) {

     Element eElement = (Element) nNode;
     System.out.println("from loop...."+eElement.getAttribute("id"));
     if(eElement.getAttribute("id").equals(id)){

                    
                     name=getTagValue("name", eElement);
                     from=getTagValue("from", eElement);
                     to=getTagValue("to", eElement);
                     arr=getTagValue("arr", eElement);
                     dep=getTagValue("dep", eElement);

     }
                       train.name=name;
                       train.from=from;
                       train.to=to;
                       train.arr=arr;
                       train.dep=dep;
  }
}



         return train;
    }

  private static String getTagValue(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();

Node nValue = (Node) nlList.item(0);

return nValue.getNodeValue();
  }





}


ClientApplication for above webservice
---------------------------------------------------------------
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package webservicexmlclient;

import com.asman.IOException_Exception;
import com.asman.Train;

/**
 *
 * @author laxman
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException_Exception {

      Train train=  getTraindetails("1");

        System.out.println("tain name"+train.getName());
        System.out.println("train number"+train.getId());
        System.out.println("arraival time"+train.getArr());
        System.out.println("dep timeee"+train.getDep());
        System.out.println("from station"+train.getFrom());
        System.out.println("to station"+train.getTo());
        // TODO code application logic here
    }

    private static Train getTraindetails(java.lang.String id) throws IOException_Exception {
        com.asman.TrainserviceService service = new com.asman.TrainserviceService();
        com.asman.Trainservice port = service.getTrainservicePort();
        return port.getTraindetails(id);
    }

}


webservice connect to database and return object

step1.
        file ->new project-->javweb-->new webapplication
















Read Data from Xml file


XML File

 <book>
<person>
  <first>Kiran</first>
  <last>Pai</last>
  <age>22</age>
</person>
<person>
  <first>Bill</first>
  <last>Gates</last>
  <age>46</age>
</person>
<person>
  <first>Steve</first>
  <last>Jobs</last>
  <age>40</age>
</person>
</book>

Program Output

Root element of the doc is book
Total no of people : 3
First Name : Kiran
Last Name : Pai
Age : 22
First Name : Bill
Last Name : Gates
Age : 46
First Name : Steve
Last Name : Jobs
Age : 40

Program Listing

The Java program to read the above XML file is shown below. Go through the program twice and you will understand all its parts. It may look intimidating at first sight, but believe me its very simple.
import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException; 

public class ReadAndPrintXMLFile{

    public static void main (String argv []){
    try {

            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (new File("book.xml"));

            // normalize text representation
            doc.getDocumentElement ().normalize ();
            System.out.println ("Root element of the doc is " + 
                 doc.getDocumentElement().getNodeName());


            NodeList listOfPersons = doc.getElementsByTagName("person");
            int totalPersons = listOfPersons.getLength();
            System.out.println("Total no of people : " + totalPersons);

            for(int s=0; s<listOfPersons.getLength() ; s++){


                Node firstPersonNode = listOfPersons.item(s);
                if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){


                    Element firstPersonElement = (Element)firstPersonNode;

                    //-------
                    NodeList firstNameList = firstPersonElement.getElementsByTagName("first");
                    Element firstNameElement = (Element)firstNameList.item(0);

                    NodeList textFNList = firstNameElement.getChildNodes();
                    System.out.println("First Name : " + 
                           ((Node)textFNList.item(0)).getNodeValue().trim());

                    //-------
                    NodeList lastNameList = firstPersonElement.getElementsByTagName("last");
                    Element lastNameElement = (Element)lastNameList.item(0);

                    NodeList textLNList = lastNameElement.getChildNodes();
                    System.out.println("Last Name : " + 
                           ((Node)textLNList.item(0)).getNodeValue().trim());

                    //----
                    NodeList ageList = firstPersonElement.getElementsByTagName("age");
                    Element ageElement = (Element)ageList.item(0);

                    NodeList textAgeList = ageElement.getChildNodes();
                    System.out.println("Age : " + 
                           ((Node)textAgeList.item(0)).getNodeValue().trim());

                    //------


                }//end of if clause


            }//end of for loop with s var


        }catch (SAXParseException err) {
        System.out.println ("** Parsing error" + ", line " 
             + err.getLineNumber () + ", uri " + err.getSystemId ());
        System.out.println(" " + err.getMessage ());

        }catch (SAXException e) {
        Exception x = e.getException ();
        ((x == null) ? e : x).printStackTrace ();

        }catch (Throwable t) {
        t.printStackTrace ();
        }
        //System.exit (0);

    }//end of main


}

Tuesday, April 17, 2012

How to convert array of bytes into File


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
 
public class ArrayOfBytesToFile
{
    public static void main( String[] args )
    {
     FileInputStream fileInputStream=null;
 
        File file = new File("C:\\testing.txt");
 
        byte[] bFile = new byte[(int) file.length()];
 
        try {
            //convert file into array of bytes
     fileInputStream = new FileInputStream(file);
     fileInputStream.read(bFile);
     fileInputStream.close();
 
     //convert array of bytes into file
     FileOutputStream fileOuputStream = 
                  new FileOutputStream("C:\\testing2.txt"); 
     fileOuputStream.write(bFile);
     fileOuputStream.close();
 
     System.out.println("Done");
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

How to convert byte[] to BufferedImage in Java


package com.laxman.image;
 
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
 
public class ImageTest {
 
 public static void main(String[] args) {
 
  try {
 
   byte[] imageInByte;
   BufferedImage originalImage = ImageIO.read(new File(
     "c:/darksouls.jpg"));
 
   // convert BufferedImage to byte array
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   ImageIO.write(originalImage, "jpg", baos);
   baos.flush();
   imageInByte = baos.toByteArray();
   baos.close();
 
   // convert byte array back to BufferedImage
   InputStream in = new ByteArrayInputStream(imageInByte);
   BufferedImage bImageFromConvert = ImageIO.read(in);
 
   ImageIO.write(bImageFromConvert, "jpg", new File(
     "c:/new-darksouls.jpg"));
 
  } catch (IOException e) {
   System.out.println(e.getMessage());
  }
 }
}

How to write our own result type in struts2


How to write our own result type in struts2

Action Class


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package com.lkr.action;


import com.lkr.service.UserService;
import com.lkr.vo.User;
import com.opensymphony.xwork2.ActionSupport;


public class GetImageAction extends ActionSupport {


 private static final long serialVersionUID = 1L;
 private UserService userService;
 private Long id;
 private User user;


 public Long getId() {
  return id;
 }


 public void setId(Long id) {
  this.id = id;
 }


 public UserService getUserService() {
  return userService;
 }


 public void setUserService(UserService userService) {
  this.userService = userService;
 }


 @Override
 public String execute() throws Exception {

  System.out.println("this is come from after display image jsp");
  user = userService.getUserById(id);
  return "imageBytesResult";
 }


 public String getContentDisposition() {
  return "";
 }

 public int getBufferSize() {
  return 4096;
 }
}

Result Type Class


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.lkr.action;


import javax.servlet.http.HttpServletResponse;


import org.apache.struts2.ServletActionContext;


import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.Result;


public class ImageBytesResult implements Result {


 private static final long serialVersionUID = 1L;


 @Override
 public void execute(ActionInvocation invocation) throws Exception {
  GetImageAction action = (GetImageAction) invocation.getAction();
  HttpServletResponse response = ServletActionContext.getResponse();


  //response.setContentType(action.getContentType());
  //response.setContentLength(action.getContentLength());
  response.getOutputStream().write(action.getImageInBytes());
  response.getOutputStream().flush();
 }


}

Service


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.lkr.service;


import java.util.List;

import com.lkr.dao.UserDAO;
import com.lkr.vo.User;


public class UserService{
 private UserDAO userDao;


 public UserDAO getUserDao() {
  return userDao;
 }


 public void setUserDao(UserDAO userDao) {
  this.userDao = userDao;
 }


 
 public User save(User user) throws Exception {


  return userDao.save(user);
 }



 public List<User> getAllUsers() throws Exception {


  return userDao.getAllUsers();
 }


 
 public User getUserById(long id) throws Exception {
  return userDao.getUserById(id);
 }
}

DAO


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.lkr.dao;


import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.List;

import org.hibernate.Transaction;

import com.lkr.vo.User;


public class UserDAO {


 
 public User save(User user) throws Exception {
  Transaction tx=getSession().beginTransaction();
  getSession().save(user);
  
  tx.commit();
  return user;
 }


 
 public List<User> getAllUsers() throws Exception {
  List<User> allUsers = getSession().createQuery("from User").list();
  return allUsers;
 }


 
 public User getUserById(long id) throws Exception {
  User user = (User) getSession().get(User.class, new Long(id));
  // Convert BLOB to byte array
  user.setImageInBytes(getImageInBytes(user));
  user.setContentLength((int) user.getImage().length());
  return user;
 }


 public byte[] getImageInBytes(User user) {


  if (user.getImage() == null) {
   return new byte[0];
  }
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  try {
   InputStream is = user.getImage().getBinaryStream();
   byte[] buf = new byte[1024];
   int i = 0;
   while ((i = is.read(buf)) >= 0) {
    baos.write(buf, 0, i);
   }
   is.close();
  } catch (Exception ex) {
   ex.printStackTrace();
  }
  return baos.toByteArray();
 }
}

struts.xml


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?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.devMode" value="false" />
 <constant name="struts.custom.i18n.resources" value="global" />
 <constant name="struts.objectFactory" value="spring" />


 <package name="commonPackage" namespace="/" extends="struts-default">


  <result-types>
   <result-type name="imageBytesResult"
    class="com.lkr.action.ImageBytesResult" />
  </result-types>


  <action name="addUserData" class="com.lkr.action.UserAction">
   <result name="input">
    WEB-INF/jsp/imageUploader.jsp
   </result>
  </action>
  <action name="displayFullImage" class="com.lkr.action.FullImageAction">
   <result name="input">
    WEB-INF/jsp/dispalyFullImage.jsp
   </result>
  </action>


  <action name="getImage" class="com.lkr.action.GetImageAction">
   <result name="imageBytesResult" type="imageBytesResult">
   </result>
  </action>
 </package>


</struts>

If you are directly getting Byte[] from the database then you don't need to convert Blob to Byte[]


Jsp:
-----



<!DOCTYPE HTML>
<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta charset="utf-8">
<title>Tracking Gadget - View User</title>
<link href="style.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="css/menu.css" type="text/css"
media="screen" charset="utf-8">

</head>
<body>



<div id="content">

<!-- scroll -->

<s:form method="post" theme="simple" name="myprofile"
id="myprofile">

<fieldset>
<legend>Licence</legend>
<table width="100%" border="0">
<tr>
<td><img alt="" width="150" height="100"
src="getImage!getImage?id=<s:property value="user.id" />"></td>
</tr>
</table>
</fieldset>


</table> <br />

</s:form>

</div>
</body>
</html>