package tarjetasServlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import m05bClasses.m05bComun;
import m05bClasses.m05bConexion;
import m05bClasses.m05bConstantes;
import m05bClasses.m05bFileLog;

import org.apache.fop.apps.Driver;
import org.apache.fop.apps.FOPException;
import org.xml.sax.InputSource;

public class m05bImpTarjetasCaducidadServlet extends
		javax.servlet.http.HttpServlet {
	java.sql.Connection conn = null;
	String sLinea;
	String sFoFileDir = "/datos/m05b/tmp/";
	File foFileDir;
	File tmpFoFile;
	FileOutputStream tmpFoFileStream;
	m05bComun miComun = new m05bComun();
	m05bFileLog miLog = new m05bFileLog();
	String FechaAlta = "";
	String FechaCaducidad = "";
	String matricula = "";
	String Nombre = "";
	String Tarjeta = "";
	String SituacionLista = "";
	String sNombreAnt = "";
	String fecha = "";
	String sSituacion = "";
	String sOrder1bis = "";

	public static final String FO_REQUEST_PARAM = "fo";

	// Logger log = null;

	public void doPost(javax.servlet.http.HttpServletRequest request,
			javax.servlet.http.HttpServletResponse response)
			throws javax.servlet.ServletException, java.io.IOException {
		try {
			doGet(request, response);
		} catch (Exception e) {
			miLog.addTraza(e);
		}
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException {
		performTask(request, response);
	}

	// if(log == null)
	// {
	// Hierarchy hierarchy = Hierarchy.getDefaultHierarchy();
	// log = hierarchy.getLoggerFor("fop");
	// log.setPriority(Priority.WARN);
	// }

	private void fncAbrirFicheroTemporal() throws java.io.IOException {
		foFileDir = new File(sFoFileDir);
		tmpFoFile = File.createTempFile("m05b", "Fo", foFileDir);
		tmpFoFileStream = new FileOutputStream(tmpFoFile);

	}

	private void fncImprimirFinPagina() throws java.io.IOException {
		sLinea = "	    </fo:table-body>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "       </fo:table>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      </fo:flow>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "   </fo:page-sequence>\n";
		tmpFoFileStream.write(sLinea.getBytes());

	}

	private void fncImprimirComienzoPagina(ResourceBundle res, String idioma)
			throws java.io.IOException, javax.naming.NamingException {
		sLinea = "<fo:page-sequence master-reference=\"general\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		// REGION BEFORE
		sLinea = "		<fo:static-content flow-name=\"xsl-region-before\" >\n";
		tmpFoFileStream.write(sLinea.getBytes());
		// -------------- CABECERA DEL LISTADO --------------
		// Cabecera 1
		sLinea = "      <fo:block text-align=\"end\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      </fo:block>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block font-weight=\"bold\" padding-top=\"10pt\">\n "
				+ res.getString("infTarjCad.titulo") + "</fo:block>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		if (sOrder1bis.equals("2")) {
			sLinea = "      <fo:block font-size=\"8pt\" font-weight=\"bold\" padding-top=\"5pt\">\n "
					+ res.getString("infTarjCad.texto1")
					+ fecha
					+ "<fo:leader leader-pattern=\"space\" leader-length=\"100pt\"/>"
					+ res.getString("infTarjCad.texto2")
					+ sSituacion
					+ "<fo:leader leader-pattern=\"space\" leader-length=\"120pt\"/><![CDATA["
					+ " Nombre:" + Nombre + "]]></fo:block>\n";
		} else {
			sLinea = "      <fo:block font-size=\"8pt\" font-weight=\"bold\" padding-top=\"5pt\">\n "
					+ res.getString("infTarjCad.texto1")
					+ fecha
					+ "<fo:leader leader-pattern=\"space\" leader-length=\"100pt\"/><![CDATA["
					+ res.getString("infTarjCad.texto2")
					+ sSituacion
					+ "]]></fo:block>\n";
		}
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = " 		</fo:static-content>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		// PIE DE PAGINA Pie
		sLinea = "		<fo:static-content flow-name=\"xsl-region-after\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		// PIE DE PAGINA Pie
		sLinea = "      <fo:block >\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "       <fo:table>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-column column-width=\"127mm\"/>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-column column-width=\"125mm\"/>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-body font-family=\"Helvetica\" font-size=\"6pt\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-row>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-cell >\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block text-align=\"left\"><![CDATA["
				+ miComun.getDetFechaActual(idioma)
				+ "]]></fo:block>";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    </fo:table-cell>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-cell >\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block text-align=\"right\">";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "Página <fo:page-number/> \n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "</fo:block>";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    </fo:table-cell>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    </fo:table-row>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    </fo:table-body>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "       </fo:table>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      </fo:block>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = " 		</fo:static-content>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		// BODY
		sLinea = "	<fo:flow flow-name=\"xsl-region-body\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		Context ctx = new InitialContext(System.getProperties());
		// -------------- DETALLE DEL LISTADO --------------
		sLinea = "        <fo:table space-after.optimum=\"12pt\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-column column-width=\"32mm\"/>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-column column-width=\"32mm\"/>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-column column-width=\"32mm\"/>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-column column-width=\"32mm\"/>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-column column-width=\"32mm\"/>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-body font-family=\"Helvetica\" font-size=\"8pt\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-row>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		// Matricula
		sLinea = "	    <fo:table-cell padding-top=\"1mm\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block font-weight=\"bold\"  text-align=\"center\">\n "
				+ res.getString("infTarjCad.col1") + "</fo:block>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    </fo:table-cell>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		// Tarjeta
		sLinea = "	    <fo:table-cell padding-top=\"1mm\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block font-weight=\"bold\" text-align=\"center\">\n "
				+ res.getString("infTarjCad.col2") + "</fo:block>";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    </fo:table-cell>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		// Fecha alta
		sLinea = "	    <fo:table-cell padding-top=\"1mm\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block font-weight=\"bold\"  text-align=\"center\">\n "
				+ res.getString("infTarjCad.col3") + "</fo:block>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    </fo:table-cell>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		// Fecha Baja
		sLinea = "	    <fo:table-cell padding-top=\"1mm\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block font-weight=\"bold\"  text-align=\"center\">\n "
				+ res.getString("infTarjCad.col4") + "</fo:block>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    </fo:table-cell>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		// Banco
		sLinea = "	    <fo:table-cell padding-top=\"1mm\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block font-weight=\"bold\"  text-align=\"center\">\n "
				+ res.getString("infTarjCad.col5") + "</fo:block>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    </fo:table-cell>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    </fo:table-row>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-row >\n";
		tmpFoFileStream.write(sLinea.getBytes());

	}

	public void performTask(javax.servlet.http.HttpServletRequest request,
			javax.servlet.http.HttpServletResponse response)
			throws ServletException {
		java.sql.Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;

		// m05bComun miComun = new m05bComun();

		try {
			HttpSession session = request.getSession(true);
			ResourceBundle res = (ResourceBundle) session
					.getAttribute("resTit");
			/* Iker. idioma */
			Locale idiomaLocal = (Locale) session.getAttribute("Local");
			String idiomaSes = ((idiomaLocal.getLanguage() == null) ? "es"
					: idiomaLocal.getLanguage());

			String campoTexto3 = "C";
			String formatoFecha="dd/MM/yyyy";
			if (!idiomaSes.equals("es")) {
				campoTexto3 = "E";
				formatoFecha = "yyyy/MM/dd";
			}
			m05bConexion miConex = new m05bConexion();
			conn = miConex.getConnection();
			FechaAlta = "";
			FechaCaducidad = "";
			matricula = "";
			Nombre = "";
			Tarjeta = "";
			SituacionLista = "";
			sNombreAnt = "";
			fecha = "";
			sSituacion = "";
			sOrder1bis = "";
			String persona = (String) session.getAttribute("persona");
			m05bFileLog miLog = new m05bFileLog();

			// Obtención de información de BD
			// Vehículo

			fecha = request.getParameter("FAntes");
			if (fecha == null) {
				fecha = "";
			}

			sSituacion = request.getParameter("SituacionTexto");
			if ((sSituacion == null) || (sSituacion.equals(""))) {
				sSituacion = "";
			} else {
				sSituacion = miComun.ListaCaracteres(sSituacion);
			}
			String sOrder1 = request.getParameter("Orden1");
			miLog.addTraza(persona, "Veh ImpTarjetasCaducidadServlet",
					"sOrder1: " + sOrder1, m05bConstantes.LOG_NIVEL_BAJO);
			if (sOrder1 == null || sOrder1.equals("NULL")) {
				sOrder1 = "ASC";
			}
			String sOrder2 = request.getParameter("Orden2");
			miLog.addTraza(persona, "Veh ImpTarjetasCaducidadServlet",
					"sOrder2: " + sOrder2, m05bConstantes.LOG_NIVEL_BAJO);
			if (sOrder2 == null || sOrder2.equals("NULL")) {
				sOrder2 = "ASC";
			}

			sOrder1bis = request.getParameter("Orden1bis");
			miLog.addTraza(persona, "Veh ImpTarjetasCaducidadServlet",
					"sOrder1bis: " + sOrder1bis, m05bConstantes.LOG_NIVEL_BAJO);
			if (sOrder1bis == null || sOrder1bis.equals("NULL")) {
				sOrder1bis = "1";
			}
			String sOrder2bis = request.getParameter("Orden2bis");
			miLog.addTraza(persona, "Veh ImpTarjetasCaducidadServlet",
					"sOrder2bis: " + sOrder2bis, m05bConstantes.LOG_NIVEL_BAJO);
			if (sOrder2bis == null || sOrder2bis.equals("NULL")) {
				sOrder2bis = "2";
			}
			miLog.addTraza(persona, "Veh ImpTarjetasCaducidadServlet",
					"sSituacion: " + sSituacion, m05bConstantes.LOG_NIVEL_BAJO);
			miLog.addTraza(m05bConstantes.LOG_NO_USER,
					"Veh ImpTarjetasCaducidadServlet", "fecha: " + fecha,
					m05bConstantes.LOG_NIVEL_BAJO);

			StringBuffer sql = new StringBuffer();

			sql.append(" SELECT ").append(m05bConstantes.COL_31_TARJETA)
					.append(",");
			sql.append(m05bConstantes.COL_31_MATRICULA).append(", TO_CHAR(");
			sql.append(m05bConstantes.COL_31_FALTA).append(
					",'" + formatoFecha + "'),TO_CHAR(");
			sql.append(m05bConstantes.COL_31_FCADUC).append(
					",'" + formatoFecha + "'),");
			sql.append(m05bConstantes.COL_03_NOMBRE).append(",");
			sql.append(m05bConstantes.COL_34_SITUACION).append(" FROM ");
			sql.append(m05bConstantes.TAB_TARJETAS).append(",");
			sql.append(m05bConstantes.TAB_VEHICULOS).append(",");
			sql.append(m05bConstantes.TAB_BANCOS).append(" WHERE ");
			sql.append(m05bConstantes.COL_31_CUENTA).append(" = ")
					.append(m05bConstantes.COL_03_NCUENTA).append(" AND ");
			sql.append(m05bConstantes.COL_31_MATRICULA).append(" = ")
					.append(m05bConstantes.COL_34_MATRICULA).append(" AND ");
			sql.append(m05bConstantes.COL_31_CUENTA).append(" = ")
					.append(m05bConstantes.COL_03_NCUENTA).append(" AND ");
			sql.append(m05bConstantes.COL_31_MATRICULA).append(" = ")
					.append(m05bConstantes.COL_34_MATRICULA).append(" AND ");
			sql.append(m05bConstantes.COL_31_SITUACION).append(" = '")
					.append(m05bConstantes.TAR_ALTA).append("' ");

			miLog.addTraza(persona, "Veh ImpTarjetasCaducidadServlet", "sql: "
					+ sql, m05bConstantes.LOG_NIVEL_BAJO);
			miLog.addTraza(m05bConstantes.LOG_NO_USER,
					"Veh ImpTarjetasCaducidadServlet", "sql: " + sql,
					m05bConstantes.LOG_NIVEL_BAJO);

			if (!(sSituacion.equals(""))) {
				sql.append(" AND ").append(m05bConstantes.COL_34_SITUACION)
						.append(" in ( ").append(sSituacion).append(" ) ");
			}
			if (!(fecha.equals(""))) {

				sql.append(" AND ").append(m05bConstantes.COL_31_FCADUC)
						.append("<= to_date('").append(fecha)
						.append("','" + formatoFecha + "') ");
			}

			if (sOrder1bis.equals("1")) {
				sql.append(" ORDER BY ").append(m05bConstantes.COL_31_FCADUC)
						.append(" ").append(sOrder1);
				sql.append(" , ").append(m05bConstantes.COL_03_NOMBRE)
						.append(" ").append(sOrder2);
			} else {
				sql.append(" ORDER BY ").append(m05bConstantes.COL_03_NOMBRE)
						.append(" ").append(sOrder2);
				sql.append(" , ").append(m05bConstantes.COL_31_FCADUC)
						.append(" ").append(sOrder1);
			}
			miLog.addTraza(persona, "Veh ImpTarjetasCaducidadServlet", "sql: "
					+ sql, m05bConstantes.LOG_NIVEL_BAJO);
			miLog.addTraza(m05bConstantes.LOG_NO_USER,
					"Veh ImpTarjetasCaducidadServlet", "sql: " + sql,
					m05bConstantes.LOG_NIVEL_BAJO);

			pstmt = conn.prepareStatement(sql.toString());
			rs = pstmt.executeQuery();

			fncAbrirFicheroTemporal();

			sLinea = "<?xml version=\"1.0\" encoding=\"windows-1252\"?>\n";
			tmpFoFileStream.write(sLinea.getBytes());

			sLinea = "<fo:root xmlns:fo=\"http://www.w3.org/1999/XSL/Format\">\n";
			tmpFoFileStream.write(sLinea.getBytes());
			// LAYOUT DEL LISTADO
			sLinea = "<fo:layout-master-set>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "	<fo:simple-page-master master-name=\"general\"  page-height=\"29.5cm\" page-width=\"21cm\" margin-top=\"2cm\" margin-bottom=\"2cm\" margin-left=\"2.5cm\" margin-right=\"2.5cm\">\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "		<fo:region-before extent=\"2cm\"/>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "		<fo:region-body  margin-top=\"2.8cm\" margin-bottom=\"1.5cm\" />\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "		<fo:region-after  extent=\"1cm\"/>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "		<fo:region-start extent=\"0cm\"/>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "		<fo:region-end extent=\"0cm\"/>\n";
			tmpFoFileStream.write(sLinea.getBytes());

			sLinea = "	</fo:simple-page-master>\n";
			tmpFoFileStream.write(sLinea.getBytes());

			sLinea = "</fo:layout-master-set>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			int cont = 0;
			while (rs.next()) {
				Tarjeta = rs.getString(1);
				matricula = rs.getString(2);
				FechaAlta = rs.getString(3);
				FechaCaducidad = rs.getString(4);
				Nombre = rs.getString(5);
				if (((!(Nombre.equals(sNombreAnt))) && (sOrder1bis.equals("2")) && (sNombreAnt != ""))
						|| (cont == 35)) {
					fncImprimirFinPagina();
					fncImprimirComienzoPagina(res, campoTexto3);
					cont = 0;
				} else if (sNombreAnt.equals("")) {
					fncImprimirComienzoPagina(res, campoTexto3);
					cont = 0;
				} else {
					cont = cont + 1;
					sLinea = "	    <fo:table-row >\n";
					tmpFoFileStream.write(sLinea.getBytes());
				}
				sNombreAnt = Nombre;
				// Matricula
				sLinea = "	    <fo:table-cell padding-top=\"2mm\" border-width=\"0.1mm\" border-style=\"solid\">\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "      <fo:block  text-align=\"center\">\n <![CDATA["
						+ matricula + "]]></fo:block>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "	    </fo:table-cell>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				// Tarjeta
				sLinea = "	    <fo:table-cell padding-top=\"2mm\" border-width=\"0.1mm\" border-style=\"solid\">\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "      <fo:block  text-align=\"center\">\n <![CDATA[" + Tarjeta
						+ "]]></fo:block>";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "	    </fo:table-cell>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				// Fecha alta
				sLinea = "	    <fo:table-cell padding-top=\"2mm\" border-width=\"0.1mm\" border-style=\"solid\">\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "      <fo:block  text-align=\"center\">\n<![CDATA["
						+ FechaAlta + "]]></fo:block>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "	    </fo:table-cell>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				// Fecha Caducidad
				sLinea = "	    <fo:table-cell padding-top=\"2mm\" border-width=\"0.1mm\" border-style=\"solid\">\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "      <fo:block  text-align=\"center\">\n<![CDATA["
						+ FechaCaducidad + "]]></fo:block>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "	    </fo:table-cell>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				// Nombre
				sLinea = "	    <fo:table-cell padding-top=\"2mm\" border-width=\"0.1mm\" border-style=\"solid\">\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "      <fo:block  text-align=\"center\">\n<![CDATA[" + Nombre
						+ "]]></fo:block>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "	    </fo:table-cell>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "	    </fo:table-row>\n";
				tmpFoFileStream.write(sLinea.getBytes());
			}
			fncImprimirFinPagina();
			rs.close();

			sLinea = "</fo:root>\n";
			tmpFoFileStream.write(sLinea.getBytes());

			tmpFoFileStream.close();
			// renderFO(new InputSource(file), response);
			generarPDFdesdeFO(sFoFileDir + tmpFoFile.getName(), sFoFileDir,
					response);

			// tmpFoFile.delete();

			// response.flushBuffer();

		} catch (Exception ex) {
			try {
				response.sendRedirect("m05bError.jsp");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				miLog.addTraza(e);
			}
		} finally {
			try {
				if (pstmt != null) {
					rs.close();
					pstmt.close();
				}

			} catch (SQLException e2) {
				try {
					response.sendRedirect("m05bError.jsp");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					miLog.addTraza(e);
				}
			}
		}
	}

	/**
	 * renders an FO inputsource into a PDF file which is rendered directly to
	 * the response object's OutputStream
	 */
	public void renderFO(InputSource foFile, HttpServletResponse response)
			throws ServletException {
		try {
			ByteArrayOutputStream out = new ByteArrayOutputStream();

			response.reset();
			OutputStream oOut = response.getOutputStream();
			BufferedOutputStream bOut = new BufferedOutputStream(oOut);
			Driver driver = new Driver(foFile, out);
			driver.setRenderer(Driver.RENDER_PDF);
			driver.run();

			response.setContentLength(out.size());
			response.setContentType("application/pdf");

			bOut.write(out.toByteArray());
			out.close();
			bOut.flush();
			bOut.close();
			// response.flushBuffer();
		} catch (Exception ex) {
			throw new ServletException(ex);
		}
	}

	public void generarPDFdesdeFO(String ficheroFO, String rutaPDF,
			HttpServletResponse response) throws FOPException {
		try {

			Driver driver = new Driver();

			driver.setRenderer(Driver.RENDER_PDF);

			// Si no existe el directrio lo crea
			File f = new File(rutaPDF);

			if (!f.exists()) {

				f.mkdir();

			}
			// Cargar los datos del .FO
			FileInputStream file = new FileInputStream(ficheroFO);

			BufferedInputStream bfile = new BufferedInputStream(file);

			driver.setInputSource(new InputSource(bfile));

			// Crear un temporal que va a ser el .pdf
			String sPdfFileDir = rutaPDF;
			File pdfFileDir = new File(sPdfFileDir);
			File tmpPdfFile = File.createTempFile("m05b", ".pdf", pdfFileDir);

			FileOutputStream fileout = new FileOutputStream(tmpPdfFile);

			BufferedOutputStream bfileout = new BufferedOutputStream(fileout);

			driver.setOutputStream(bfileout);

			driver.run();

			bfile.close();

			bfileout.close();
			// Longitus del Fichero PDF.
			Long longitud = new Long(tmpPdfFile.length());
			String sLongitud = "" + longitud;
			int iLongitud = Integer.parseInt(sLongitud);

			response.setContentLength((int) iLongitud);
			response.setContentType("application/pdf");

			byte[] fileBytes = new byte[longitud.intValue()];
			FileInputStream fisficheroPdf = new FileInputStream(tmpPdfFile);
			fisficheroPdf.read(fileBytes);
			ServletOutputStream os = response.getOutputStream();
			((OutputStream) os).write(fileBytes);
			((OutputStream) os).flush();
			((OutputStream) os).close();

			// BORRAR EL FICHERO FO

			File fichero = new File(ficheroFO);

			boolean borrado = fichero.delete();
			boolean borrado2 = tmpPdfFile.delete();

		} catch (Exception e) {

			// System.out.println("EXCEPCION !!! : Error pasando de FO a PDF: "
			// + e);

		}

	}

}