View Javadoc
1   package ecar.servlet.relatorio;
2   
3   import java.io.ByteArrayInputStream;
4   import java.io.ByteArrayOutputStream;
5   import java.io.File;
6   import java.io.FileOutputStream;
7   import java.io.IOException;
8   
9   
10  import javax.servlet.ServletException;
11  import javax.servlet.http.HttpServlet;
12  import javax.servlet.http.HttpServletRequest;
13  import javax.servlet.http.HttpServletResponse;
14  import javax.xml.transform.sax.SAXSource;
15  import javax.xml.transform.sax.SAXTransformerFactory;
16  import javax.xml.transform.stream.StreamResult;
17  import javax.xml.transform.stream.StreamSource;
18  
19  import org.apache.fop.apps.Driver;
20  import org.apache.fop.image.FopImageFactory;
21  import org.apache.log4j.Logger;
22  import org.xml.sax.InputSource;
23  import org.xml.sax.XMLFilter;
24  
25  import ecar.exception.ECARException;
26  
27  /**
28   * @author fabios
29   */
30  public abstract class AbstractServletReportXmlXsl extends HttpServlet {
31  
32  	protected Logger logger = null;
33  	
34  	public static String SAIDA_DOWNLOAD = "SAIDA_DOWNLOAD"; 
35  	public static String SAIDA_GRAVAR = "SAIDA_GRAVAR"; 
36  	public static String SAIDA_DOWNLOAD_E_GRAVAR = "SAIDA_DOWNLOAD_E_GRAVAR"; 
37  
38  	private String saida = SAIDA_DOWNLOAD;
39  	private String caminhoArquivoSaidaGravar = "";
40      
41  	
42  	/**
43  	 * Construtor.<br>
44  	 */
45      public AbstractServletReportXmlXsl() {
46          this.logger = Logger.getLogger(this.getClass());
47      }
48  
49      /**
50       * Retorna String saida.<br>
51       * 
52       * @author N/C
53       * @since N/C
54       * @version N/C
55       * @return String
56       */
57      public String getSaida() {
58  		return saida;
59  	}
60  
61      /**
62       * Atribui velor especificado para String saida.<br>
63       * 
64       * @author N/C
65       * @since N/C
66       * @version N/C
67       * @param String saida
68       */
69  	public void setSaida(String saida) {
70  		this.saida = saida;
71  	}
72  
73  	/**
74  	 * Prepara relatorio para ser impresso, mesclando XSL e XML.<br>
75  	 * 
76  	 * @author N/C
77       * @since N/C
78       * @version N/C
79  	 * @param HttpServletRequest request
80  	 * @param HttpServletResponse response
81  	 * @throws ECARException
82  	 * @throws IOException
83  	 */
84  	
85  	public final void service(HttpServletRequest request, HttpServletResponse response)
86      	throws ServletException, IOException {
87  
88  		String filesPath = this.getServletContext().getRealPath(File.separator + "relatorios" + File.separator + "xsl");
89  		String imagesPath = this.getServletContext().getRealPath(File.separator + "images" + File.separator + "relAcomp");
90  		String xslPath = filesPath + File.separator + getXslFileName();
91  
92  		String protocol = ( request.getRequestURL().indexOf("https") == 0 ? "https://" : "http://" );
93  		org.apache.fop.configuration.Configuration.put("baseDir", protocol + request.getLocalName() + ":" + request.getLocalPort() + request.getContextPath() + "/");
94  		
95          try {
96          	
97          	FopImageFactory.resetCache();
98              StringBuffer relatorio = getXml(request);
99              String tipoArquivoRelatorio = request.getParameter("tipoArquivoRelatorio"); 
100             
101             // Adicionado if que possibilita a geração do relatório em PPT
102             if (tipoArquivoRelatorio!=null && tipoArquivoRelatorio.equals("ppt")) {
103             	parserPPT(imagesPath, relatorio, request, response);
104             } else {
105             	parser(new File(xslPath), relatorio, response);
106             }
107                         
108         } catch (ECARException e) {
109         	this.logger.error(e);
110             response.sendRedirect(getErrorPage(request, e.getMessageKey()));
111         }
112     }
113     
114 	/**
115 	 * 
116 	 * 
117 	 * @author N/C
118      * @since N/C
119      * @version N/C
120 	 * @param HttpServletRequest request
121 	 * @return StringBuffer
122 	 * @throws ECARException
123 	 */
124     public abstract StringBuffer getXml(HttpServletRequest request) throws ECARException;
125     
126     /**
127      * @author N/C
128      * @since N/C
129      * @version N/C
130      * @return String
131      */
132     public abstract String getXslFileName();
133     
134     /**
135      * @author N/C
136      * @since N/C
137      * @version N/C
138      * @param HttpServletRequest request
139      * @param String mensagem
140      * @return String
141      */
142     public abstract String getErrorPage(HttpServletRequest request, String mensagem);
143     
144     /**
145      * Mescla dados do XML com XSL.<br>
146      * 
147      * @author N/C
148      * @since N/C
149      * @version N/C
150      * @param String stylesheet
151      * @param StringBuffer xml
152      * @param HttpServletResponse response
153      * @throws ECARException
154      */
155     private void parser(File stylesheet , StringBuffer xml, HttpServletResponse response) throws ECARException{    	
156         try{
157 			InputSource xmlSource = new InputSource(new ByteArrayInputStream(xml.toString().getBytes("ISO-8859-1")));
158 			//XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
159 			// arquivo onde vai ser gerado o FO
160 	        ByteArrayOutputStream outFo = new ByteArrayOutputStream();
161 
162 			//java.io.PrintWriter out = response.getWriter();
163 			StreamResult result = new StreamResult(outFo);
164 			XMLFilter style = null;
165 			SAXTransformerFactory stf = (SAXTransformerFactory)SAXTransformerFactory.newInstance();
166 			try{
167 				StreamSource ss = new StreamSource(stylesheet);
168 				style = stf.newXMLFilter(ss);
169 			}catch(javax.xml.transform.TransformerConfigurationException ex){
170 			    logger.error(ex);
171 			}
172 
173 			SAXSource transformSource = new SAXSource(style, xmlSource);
174 			stf.newTransformer().transform(transformSource, result);
175            
176 			outFo.close();
177 
178 	        InputSource foInput = new InputSource(new ByteArrayInputStream(outFo.toByteArray()));
179 
180 	        ByteArrayOutputStream outPdf = new ByteArrayOutputStream();
181 
182    	        //response.setHeader("Content-Disposition", "attachment; filename=\"MyFile.pdf\""); //$NON-NLS-1$ //$NON-NLS-2$
183 	        response.setHeader("Content-Disposition","inline");
184 	        response.setContentType("application/pdf");
185 	        
186 			// instanciando o driver FOP para fazer a renderização do documento
187             Driver driver = new Driver(foInput, outPdf);
188            	// setando o tipo da renderização a ser aplicada (PDF)
189             driver.setRenderer(Driver.RENDER_PDF);            
190           
191             driver.run();
192 
193             byte[] content = outPdf.toByteArray();
194             
195             if(SAIDA_DOWNLOAD.equals(this.getSaida()) || SAIDA_DOWNLOAD_E_GRAVAR.equals(this.getSaida())) {
196 	            response.setContentLength(content.length);
197 	            response.getOutputStream().write(content);
198 	            response.getOutputStream().flush();
199 				response.getOutputStream().close();
200             } 
201             
202             if(SAIDA_GRAVAR.equals(this.getSaida()) || SAIDA_DOWNLOAD_E_GRAVAR.equals(this.getSaida())) {
203             	FileOutputStream arq = new FileOutputStream(this.getCaminhoArquivoSaidaGravar());
204             	arq.write(content);
205             	arq.flush();
206             	arq.close();
207             }
208 		}catch(Exception e){
209     		this.logger.error(e);
210 			throw new ECARException("Erro na renderizacao do arquivo PDF");
211 		}
212     }
213 
214     /**
215      * Mescla dados do XML com XSL e exporta o relatorio para PPT.<br>
216      * 
217      * @author N/C
218      * @since N/C
219      * @version N/C
220      * @param String stylesheet
221      * @param StringBuffer xml
222      * @param HttpServletResponse response
223      * @throws ECARException
224      */
225     private void parserPPT(String caminhoImagens, StringBuffer xml, HttpServletRequest request, HttpServletResponse response) throws ECARException{    	
226         try{
227 			        	        	
228         	MontaPPT paserXMLPPT = new MontaPPT();
229         	paserXMLPPT.parserXMLPPT(xml, caminhoImagens, request, response);     	
230         		
231 		}catch(Exception e){
232     		this.logger.error(e);
233 			throw new ECARException("Erro na renderizacao do arquivo PDF");
234 		}
235     }
236         
237     /**
238      * Retorna String caminhoArquivoSaidaGravar.<br>
239      * 
240      * @author N/C
241      * @since N/C
242      * @version N/C
243      * @return String - (caminhoArquivoSaidaGravar)
244      */
245 	public String getCaminhoArquivoSaidaGravar() {
246 		return caminhoArquivoSaidaGravar;
247 	}
248 
249 	/**
250 	 * Atribui valor especificado para String caminhoArquivoSaidaGravar.<br>
251 	 * 
252 	 * @author N/C
253      * @since N/C
254      * @version N/C
255 	 * @param String caminhoArquivoSaidaGravar
256 	 */
257 	public void setCaminhoArquivoSaidaGravar(String caminhoArquivoSaidaGravar) {
258 		this.caminhoArquivoSaidaGravar = caminhoArquivoSaidaGravar;
259 	}
260 	
261 	
262 	
263 }