Java 如何以编程方式为BIRT报告设置数据源?

Java 如何以编程方式为BIRT报告设置数据源?,java,reporting,report,birt,Java,Reporting,Report,Birt,我有一份BIRT报告,它连接到我们的测试数据库。在生产环境中,我希望提供一个由容器通过jndi提供的数据源 如何以编程方式为给定报表设置数据源 ... IReportRunnable design = birtEngine.openReportDesign ( new File ( properties.getProperty ( "reportPath" ), report + ".rptdesign" ).getAbsolutePath () ); IRunAndRe

我有一份BIRT报告,它连接到我们的测试数据库。在生产环境中,我希望提供一个由容器通过jndi提供的数据源

如何以编程方式为给定报表设置数据源

    ...
    IReportRunnable design = birtEngine.openReportDesign ( new File ( properties.getProperty ( "reportPath" ), report + ".rptdesign" ).getAbsolutePath () );
    IRunAndRenderTask task = birtEngine.createRunAndRenderTask ( design );

    PDFRenderOption options = new PDFRenderOption ();
    options.setOutputFormat ( PDFRenderOption.OUTPUT_FORMAT_PDF );
    options.setOutputStream ( out );
    task.setRenderOption ( options );
    for ( Entry<String, Object> entry : parameters.entrySet () )
    {
        task.setParameterValue ( entry.getKey (), entry.getValue () );
    }

    task.run ();
    task.close ();
    ...
。。。
IReportRunnable design=birtEngine.openReportDesign(新文件(properties.getProperty(“reportPath”)、report+“.rptdesign”).getAbsolutePath());
IRunAndRenderTask=birtEngine.createRunAndRenderTask(设计);
PDFRenderOption=newpdfrenderoption();
options.setOutputFormat(PDFRenderOption.OUTPUT_格式_PDF);
options.setOutputStream(输出);
task.setRenderOption(选项);
for(条目:parameters.entrySet())
{
task.setParameterValue(entry.getKey(),entry.getValue());
}
task.run();
task.close();
...

我想我必须修改
设计
,但另一方面
任务
有一个方法
setDataSource
,但这看起来有点像我必须提供一些xml dom元素。

在运行时只设置数据源会有问题,因为数据集绑定到单个数据源和控件然后将报表上的数据绑定到特定的数据集。在每次运行报表时,尝试自己构建这个层次结构会非常困难

您可以参数化数据源定义的所有方面,从而使您的设计可在所有环境中移植。编辑数据源时,请查看左侧的属性绑定分组。这将为您提供足够的灵活性,使您的数据源更具可移植性。您可以为JDBCURL元素或运行时JNDI配置文件指定运行时参数


希望这有帮助。

您可以为数据库连接字符串创建一个报告参数

然后,将数据源->属性绑定->JNDI URL下的JNDI URL设置为:params[“Database”]。value

(其中“Database”是报表参数的名称)

查看以下代码,您可能会在运行时获得一些关于提供数据源的帮助

按照我的要求,它很好用

我是从某个网站上得到的,不记得了

import java.io.IOException;
import java.util.ArrayList; 

import org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.report.model.api.CellHandle;
import org.eclipse.birt.report.model.api.DataItemHandle;
import org.eclipse.birt.report.model.api.DesignConfig; 
import org.eclipse.birt.report.model.api.ElementFactory;
import org.eclipse.birt.report.model.api.IDesignEngine;
import org.eclipse.birt.report.model.api.IDesignEngineFactory;
import org.eclipse.birt.report.model.api.LabelHandle;
import org.eclipse.birt.report.model.api.OdaDataSetHandle;
import org.eclipse.birt.report.model.api.OdaDataSourceHandle;
import org.eclipse.birt.report.model.api.PropertyHandle;
import org.eclipse.birt.report.model.api.ReportDesignHandle;
import org.eclipse.birt.report.model.api.RowHandle;
import org.eclipse.birt.report.model.api.SessionHandle;
import org.eclipse.birt.report.model.api.StructureFactory;
import org.eclipse.birt.report.model.api.TableHandle;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.elements.structures.ComputedColumn;

import com.ibm.icu.util.ULocale;

/**
 * Dynamic Table BIRT Design Engine API (DEAPI) demo.
 */

public class DECreateDynamicTable
{
    ReportDesignHandle designHandle = null;
    ElementFactory designFactory = null;
    StructureFactory structFactory = null;  

    public static void main( String[] args )
    {
        try
        {
            DECreateDynamicTable de = new DECreateDynamicTable();
            ArrayList al = new ArrayList();
            al.add("USERNAME");
            al.add("COUNTRY");
            de.buildReport(al, "From GTM_REPORT_APP_USER" );
        }
        catch ( IOException e )
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch ( SemanticException e )
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    void buildDataSource( ) throws SemanticException
    {

        OdaDataSourceHandle dsHandle = designFactory.newOdaDataSource(
                "Data Source", "org.eclipse.birt.report.data.oda.jdbc" );
        dsHandle.setProperty( "odaDriverClass",
                "oracle.jdbc.driver.OracleDriver" );
        dsHandle.setProperty( "odaURL", "jdbc:oracle:thin:@xeon:1521:ora9i" );
        dsHandle.setProperty( "odaUser", "AIMS_GTMNE" );
        dsHandle.setProperty( "odaPassword", "AIMS_GTMNE" );

        designHandle.getDataSources( ).add( dsHandle );

    }

    void buildDataSet(ArrayList cols, String fromClause ) throws SemanticException
    {

        OdaDataSetHandle dsHandle = designFactory.newOdaDataSet( "ds",
                "org.eclipse.birt.report.data.oda.jdbc.JdbcSelectDataSet" );
        dsHandle.setDataSource( "Data Source" );
        String qry = "Select ";
        for( int i=0; i < cols.size(); i++){
            qry += " " + cols.get(i);
            if( i != (cols.size() -1) ){
                qry += ",";
            }

        }
        qry += " " + fromClause;

        dsHandle.setQueryText( qry );

        designHandle.getDataSets( ).add( dsHandle );



    }
    void buildReport(ArrayList cols, String fromClause ) throws IOException, SemanticException
    {


        //Configure the Engine and start the Platform
        DesignConfig config = new DesignConfig( );

        config.setProperty("BIRT_HOME", "D:/Softwares/Frame Works - APIs-Tools/birt-runtime-2_6_1/birt-runtime-2_6_1/ReportEngine");

        IDesignEngine engine = null;
        try{


            Platform.startup( config );
            IDesignEngineFactory factory = (IDesignEngineFactory) Platform.createFactoryObject( IDesignEngineFactory.EXTENSION_DESIGN_ENGINE_FACTORY );
            engine = factory.createDesignEngine( config );

        }catch( Exception ex){
            ex.printStackTrace();
        }       


        SessionHandle session = engine.newSessionHandle( ULocale.ENGLISH ) ;



        try{
            //open a design or a template

            designHandle = session.openDesign("D:/tempBirtReport/test.rptdesign");

            designFactory = designHandle.getElementFactory( );

            buildDataSource();
            buildDataSet(cols, fromClause);

            TableHandle table = designFactory.newTableItem( "table", cols.size() );
            table.setWidth( "100%" );
            table.setDataSet( designHandle.findDataSet( "ds" ) );


            PropertyHandle computedSet = table.getColumnBindings( ); 
            ComputedColumn  cs1 = null;

            for( int i=0; i < cols.size(); i++){
                cs1 = StructureFactory.createComputedColumn();
                cs1.setName((String)cols.get(i));
                cs1.setExpression("dataSetRow[\"" + (String)cols.get(i) + "\"]");
                computedSet.addItem(cs1);
            }


            // table header
            RowHandle tableheader = (RowHandle) table.getHeader( ).get( 0 );


            for( int i=0; i < cols.size(); i++){
                LabelHandle label1 = designFactory.newLabel( (String)cols.get(i) ); 
                label1.setText((String)cols.get(i));
                CellHandle cell = (CellHandle) tableheader.getCells( ).get( i );
                cell.getContent( ).add( label1 );
            }                           

            // table detail
            RowHandle tabledetail = (RowHandle) table.getDetail( ).get( 0 );
            for( int i=0; i < cols.size(); i++){
                CellHandle cell = (CellHandle) tabledetail.getCells( ).get( i );
                DataItemHandle data = designFactory.newDataItem( "data_"+(String)cols.get(i) );
                data.setResultSetColumn( (String)cols.get(i));
                cell.getContent( ).add( data );
            }

            designHandle.getBody( ).add( table );

            // Save the design and close it. 

            designHandle.saveAs( "D:/tempBirtReport/test.rptdesign" ); //$NON-NLS-1$
            designHandle.close( );
            System.out.println("Finished");
        }catch (Exception e){
            e.printStackTrace();
        }       

    }
 }
import java.io.IOException;
导入java.util.ArrayList;
导入org.eclipse.birt.core.framework.Platform;
导入org.eclipse.birt.report.model.api.CellHandle;
导入org.eclipse.birt.report.model.api.DataItemHandle;
导入org.eclipse.birt.report.model.api.DesignConfig;
导入org.eclipse.birt.report.model.api.ElementFactory;
导入org.eclipse.birt.report.model.api.IDesignEngine;
导入org.eclipse.birt.report.model.api.IDesignEngineFactory;
导入org.eclipse.birt.report.model.api.LabelHandle;
导入org.eclipse.birt.report.model.api.odadasethandle;
导入org.eclipse.birt.report.model.api.odatasourcehandle;
导入org.eclipse.birt.report.model.api.PropertyHandle;
导入org.eclipse.birt.report.model.api.ReportDesignHandle;
导入org.eclipse.birt.report.model.api.RowHandle;
导入org.eclipse.birt.report.model.api.SessionHandle;
导入org.eclipse.birt.report.model.api.StructureFactory;
导入org.eclipse.birt.report.model.api.TableHandle;
导入org.eclipse.birt.report.model.api.activity.SemanticException;
导入org.eclipse.birt.report.model.api.elements.structures.ComputedColumn;
导入com.ibm.icu.util.ULocale;
/**
*动态表BIRT设计引擎API(DEAPI)演示。
*/
公共类可减量化
{
ReportDesignHandle designHandle=null;
ElementFactory designFactory=null;
StructureFactory structFactory=null;
公共静态void main(字符串[]args)
{
尝试
{
DECreateDynamicTable de=新的DECreateDynamicTable();
ArrayList al=新的ArrayList();
添加(“用户名”);
al.添加(“国家”);
de.buildReport(al,“来自GTM报告应用程序用户”);
}
捕获(IOE异常)
{
//TODO自动生成的捕捉块
e、 printStackTrace();
}
catch(语义异常e)
{
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
void buildDataSource()抛出语义异常
{
ODatasourceHandle dsHandle=designFactory.NewODatasource(
“数据源”,“org.eclipse.birt.report.Data.oda.jdbc”);
dsHandle.setProperty(“odaDriverClass”,
“oracle.jdbc.driver.OracleDriver”);
setProperty(“odaURL”,“jdbc:oracle:thin:@xeon:1521:ora9i”);
setProperty(“odaUser”、“aimsgtmne”);
setProperty(“odaPassword”、“aimsgtmne”);
designHandle.getDataSources().add(dsHandle);
}
void buildDataSet(ArrayList cols,String fromClause)抛出SemanticException
{
ODataSethandle dsHandle=designFactory.NewODataset(“ds”,
“org.eclipse.birt.report.data.oda.jdbc.JdbcSelectDataSet”);
dsHandle.setDataSource(“数据源”);
字符串qry=“选择”;
对于(int i=0;i    /*
 * Change the data sources in the .rptdesign
 */
void changeDataSource(ElementFactory designFactory,
        ReportDesignHandle designHandle, String userConnect)
        throws SemanticException {

    SlotHandle datasources = designHandle.getDataSources();
    SlotIterator iter = (SlotIterator) datasources.iterator();
    while (iter.hasNext()) {
        DesignElementHandle dsHandle = (DesignElementHandle) iter.next();
        if (dsHandle instanceof OdaDataSourceHandle && dsHandle.getName().equals("lisa")) {
            log.debug("changeDataSource: Changing datasource "
                    + dsHandle.getName() + " new url=" + getLisaDbUrl());
            dsHandle.setProperty("odaDriverClass",
                    "oracle.jdbc.driver.OracleDriver");
            dsHandle.setProperty("odaURL", getLisaDbUrl());
            dsHandle.setProperty("odaUser", getLisaUser());
            dsHandle.setProperty("odaPassword", getLisaPassword());
        } else {
            log.debug("changeDataSource: Ignoring DS " + dsHandle.getName());
        }
    }
}
  Context initialContext = new InitialContext();
     if ( initialContext == null){
     System.out.println("JNDI problem. Cannot get InitialContext.");
        }
        DataSource datasource = (DataSource)initialContext.lookup("java:/datasources/SAMPLE");
     task.getAppContext().put("OdaJDBCDriverPassInConnection", datasource.getConnection());