[RESOLVIDO] Dúvidas Ireport/JRBeanCollectionDataSource

7 respostas
S

Pessoal, to tentando utilizar o Ireport pra fazer os relatórios da minha aplicação web, usando JRBeanCollectionDataSource.
Tá gerando o relatório em Jasper View, mas não to conseguindo transformá-lo em PDF.

Código:
public String gerarRelatorio() throws JRException, FileNotFoundException {
		
	String dirApp = ("C:/minhaApp/WebContent/WEB-INF/");
	JasperReport report = (JasperReport) JRLoader.loadObject(dirApp + "relatorios/report1.jasper");
	clients = clientDAO.listClientDAO();		
	JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(clients);		
	try {
		JasperPrint impressao = JasperFillManager.fillReport(report, null, ds);
		//JasperViewer viewer = new JasperViewer(impressao, true); 
		//viewer.setVisible(true); -------> Abre uma Jasper View com o relatório
		String dirPdf = (dirApp + "relatorios/report1.pdf");
		JasperExportManager.exportReportToPdfFile(impressao, dirPdf);
		JasperViewer.viewReport(dirPdf, true);
	} catch (JRException e) {
		System.out.println(e.getMessage());
	}
	return "gerarRelatorio";
}
Dúvidas: Linha 03 - Qual a maneira de pegar o diretório (C:/minhaApp/WebContent/WEB-INF/) no contexto do JSF? Uso o Jboss Seam Linha 04 - O correto é o .jasper mesmo? Já vi exemplos utilizando o .jrxml Linha 12 - O método exportReportToPdfFile() não tá gerando o PDF, falta alguma coisa antes disso para que seja gerado? Linha 13 - Dessa maneira exibiria o relatório? Lembrando que é uma app web. Quando chamo o método gerarRelatorio(), gera a seguinte excessão e o servidor para de rodar!
2:34:34,922 INFO  [ServerImpl] Runtime shutdown hook called, forceHalt: true
12:34:34,922 INFO  [Http11Protocol] Pausing Coyote HTTP/1.1 on http-localhost%2F127.0.0.1-8080
12:34:34,922 INFO  [Http11Protocol] Stopping Coyote HTTP/1.1 on http-localhost%2F127.0.0.1-8080
12:34:34,922 INFO  [AjpProtocol] Pausing Coyote AJP/1.3 on ajp-localhost%2F127.0.0.1-8009
12:34:34,922 INFO  [AjpProtocol] Stopping Coyote AJP/1.3 on ajp-localhost%2F127.0.0.1-8009
12:34:34,954 INFO  [ConnectionFactory] org.jboss.jms.server.connectionfactory.ConnectionFactory@ed06ea undeployed
12:34:34,954 INFO  [ConnectionFactory] org.jboss.jms.server.connectionfactory.ConnectionFactory@148392b undeployed
12:34:34,954 INFO  [ConnectionFactory] org.jboss.jms.server.connectionfactory.ConnectionFactory@46554d undeployed
12:34:34,969 INFO  [TomcatDeployment] undeploy, ctxPath=/web-console
12:34:34,985 INFO  [QueueService] Queue[/queue/ExpiryQueue] stopped
12:34:34,985 INFO  [QueueService] Queue[/queue/DLQ] stopped
12:34:35,000 INFO  [SessionSpecContainer] Stopping jboss.j2ee:jar=profileservice-secured.jar,name=SecureProfileService,service=EJB3
12:34:35,016 INFO  [EJBContainer] STOPPED EJB: org.jboss.profileservice.ejb.SecureProfileServiceBean ejbName: SecureProfileService
12:34:35,063 INFO  [SessionSpecContainer] Stopping jboss.j2ee:jar=profileservice-secured.jar,name=SecureDeploymentManager,service=EJB3
12:34:35,079 INFO  [EJBContainer] STOPPED EJB: org.jboss.profileservice.ejb.SecureDeploymentManager ejbName: SecureDeploymentManager
12:34:35,141 INFO  [SessionSpecContainer] Stopping jboss.j2ee:jar=profileservice-secured.jar,name=SecureManagementView,service=EJB3
12:34:35,157 INFO  [EJBContainer] STOPPED EJB: org.jboss.profileservice.ejb.SecureManagementView ejbName: SecureManagementView
12:34:35,204 INFO  [ConnectionFactoryBindingService] Unbound ConnectionManager 'jboss.jca:service=ConnectionFactoryBinding,name=JmsXA' from JNDI name 'java:JmsXA'
12:34:35,235 INFO  [ServerPeer] JMS ServerPeer[0] stopped
12:34:35,235 INFO  [TomcatDeployment] undeploy, ctxPath=/invoker
12:34:35,282 INFO  [TomcatDeployment] undeploy, ctxPath=/jbossws
12:34:35,282 INFO  [TomcatDeployment] undeploy, ctxPath=/admin-console
12:34:35,282 INFO  [TomcatDeployment] undeploy, ctxPath=/
12:34:35,297 INFO  [TomcatDeployment] undeploy, ctxPath=/jmx-console
12:34:35,313 INFO  [TomcatDeployment] undeploy, ctxPath=/InfralogJava2
12:34:35,329 INFO  [SessionFactoryImpl] closing
12:34:35,344 INFO  [StandardService] Stopping service jboss.web
12:34:35,422 INFO  [MailService] Mail service 'java:/Mail' removed from JNDI
12:34:35,485 INFO  [PersistenceUnitDeployment] Stopping persistence unit persistence.unit:unitName=#InfralogJava2
12:34:35,485 INFO  [SessionFactoryImpl] closing
12:34:35,485 INFO  [SessionFactoryObjectFactory] Unbinding factory from JNDI name: persistence.unit:unitName=#InfralogJava2
12:34:35,485 INFO  [NamingHelper] JNDI InitialContext properties:{java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory, java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces}
12:34:35,485 INFO  [SessionFactoryObjectFactory] Unbound factory from JNDI name: persistence.unit:unitName=#InfralogJava2
12:34:35,500 INFO  [ConnectionFactoryBindingService] Unbound ConnectionManager 'jboss.jca:service=DataSourceBinding,name=InfralogJava2Datasource' from JNDI name 'java:InfralogJava2Datasource'
12:34:41,219 INFO  [ConnectionFactoryBindingService] Unbound ConnectionManager 'jboss.jca:service=DataSourceBinding,name=DefaultDS' from JNDI name 'java:DefaultDS'
12:34:41,250 INFO  [QuartzScheduler] Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED shutting down.
12:34:41,250 INFO  [QuartzScheduler] Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED paused.
12:34:41,250 INFO  [SimpleThreadPool] There are still 40 worker threads active. See javadoc runInThread(Runnable) for a possible explanation
12:34:41,250 INFO  [QuartzScheduler] Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED shutdown complete.
12:34:41,579 INFO  [TransactionManagerService] Stopping transaction recovery manager
12:34:41,579 INFO  [TransactionManagerService] Destroying TransactionManagerService
12:34:42,047 INFO  [HypersonicDatabase] Database standalone closed clean
12:34:46,672 INFO  [ServerImpl] Shutdown complete
Shutdown complete
Halting VM

Alguém teria um exemplo de como fazer isso numa aplicação web/jsf?
Abraços!

7 Respostas

fabiocsilva

Dá uma olhada nesse post pra ver se ajuda:

http://www.guj.com.br/posts/list/133449.java

S

fabiocsilva:
Dá uma olhada nesse post pra ver se ajuda:

http://www.guj.com.br/posts/list/133449.java


Valeu velhinho, já tinha visto esse tópico, mas não ajudou muito não, eu uso JSF…

O que preciso mesmo é que alguém, se puder, respondesse minhas dúvidas.

Abraços!

Mero_Aprendiz

Olá,
Acredito que esse tópico aqui além de responder suas dúvidas, pode agilizar o seu desenvolvimento ai.

http://www.guj.com.br/posts/list/76720.java

[]'s
JL

fabiocsilva

ServletContext servletContext = (ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext(); JasperPrint jasperPrint = JasperFillManager.fillReport(servletContext.getRealPath("/WEB-INF/relatorios/report1.jasper");

Sempre use o .jasper a menos que tenha apenas o jrxml, o que não parece ser o caso.

Você deve escrever no outputstream, a menos que queira armazenar o pdf na máquina, o que não parece ser o caso.

ByteArrayOutputStream output = new ByteArrayOutputStream();
                JasperExportManager.exportReportToPdfStream(jasperPrint, output);

Na web você chama o pdf diretamente, ao invés de chamar o jasperview.

HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
    	        response.setContentType("application/pdf");
		response.addHeader("Content-Disposition","attachment;filename=report1.pdf");
		response.setContentLength(output.size());
		ServletOutputStream servletOutputStream = response.getOutputStream();
		servletOutputStream.write(output.toByteArray(), 0, output.size());
		servletOutputStream.flush();
		servletOutputStream.close();
		FacesContext.getCurrentInstance().responseComplete();
S

Valeu aí Mero_aprendiz e Fabio...

Meu método ficou assim:
public String gerarRelatorio() throws JRException, IOException {
	String relatorioPath = ("WEB-INF/relatorios/report1.jasper");
	
	FacesContext facesContext = FacesContext.getCurrentInstance();
	ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
	String pathRel = servletContext.getRealPath(relatorioPath);
	HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
	ServletOutputStream servletOutputStream = response.getOutputStream();
	
	clients = clientDAO.listClientDAO();		
	JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(clients);		
	try {
		JasperPrint print = JasperFillManager.fillReport(pathRel, null, ds);
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		JasperExportManager.exportReportToPdfStream(print, output);
		response.setContentType("application/pdf");  
		response.addHeader("Content-Disposition","attachment;filename=report1.pdf");  
		response.setContentLength(output.size());  
		
		servletOutputStream.write(output.toByteArray(), 0, output.size());  
		servletOutputStream.flush();  
		servletOutputStream.close();  
		facesContext.responseComplete();  
	} catch (JRException e) {
		System.out.println(e.getMessage());
	}
	return "gerarRelatorio";
}
Infelizmente ainda não deu certo, não abriu PDF, apareceu essa excpetion
Exception during request processing: Caused by javax.el.ELException with message: "java.lang.reflect.InvocationTargetException"
na chamada do método exportReportToPdfStream()...saberiam dizer porque?

Agradeço novamente!

fabiocsilva

Posta o log completo, mas ELException está mais pra um problema com tag na página jsf. Dizem pra não utilizar componentes ajax quando se escreve algo no response(como o relatório faz)…

Meu chute :smiley: seria trocar o a4j:commandButton para o h:commandButton.

S

fabiocsilva:
Posta o log completo, mas ELException está mais pra um problema com tag na página jsf. Dizem pra não utilizar componentes ajax quando se escreve algo no response(como o relatório faz)…

Meu chute :smiley: seria trocar o a4j:commandButton para o h:commandButton.


Troquei para o h:commandButton e continuou dando erro, mas aí mostrou um log gigantesco e pude ver o que tava faltando: o arquivo iText-2.1.0.jar

Aí funcionou certinho, valeu galera!!! AGora vou tentar fazer um relatório com parâmetros, vamos ver oque dá!

Abraços

Criado 25 de março de 2010
Ultima resposta 26 de mar. de 2010
Respostas 7
Participantes 3