Boa Noite Galera…
Iniciante é fogo mesmo né
Seguinte to desenvolvendo um sistema de pedidos estou usando o Mentawai como Framework MVC…
E agora preciso apresentar alguns relatórios na tela…
E como a algum tempo atras vi o PortalJavaSuport resolvi pegar 2 classes dele que servem para gerar os relatórios e apresentar na tela.
Abaixo segue a classe.
package principal.consequence;
import java.io.ByteArrayOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import *.;
public class JasperConsequence implements Consequence {
public static String TYPE_PDF = "pdf";
public static String TYPE_XLS = "xls";
public static String TYPE_CSV = "csv";
public static String TYPE_DOC = "doc";
public static String TYPE_XML = "xml";
public static String TYPE_HTML = "html";
public static String REPORT_ON_FILE = "FILE";
public static String REPORT_ON_BROWSER = "BROWSER";
public static final String REPORT_BEAN_KEY = "reportBean";
private String report_bean_key = REPORT_BEAN_KEY;
private JasperConsequenceBean JCB;
// referencias para facilitar o acesso dentro da classe
private HttpServletRequest request;
private HttpServletResponse response;
public JasperConsequence() {
this.init();
}
public JasperConsequence(String report_bean_key) {
this.init();
this.report_bean_key = report_bean_key;
}
private void init() {
this.JCB = null;
this.request = null;
this.response = null;
}
public void execute(
Action a,
HttpServletRequest req,
HttpServletResponse res
) throws ConsequenceException {
this.request = req;
this.response = res;
Output output = a.getOutput();
Object obj = output.getValue( this.report_bean_key );
try {
if (obj instanceof JasperConsequenceBean ) {
this.JCB = (JasperConsequenceBean)obj;
this.processamento();
} else {
throw new ConsequenceException("Cannot find reportBean: " + this.report_bean_key );
}
} catch ( Exception e ) {
throw new ConsequenceException(e);
}
}
private void processamento() throws Exception {
// chamando método para definir o cabeçalho
this.defineHeader();
// definindo o exportador
JRExporter exporter = this.getJRExporter( this.JCB.getReportFileType() );
// gera o relatório em memória
JasperPrint printer = JasperFillManager.fillReport(
JasperConsequence.class.getResourceAsStream( this.JCB.getReportFileModel() ),
this.JCB.getReportParameters(),
new JRBeanCollectionDataSource( this.JCB.getReportDataList() )
);
// lista de bytes do arquivo carregado em memória
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// seta o objeto 'baos' como parametro de streamming de saida no objeto 'exporter'
exporter.setParameter( JRExporterParameter.OUTPUT_STREAM, baos );
// seta o objeto 'printer' como parametro de impressao no objeto 'exporter'
exporter.setParameter( JRExporterParameter.JASPER_PRINT, printer);
// seta a codificação dos caracteres como parametro de impressao no objeto 'exporter'
exporter.setParameter( JRExporterParameter.CHARACTER_ENCODING, "ISO-8859-9");
// exporta o relatório com a saida escolha em memória (formato Streamming)
exporter.exportReport();
// informa o tamanho total do arquivo
this.response.setContentLength( baos.size() );
// escreve o relatório na memória do objeto 'response'
this.response.getOutputStream().write( baos.toByteArray() ) ;
this.response.getOutputStream().flush();
// libera a memória
baos.flush();
// fecha o arquivo em memória
baos.close();
private void defineHeader() {
if(
( this.JCB.getReportFileType() != null ) &&
( this.JCB.getReportFileType().trim().length() > 0 )
) {
this.response.setContentType( this.getContentType( this.JCB.getReportFileType() ) );
}
else {
this.response.setContentType( this.getContentType( TYPE_PDF ) );
this.JCB.setReportFileType( TYPE_PDF );
}
// String para setar no response
String contentDisposition = "";
if(
( this.JCB.getVisualizeOn() != null ) &&
( this.JCB.getVisualizeOn().trim().length() > 0 )
) {
if( ( this.JCB.getVisualizeOn().toUpperCase().equals( REPORT_ON_BROWSER ) ) &&
( this.canShowOnBrowser( this.JCB.getReportFileType() ) ) ) {
contentDisposition += "inline; ";
} else {
contentDisposition += "attachment; ";
}
}
if(
( this.JCB.getReportFileName() != null ) &&
( this.JCB.getReportFileName().trim().length() > 0 )
) {
contentDisposition += "filename=" + this.JCB.getReportFileName();
}
this.response.setHeader( "Content-Disposition", contentDisposition );
}
private String getContentType( String fileType ) {
if( fileType.equals( TYPE_PDF ) ) {
return "application/pdf";
} else if( fileType.equals( TYPE_XLS ) ) {
return "application/vnd.ms-excel";
} else if( fileType.equals( TYPE_DOC ) ) {
return "application/msword";
} else if( fileType.equals( TYPE_CSV ) ) {
return "text/html";
} else if( fileType.equals( TYPE_XML ) ) {
return "text/xml";
} else if( fileType.equals( TYPE_HTML ) ) {
return "text/html";
} else {
return "text/html";
}
}
private JRExporter getJRExporter( String fileType ) {
// verificando o tipo do arquivo de saida do relatório
if( fileType.equals( TYPE_PDF ) ) {
return new JRPdfExporter();
} else if( fileType.equals( TYPE_XLS ) ) {
return new JRXlsExporter();
} else if( fileType.equals( TYPE_DOC ) ) {
return new JRRtfExporter();
} else if( fileType.equals( TYPE_CSV ) ) {
return new JRCsvExporter();
} else if( fileType.equals( TYPE_XML ) ) {
return new JRXmlExporter();
} else if( fileType.equals( TYPE_HTML ) ) {
return new JRHtmlExporter();
} else {
return new JRPdfExporter();
}
}
private boolean canShowOnBrowser( String fileType ) {
boolean isIE = true;
isIE = this.request.getHeader("User-Agent").toLowerCase().indexOf("msie") != -1;
if ( fileType.equals( TYPE_DOC ) && isIE){
return true;
}
else
if ( fileType.equals( TYPE_XLS ) && isIE){
return true;
} else
if( fileType.equals( TYPE_PDF ) || fileType.equals( TYPE_XML ) || fileType.equals( TYPE_HTML ) ) {
return true;
} else {
return false;
}
}
}
Esta é a classe que seria para apresentar o relatório. Ela esta muito bem documentada(lógico que eu tire quase todos os comentários)
E Também temos uma Classe JasperConsequenceBean que seria um bean com os parametros do relatório…
E na Action eu to fazendo o seguinte
[code]JasperConsequenceBean jasperBean = new JasperConsequenceBean();
jasperBean.setReportFileType(JasperConsequence.TYPE_PDF);
jasperBean.setReportFileName("Pedidos Entrega");
jasperBean.setReportFileModel("/relatorios/pedido/RelPedidos.jrxml");
//Parametros do Relatório
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("HIBERNATE_SESSION", input.getValue("session") );
jasperBean.setReportParameters(parameters);
output.setValue("reportBean", jasperBean);[/code]
Mas minha duvida mesmo é o que eu devo passar para o relatório funcionar…
Ja debuguei e o lugar aonde ocorre o erro é este
// gera o relatório em memória
JasperPrint printer = JasperFillManager.fillReport(
JasperConsequence.class.getResourceAsStream( this.JCB.getReportFileModel() ),
this.JCB.getReportParameters(),
new JRBeanCollectionDataSource( this.JCB.getReportDataList() )
);
Este trecho esta na classe JasperConsequence
no método processamento
A maneira como faço isto aqui está correto jasperBean.setReportFileModel("/relatorios/pedido/RelPedidos.jrxml");
E o Erro
23:32:23,281 ERROR [STDERR] org.mentawai.core.ConsequenceException: java.lang.Nu
llPointerException
23:32:23,281 ERROR [STDERR] at java.io.ObjectInputStream$PeekInputStream.rea
d(ObjectInputStream.java:2266)
23:32:23,281 ERROR [STDERR] at java.io.ObjectInputStream$PeekInputStream.rea
dFully(ObjectInputStream.java:2279)
23:32:23,281 ERROR [STDERR] at java.io.ObjectInputStream$BlockDataInputStrea
m.readShort(ObjectInputStream.java:2750)
23:32:23,281 ERROR [STDERR] at java.io.ObjectInputStream.readStreamHeader(Ob
jectInputStream.java:780)
23:32:23,281 ERROR [STDERR] at java.io.ObjectInputStream.<init>(ObjectInputS
tream.java:280)
23:32:23,281 ERROR [STDERR] at net.sf.jasperreports.engine.util.JRLoader.loa
dObject(JRLoader.java:191)
23:32:23,281 ERROR [STDERR] at net.sf.jasperreports.engine.JasperFillManager
.fillReport(JasperFillManager.java:580)
23:32:23,281 ERROR [STDERR] at principal.consequence.JasperConsequence.proce
ssamento(JasperConsequence.java:143)
23:32:23,281 ERROR [STDERR] at principal.consequence.JasperConsequence.execu
te(JasperConsequence.java:122)
23:32:23,281 ERROR [STDERR] at org.mentawai.core.Controller.service(Controll
er.java:546)
23:32:23,281 ERROR [STDERR] at javax.servlet.http.HttpServlet.service(HttpSe
rvlet.java:803)
23:32:23,281 ERROR [STDERR] at org.apache.catalina.core.ApplicationFilterCha
in.internalDoFilter(ApplicationFilterChain.java:290)
23:32:23,281 ERROR [STDERR] at org.apache.catalina.core.ApplicationFilterCha
in.doFilter(ApplicationFilterChain.java:206)
23:32:23,281 ERROR [STDERR] at org.displaytag.filter.ResponseOverrideFilter.
doFilter(ResponseOverrideFilter.java:125)
23:32:23,281 ERROR [STDERR] at org.apache.catalina.core.ApplicationFilterCha
in.internalDoFilter(ApplicationFilterChain.java:235)
23:32:23,281 ERROR [STDERR] at org.apache.catalina.core.ApplicationFilterCha
in.doFilter(ApplicationFilterChain.java:206)
23:32:23,281 ERROR [STDERR] at org.jboss.web.tomcat.filters.ReplyHeaderFilte
r.doFilter(ReplyHeaderFilter.java:96)
23:32:23,281 ERROR [STDERR] at org.apache.catalina.core.ApplicationFilterCha
in.internalDoFilter(ApplicationFilterChain.java:235)
23:32:23,281 ERROR [STDERR] at org.apache.catalina.core.ApplicationFilterCha
in.doFilter(ApplicationFilterChain.java:206)
23:32:23,281 ERROR [STDERR] at org.apache.catalina.core.StandardWrapperValve
.invoke(StandardWrapperValve.java:230)
23:32:23,281 ERROR [STDERR] at org.apache.catalina.core.StandardContextValve
.invoke(StandardContextValve.java:175)
23:32:23,281 ERROR [STDERR] at org.jboss.web.tomcat.security.SecurityAssocia
tionValve.invoke(SecurityAssociationValve.java:179)
23:32:23,281 ERROR [STDERR] at org.jboss.web.tomcat.security.JaccContextValv
e.invoke(JaccContextValve.java:84)
23:32:23,281 ERROR [STDERR] at org.apache.catalina.core.StandardHostValve.in
voke(StandardHostValve.java:128)
23:32:23,281 ERROR [STDERR] at org.apache.catalina.valves.ErrorReportValve.i
nvoke(ErrorReportValve.java:104)
23:32:23,281 ERROR [STDERR] at org.jboss.web.tomcat.service.jca.CachedConnec
tionValve.invoke(CachedConnectionValve.java:157)
23:32:23,281 ERROR [STDERR] at org.apache.catalina.core.StandardEngineValve.
invoke(StandardEngineValve.java:109)
23:32:23,281 ERROR [STDERR] at org.apache.catalina.connector.CoyoteAdapter.s
ervice(CoyoteAdapter.java:241)
23:32:23,281 ERROR [STDERR] at org.apache.coyote.http11.Http11Processor.proc
ess(Http11Processor.java:844)
23:32:23,281 ERROR [STDERR] at org.apache.coyote.http11.Http11Protocol$Http1
1ConnectionHandler.process(Http11Protocol.java:580)
23:32:23,281 ERROR [STDERR] at org.apache.tomcat.util.net.JIoEndpoint$Worker
.run(JIoEndpoint.java:447)
23:32:23,281 ERROR [STDERR] at java.lang.Thread.run(Thread.java:619)
23:32:23,281 ERROR [STDERR] Caused by: java.lang.NullPointerException
23:32:23,281 ERROR [STDERR] ... 32 more
23:32:23,281 ERROR [[Controller]] Servlet.service() for servlet Controller threw
exception
java.lang.NullPointerException
at java.io.ObjectInputStream$PeekInputStream.read(ObjectInputStream.java
:2266)
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream
.java:2279)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputS
tream.java:2750)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:780
)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:280)
at net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:19
1)
at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillMa
nager.java:580)
at principal.consequence.JasperConsequence.processamento(JasperConsequen
ce.java:143)
at principal.consequence.JasperConsequence.execute(JasperConsequence.jav
a:122)
at org.mentawai.core.Controller.service(Controller.java:546)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(Appl
icationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationF
ilterChain.java:206)
at org.displaytag.filter.ResponseOverrideFilter.doFilter(ResponseOverrid
eFilter.java:125)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(Appl
icationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationF
ilterChain.java:206)
at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFi
lter.java:96)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(Appl
icationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationF
ilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperV
alve.java:230)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextV
alve.java:175)
at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(Securit
yAssociationValve.java:179)
at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValv
e.java:84)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.j
ava:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.j
ava:104)
at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedC
onnectionValve.java:157)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineVal
ve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.jav
a:241)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java
:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.proce
ss(Http11Protocol.java:580)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:44
7)
at java.lang.Thread.run(Thread.java:619)
Eu vi que na primeira linha ja aparece java.lang.NullPointerException mas esse null não me pareceu ser no meu programa
Eu só não consegui axar aonde é que o danado está??
Peço Desculpa pelo post enorme…
E Agradeço a atenção de todos