import java.io.*;
import java.util.*;
import java.sql.*;

import javax.servlet.*;
import javax.servlet.http.*;

import com.oreilly.servlet.MultipartRequest;
import com.sun.image.codec.jpeg.*;
import java.awt.image.*;

public class ServletShow extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) 
	throws ServletException, IOException {
	
	String sql;
	Connection con = null;
	PreparedStatement pstmt;
	ResultSet rs; 
	
	String url = "jdbc:postgresql://sqlserver.sci.univr.it/esercitazioni";

	/** 
	 * Inserire login e passw per l'accesso alla base di dati.
	 */
	
	String user = "";
	String passwd = "";
	
	/** 
	 * Caricamento del driver JDBC per il database
	 */

	try {
             	        Class.forName("org.postgresql.Driver");
	} catch (ClassNotFoundException cnfe) {
                          log("Driver jdbc non trovato: " + cnfe.getMessage());
	}

	
	try {
	    
		sql =  "SELECT * " +
                                               "FROM prova " +
                                               "WHERE codice = 1";
 
          	 /** 
             	     * Connessione alla base di dati
                      */           
           
		 con = DriverManager.getConnection(url, user, passwd);     
	    	pstmt = con.prepareStatement(sql);

            	/** 
            	 * Esecuzione dell'interrogazione
             	*/  
           		 rs=pstmt.executeQuery(); 

	    	response.setContentType("image/jpeg");

	    	while (rs.next()) {
			//FileInputStream fis = rs.getBinaryStream("img");
			InputStream is = rs.getBinaryStream("img");
			JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(is);
			BufferedImage bi = decoder.decodeAsBufferedImage();

			ServletOutputStream sos = response.getOutputStream();
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);
			encoder.encode(bi);
	   	 }
	    	con.close();
		}catch (SQLException sqle) {
	    	sqle.printStackTrace();
		}

    }
}


