birt系列(4)--birt報表自定義數據源

 

 handler相關類中,關鍵是動態設置IDataSourceInstance dataSource,相關處理代碼如下:

這段代碼實現功能是:優先用報表管理的數據源,如果報表本身沒有設置數據源,則採用公共數據源(配置文件中配置)

public class BirtDataSource extends DataSourceEventAdapter {
	private ReportDao repDao = new ReportDao();
	//ReportDesignHandle designHandle = null; // 報表設計引擎
	//ElementFactory designFactory = null; // 元素工廠
	//StructureFactory structFactory = null;

	@Override
	public void beforeOpen(IDataSourceInstance dataSource,
			IReportContext reportContext) throws ScriptException {
		super.beforeOpen(dataSource, reportContext);
		String name = reportContext.getReportRunnable().getReportName();
		String reportName = name.substring(name.lastIndexOf("/")+1);
		
		System.out.println("【BirtDataSource】當前連接報表的名稱爲:"+reportName);
		
		
		
		
		DataSource dt = repDao.getDataSourceByReportName(reportName);
		dataSource.setExtensionProperty("odaURL", dt.getDataSourceUrl());
		dataSource.setExtensionProperty("odaUser", dt.getDataSourceUserName());
		dataSource.setExtensionProperty("odaPassword", dt.getDataSoucePassword());
		dataSource.setExtensionProperty("odaDriverClass",dt.getDataSourceDriver());
		
		System.out.println("【BirtDataSource】當前報表連接的數據源爲:"+dt.getDataSourceName());
		
		if(dt.getDataSourceName()==null&&dt.getDataSoucePassword()==null&&dt.getDataSourceDriver()==null){
			System.out.println("【BirtDataSource】多數據源爲空,直接讀取dbconfig2.properties");
			
			InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("dbconfig2.properties");
			Properties p = new Properties();
			try {
				p.load(inputStream);
				String username = p.getProperty("username");
				dataSource.setExtensionProperty("odaURL", p.getProperty("url"));
				dataSource.setExtensionProperty("odaUser", username);
				dataSource.setExtensionProperty("odaPassword", p.getProperty("password"));
				dataSource.setExtensionProperty("odaDriverClass", p.getProperty("driver"));
				System.out.println("讀取dbconfig2.properties。。。。。。。");
				//判讀連接是否可用
				Class.forName(p.getProperty("driver"));
				Connection conn = DriverManager.getConnection(p.getProperty("url"),username,p.getProperty("password"));
				if(conn == null){
					System.out.println("【BirtDataSource】當前報表連接不上數據庫,請檢查數據庫連接");
				}else{
					conn.close();
				}
				
			} catch (IOException e1) {
				e1.printStackTrace();
			} catch (SQLException e) {
				System.out.println("【BirtDataSource】:"+e.getMessage());
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章