ImageViewer.java
上传用户:psq1974
上传日期:2007-01-06
资源大小:1195k
文件大小:12k
源码类别:

mpeg/mp3

开发平台:

C/C++

  1. package example;
  2. import java.awt.*;
  3. import java.awt.event.*;
  4. import java.io.*;
  5. import java.sql.*;
  6. import postgresql.largeobject.*;
  7. /**
  8.  * This example is a small application that stores and displays images
  9.  * held on a postgresql database.
  10.  *
  11.  * Before running this application, you need to create a database, and
  12.  * on the first time you run it, select "Initialise" in the "PostgreSQL"
  13.  * menu.
  14.  *
  15.  * Important note: You will notice we import the postgresql.largeobject
  16.  * package, but don't import the postgresql package. The reason for this is
  17.  * that importing postgresql can confuse javac (we have conflicting class names
  18.  * in postgresql.* and java.sql.*). This doesn't cause any problems, as long
  19.  * as no code imports postgresql.
  20.  *
  21.  * Under normal circumstances, code using any jdbc driver only needs to import
  22.  * java.sql, so this isn't a problem.
  23.  *
  24.  * It's only if you use the non jdbc facilities, do you have to take this into
  25.  * account.
  26.  *
  27.  * Note: For PostgreSQL 6.4, the driver is now Thread safe, so this example
  28.  * application has been updated to use multiple threads, especially in the
  29.  * image storing and retrieving methods.
  30.  */
  31. public class ImageViewer implements ItemListener
  32. {
  33.   Connection db;
  34.   Statement stat;
  35.   LargeObjectManager lom;
  36.   Frame frame;
  37.   Label label; // Label used to display the current name
  38.   List list; // The list of available images
  39.   imageCanvas canvas; // Canvas used to display the image
  40.   String currentImage; // The current images name
  41.   
  42.   // This is a simple component to display our image
  43.   public class imageCanvas extends Canvas
  44.   {
  45.     // holds the image
  46.     private Image image;
  47.     
  48.     // holds the background buffer
  49.     private Image bkg;
  50.     
  51.     // the size of the buffer
  52.     private Dimension size;
  53.     
  54.     public imageCanvas()
  55.     {
  56.       image=null;
  57.     }
  58.     
  59.     public void setImage(Image img)
  60.     {
  61.       image=img;
  62.       repaint();
  63.     }
  64.     
  65.     // This defines our minimum size
  66.     public Dimension getMinimumSize()
  67.     {
  68.       return new Dimension(400,400);
  69.     }
  70.     
  71.     public Dimension getPreferedSize()
  72.     {
  73.       return getMinimumSize();
  74.     }
  75.     
  76.     public void update(Graphics g)
  77.     {
  78.       paint(g);
  79.     }
  80.     
  81.     /**
  82.      * Paints the image, using double buffering to prevent screen flicker
  83.      */
  84.     public void paint(Graphics gr)
  85.     {
  86.       Dimension s = getSize();
  87.       
  88.       if(size==null || bkg==null || !s.equals(size)) {
  89. size = s;
  90. bkg = createImage(size.width,size.height);
  91.       }
  92.       
  93.       // now set the background
  94.       Graphics g = bkg.getGraphics();
  95.       g.setColor(Color.gray);
  96.       g.fillRect(0,0,s.width,s.height);
  97.       
  98.       // now paint the image over the background
  99.       if(image!=null)
  100. g.drawImage(image,0,0,this);
  101.       
  102.       // dispose the graphics instance
  103.       g.dispose();
  104.       
  105.       // paint the image onto the component
  106.       gr.drawImage(bkg,0,0,this);
  107.       
  108.     }
  109.     
  110.   }
  111.   
  112.   public ImageViewer(Frame f,String url,String user,String password) throws ClassNotFoundException, FileNotFoundException, IOException, SQLException
  113.   {
  114.     frame = f;
  115.     
  116.     MenuBar mb = new MenuBar();
  117.     Menu m;
  118.     MenuItem i;
  119.     
  120.     f.setMenuBar(mb);
  121.     mb.add(m = new Menu("PostgreSQL"));
  122.     m.add(i= new MenuItem("Initialise"));
  123.     i.addActionListener(new ActionListener() {
  124.       public void actionPerformed(ActionEvent e) {
  125. ImageViewer.this.init();
  126.       }
  127.     });
  128.     
  129.     m.add(i= new MenuItem("Exit"));
  130.     ActionListener exitListener = new ActionListener() {
  131.       public void actionPerformed(ActionEvent e) {
  132. ImageViewer.this.close();
  133.       }
  134.     };
  135.     m.addActionListener(exitListener);
  136.     
  137.     mb.add(m = new Menu("Image"));
  138.     m.add(i= new MenuItem("Import"));
  139.     ActionListener importListener = new ActionListener() {
  140.       public void actionPerformed(ActionEvent e) {
  141. ImageViewer.this.importImage();
  142.       }
  143.     };
  144.     i.addActionListener(importListener);
  145.     
  146.     m.add(i= new MenuItem("Remove"));
  147.     ActionListener removeListener = new ActionListener() {
  148.       public void actionPerformed(ActionEvent e) {
  149. ImageViewer.this.removeImage();
  150.       }
  151.     };
  152.     i.addActionListener(removeListener);
  153.     
  154.     // To the north is a label used to display the current images name
  155.     f.add("North",label = new Label());
  156.     
  157.     // We have a panel to the south of the frame containing the controls
  158.     Panel p = new Panel();
  159.     p.setLayout(new FlowLayout());
  160.     Button b;
  161.     p.add(b=new Button("Refresh List"));
  162.     b.addActionListener(new ActionListener() {
  163.       public void actionPerformed(ActionEvent e) {
  164. ImageViewer.this.refreshList();
  165.       }
  166.     });
  167.     p.add(b=new Button("Import new image"));
  168.     b.addActionListener(importListener);
  169.     p.add(b=new Button("Remove image"));
  170.     b.addActionListener(removeListener);
  171.     p.add(b=new Button("Quit"));
  172.     b.addActionListener(exitListener);
  173.     f.add("South",p);
  174.     
  175.     // And a panel to the west containing the list of available images
  176.     f.add("West",list=new List());
  177.     list.addItemListener(this);
  178.     
  179.     // Finally the centre contains our image
  180.     f.add("Center",canvas = new imageCanvas());
  181.     
  182.     // Load the driver
  183.     Class.forName("postgresql.Driver");
  184.     
  185.     // Connect to database
  186.     System.out.println("Connecting to Database URL = " + url);
  187.     db = DriverManager.getConnection(url, user, password);
  188.     
  189.     // Create a statement
  190.     stat = db.createStatement();
  191.     
  192.     // Also, get the LargeObjectManager for this connection
  193.     lom = ((postgresql.Connection)db).getLargeObjectAPI();
  194.     
  195.     // Now refresh the image selection list
  196.     refreshList();
  197.   }
  198.   
  199.   
  200.   /**
  201.    * This method initialises the database by creating a table that contains
  202.    * the image names, and Large Object OID's
  203.    */
  204.   public void init()
  205.   {
  206.     try {
  207.       stat.executeUpdate("create table images (imgname name,imgoid oid)");
  208.       label.setText("Initialised database");
  209.     } catch(SQLException ex) {
  210.       label.setText(ex.toString());
  211.     }
  212.   }
  213.   
  214.   /**
  215.    * This closes the connection, and ends the application
  216.    */
  217.   public void close()
  218.   {
  219.     try {
  220.       db.close();
  221.     } catch(SQLException ex) {
  222.       System.err.println(ex.toString());
  223.     }
  224.     System.exit(0);
  225.   }
  226.   
  227.   /**
  228.    * This imports an image into the database, using a Thread to do this in the
  229.    * background.
  230.    */
  231.   public void importImage()
  232.   {
  233.     FileDialog d = new FileDialog(frame,"Import Image",FileDialog.LOAD);
  234.     d.setVisible(true);
  235.     String name = d.getFile();
  236.     String dir = d.getDirectory();
  237.     d.dispose();
  238.     
  239.     // now start the true importer
  240.     Thread t = new importer(db,name,dir);
  241.     //t.setPriority(Thread.MAX_PRIORITY);
  242.     t.start();
  243.   }
  244.   
  245.   /**
  246.    * This is an example of using a thread to import a file into a Large Object.
  247.    * It uses the Large Object extension, to write blocks of the file to the
  248.    * database.
  249.    */
  250.   class importer extends Thread
  251.   {
  252.     String name,dir;
  253.     Connection db;
  254.     
  255.     public importer(Connection db,String name,String dir) {
  256.       this.db = db;
  257.       this.name = name;
  258.       this.dir = dir;
  259.     }
  260.     
  261.     public void run() {
  262.       
  263.       // Now the real import stuff
  264.       if(name!=null && dir!=null) {
  265. Statement stat = null;
  266. try {
  267.   // fetch the large object manager
  268.   LargeObjectManager lom = ((postgresql.Connection)db).getLargeObjectAPI();
  269.   
  270.   System.out.println("Importing file");
  271.   // A temporary buffer - this can be as large as you like
  272.   byte buf[] = new byte[2048];
  273.   
  274.   // Open the file
  275.   System.out.println("Opening file "+dir+"/"+name);
  276.   FileInputStream fis = new FileInputStream(new File(dir,name));
  277.   
  278.   // Gain access to large objects
  279.   System.out.println("Gaining LOAPI");
  280.   
  281.   // Now create the large object
  282.   System.out.println("creating blob");
  283.   int oid = lom.create();
  284.   
  285.   System.out.println("Opening "+oid);
  286.   LargeObject blob = lom.open(oid);
  287.   
  288.   // Now copy the file into the object.
  289.   //
  290.   // Note: we dont use write(buf), as the last block is rarely the same
  291.   // size as our buffer, so we have to use the amount read.
  292.   System.out.println("Importing file");
  293.   int s,t=0;
  294.   while((s=fis.read(buf,0,buf.length))>0) {
  295.     System.out.println("Block s="+s+" t="+t);t+=s;
  296.     blob.write(buf,0,s);
  297.   }
  298.   
  299.   // Close the object
  300.   System.out.println("Closing blob");
  301.   blob.close();
  302.   
  303.   // Now store the entry into the table
  304.   
  305.   // As we are a different thread to the other window, we must use
  306.   // our own thread
  307.   stat = db.createStatement();
  308.   stat.executeUpdate("insert into images values ('"+name+"',"+oid+")");
  309.   
  310.   // Finally refresh the names list, and display the current image
  311.   ImageViewer.this.refreshList();
  312.   ImageViewer.this.displayImage(name);
  313. } catch(Exception ex) {
  314.   label.setText(ex.toString());
  315. } finally {
  316.   // ensure the statement is closed after us
  317.   try {
  318.     if(stat != null)
  319.       stat.close();
  320.   } catch(SQLException se) {
  321.     System.err.println("closing of Statement failed");
  322.   }
  323. }
  324.       }
  325.     }
  326.   }
  327.   
  328.   /**
  329.    * This refreshes the list of available images
  330.    */
  331.   public void refreshList()
  332.   {
  333.     try {
  334.       // First, we'll run a query, retrieving all of the image names
  335.       ResultSet rs = stat.executeQuery("select imgname from images order by imgname");
  336.       if(rs!=null) {
  337. list.removeAll();
  338. while(rs.next())
  339.   list.addItem(rs.getString(1));
  340. rs.close();
  341.       }
  342.     } catch(SQLException ex) {
  343.       label.setText(ex.toString()+" Have you initialised the database?");
  344.     }
  345.   }
  346.   
  347.   /**
  348.    * This removes an image from the database
  349.    *
  350.    * Note: With postgresql, this is the only way of deleting a large object
  351.    * using Java.
  352.    */
  353.   public void removeImage()
  354.   {
  355.     try {
  356.       // Delete any large objects for the current name
  357.       ResultSet rs = stat.executeQuery("select imgoid from images where imgname='"+currentImage+"'");
  358.       if(rs!=null) {
  359. // Even though there should only be one image, we still have to
  360. // cycle through the ResultSet
  361. while(rs.next()) {
  362.   System.out.println("Got oid "+rs.getInt(1));
  363.   lom.delete(rs.getInt(1));
  364.   System.out.println("Import complete");
  365. }
  366.       }
  367.       rs.close();
  368.       
  369.       // Finally delete any entries for that name
  370.       stat.executeUpdate("delete from images where imgname='"+currentImage+"'");
  371.       
  372.       label.setText(currentImage+" deleted");
  373.       currentImage=null;
  374.       refreshList();
  375.     } catch(SQLException ex) {
  376.       label.setText(ex.toString());
  377.     }
  378.   }
  379.   
  380.   /**
  381.    * This displays an image from the database.
  382.    *
  383.    * For images, this is the easiest method.
  384.    */
  385.   public void displayImage(String name)
  386.   {
  387.     try {
  388.       System.out.println("Selecting oid for "+name);
  389.       ResultSet rs = stat.executeQuery("select imgoid from images where imgname='"+name+"'");
  390.       if(rs!=null) {
  391. // Even though there should only be one image, we still have to
  392. // cycle through the ResultSet
  393. while(rs.next()) {
  394.   System.out.println("Got oid "+rs.getInt(1));
  395.   canvas.setImage(canvas.getToolkit().createImage(rs.getBytes(1)));
  396.   System.out.println("Import complete");
  397.   label.setText(currentImage = name);
  398. }
  399.       }
  400.       rs.close();
  401.     } catch(SQLException ex) {
  402.       label.setText(ex.toString());
  403.     }
  404.   }
  405.   
  406.   public void itemStateChanged(ItemEvent e) {
  407.     displayImage(list.getItem(((Integer)e.getItem()).intValue()));
  408.   }
  409.   
  410.   /**
  411.    * This is the command line instructions
  412.    */
  413.   public static void instructions()
  414.   {
  415.     System.err.println("java example.ImageViewer jdbc-url user password");
  416.     System.err.println("nExamples:n");
  417.     System.err.println("java -Djdbc.driver=postgresql.Driver example.ImageViewer jdbc:postgresql:test postgres passwordn");
  418.     
  419.     System.err.println("This example tests the binary large object api of the driver.nBasically, it will allow you to store and view images held in the database.");
  420.     System.err.println("Note: If you are running this for the first time on a particular database,nyou have to select "Initialise" in the "PostgreSQL" menu.nThis will create a table used to store image names.");
  421.   }
  422.   
  423.   /**
  424.    * This is the application entry point
  425.    */
  426.   public static void main(String args[])
  427.   {
  428.     if(args.length!=3) {
  429.       instructions();
  430.       System.exit(1);
  431.     }
  432.     
  433.     try {
  434.       Frame frame = new Frame("PostgreSQL ImageViewer v6.4 rev 1");
  435.       frame.setLayout(new BorderLayout());
  436.       ImageViewer viewer = new ImageViewer(frame,args[0],args[1],args[2]);
  437.       frame.pack();
  438.       frame.setVisible(true);
  439.     } catch(Exception ex) {
  440.       System.err.println("Exception caught.n"+ex);
  441.       ex.printStackTrace();
  442.     }
  443.   }
  444. }