• Home
  • RSS Feed
  • Log in

Eclipse BIRT in Spring web applications
Posted by Silvester Van der Bijl at around evening time: August 29th, 2006

Many applications we built have to provide reporting to allow end users to monitor results, progress, etc. In most cases a simple query and an Excel export is more than sufficient. In cases where more advanced reports are required we often look at projects like JasperReports or if that doesn't suffice maybe even Crystal Reports. As I'll try to explain in this blog, it might be worth your time to take a look at Eclipse BIRT.

The Eclipse “Business Intelligence and Reporting Tools” is one of those Eclipse projects I've been tracking for some time now. Its current release features a report designer based on our favorite IDE (also available as standalone download) which allows non-technical users to create reports with charts, tables, etc. It includes a web based report viewer application. It can of course execute the report designs, but also provides export capabilities (with AJAX column selection) and a range of other features.

For a more thorough overview of the features of BIRT, take a look at their website at http://eclipse.org/birt/phoenix. Features I found interesting:

  • Standalone designer (based on the Eclipse IDE)
  • Support for various datasources (including XML)
  • Different output formats (with similiar layout)

    Currently it supports PDF and HTML, but there is also an (experimental) XLS emitter available. Look for "tribix" here: http://qauck.blogspot.com

In most cases we want to include the reporting directly in our applications (to be able to provide security, caching, etc.). Since most of our applications are built using the Spring framework it would be convenient if we could use BIRT by instantiating a few beans. As it turns out we can, but it took me some time reading (sometimes) badly documented source code and googling a lot. The remainder of this blog describes the steps I took to integrate BIRT in a sample Spring web application.

Installation of the BIRT runtime
The BIRT project provides a download of just the components needed to execute and render reports in JEE environments named appropriately the "BIRT Runtime". For the example application I used the 2.1RC6 version. You can download it from Eclipse.org and extract it to ${eclipse.birt.home} (we're using this property later on).

Example project
I've attached a Maven 1.x example project to this page which includes all the code and necessary configuration. Since the BIRT libraries are not (yet) available on any public repository, you will need to copy the required libraries from the BIRT runtime (see ${eclipse.birt.home}/WebViewExample/WEB-INF/lib) and rename them according to the project.xml.

Firing up BIRT
Before we can start calling the BIRT API to execute and render reports, the BIRT platform itself must first be started using the appropriate configuration objects. Doing this from inside a Spring application context using just the BIRT classes turned out be difficult, so I've created two utility classes:

BirtConfiguration
Besides the getters and setters for properties this class provides the getEngineConfig() method, which creates an instance of EngineConfig used to configure BIRT upon startup. The "birtInstallation" property by itself is enough to start it and render reports, but the HTML export will use file:// uri's to reference any images you've included. We can solve this by telling BIRT to use the HTMLServerImageHandler and set the appropriate configuration (see BIRT spring configuration). In addition we can also specify the loglevel here.

public EngineConfig getEngineConfig() {
    if (engineConfig == null) {
      if (log.isDebugEnabled()) {
        log.debug("Creating new instance of EngineConfig");
      }

      engineConfig = new EngineConfig();
      engineConfig.setEngineHome(birtRuntimeLocation);
      engineConfig.setLogConfig(logLocation, logLevel);

      HTMLEmitterConfig htmlConfig = new HTMLEmitterConfig();
      htmlConfig.setActionHandler(new HTMLActionHandler());

      // This allows images to be referenced by url
      htmlConfig.setImageHandler(new HTMLServerImageHandler());

      engineConfig.getEmitterConfigs().put("html", htmlConfig);
    }

    return engineConfig;
  }

BirtPlatformListener
This class uses the EngineConfig (as created by the BirtConfiguration class) to start and initalize the platform, and allows the creation of an IReportEngine which in turn can be used to execute and render reports.

  public void start() {
    try {
      Platform.startup(engineConfig);
    } catch (BirtException be) {
      throw new IllegalArgumentException("Failure starting BIRT platform", be);
    }
  }

  public void shutdown() {
    if (reportEngine != null) {
      reportEngine.shutdown();
    }

    // Just call shutdown
    Platform.shutdown();
  }

  public IReportEngine getReportEngine() {
    if (reportEngine == null) {
      IReportEngineFactory factory = (IReportEngineFactory)
      Platform.createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY);

      reportEngine = factory.createReportEngine(engineConfig);
    }

    return reportEngine;
  }

Bean definitions
Once we have these two classes, it's simply a matter of configuring beans to be able to use BIRT whenever we want to. The following snippet from the spring context shows all the required definitions to start and stop the platform along with the application and create an IReportEngine instance.

	<!-- BIRT configuration -->
	<bean id="birtConfig"
		class="com.xebia.springbirt.util.BirtConfiguration">
		<property name="birtRuntimeLocation"
			value="${eclipse.birt.home}/ReportEngine" />
		<property name="logLocation" value="${eclipse.birt.logdir}" />
	</bean>

	<bean id="platformListener"
		class="com.xebia.springbirt.util.BirtPlatformListener"
		init-method="start" destroy-method="shutdown">
		<property name="engineConfig">
			<bean factory-bean="birtConfig"
				factory-method="getEngineConfig" />
		</property>
	</bean>

	<bean id="reportEngine" factory-bean="platformListener"
		factory-method="getReportEngine" />

	<!-- Render context beans -->
	<bean id="pdfRenderContext"
		class="org.eclipse.birt.report.engine.api.PDFRenderContext">
		<property name="supportedImageFormats" value="JPG;PNG;BMP;SVG" />
	</bean>

	<bean id="htmlRenderContext"
		class="org.eclipse.birt.report.engine.api.HTMLRenderContext">
		<property name="supportedImageFormats" value="JPG;PNG;BMP" />
		<property name="baseImageURL" value="${springbirt.url}/reportImage.html?id="/>
		<property name="imageDirectory" value="${eclipse.images.dir}"/>
	</bean>

Adding some controllers
I've created two Spring MVC controllers for the sample application. The ReportImageController is responsible for receiving requests for images included in the reports. It simply tries to open the file and writes back the contents (and deletes the files afterwards).

The ReportController is responsible for calling BIRT and executing our example report. The sample application includes a report design that uses the Slashdot RSS feed as datasource. The following code shows how to execute and render this report:

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String format = RequestUtils.getStringParameter(request, "format", "html");

    IReportRunnable runnable = reportEngine.openReportDesign(new ClassPathResource("BirtExample.rptdesign").getInputStream());
    IRunAndRenderTask runAndRenderTask = reportEngine.createRunAndRenderTask(runnable);

    // Although it's called HtmlRenderOption, it is used for all formats
    HTMLRenderOption htmlRenderOption = new HTMLRenderOption();
    htmlRenderOption.setOutputFormat(format);
    htmlRenderOption.setOutputStream(response.getOutputStream());

    runAndRenderTask.setAppContext(renderOptions);
    runAndRenderTask.setRenderOption(htmlRenderOption);
    runAndRenderTask.run();

    return null;
  }

Accessing the application (by default http://localhost:8080/springbirt/) should result in a HTML page which looks similar to this (altough probably with new entries :-) ):
Screenshot of Slashdot Birt report

If you'd rather take a look at the PDF version, just append ?format=pdf to the URL. You should now get a nice PDF in the same format as the HTML version.

The example application is simple. It only allows viewing an entire report without any interaction (which in most cases is enough), but it could be extended to provide similar features to the web applicatation that BIRT provides...

Conclusion
Although BIRT still has some flaws (e.g. the designer that keeps mixing up formatting of my charts), it's a powerful platform that I'm certainly going to be using for reporting more often.

  • Share/Bookmark

Filed under Eclipse, Java, Spring | 9 Comments »



9 Responses to “Eclipse BIRT in Spring web applications”



    Michael Franken Says:
    Posted at: September 1, 2006 at 11:32 am

    Great work, Silvester. Are you considering donating the com.xebia.springbirt stuff to Spring or make it available as Open Source?



    Silvester Van der Bijl Says:
    Posted at: September 1, 2006 at 3:52 pm

    Thanks! I\’ve been looking at the support for JasperReports in Spring, and I\’m considering creating View classes (like AbstractJasperReportsView). If the people add Spring are interested I\’ll be happy to donate it…

    Update: seems more people are interested in seeing Spring support for BIRT: http://opensource.atlassian.com/projects/spring/browse/SPR-1220



    Jason Weathersby Says:
    Posted at: November 9, 2006 at 9:43 pm

    Silvester,

    Nicely done. It would be great if you could add this example to the BIRT wiki. If you are interested send me an email at jasonweathersby at alltel.net.

    Thanks

    Jason



    M Chisty Says:
    Posted at: March 7, 2007 at 5:30 am

    Can u show us how is it possible to integrate BIRT with Struts 2 with an example?



    Leonard Says:
    Posted at: November 23, 2007 at 7:46 pm

    Is there any example of integreting BIRT with struts 2 ?
    M Chisty, did you find something ?



    David Apimerika Says:
    Posted at: March 5, 2008 at 10:26 am

    Cool stuff. I would like to see a tutorial that takes the jpetstore and extend it to produce reports using BIRT. As jpetstore supports either Spring or Struts, one of the questions above may be covered in the process. The jpetstore is a great learning aid (for me), especially couple with that book “Better, Faster, Lighter Java”.



    kishore maddipoti Says:
    Posted at: April 28, 2008 at 6:43 am

    This is very informative for the beginners and very excellent to refer



    Prakash Palanisamy Says:
    Posted at: July 4, 2008 at 12:50 pm

    thanks dude. Found superb information about the integration of BIRT with Spring. thank you so much. Keep post.



    Burt Says:
    Posted at: August 24, 2009 at 8:07 pm

    I got bir exception while display the rptdesign. invalid javascript dataSetRow[...]
    I use birt 2.5, Jboss4.2, Eclipse 3.2, spring



Leave a Reply

Click here to cancel reply.

Deployment automation for Java application running on Websphere, WebLogic and JBoss

Archives

  • January 2010
  • December 2009
  • November 2009
  • October 2009
  • September 2009
  • August 2009
  • July 2009
  • June 2009
  • May 2009
  • April 2009
  • March 2009
  • February 2009

Xebia Sites

  • Xebia Corporate
  • Xebia France
  • Xebia India

Categories

  • Java (279)
  • Agile (109)
  • General (50)
  • Testing (42)
  • Performance (42)
  • Hibernate (36)
  • Scrum (33)
  • Podcast (31)
  • Architecture (31)
  • Spring (28)
  • SOA (24)
  • Maven (22)
  • Project Management (22)
  • Flex (17)
  • JPA (17)
    • JPA implementation patterns (13)
  • Eclipse (15)
  • Quality Assurance (14)
  • Middleware (19)
  • Frameworks (13)

Tag Cloud

    Agile Agile Awareness Workshop product owner Semantic Web Ajax Functional Programming Groovy Spring Scrum XML Scala fitnesse Grails Introduction to Agile Lean qcon Closures SOA Poppendieck Xebia Seam Testing Java IntelliJ esb Maven Hibernate Architecture Performance JavaOne
medicin depression buy phentermine without a perscription aricept generic hair loss help how do you prevent bone loss urinary tract infection symptoms viagra sex domination cialis viagra cures for throat infection buy sumycin acne care new medication for cancer treatment help for sleeping problems on-line pharmacies cure snoring medications to help clot blood what is aspirin buy zestoretic bronchitis vs pneumonia back pain muscle acne face medication muscle women pain behind knee fat blocker man health arthritis natural cure woman health women insomnia cheap phentermine online cats and irritable bowel syndrome buy cialis generic online nutritional diet for osteoporosis abnormal blood clots treatments for hair loss what is zyprexa dental whitening products impotence herbs drugs for diabetes allergy prevention buy canada levitra Mentax adhd in children hair loss in woman medicines for blood clot online imitrex viagra buy free dog products clindamycin drug how to stop hair loss chloramphenicol discount drug viagra what valium does permanent hair loss heart failure medicine avapro 150mg ordering viagra online food allergies order viagra online online viagra prescription carisoprodol mg improve your skin discount erectile dysfunction medication buy xanax online buy order viagra scabies teatments information allegra vitamine b1 diazepam breast cancer support free stop smoking cipro side effects ultram cheapest treatment attention deficit disorder discount vitamins supplements how to get viagra online synthroid buy cheapest cialis zyrtec online how to clear acne preventive osteoporosis immune stimulants what is hoodia On Line Viagra getting over the pain diflucan dosage health asthma online stores hair loss products blood clot drugs colon parasites hair loss products discount medicine pravastatin buy griseofulvin tablets order indomethacin dog health products how to take a beta-blocker diazapan is valium treating cold sores chronic pain drug what is osteoporosis stress drug tooth whitening lowering cholesterol naturally legality of buying cialis online order levitra treatment for insomnia cheapest cialis index depakote overdose alprazolam condom sales treatment of yeast infection xanax sales taking viagra after cialis how to control pain new birth control chest pain health prozac prescription blood clots viagra in mexico chlamydia pill cancer drugs cold flu drugs how do i order viagra online super viagra acyclovir medicine benadryl dosage erythromycin pregnancy buy contoured condom chronic muscle pain pet health dogs treatment attention deficit disorder dental teeth whitening asthma medicine free prescription drugs herpes drug diabetes treatment buy tooth whitening gel cheap fast valium generic levitra buy cheapest viagra online lopressor drug pharmacy drug prices ultram dosing treatments for bipolar disorder neurontin withdrawal parasite medication chlamydia tips for increasing breast size ways to enhance breast what is valium used for metformin tablet order birth control hair loss for men how does xanax work treatment hepatitis c rythmol cheap acai antioxidants nexium generic blood pressure pills levitra online no prescription Levitra Online medications on line motion sickness drugs bactrim online order roxithromycin nicotine where can i order viagra immune supplements buy erexin v bph prostate allopurinol xanax for depression drug new smoking stop cheap impotence drug generic cialis delivery new treatment for depression antibiotics for cat viagra china alternative medicine cholesterol viagra dose anxiety disorder treatment severe muscle pain treatment of cancer calcium carbonate penis enlargement without pill valium maximum dosage reasons for high blood pressure energy product breast enlargement info cheap effexor building your body wrinkle cream aricept dosage alpha blocker increasing female sex drive valium depression new pain meds no rx xanax drug trileptal mg imitrex avapro 150mg medicine drugs contraception female claritin pill medication for acne med orders buy viagra internet levitra effect treatment for blood clots order sominex buy creatine buy precose cheap viagra overnight lopressor drug body building info health drugs general health and medical what is diazepam eye infections in dogs online prescription pills diclofenac tablet new medication anxiety buy citalopram medication male enhancement enhancement fat blocker medicine for throat infection order cardizem about soma health remedies for dogs generic xanax cheap zyrtec for depression medicine viagra sex domination buy acne skin care product hypnosis help study cure vaginal yeast infection weight loss supplement program muscle pain in leg how to increase erection buy viagra what is cla augmentin doses gaining muscle mass health med online heart rate treatments lopressor drug dog ear canal phentermine without prescription viagra order online weight loss glipizide diabetes astelin generic fat blocker buy gel tooth whitening cheap wellbutrin online weight loss program buy antiox anti-biotics acne skin treatmen tramadole vpxl pill drugs affecting levitra immune system support augmentin hypothyroidism medication buy erexin v uy prescription medication without a prescription buy discount order osteo arthritis online buy pilocarpine cheapest place to buy phentermine parasite treatment impotence help body fat loss viagra herb alternative constipation supplements treatment dementia adhd and medications muscle spasm relief viagra online cheap relieve upper back pain stop hair loss discount viagra online menstrual cycle problems antifungal shampoo side effects ativan gabapentin medication where can i buy viagra diazepam buy soma online clonidine dosage viagra gel top hair loss fast antibiotics cure chlamydia skin fungal infections drug zofran give up smoking alternative medicine cholesterol sleeping help best online viagra scams prednisone 10mg viagra sex domination lotensin easy weight loss pain meds without prescription over the counter drugs new high blood pressure medic generic compazine cetirizine drug order phentermine best fat blockers woman enhancement supplement drug zofran buy precose new drug treatment for cancer how to increase fertility viagra in australia benadryl dosing buy alcoholism medications order l arginine buy diazepam generic for ativan ativan prescription drugs weight loss treatment for chest pain woman health where can i buy phentermine online skin fungal infection give up smoking viagra on line hoodia information how does osteoporosis occur buy viagra online buy alcoholism medications depakote overdose klonopin pill tetracycline capsules what is high blood pressure bladder control for dogs generic for lipitor glucophage online pharmacy gabapentin dosage treating yeast infections dog health info cymbalta anxiety cheap tramadol without prescription hydrea drugs used for cancer cure for high blood pressure alcohol and valium relief from constipation liver infection treatment cialis soft zantac medication help sleep problems all natural antibiotics order medication without prescription sleep problems free hypnotherapy gaining muscle mass cheap viagra order online natural help for pain how to buy viagra drug price celebrex information otc diuretic levitra 10 mg buy medicine online pets products relief foot pain cialis without prescription med care cheapest generic cialis rapid hair loss pain medications generic side effects meds without prescriptions cat anxiety buy simplicef natural cure arthritis effects of high blood pressure lowest price generic viagra how to get birth control new breast cancer drug buy topamax blood pressure meds when are beta blockers prescribed how to get pain meds order fosamax online viagra name order viagra viagra cialis cat's eye health how to relieve lower back pain treating ear infections diazapan is valium online pain doctors high blood pressure in elderly medication to stop smoking wellbutrin dosages diabetes blood sugar levels weight loss diet pill side effects of prescribed pain pills drug list high blood pressure buy cialis online in usa ultram cost how to help osteoporosis how to use clomid discount brand viagra wellbutrin cymbalta buy pills without a prescription buy pain medicine online tab tramadol depression symptoms treatment how levitra work hypertension medications beta blockers prevent premature ejaculation xanax interactions with other medicines purchase medicine on line does alli work xenical mexico prescriptions buy sumycin uy prescription medication without a prescription ambien cost methocarbamol effects cheap beta blockers cats bladder reduce cholesterol naturally metformin tablet scabies medicine breast enhancer pills body building over 50 order viagra cheap zestril medication how to buy prescription medications online pharma kamagra drugs depression ear infection symptoms big muscle controlling blood pressure pain meds and pregnancy buy diazepam without prescription skin allergies antibiotic zoloft buy weight loss nutrition program Buy Cialis breast increase meds without prescriptions blood clots medical edema treatment for flu best hangover remedy diabetes drugs