Home » Archived » BIRT » DataSource from an external factory
DataSource from an external factory [message #198084] |
Fri, 27 October 2006 16:53  |
Eclipse User |
|
|
|
Originally posted by: trevor.l.torrez.accenture.com
Is there an easy way to have birt use a DataSource from an external
factory without using a 'scripted datasource' which requires me to hand
code the column retrieval (think 200+ columns)? I use spring for a lot
of configuration, so ideally I would like to be able to hand birt a
DataSource and just say 'use this'. Any thoughts? How about having the
factory create the data source and binding it to JDNI; and having birt
retrieve it from JNDI?
--
-t.
|
|
| | | |
Re: DataSource from an external factory [message #198881 is a reply to message #198830] |
Thu, 02 November 2006 15:49   |
Eclipse User |
|
|
|
This is a multi-part message in MIME format.
--------------040305030701020108070209
Content-Type: text/plain; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 7bit
I am using a servlet with the attached files.
I am very happy with BIRT from a report design perspective but from an integration perspective it is
far more complicated than I thought it would be.
Jason Weathersby wrote:
> Ryan,
>
> I wish you would log a bug for the warning.
> How do you have the report deployed?
>
> Jason
>
> "Ryan Barker" <barker@itgssi.com> wrote in message
> news:eid7bh$dqo$1@utils.eclipse.org...
>
>>I have the same issue. I do have access to the datasource in spring, and
>>would prefer to pass it in at runtime, as we are trying to centralize all
>>our configuration. Examples of how to do this would be great. We would be
>>ok with a way to pass in the jndi name if it didnt have the error below.
>>
>>I attempted to use the jndi datasource (java:comp/env/MyDataSource) but I
>>get the following WARNING from my jboss pool:
>>WARN org.jboss.resource.connectionmanager.JBossManagedConnectionP ool -
>>Destroying connection that could not be successfully matched
>>
>>The following is from my jboss JCA config:
>> <no-tx-datasource>
>> <jndi-name>${jdbc.datasource.name}</jndi-name>
>> <connection-url>${jdbc.datasource.url}</connection-url>
>> <driver-class>${jdbc.datasource.driver.class}</driver-class >
>> <user-name>${jdbc.datasource.username}</user-name>
>> <password>${jdbc.datasource.password}</password>
>> <min-pool-size>${jdbc.datasource.poolsize.min}</min-pool-size >
>> <max-pool-size>${jdbc.datasource.poolsize.max}</max-pool-size >
>> <idle-timeout-minutes>30</idle-timeout-minutes>
>> <blocking-timeout-millis>5000</blocking-timeout-millis>
>>
>><check-valid-connection-sql>${jdbc.datasource.validationsql} </check-valid-connection-sql>
>>
>><exception-sorter-class-name>${jdbc.datasource.exceptionsorter} </exception-sorter-class-name>
>> </no-tx-datasource>
>>
>>Thanks,
>>Ryan
>>
>>Jason Weathersby wrote:
>>
>>
>>>Trevor,
>>>
>>>There are ways to pass preloaded objects into Birt, but you still may
>>>have the same problem if you want all 200 columns to show up in your data
>>>set view.
>>>A custom ODA may work in this situation. Let me know if you try the JNDI
>>>approach.
>>>
>>>Jason
>>>
>>>"Trevor Torrez" <trevor.l.torrez@accenture.com> wrote in message
>>>news:ehtric$rpt$1@utils.eclipse.org...
>>>
>>>
>>>>Is there an easy way to have birt use a DataSource from an external
>>>>factory without using a 'scripted datasource' which requires me to hand
>>>>code the column retrieval (think 200+ columns)? I use spring for a lot
>>>>of configuration, so ideally I would like to be able to hand birt a
>>>>DataSource and just say 'use this'. Any thoughts? How about having the
>>>>factory create the data source and binding it to JDNI; and having birt
>>>>retrieve it from JNDI?
>>>>
>>>>
>>>>--
>>>>-t.
>>>
>>>
>
--------------040305030701020108070209
Content-Type: text/x-java;
name="BirtReportServlet.java"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline;
filename="BirtReportServlet.java"
package com.itgssi.apr.logic.report.birt;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.eclipse.birt.report.engine.api.EngineException;
import org.eclipse.birt.report.engine.api.HTMLRenderOption;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;
import org.springframework.web.context.support.WebApplicationContex tUtils;
public class BirtReportServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Constructor of the object.
*/
private BirtPlatformListener birtPlatformFactory = null;
protected static Logger log = Logger.getLogger(BirtReportServlet.class);
public BirtReportServlet() {
super();
}
public void init(ServletConfig arg0) throws ServletException {
super.init(arg0);
this.birtPlatformFactory = (BirtPlatformListener) WebApplicationContextUtils.
getWebApplicationContext(getServletContext()).getBean("platformListener ");
}
/**
* Destruction of the servlet.
*/
public void destroy() {
super.destroy();
}
/**
* The doGet method of the servlet.
*/
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
long startTime = System.currentTimeMillis();
log.debug("obtaining engine");
// get report name and launch the engine
// resp.setContentType("text/html");
// resp.setContentType( "application/pdf" );
// resp.setHeader ("Content-Disposition","inline; filename=test.pdf");
IReportEngine birtReportEngine = birtPlatformFactory.getReportEngine();
String reportName = req.getParameter("ReportName");
if (log.isDebugEnabled()) {
log.debug("opening design: " + reportName);
}
IReportRunnable design = null;
IRunAndRenderTask task = null;
try {
// Open report design
design = openReportDesign(reportName, birtReportEngine);
log.debug("design opened");
// create task to run and render report
task = birtReportEngine.createRunAndRenderTask(design);
autoAnswerPrompt(req,task);
task.setAppContext(birtPlatformFactory.getBirtConfig().getAp pContext());
log.debug("renderTask created");
// set output options
ByteArrayOutputStream baos = new ByteArrayOutputStream(2048);
HTMLRenderOption options = getRenderOptions(baos);
task.setRenderOption(options);
log.debug("options set");
// run report
task.run();
log.debug("task run");
task.close();
resp.getWriter().write(baos.toString());
log.debug("task close");
}
catch (Exception e) {
e.printStackTrace();
throw new ServletException(e);
} finally {
if (task != null) {
task.close();
}
}
long endTime = System.currentTimeMillis();
log.info(reportName + " generated in " + (endTime - startTime)/1000.0 + "s");
}
private IReportRunnable openReportDesign(String reportName, IReportEngine birtReportEngine) throws EngineException {
IReportRunnable design;
ServletContext sc = getServletContext();
InputStream stream = sc.getResourceAsStream("/WEB-INF/reports/" + reportName);
design = birtReportEngine.openReportDesign(reportName, stream);
return design;
}
private HTMLRenderOption getRenderOptions(ByteArrayOutputStream baos) {
HTMLRenderOption options = new HTMLRenderOption();
// options.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_PDF);
options.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_HTML) ;
options.setEmbeddable(true);
// can not directly call getOutputStream because its already been written to!
options.setOutputStream(baos);
return options;
}
private void autoAnswerPrompt(HttpServletRequest req, IRunAndRenderTask task) {
HttpSession session = req.getSession();
Object value = session.getAttribute("calculationResultsID");
task.setParameterValue("calculationResultsID", value);
}
// Below shows how to iterate over prompts. Its overkill for what we do though.
// protected Map answerPrompts(HttpServletRequest req, IReportEngine birtReportEngine, IReportRunnable design) {
// // answer the prompts
// IGetParameterDefinitionTask task = birtReportEngine.createGetParameterDefinitionTask(design);
// Collection params = task.getParameterDefns(true);
// Map promptAnswers = new HashMap();
// Iterator i = params.iterator();
// while (i.hasNext()) {
// IParameterDefnBase param = (IParameterDefnBase) i.next();
// if (param instanceof IParameterGroupDefn) {
// answerPrompts(req, promptAnswers, (IParameterGroupDefn) param);
// } else if (param instanceof IScalarParameterDefn) {
// answerPrompt(req, promptAnswers, (IScalarParameterDefn) param);
// } else {
// log.error("Unknown parameter!" + com.itgssi.util.FormatUtils.toString(param));
// }
//
// }
// return promptAnswers;
// }
//
//
// private void answerPrompts(HttpServletRequest req, Map promptAnswers, IParameterGroupDefn group) {
// Iterator i = group.getContents().iterator();
// while (i.hasNext()){
// answerPrompt(req, promptAnswers, (IScalarParameterDefn) i.next());
// }
//
//
// }
// private void answerPrompt(HttpServletRequest req,Map promptAnswers, IScalarParameterDefn defn) {
// String promptText =defn.getPromptText();
// HttpSession session = req.getSession();
// if (promptText != null) {
// if (promptText.equals("Result Id")) {
// Object value = session.getAttribute("calculationResultsID");
// if (value != null) {
// promptAnswers.put(defn.getName(),value);
// }
// }
//
// }
//
// }
/**
* The doPost method of the servlet.
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
--------------040305030701020108070209
Content-Type: text/x-java;
name="BirtConfig.java"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline;
filename="BirtConfig.java"
package com.itgssi.apr.logic.report.birt;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.logging.Level;
import javax.servlet.ServletContext;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.log4j.Logger;
import org.eclipse.birt.core.framework.IPlatformContext;
import org.eclipse.birt.core.framework.PlatformServletContext;
import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.HTMLActionHandler;
import org.eclipse.birt.report.engine.api.HTMLEmitterConfig;
import org.eclipse.birt.report.engine.api.HTMLServerImageHandler;
import org.springframework.web.context.ServletContextAware;
public class BirtConfig implements ServletContextAware {
private Logger log = Logger.getLogger(BirtConfig.class);
private Map engineProperties;
private Map appContext;
private ServletContext sc;
private String logDirectory;
private Level logLevel;
private EngineConfig engineConfig;
public void initialize() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
engineConfig = new EngineConfig();
PropertyUtils.copyProperties(engineProperties,engineConfig);
engineConfig.setLogConfig(logDirectory,logLevel);
HTMLEmitterConfig htmlConfig = new HTMLEmitterConfig();
htmlConfig.setActionHandler(new HTMLActionHandler());
htmlConfig.setImageHandler(new HTMLServerImageHandler());
engineConfig.getEmitterConfigs().put("html", htmlConfig);
IPlatformContext context = new PlatformServletContext(sc);
engineConfig.setPlatformContext(context);
}
public void setServletContext(ServletContext servletContext) {
this.sc = servletContext;
}
public Map getEngineProperties() {
return engineProperties;
}
public void setEngineProperties(Map config) {
this.engineProperties = config;
}
public void setLogDirectory(String logDirectory) {
this.logDirectory = logDirectory;
}
public void setLogLevel(String logLevel) {
this.logLevel = java.util.logging.Level.parse(logLevel);
}
public EngineConfig getEngineConfig() {
return engineConfig;
}
public Map getAppContext() {
return appContext;
}
public void setAppContext(Map renderOptions) {
this.appContext = renderOptions;
}
}
--------------040305030701020108070209
Content-Type: text/x-java;
name="BirtImageServlet.java"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline;
filename="BirtImageServlet.java"
package com.itgssi.apr.logic.report.birt;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.eclipse.birt.report.engine.api.EngineConstants;
import org.eclipse.birt.report.engine.api.HTMLRenderContext;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.context.support.WebApplicationContex tUtils;
public class BirtImageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private BirtPlatformListener birtPlatformFactory = null;
protected static Logger log = Logger.getLogger(BirtImageServlet.class);
public BirtImageServlet() {
super();
}
public void init(ServletConfig arg0) throws ServletException {
super.init(arg0);
this.birtPlatformFactory = (BirtPlatformListener) WebApplicationContextUtils.
getWebApplicationContext(getServletContext()).getBean("platformListener ");
}
/**
* Destruction of the servlet.
*/
public void destroy() {
super.destroy();
}
/**
* The doGet method of the servlet.
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String imageName = request.getParameter("id");
if (imageName == null)
throw new ServletException("Missing id parameters");
// Cast to file, so we can extract just the filename
File imageFile = new File(imageName);
imageName = imageFile.getName();
Map appContext = birtPlatformFactory.getBirtConfig().getAppContext();
HTMLRenderContext htmlContext = (HTMLRenderContext) appContext.get(EngineConstants.APPCONTEXT_HTML_RENDER_CONTEX T);
String imageDirectory = htmlContext.getImageDirectory();
imageFile = new File(imageDirectory + File.separator + imageName);
FileInputStream fis = new FileInputStream(imageFile);
OutputStream os = response.getOutputStream();
try {
FileCopyUtils.copy(fis, os);
// file is only requested once
imageFile.delete();
}
finally {
fis.close();
}
}
/**
* The doPost method of the servlet.
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
--------------040305030701020108070209
Content-Type: text/x-java;
name="BirtPlatformListener.java"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline;
filename="BirtPlatformListener.java"
/*
* Copyright 2006, Xebia BV, the Netherlands
*
* info@inspiring.nl
*/
package com.itgssi.apr.logic.report.birt;
import org.apache.log4j.Logger;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportEngineFactory;
/**
* Helper class to start and stop Eclipse BIRT.
*
* @author Silvester van der Bijl
*
*/
public class BirtPlatformListener {
protected static Logger log = Logger.getLogger(BirtPlatformListener.class);
/** Eclipse {@link EngineConfig}. */
private BirtConfig birtConfig;
/** Instance of the {@link IReportEngine}. */
private IReportEngine reportEngine;
/**
* Must be called before using the BIRT APIs. After retrieving the configuration from
* {@link XReportConfiguration} will start the BIRT {@link Platform}.
*/
public void start() {
if (log.isDebugEnabled()) {
log.debug("Starting Eclipse BIRT platform");
}
EngineConfig engineConfig = birtConfig.getEngineConfig();
try {
Platform.startup(engineConfig);
} catch (BirtException be) {
throw new IllegalArgumentException("Failure starting BIRT platform", be);
}
if (log.isDebugEnabled()) {
log.debug("Creating new instance of report engine.");
}
IReportEngineFactory factory = (IReportEngineFactory) Platform.createFactoryObject(IReportEngineFactory.EXTENSION_ REPORT_ENGINE_FACTORY);
reportEngine = factory.createReportEngine(engineConfig);
reportEngine.changeLogLevel(engineConfig.getLogLevel());
}
/**
* Must be called after finishing use of the Eclipse BIRT APIs. E.g. at application shutdown
* (hint, look at the destroy-method property of spring beans).
*
*/
public void shutdown() {
if (log.isDebugEnabled()) {
log.debug("Shutting down Eclipse BIRT platform");
}
if (reportEngine != null) {
if (log.isDebugEnabled()) {
log.debug("Shutting down report engine instance.");
}
reportEngine.shutdown();
}
// Just call shutdown
Platform.shutdown();
}
/**
* Create or return the cached instance of the {@link IReportEngine}.
*
* @return instance of {@link IReportEngine}
*/
public IReportEngine getReportEngine() {
return reportEngine;
}
/**
* Sets the engineConfig.
*
* @param engineConfig The engineConfig to set.
*/
public void setBirtConfig(BirtConfig birtConfig) {
this.birtConfig = birtConfig;
}
public BirtConfig getBirtConfig() {
return birtConfig;
}
}
--------------040305030701020108070209--
|
|
|
Re: DataSource from an external factory [message #199051 is a reply to message #198881] |
Fri, 03 November 2006 15:07  |
Eclipse User |
|
|
|
Ryan,
Here is the plugin.
Here is an example of setting the connection.
Jason
import java.util.HashMap;
import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.EngineException;
import org.eclipse.birt.report.engine.api.HTMLRenderContext;
import org.eclipse.birt.report.engine.api.HTMLRenderOption;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;
import org.eclipse.birt.report.engine.api.ReportEngine;
import org.eclipse.birt.report.engine.api.EngineConstants;
import java.sql.*;
public class ExecuteConnectionPool {
private java.sql.Connection setupJdbcConnection(){
java.sql.Connection conn = null;
try{
Class.forName( "com.mysql.jdbc.Driver" );
conn = java.sql.DriverManager.getConnection(
"jdbc:mysql://localhost/classicmodels", "root", "root");
}
catch ( Exception e )
{
e.printStackTrace();
System.exit(0);
}
return( conn );
}
public void executeReport() throws EngineException
{
//Engine Configuration - set and get temp dir, BIRT home, Servlet context
EngineConfig config = new EngineConfig();
config.setEngineHome(
"C:\\birt-runtime-2.1RC5\\birt-runtime-2_1_0\\ReportEngine" );
//Create the report engine
ReportEngine engine = new ReportEngine( config );
//Open a report design - use design to modify design, retrieve embedded
images etc.
IReportRunnable design =
engine.openReportDesign("C:/xport/appcontext.rptdesign");
//Create task to run the report - use the task to execute and run the
report,
//retrieve report parameter values from ParameterDefinitionTask();
IRunAndRenderTask task = engine.createRunAndRenderTask(design);
//Set Render context to handle url and image locataions
HTMLRenderContext renderContext = new HTMLRenderContext();
renderContext.setImageDirectory("image");
HashMap contextMap = new HashMap();
contextMap.put( EngineConstants.APPCONTEXT_HTML_RENDER_CONTEXT,
renderContext );
//add the connection object to the map
contextMap.put(
"org.eclipse.birt.report.data.oda.subjdbc.SubOdaJdbcDriver",
setupJdbcConnection() );
task.setAppContext( contextMap );
//Set rendering options - such as file or stream output,
//output format, whether it is embeddable, etc
HTMLRenderOption options = new HTMLRenderOption();
//options.setOutputStream(System.out);
options.setOutputFileName("C:/work/birt/connectionpool/AppContextTest.html ");
options.setOutputFormat("html");
task.setRenderOption(options);
//run the report and destroy the engine
task.run();
engine.destroy();
}
/**
* @param args
*/
public static void main(String[] args) {
try
{
ExecuteConnectionPool ecp = new ExecuteConnectionPool();
ecp.executeReport( );
}
catch ( Exception e )
{
e.printStackTrace();
}
}
}
"Ryan Barker" <barker@itgssi.com> wrote in message
news:eidlkp$874$1@utils.eclipse.org...
>I am using a servlet with the attached files.
>
> I am very happy with BIRT from a report design perspective but from an
> integration perspective it is
> far more complicated than I thought it would be.
>
>
>
>
> Jason Weathersby wrote:
>> Ryan,
>>
>> I wish you would log a bug for the warning.
>> How do you have the report deployed?
>>
>> Jason
>>
>> "Ryan Barker" <barker@itgssi.com> wrote in message
>> news:eid7bh$dqo$1@utils.eclipse.org...
>>
>>>I have the same issue. I do have access to the datasource in spring, and
>>>would prefer to pass it in at runtime, as we are trying to centralize all
>>>our configuration. Examples of how to do this would be great. We would
>>>be
>>>ok with a way to pass in the jndi name if it didnt have the error below.
>>>
>>>I attempted to use the jndi datasource (java:comp/env/MyDataSource) but I
>>>get the following WARNING from my jboss pool:
>>>WARN org.jboss.resource.connectionmanager.JBossManagedConnectionP ool -
>>>Destroying connection that could not be successfully matched
>>>
>>>The following is from my jboss JCA config:
>>> <no-tx-datasource>
>>> <jndi-name>${jdbc.datasource.name}</jndi-name>
>>> <connection-url>${jdbc.datasource.url}</connection-url>
>>> <driver-class>${jdbc.datasource.driver.class}</driver-class >
>>> <user-name>${jdbc.datasource.username}</user-name>
>>> <password>${jdbc.datasource.password}</password>
>>> <min-pool-size>${jdbc.datasource.poolsize.min}</min-pool-size >
>>> <max-pool-size>${jdbc.datasource.poolsize.max}</max-pool-size >
>>> <idle-timeout-minutes>30</idle-timeout-minutes>
>>> <blocking-timeout-millis>5000</blocking-timeout-millis>
>>>
>>><check-valid-connection-sql>${jdbc.datasource.validationsql} </check-valid-connection-sql>
>>>
>>><exception-sorter-class-name>${jdbc.datasource.exceptionsorter} </exception-sorter-class-name>
>>> </no-tx-datasource>
>>>
>>>Thanks,
>>>Ryan
>>>
>>>Jason Weathersby wrote:
>>>
>>>
>>>>Trevor,
>>>>
>>>>There are ways to pass preloaded objects into Birt, but you still may
>>>>have the same problem if you want all 200 columns to show up in your
>>>>data
>>>>set view.
>>>>A custom ODA may work in this situation. Let me know if you try the
>>>>JNDI
>>>>approach.
>>>>
>>>>Jason
>>>>
>>>>"Trevor Torrez" <trevor.l.torrez@accenture.com> wrote in message
>>>>news:ehtric$rpt$1@utils.eclipse.org...
>>>>
>>>>
>>>>>Is there an easy way to have birt use a DataSource from an external
>>>>>factory without using a 'scripted datasource' which requires me to hand
>>>>>code the column retrieval (think 200+ columns)? I use spring for a lot
>>>>>of configuration, so ideally I would like to be able to hand birt a
>>>>>DataSource and just say 'use this'. Any thoughts? How about having
>>>>>the
>>>>>factory create the data source and binding it to JDNI; and having birt
>>>>>retrieve it from JNDI?
>>>>>
>>>>>
>>>>>--
>>>>>-t.
>>>>
>>>>
>>
>
>
------------------------------------------------------------ --------------------
> package com.itgssi.apr.logic.report.birt;
>
> import java.io.ByteArrayOutputStream;
> import java.io.IOException;
> import java.io.InputStream;
>
> import javax.servlet.ServletConfig;
> import javax.servlet.ServletContext;
> import javax.servlet.ServletException;
> import javax.servlet.http.HttpServlet;
> import javax.servlet.http.HttpServletRequest;
> import javax.servlet.http.HttpServletResponse;
> import javax.servlet.http.HttpSession;
>
> import org.apache.log4j.Logger;
> import org.eclipse.birt.report.engine.api.EngineException;
> import org.eclipse.birt.report.engine.api.HTMLRenderOption;
> import org.eclipse.birt.report.engine.api.IReportEngine;
> import org.eclipse.birt.report.engine.api.IReportRunnable;
> import org.eclipse.birt.report.engine.api.IRunAndRenderTask;
> import org.springframework.web.context.support.WebApplicationContex tUtils;
>
>
> public class BirtReportServlet extends HttpServlet {
>
> private static final long serialVersionUID = 1L;
> /**
> * Constructor of the object.
> */
> private BirtPlatformListener birtPlatformFactory = null;
> protected static Logger log = Logger.getLogger(BirtReportServlet.class);
>
> public BirtReportServlet() {
> super();
> }
>
> public void init(ServletConfig arg0) throws ServletException {
> super.init(arg0);
> this.birtPlatformFactory = (BirtPlatformListener)
> WebApplicationContextUtils.
>
> getWebApplicationContext(getServletContext()).getBean("platformListener ");
>
> }
>
> /**
> * Destruction of the servlet.
> */
> public void destroy() {
> super.destroy();
> }
>
> /**
> * The doGet method of the servlet.
> */
> public void doGet(HttpServletRequest req, HttpServletResponse resp)
> throws ServletException, IOException {
> long startTime = System.currentTimeMillis();
>
> log.debug("obtaining engine");
> // get report name and launch the engine
> // resp.setContentType("text/html");
> // resp.setContentType( "application/pdf" );
> // resp.setHeader ("Content-Disposition","inline;
> filename=test.pdf");
> IReportEngine birtReportEngine =
> birtPlatformFactory.getReportEngine();
> String reportName = req.getParameter("ReportName");
> if (log.isDebugEnabled()) {
> log.debug("opening design: " + reportName);
> }
> IReportRunnable design = null;
> IRunAndRenderTask task = null;
> try {
> // Open report design
> design = openReportDesign(reportName, birtReportEngine);
>
> log.debug("design opened");
>
>
> // create task to run and render report
> task = birtReportEngine.createRunAndRenderTask(design);
> autoAnswerPrompt(req,task);
>
>
>
> task.setAppContext(birtPlatformFactory.getBirtConfig().getAp pContext());
> log.debug("renderTask created");
>
>
> // set output options
> ByteArrayOutputStream baos = new ByteArrayOutputStream(2048);
> HTMLRenderOption options = getRenderOptions(baos);
> task.setRenderOption(options);
> log.debug("options set");
>
> // run report
> task.run();
> log.debug("task run");
> task.close();
> resp.getWriter().write(baos.toString());
> log.debug("task close");
> }
> catch (Exception e) {
>
> e.printStackTrace();
> throw new ServletException(e);
> } finally {
> if (task != null) {
> task.close();
> }
> }
> long endTime = System.currentTimeMillis();
> log.info(reportName + " generated in " + (endTime - startTime)/1000.0
> + "s");
> }
>
> private IReportRunnable openReportDesign(String reportName,
> IReportEngine birtReportEngine) throws EngineException {
> IReportRunnable design;
> ServletContext sc = getServletContext();
> InputStream stream = sc.getResourceAsStream("/WEB-INF/reports/" +
> reportName);
> design = birtReportEngine.openReportDesign(reportName, stream);
> return design;
> }
>
> private HTMLRenderOption getRenderOptions(ByteArrayOutputStream baos) {
> HTMLRenderOption options = new HTMLRenderOption();
> // options.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_PDF);
> options.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_HTML) ;
> options.setEmbeddable(true);
>
> // can not directly call getOutputStream because its already been
> written to!
> options.setOutputStream(baos);
> return options;
> }
>
> private void autoAnswerPrompt(HttpServletRequest req, IRunAndRenderTask
> task) {
> HttpSession session = req.getSession();
> Object value = session.getAttribute("calculationResultsID");
> task.setParameterValue("calculationResultsID", value);
> }
> // Below shows how to iterate over prompts. Its overkill for what we do
> though.
> // protected Map answerPrompts(HttpServletRequest req, IReportEngine
> birtReportEngine, IReportRunnable design) {
> // // answer the prompts
> // IGetParameterDefinitionTask task =
> birtReportEngine.createGetParameterDefinitionTask(design);
> // Collection params = task.getParameterDefns(true);
> // Map promptAnswers = new HashMap();
> // Iterator i = params.iterator();
> // while (i.hasNext()) {
> // IParameterDefnBase param = (IParameterDefnBase) i.next();
> // if (param instanceof IParameterGroupDefn) {
> // answerPrompts(req, promptAnswers, (IParameterGroupDefn)
> param);
> // } else if (param instanceof IScalarParameterDefn) {
> // answerPrompt(req, promptAnswers, (IScalarParameterDefn)
> param);
> // } else {
> // log.error("Unknown parameter!" +
> com.itgssi.util.FormatUtils.toString(param));
> // }
> //
> // }
> // return promptAnswers;
> // }
> //
> //
> // private void answerPrompts(HttpServletRequest req, Map promptAnswers,
> IParameterGroupDefn group) {
> // Iterator i = group.getContents().iterator();
> // while (i.hasNext()){
> // answerPrompt(req, promptAnswers, (IScalarParameterDefn)
> i.next());
> // }
> //
> //
> // }
> // private void answerPrompt(HttpServletRequest req,Map promptAnswers,
> IScalarParameterDefn defn) {
> // String promptText =defn.getPromptText();
> // HttpSession session = req.getSession();
> // if (promptText != null) {
> // if (promptText.equals("Result Id")) {
> // Object value = session.getAttribute("calculationResultsID");
> // if (value != null) {
> // promptAnswers.put(defn.getName(),value);
> // }
> // }
> //
> // }
> //
> // }
>
> /**
> * The doPost method of the servlet.
> */
> public void doPost(HttpServletRequest request, HttpServletResponse
> response) throws ServletException, IOException {
> doPost(request,response);
> }
>
>
> }
>
------------------------------------------------------------ --------------------
> package com.itgssi.apr.logic.report.birt;
>
> import java.lang.reflect.InvocationTargetException;
> import java.util.Map;
> import java.util.logging.Level;
>
> import javax.servlet.ServletContext;
>
> import org.apache.commons.beanutils.PropertyUtils;
> import org.apache.log4j.Logger;
> import org.eclipse.birt.core.framework.IPlatformContext;
> import org.eclipse.birt.core.framework.PlatformServletContext;
> import org.eclipse.birt.report.engine.api.EngineConfig;
> import org.eclipse.birt.report.engine.api.HTMLActionHandler;
> import org.eclipse.birt.report.engine.api.HTMLEmitterConfig;
> import org.eclipse.birt.report.engine.api.HTMLServerImageHandler;
> import org.springframework.web.context.ServletContextAware;
>
>
> public class BirtConfig implements ServletContextAware {
>
> private Logger log = Logger.getLogger(BirtConfig.class);
> private Map engineProperties;
> private Map appContext;
>
> private ServletContext sc;
>
> private String logDirectory;
>
> private Level logLevel;
>
> private EngineConfig engineConfig;
>
> public void initialize() throws IllegalAccessException,
> InvocationTargetException, NoSuchMethodException {
> engineConfig = new EngineConfig();
>
> PropertyUtils.copyProperties(engineProperties,engineConfig);
> engineConfig.setLogConfig(logDirectory,logLevel);
>
> HTMLEmitterConfig htmlConfig = new HTMLEmitterConfig();
> htmlConfig.setActionHandler(new HTMLActionHandler());
> htmlConfig.setImageHandler(new HTMLServerImageHandler());
> engineConfig.getEmitterConfigs().put("html", htmlConfig);
>
> IPlatformContext context = new PlatformServletContext(sc);
> engineConfig.setPlatformContext(context);
> }
>
>
> public void setServletContext(ServletContext servletContext) {
> this.sc = servletContext;
> }
>
> public Map getEngineProperties() {
> return engineProperties;
> }
>
> public void setEngineProperties(Map config) {
> this.engineProperties = config;
> }
> public void setLogDirectory(String logDirectory) {
> this.logDirectory = logDirectory;
> }
>
> public void setLogLevel(String logLevel) {
> this.logLevel = java.util.logging.Level.parse(logLevel);
> }
>
>
>
> public EngineConfig getEngineConfig() {
> return engineConfig;
> }
>
>
>
> public Map getAppContext() {
> return appContext;
> }
>
>
>
> public void setAppContext(Map renderOptions) {
> this.appContext = renderOptions;
> }
>
>
>
> }
------------------------------------------------------------ --------------------
> package com.itgssi.apr.logic.report.birt;
>
> import java.io.File;
> import java.io.FileInputStream;
> import java.io.IOException;
> import java.io.OutputStream;
> import java.util.Map;
>
> import javax.servlet.ServletConfig;
> import javax.servlet.ServletException;
> import javax.servlet.http.HttpServlet;
> import javax.servlet.http.HttpServletRequest;
> import javax.servlet.http.HttpServletResponse;
>
> import org.apache.log4j.Logger;
> import org.eclipse.birt.report.engine.api.EngineConstants;
> import org.eclipse.birt.report.engine.api.HTMLRenderContext;
> import org.springframework.util.FileCopyUtils;
> import org.springframework.web.context.support.WebApplicationContex tUtils;
>
> public class BirtImageServlet extends HttpServlet {
>
> private static final long serialVersionUID = 1L;
> private BirtPlatformListener birtPlatformFactory = null;
> protected static Logger log = Logger.getLogger(BirtImageServlet.class);
>
> public BirtImageServlet() {
> super();
> }
>
> public void init(ServletConfig arg0) throws ServletException {
> super.init(arg0);
> this.birtPlatformFactory = (BirtPlatformListener)
> WebApplicationContextUtils.
>
> getWebApplicationContext(getServletContext()).getBean("platformListener ");
> }
>
> /**
> * Destruction of the servlet.
> */
> public void destroy() {
> super.destroy();
> }
>
> /**
> * The doGet method of the servlet.
> */
> public void doGet(HttpServletRequest request, HttpServletResponse
> response) throws ServletException, IOException {
>
> String imageName = request.getParameter("id");
> if (imageName == null)
> throw new ServletException("Missing id parameters");
>
> // Cast to file, so we can extract just the filename
> File imageFile = new File(imageName);
> imageName = imageFile.getName();
>
> Map appContext = birtPlatformFactory.getBirtConfig().getAppContext();
> HTMLRenderContext htmlContext = (HTMLRenderContext)
> appContext.get(EngineConstants.APPCONTEXT_HTML_RENDER_CONTEX T);
> String imageDirectory = htmlContext.getImageDirectory();
>
> imageFile = new File(imageDirectory + File.separator + imageName);
> FileInputStream fis = new FileInputStream(imageFile);
> OutputStream os = response.getOutputStream();
> try {
> FileCopyUtils.copy(fis, os);
> // file is only requested once
> imageFile.delete();
> }
> finally {
> fis.close();
> }
>
> }
>
> /**
> * The doPost method of the servlet.
> */
> public void doPost(HttpServletRequest request, HttpServletResponse
> response) throws ServletException, IOException {
> doGet(request,response);
> }
>
>
> }
>
------------------------------------------------------------ --------------------
> /*
> * Copyright 2006, Xebia BV, the Netherlands
> *
> * info@inspiring.nl
> */
>
> package com.itgssi.apr.logic.report.birt;
>
> import org.apache.log4j.Logger;
> import org.eclipse.birt.core.exception.BirtException;
> import org.eclipse.birt.core.framework.Platform;
> import org.eclipse.birt.report.engine.api.EngineConfig;
> import org.eclipse.birt.report.engine.api.IReportEngine;
> import org.eclipse.birt.report.engine.api.IReportEngineFactory;
>
>
> /**
> * Helper class to start and stop Eclipse BIRT.
> *
> * @author Silvester van der Bijl
> *
> */
> public class BirtPlatformListener {
> protected static Logger log =
> Logger.getLogger(BirtPlatformListener.class);
>
> /** Eclipse {@link EngineConfig}. */
> private BirtConfig birtConfig;
>
> /** Instance of the {@link IReportEngine}. */
> private IReportEngine reportEngine;
>
> /**
> * Must be called before using the BIRT APIs. After retrieving the
> configuration from
> * {@link XReportConfiguration} will start the BIRT {@link Platform}.
> */
> public void start() {
> if (log.isDebugEnabled()) {
> log.debug("Starting Eclipse BIRT platform");
> }
> EngineConfig engineConfig = birtConfig.getEngineConfig();
> try {
> Platform.startup(engineConfig);
> } catch (BirtException be) {
> throw new IllegalArgumentException("Failure starting BIRT platform",
> be);
> }
> if (log.isDebugEnabled()) {
> log.debug("Creating new instance of report engine.");
> }
> IReportEngineFactory factory = (IReportEngineFactory)
> Platform.createFactoryObject(IReportEngineFactory.EXTENSION_ REPORT_ENGINE_FACTORY);
>
> reportEngine = factory.createReportEngine(engineConfig);
> reportEngine.changeLogLevel(engineConfig.getLogLevel());
>
> }
>
> /**
> * Must be called after finishing use of the Eclipse BIRT APIs. E.g. at
> application shutdown
> * (hint, look at the destroy-method property of spring beans).
> *
> */
> public void shutdown() {
> if (log.isDebugEnabled()) {
> log.debug("Shutting down Eclipse BIRT platform");
> }
>
> if (reportEngine != null) {
> if (log.isDebugEnabled()) {
> log.debug("Shutting down report engine instance.");
> }
> reportEngine.shutdown();
> }
>
> // Just call shutdown
> Platform.shutdown();
> }
>
> /**
> * Create or return the cached instance of the {@link IReportEngine}.
> *
> * @return instance of {@link IReportEngine}
> */
> public IReportEngine getReportEngine() {
> return reportEngine;
> }
>
> /**
> * Sets the engineConfig.
> *
> * @param engineConfig The engineConfig to set.
> */
> public void setBirtConfig(BirtConfig birtConfig) {
> this.birtConfig = birtConfig;
> }
> public BirtConfig getBirtConfig() {
> return birtConfig;
> }
> }
>
|
|
|
Goto Forum:
Current Time: Sun May 11 12:55:50 EDT 2025
Powered by FUDForum. Page generated in 0.04184 seconds
|