Friday, October 24, 2008

Java: Multi-Part Form Request using Apache Commons HttpClient

I previously wrote about how to do a simple HTTPUrlConnection request to a web page. This has served me well for quite some time. However, I ran into an issue on a recent project where I needed to do POST request and do a Multi-Part form to post large XML feeds to a service an a web appliance. This is where using HTTPUrlConnection broke down for my needs. While it is possible to do a Multi-Part POST using these classes, it turned out to be more trouble than it was worth.

This is where the Apache Commons HttpClient libraries came into play. Using the more robust Apache Commons libraries, I was easily able to throw together a Multi-Part form POST. There is one slight caveat when using HttpClient, you will need to include the Apache Commons Logging and Apache Commons Codec libraries in your classpath. Even if you do not use them in your implementation, HttpClient apparently uses them internally.

Below is a simplified example of using the HttpClient libraries to do a Multi-Part form POST. I commented out the sections relating to Cookies and posting Files since I was using XML strings.



package com.digiassn.blogspot;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class ApacheHttpClientRequest {
private URL serverAddress;
private String multiPart;
private String result;
private String originalURL;

/**
* Main constructor
*
* @param urlString
* @param queryString
* @param mainReferenceIn
*/
public ApacheHttpClientRequest(String urlString)
{
try {
//This is only used to test the URL as a valid URL, serverAddress is not actually used anywhere
serverAddress = new URL(urlString);
originalURL = urlString;
} catch (MalformedURLException e) {
e.printStackTrace();
}
}

/**
* This method will connect to server, and return the results of the push
* You must set Query first, which is the contents of your XML file
*/
private void executeQuery()
{
PostMethod filePost = null;
HttpClient client = null;
try {
//create new post method, and set parameters
filePost = new PostMethod(originalURL);
filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE,
true);


if ((multiPart.equals("")) || (multiPart == null))
{
throw new Exception("Query is null");
}

//create bytearray multi-part source from the query
ByteArrayPartSource targetFile = new ByteArrayPartSource("data", multiPart.getBytes());

//instead of a ByteArrayPartSource, the following could just as easily be used
//to include a file
//File f = new File("");
//FilePartSource fileSource = new FilePartSource(f);

Part[] parts = {
new StringPart("firstParameter", "value"),
new StringPart("secondParameter", "value"),
new FilePart("data", targetFile)
};

//Create the multi-part request
filePost.setRequestEntity(
new MultipartRequestEntity(parts, filePost.getParams())
);

//connect to server
client = new HttpClient();
client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

//the Cookie Handler, if your using manual cookies
//filePost.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
//filePost.setRequestHeader("Cookie", "name=value");

//execute and return status
int status = client.executeMethod(filePost);
if (status == HttpStatus.SC_OK) {
System.out.println("Upload success");
} else {
System.out.println("Upload failed: " + HttpStatus.getStatusText(status));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
//set objects to null and garbage collect, not normally necessary but
//some issues popped up in the multi-threaded environment with memory consumption if this
//was not included
filePost = null;
client = null;

//force garbage collection. Expect to take a hit here in performance, may not be necessary
Runtime r = Runtime.getRuntime();
r.gc();
}
}

//below here are the gets and sets
public void setMultiPartString(String query) {
this.multiPart = query;
}

public String getResult() {
return result;
}

public URL getServerAddress() {
return serverAddress;
}

public void setServerAddress(URL serverAddress) {
this.serverAddress = serverAddress;
}
}

Thursday, October 23, 2008

ASM: Drawing a Checkerboard

Someone asked a question on a C++ Newgroup about how to draw a checkerboard. Of course, I wasn't satisfied doing this in C++, and I've been looking for a ASM task to do just for practice. This is what I whipped up really quick. The following example will set the video mode to 320x200x256 VGA mode, and draw a black and white checkerboard.

The comments don't belong, I just added them so it is easier to follow. The following was done using DOS Debug.

--Initialize to 320*200*256 color mode
MOV AX,0013
INT 10
--Point the data and extra segments to the video memory directly and clear the DI register
MOV AX,A000
MOV DS,AX
MOV ES,AX
XOR DI,DI
--Set AX to the first pallete entry (using 2 byte for the STOSW instructions instead of one)
--Set BX to second one. We will swap these after our checkerboard rows are done
MOV AX,0F0F
MOV BX,0000
--initialize CX, our outmost loop, to the number of rows to draw
MOV CX,0008
PUSH CX
--set CX, the middle loop, set to the number of times we need to draw a line pattern for the square
--The way it works is like this, there are 8 pattern breaks in a line (black white alternations).
--we need to repeat that alternation 25 times in order to make a single increment of that alteration
--on the veritcal plane, so 25 * 8 = 200
MOV CX,00C8
PUSH CX
--set Cx to the number of horizontal pixels in a square, which is 20 (320 / 8) = 160, which
--is the 320 / 2 since we are using a word instruction, not a byte instruction
MOV CX,0014
--copy what is in AX to video memory 20 times
REPZ
STOSW
--swap the pallete bytes
PUSH AX
MOV AX,BX
POP BX
--get the value of our middle loop
POP CX
LOOP 011B
--we are at the end of a single verital iteration, swap the pallete entries and go again, until
--the outtermost loop is at 0
PUSH AX
MOV AX,BX
POP BX
POP CX
LOOP 0117
--wait for keypress
MOV AH,10
INT 16
--reset video mode
MOV AX,0003
INT 10
--return to dos
MOV AX,4C00
INT 21

Java: Simple HTTPUrlConnection example

I’ve been a little lax in posting lately. Since I have been doing a little more network based programming in Java as of late, and I wanted to post some more basic programming articles, I felt I would kill two birds with one stone. Fortunately most of it has been simple HTTP based requests, so it has been pretty simple stuff in terms of implementation. Most of how to do so is well documented already, so I won’t echo what has been written better by others. Instead, I will just share a simple example of how to establish an HTTP GET request using the HttpURLConnection and display the results to the console.
package com.digiassn.blogspot;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class SimpleHTTPRequest {

/**
* @param args
*/
public static void main(String[] args) {
HttpURLConnection connection = null;
OutputStreamWriter wr = null;
BufferedReader rd = null;
StringBuilder sb = null;
String line = null;

URL serverAddress = null;

try {
serverAddress = new URL("http://localhost");
//set up out communications stuff
connection = null;

//Set up the initial connection
connection = (HttpURLConnection)serverAddress.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setReadTimeout(10000);

connection.connect();

//get the output stream writer and write the output to the server
//not needed in this example
//wr = new OutputStreamWriter(connection.getOutputStream());
//wr.write("");
//wr.flush();

//read the result from the server
rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
sb = new StringBuilder();

while ((line = rd.readLine()) != null)
{
sb.append(line + '\n');
}

System.out.println(sb.toString());

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally
{
//close the connection, set all objects to null
connection.disconnect();
rd = null;
sb = null;
wr = null;
connection = null;
}
}
}


Next post will show how to use the Apache HTTPClient to establish a Multi-Part form POST request.

Monday, September 29, 2008

OSGi: JAXB with OSGi

For the past few months I have kept my head down, kept a low profile, and have been studying and learning things that I have had little to no experience with. One such thing is working with building applications with the OSGi framework. I have come across a number of good articles that have explained how to build OSGi based applications in all the major implementations. The better of all the articles are listed here:

But I ran into some issues with the project I was working on. All of these issues had to do with Classloaders in the OSGI framework not being compatible with whatever packages I was working with. One such case was with JAXB.

Fortunatly, I came across the DynamicJava website. These guys seem dedicated to creating OSGi Launchers and JSR API's that are compatible with OSGi. Neat trick, and they work too. However, to get these to work within Eclipse is another story all together.

First, download the following packages from their site:
  • STAX
  • JPA
  • JAXB
All of these are necessary for JAXB to work. Create three projects in Eclipse, each with their respective names off STAX, JPA, and JAXB. In my case, I created these three projects:

  • org.dynamicjava.jsr.jaxb_api
  • org.dynamicjava.jsr.jpa_api
  • org.dynamicjava.jsr.stax_api
Extract the three archives downloaded into the respective packages. In my case, I moved all the source files into the /src folders under their plugin folders.

For the STAX package, the only modification that needed to be made was in the build.properties file. It should read like so:

source.. = src/
output.. = bin/
bin.includes = META-INF/,\
.

Be sure to include the dot on the line for bin.includes. Eclipse did a really strange thing where it kept losing it for me.

I did end up needing to make a few changes for the JPA_API plugin. The MANIFEST.MF read as follows when I was done:

Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-SymbolicName: org.dynamicjava.jsr.jpa_api
Bundle-Version: 1.0.0
Bundle-Activator: javax.persistence.internal.Activator
Bundle-Name: DynamicJava.org: JSR: JPA-API
Export-Package: javax.persistence;version="1.0.0",
javax.persistence.internal,
javax.persistence.internal.classloading_utils,
javax.persistence.internal.support,
javax.persistence.spi;version="1.0.0"
Import-Package: org.osgi.framework
Require-Bundle: org.eclipse.osgi


The Build.properties was exactly the same as the STAX_API.

If both projects are building correctly in Eclipse, then the final part will be to get JAXB working. This one really proved to be a big PITA. First, download the geronimo-activation_1.1_spec-1.0.2.jar. This jar is available inside of the test program that the Dynamic Java guys provide. The JPA plugin should contain this, however I had issues putting this into the JPA plugin, so I ended up putting it into the JAXB plugin (which I may change at some point). Download the jar and put it into the /lib folder in the JAXB plugin. You will also need the jaxb-impl.jar file, available in the same archive.

From there, the Manifest.MF for the JAXB project should read like so:

Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-SymbolicName: org.dynamicjava.jsr.jaxb_api
Bundle-Version: 1.0.0
Bundle-Activator: javax.xml.bind.internal.Activator
Bundle-Name: DynamicJava.org: JSR: JAXB-API
Export-Package: com.sun.xml.bind,
com.sun.xml.bind.v2,
javax.activation,
javax.xml.bind;version="2.1.0",
javax.xml.bind.annotation;version="2.1.0",
javax.xml.bind.annotation.adapters;version="2.1.0",
javax.xml.bind.attachment;version="2.1.0",
javax.xml.bind.helpers;version="2.1.0",
javax.xml.bind.util;version="2.1.0"
Import-Package: javax.xml.namespace,
javax.xml.stream;version="1.0.0",
javax.xml.transform
Bundle-License: http://www.opensource.org/licenses/cddl1.php
Require-Bundle: org.dynamicjava.jsr.stax_api,
org.dynamicjava.jsr.jpa_api,
org.eclipse.osgi
Bundle-ClassPath: lib/jaxb-impl.jar,
.,
lib/geronimo-activation_1.1_spec-1.0.2.jar

The Build.properties files needs to be modified to read like so:

source.. = src/
output.. = bin/
bin.includes = META-INF/,\
.,\
lib/jaxb-impl.jar,\
lib/geronimo-activation_1.1_spec-1.0.2.jar

Now, you can use JAXB from within OSGi.

Monday, August 11, 2008

BIRT: Launch a BIRT RCP Application through Java Web Start

Its been a while since I've written a good tutorial. So I was fortunate that I had a fellow ask me about writing launching BIRT from Java Web Start. After some investigation, I found that there is a bit of a problem with the OSGi startup in an application. So, I did a little digging into how I can launch an RCP application from Java Web Start. These are the steps I followed on how to be able to do that. The following example will show how to embed BIRT into an RCP application, and then set that RCP application up to run from Java Web Start. I will also store my BIRT report on a web server, load the BIRT report from the web server, and launch it.

I followed, for the most part, the instructions from the following sites:

http://www.onjava.com/pub/a/onjava/2006/07/26/deploying-birt.html?page=4

http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.platform.doc.isv/guide/java_web_start.htm

I did have to modify this slightly since both of these articles were a little out of date.

First step is to create the RCP application with BIRT capable of running my report.

  1. Create a new Eclipse Plug-In project.

  2. Name the Eclipse project BIRTRCPViewer, and keep the default option.

  3. In the next screen, set that this project will make contributions to the UI, and that it is an RCP Application.

  4. Specify that this will be a RCP application with a view. You can click Finish at this point.

  5. In the Plugin Editor, go over to the Dependencies tab. Add in the org.eclipse.birt.core and org.eclipse.birt.report.engine packages to dependencies, and in the Imported Packages, add in the oda.jdbc, oda.sampledb, and emitter.html packages. If you plan to use other formats besides HTML for your final report output, add them here.

  6. Open up the View.java file and modify it to have a simple Browser element embedded in a fill layout. (Code will be displayed at the end of the next step)
  7. Now, we need to start the BIRT engine, and render a report. I have created a simple report called test.rptdesign, and stored it on my local Apache web server, located at localhost:8080/birt/test.rptdesign. I put all the BIRT startup and render code in the createPartControl method, and set it so that the results will be displayed in the Browser control. The finished code for the View.java is as follows:

    package rcptest;

    import java.io.ByteArrayOutputStream;
    import java.io.InputStream;
    import java.net.URL;
    import java.util.HashMap;

    import org.eclipse.birt.core.framework.Platform;
    import org.eclipse.birt.report.engine.api.EngineConfig;
    import org.eclipse.birt.report.engine.api.EngineConstants;
    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.IRenderOption;
    import org.eclipse.birt.report.engine.api.IReportEngine;
    import org.eclipse.birt.report.engine.api.IReportEngineFactory;
    import org.eclipse.birt.report.engine.api.IReportRunnable;
    import org.eclipse.birt.report.engine.api.IRunAndRenderTask;
    import org.eclipse.swt.SWT;
    import org.eclipse.swt.browser.Browser;
    import org.eclipse.swt.widgets.Composite;
    import org.eclipse.ui.part.ViewPart;

    public class View extends ViewPart {
    public static final String ID = "RCPTest.view";
    private Browser browser;

    /**
    * This is a callback that will allow us to create the viewer and initialize
    * it.
    */
    public void createPartControl(Composite parent) {
    browser = new Browser(parent, SWT.NONE);

    try {
    this.previewReport();
    } catch (EngineException e) {
    e.printStackTrace();
    }
    }

    private void previewReport()
    throws EngineException {
    EngineConfig config = new EngineConfig();
    // Create the report engine
    IReportEngineFactory factory =
    (IReportEngineFactory) Platform
    .createFactoryObject(
    IReportEngineFactory.
    EXTENSION_REPORT_ENGINE_FACTORY );
    IReportEngine engine = factory.
    createReportEngine( config );
    IReportRunnable design = null;

    try {
    // Open a report design -
    // use design to
    // modify design, retrieve
    // embedded images etc.
    String report = "http://localhost:8080/birt/test.rptdesign";
    URL url = new URL(report);

    InputStream fs = url.openStream();
    design = engine.openReportDesign(fs);
    IRunAndRenderTask task = engine.
    createRunAndRenderTask(design);

    // Set Render context to handle url
    // and image locations
    HTMLRenderContext renderContext =
    new HTMLRenderContext();

    renderContext.setImageDirectory(
    "c:/test/image");
    HashMap< String, HTMLRenderContext >
    contextMap = new
    HashMap< String, HTMLRenderContext >();
    contextMap.put( EngineConstants.
    APPCONTEXT_HTML_RENDER_CONTEXT,
    renderContext );
    task.setAppContext(contextMap);

    // Set rendering options -
    // such as file or stream output,
    // output format, whether it is
    // embeddable, etc
    // Render report to
    // Byte Array
    IRenderOption options;
    options = new HTMLRenderOption( );
    ByteArrayOutputStream bos =
    new ByteArrayOutputStream();

    options.setOutputStream(bos);
    options.setOutputFormat("html");

    task.setRenderOption(options);

    // run the report and destroy the engine

    task.run();
    task.close();

    //set Browser text accordingly
    browser.setText(bos.toString());
    engine.destroy();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }

    /**
    * Passing the focus request to the viewer's control.
    */
    public void setFocus() {
    //do nothing
    }
    }


  8. From the Plug-In editor, under the Overview tab, select Launch Eclipse application to confirm that the application works. As you can see from the screenshot, we now have a simple application with a brower with our BIRT results.

  9. Right-mouse click on the BIRTRCPViewer project, go to Other, and under the Plug-In projects, select Product Configuration.

  10. Name your product configuration BIRTRCPViewer.product, or whatever you named your project, and base it off of the launch configuration that we just created. In my screenshot below, I based it off of RCPTest.product launch configuration.
  11. In the Product Configuration Dialog, make sure you have the Product Name and Product ID filled in. Otherwise, when you go to launch the application in Web Start, OSGi will complain about not being able to find a Product ID.

Now, feel free to test launch with the Product Configuration to make sure your application works. Once completed, we will now need to make a “wrapper” for the Java Web Start launch. For the most part, I followed the instructions in the above link. But to be absolute, here are the steps I followed to create the Web Start application.

  1. Create a new Feature Project

  2. Name your Feature Project, and be sure to put in a Feature Provider.

  3. On the next screen, set to initialize from Launch Configuration.

  4. Create a folder under the new Feature product called Startup.

  5. Copy C:\eclipse\plugins\org.eclipse.equinox.launcher_.jar to your projects Startup folder, and rename it startup.jar. This took me a few steps to figure out since in newer version of Eclipse, they did away with the startup.jar in favor of the Equinox launcher.

  6. Under the Overview tab of the Feature product, click on the Export Wizard link.
  7. Specify your output folder.

  8. Under the Options tab, check Package as individual JAR archives (required for JNLP and update sites.

  9. Under the Jar signing tab, enter the relevant information. For better instructions than I can provide on how to set up the Java Keystore, check here: http://www.exampledepot.com/egs/java.security.cert/CreateCert.html

  10. In the Java Web Start tab, put in the Site URL where you will store your application and the JRE version.

  11. Now, export your wrapper. If all went according to plan, you should have a structure similar to below

  12. We are missing 1 thing in this file structure, the JNLP file that needs to launch the whole thing. Below is my final JNLP based off of the example in the web start link at the top of the article.
    <?xml version="1.0" encoding="UTF-8"?>
    <jnlp
    spec="1.0+"
    codebase="http://localhost:8080/birt"
    href="/birt/startup.jnlp"> <!-- URL to the site containing the jnlp application. It should match the value used on export. Href, the name of this file -->
    <information>
    <!-- user readable name of the application -->
    <title> BIRT RCP Viewer </title>
    <!-- vendor name -->
    <vendor>digiassn.blogspot.com</vendor>
    <!-- vendor homepage -->
    <homepage href="My company website" />
    <!-- product description -->
    <description>This is a RCP BIRT Viewer</description>
    <icon kind="splash" href="splash.gif"/>
    <offline-allowed/>
    </information>

    <!--request all permissions from the application. This does not change-->
    <security>
    <all-permissions/>
    </security>

    <!-- The name of the main class to execute. This does not change-->
    <application-desc main-class="org.eclipse.equinox.launcher.WebStartMain">
    <argument>-nosplash</argument>
    </application-desc>

    <resources>
    <!-- Reference to the startup.jar. This does not change -->
    <jar href="startup.jar"/>

    <!-- Reference to all the plugins and features constituting the application -->
    <!-- Here we are referring to the wrapper feature since it transitively refers to all the other plug-ins necessary -->
    <extension
    name="Wrapper feature"
    href="/birt/features/MyRCP_1.0.0.jnlp"/>

    <!-- Information usually specified in the config.ini -->
    <property
    name="osgi.instance.area"
    value="@user.home/Application Data/birt"/>
    <property
    name="osgi.configuration.area"
    value="@user.home/Application Data/birt"/>

    <!-- The id of the product to run, like found in the overview page of the product editor -->
    <property
    name="eclipse.product"
    value="RCPTest.product"/>
    </resources>

    <!-- Indicate on a platform basis which JRE to use -->
    <resources os="Mac">
    <j2se version="1.5+" java-vm-args="-XstartOnFirstThread"/>
    </resources>
    <resources os="Windows">
    <j2se version="1.4+"/>
    </resources>
    <resources os="Linux">
    <j2se version="1.4+"/>
    </resources>
    </jnlp>


  13. Copy everything to the /birt folder on Apache Tomcat.

And that’s it, now, I can go to my web server at http://localhost:8080/birt/startup.jnlp and launch my new RCP application via Java Web Start.

Saturday, July 12, 2008

BIRT: Reading Chart From Library and Adding to Report Design

I recently came back from a client engagement that was pretty exciting. They are integrating BIRT into their product using a “report wizard” to dynamically build reports. I was pretty stoked by this. There are different ways to accomplish what they wanted internal to the BIRT report scripting and Report Engine environment, and the way they are utilizing it is pretty darn cool.

One of the ideas we came up with was to read chart prototypes from a library and to add them using the Report Engine API to their final report design. There are several advantages to this. First on, of course, is that this gives them the ability to graphically build the visual attributes of their charts using the BIRT Report Designer, and the ability to rapidly change elements and have them propagate to any report consuming them. This will keep chart look and feel consistent throughout their site. But with any approach, pros and cons need to be taken into consideration. In this case, there were a few hurdles to overcome. First being that since their data is build dynamically through their report wizard, data binding to the chart cannot be done in the report library and would need to be done at run-time, as would any chart series formatting. This differs from my previous example in that it actually adds to a report, not just rendering a stand-alone chart.

The following example of how to read a chart from a Library design, and add the data binding to it. There are a few things to notate about this example. First, if you look at my previous Chart Engine API example, you will notice that data is bound differently. When you work with the Chart Engine API in a standalone fashion, you have to manually create what is called a Data Set (not to be confused with a BIRT Report Data Set). A Data Set in the Chart Engine API is basically an array of values bound to an axis, there are no report binding elements involved. When adding to a report, you have to create a dataset binding to the ExtendedReportItem, not the chart itself.

package com.digiassn.blogspot.birt.chartBuilder;

import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;

import org.eclipse.birt.chart.model.ChartWithoutAxes;
import org.eclipse.birt.chart.model.component.Series;
import org.eclipse.birt.chart.model.component.impl.SeriesImpl;
import org.eclipse.birt.chart.model.data.Query;
import org.eclipse.birt.chart.model.data.SeriesDefinition;
import org.eclipse.birt.chart.model.data.impl.QueryImpl;
import org.eclipse.birt.chart.model.data.impl.SeriesDefinitionImpl;
import org.eclipse.birt.chart.model.type.PieSeries;
import org.eclipse.birt.chart.model.type.impl.PieSeriesImpl;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.core.framework.PlatformConfig;
import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.EngineConstants;
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.IRenderTask;
import org.eclipse.birt.report.engine.api.IReportDocument;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportEngineFactory;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IRunTask;
import org.eclipse.birt.report.model.api.DataSetHandle;
import org.eclipse.birt.report.model.api.DataSourceHandle;
import org.eclipse.birt.report.model.api.DesignConfig;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.DesignFileException;
import org.eclipse.birt.report.model.api.ElementFactory;
import org.eclipse.birt.report.model.api.ExtendedItemHandle;
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.LibraryHandle;
import org.eclipse.birt.report.model.api.PropertyHandle;
import org.eclipse.birt.report.model.api.ReportDesignHandle;
import org.eclipse.birt.report.model.api.SessionHandle;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.command.ContentException;
import org.eclipse.birt.report.model.api.command.NameException;
import org.eclipse.birt.report.model.api.elements.structures.ComputedColumn;

import com.ibm.icu.util.ULocale;

public class ChartBuilder7 {
private static String BIRT_HOME = "C:/birt-runtime-2_2_1_1/ReportEngine";

public static void main(String[] args) {
try {
final ChartBuilder7 cb = new ChartBuilder7();

cb.buildReport();
cb.runReport();
cb.renderReport();
//cb.renderReportlet();

cb.shutdown();
} catch (final ContentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (final NameException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (final SemanticException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (final DesignFileException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (final BirtException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (final IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

//factories and engines used in program
IDesignEngine dengine;
IDesignEngineFactory designFactory;
IReportEngine rengine; // stores the single instance of the report engine

SessionHandle session;

public ChartBuilder7() throws BirtException {
final PlatformConfig platformConfig = new PlatformConfig();
platformConfig.setBIRTHome(BIRT_HOME);
Platform.startup(platformConfig);

// create a new report engine factory
final IReportEngineFactory reportFactory = (IReportEngineFactory) Platform
.createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY);

// create a new report engine
final EngineConfig engineConfig = new EngineConfig();
engineConfig.setBIRTHome(BIRT_HOME); // will replace with
// configuration file
rengine = reportFactory.createReportEngine(engineConfig);

final DesignConfig dconfig = new DesignConfig();
dconfig.setBIRTHome(BIRT_HOME);

// try to start up the eclipse platform
designFactory = (IDesignEngineFactory) Platform
.createFactoryObject(IDesignEngineFactory.EXTENSION_DESIGN_ENGINE_FACTORY);
dengine = designFactory.createDesignEngine(dconfig);

// create a new session, open the library, and retrieve the first data
// source since it is uniform in our library
session = dengine.newSessionHandle(ULocale.ENGLISH);

}

/**
* Adds data binding information to chart retrieved from library
*
* @param eih
*/

public void addPieChartFromLibrary(ExtendedItemHandle eih) {
try {
// create chart and set standard options
ChartWithoutAxes cwaPie = (ChartWithoutAxes)eih.getReportItem().getProperty("chart.instance");

//clear any existing definitions from the chart
cwaPie.getSeriesDefinitions().clear();

//create actual series data. This will not be in the library chart
Series seCategory = SeriesImpl.create( );

//This is where things differ from standalone charts. A Query is an EList
//that contains an expression for data. Keep in mind we need to set out
//data set below, otherwise setting these expressions are pointless
Query query = QueryImpl.create( "row[\"OrganizationName\"]");//$NON-NLS-1$
// When creating a series, getDataDefinition() is expecting the EList,
// and the Query is an instance of that
seCategory.getDataDefinition( ).add( query );

SeriesDefinition series = SeriesDefinitionImpl.create( );
series.getSeries( ).add( seCategory );
cwaPie.getSeriesDefinitions( ).add( series );
series.getSeriesPalette().shift(1); // to change the color of the next slice

// Orthogonal Series
PieSeries sePie = (PieSeries) PieSeriesImpl.create( );

Query query2 = QueryImpl.create( "row[\"CandidatesImage\"]");//$NON-NLS-1$
sePie.getDataDefinition().add(query2);
sePie.setExplosion( 5 );

SeriesDefinition sdEmpCount = SeriesDefinitionImpl.create( );
sdEmpCount.getSeriesPalette().shift(2);
series.getSeriesDefinitions( ).add( sdEmpCount );
sdEmpCount.getSeries( ).add( sePie );

//add to report
// eih.loadExtendedElement(); // this may or may not need to
//be called - it's typically used for reading (if already in the rpt design file)
// eih.getReportItem().setProperty("chart.instance", cwaPie);
eih.setProperty("outputFormat", "PNG");
eih.setProperty("dataSet", "GridXMLDataSet"); // tell the chart which dataset to use to bind the chart to the report

//do the bindings to the extended element handle
PropertyHandle computedSet = eih.getColumnBindings( );
ComputedColumn cs1 = new ComputedColumn();
cs1.setExpression( "dataSetRow[\"OrganizationName\"]");//$NON-NLS-1$
cs1.setName( "OrgName" );
cs1.setDataType( "string" );
computedSet.addItem( cs1 );

ComputedColumn cs2 = new ComputedColumn();
cs2.setExpression( "dataSetRow[\"CandidatesImage\"]");//$NON-NLS-1$
cs2.setName( "Candidates" );
cs2.setDataType( "float" );
computedSet.addItem( cs2 );
}
catch ( Exception E ) {
E.printStackTrace();
}
}


/**
* Build report
* @throws ContentException
* @throws NameException
* @throws SemanticException
* @throws DesignFileException
* @throws IOException
*/
public void buildReport() throws ContentException, NameException,
SemanticException, DesignFileException, IOException {
// create a new report
final ReportDesignHandle reportDesign = session.createDesign();

final ElementFactory ef = reportDesign.getElementFactory();

// add new master page element
final DesignElementHandle element = ef
.newSimpleMasterPage("Page Master");
reportDesign.getMasterPages().add(element);

// get the session, open the library
final SessionHandle session = dengine.newSessionHandle(ULocale.ENGLISH);
final LibraryHandle library = session
.openLibrary("C:\\contracts\\CompanyA\\ChartBuild\\chart_library.rptlibrary");

// get the data source and date set from library
final DataSourceHandle dataSourceHandle = (DataSourceHandle) library
.getDataSources().get(0);
final DataSetHandle dataSetHandle = (DataSetHandle) library
.getDataSets().get(0);

// add the data sources and data sets to report
reportDesign.getDataSources().add(dataSourceHandle);
reportDesign.getDataSets().add(dataSetHandle);

// create a new extended item handle and add. This is read in the library
//so we do not need to manually create visual elements. Then add to the body of our
//new report design
final ExtendedItemHandle eih = (ExtendedItemHandle)library.findElement("PieChart");
reportDesign.getBody().add(eih);

//modify the chart with data bindings so that it is bound to our new report design
this.addPieChartFromLibrary(eih);

// add some sample labels
final LabelHandle lh = ef.newLabel("New Label");
lh.setText("Can you see me?");
reportDesign.getBody().add(lh);

// set my initial properties for the new report
final String reportName = "Example Chart";
reportDesign.setDisplayName(reportName);
reportDesign.setDescription(reportName);
reportDesign.setIconFile("/templates/blank_report.gif");
reportDesign.setFileName("C:/Temp/" + reportName + ".rptdesign");
reportDesign.setDefaultUnits("in");
reportDesign.setProperty("comments", reportName);
reportDesign.setProperty(IReportRunnable.TITLE, reportName);

// save report design
reportDesign.saveAs("C:/Temp/" + reportName + ".rptdesign");
}

/**
* Render full report
*/
public void renderReport() {
try {
final IReportDocument rptdoc = rengine
.openReportDocument("C:/temp/tempDoc.rptDocument");

// Create Render Task
final IRenderTask rtask = rengine.createRenderTask(rptdoc);

// Set Render context to handle url and image locataions
final HTMLRenderContext renderContext = new HTMLRenderContext();
// Set the Base URL for all actions
renderContext.setBaseURL("http://localhost/");
// Tell the Engine to prepend all images with this URL - Note this
// requires using the HTMLServerImageHandler
renderContext.setBaseImageURL("http://localhost/myimages");
// Tell the Engine where to write the images to
renderContext.setImageDirectory("C:/xampplite/htdocs/myimages");
// Tell the Engine what image formats are supported. Note you must
// have SVG in the string
// to render charts in SVG.
renderContext.setSupportedImageFormats("JPG;PNG;BMP;SVG");
final HashMap<String, HTMLRenderContext> contextMap = new HashMap<String, HTMLRenderContext>();
contextMap.put(EngineConstants.APPCONTEXT_HTML_RENDER_CONTEXT,
renderContext);
rtask.setAppContext(contextMap);

// Set rendering options - such as file or stream output,
// output format, whether it is embeddable, etc
final HTMLRenderOption options = new HTMLRenderOption();

// Remove HTML and Body tags
// options.setEmbeddable(true);

// Set ouptut location
options.setOutputFileName("C:/temp/outputReport.html");

// Set output format
options.setOutputFormat("html");
rtask.setRenderOption(options);

rtask.render();

// render the report and destroy the engine
// Note - If the program stays resident do not shutdown the Platform
// or the Engine
rtask.close();
} catch (final EngineException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

/**
* render just a reportlet
*/
public void renderReportlet() {
try {
final IReportDocument rptdoc = rengine
.openReportDocument("C:/temp/tempDoc.rptDocument");

// Create Render Task
final IRenderTask rtask = rengine.createRenderTask(rptdoc);

// Set Render context to handle url and image locataions
final HTMLRenderContext renderContext = new HTMLRenderContext();
// Set the Base URL for all actions
renderContext.setBaseURL("http://localhost/");
// Tell the Engine to prepend all images with this URL - Note this
// requires using the HTMLServerImageHandler
renderContext.setBaseImageURL("http://localhost/myimages");
// Tell the Engine where to write the images to
renderContext.setImageDirectory("C:/xampplite/htdocs/myimages");
// Tell the Engine what image formats are supported. Note you must
// have SVG in the string
// to render charts in SVG.
renderContext.setSupportedImageFormats("JPG;PNG;BMP;SVG");
final HashMap<String, HTMLRenderContext> contextMap = new HashMap<String, HTMLRenderContext>();
contextMap.put(EngineConstants.APPCONTEXT_HTML_RENDER_CONTEXT,
renderContext);
rtask.setAppContext(contextMap);

// Set rendering options - such as file or stream output,
// output format, whether it is embeddable, etc
final HTMLRenderOption options = new HTMLRenderOption();

// Remove HTML and Body tags
// options.setEmbeddable(true);

// Set ouptut location
options.setOutputFileName("C:/temp/outputReportlet.html");

// Set output format
options.setOutputFormat("html");
rtask.setRenderOption(options);

rtask.setReportlet("ChartToRender");
rtask.render();

// render the report and destroy the engine
// Note - If the program stays resident do not shutdown the Platform
// or the Engine
rtask.close();
} catch (final EngineException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

/**
* Run report
*/
public void runReport() {
try {
final IReportRunnable design = rengine.openReportDesign("C:/Temp/"
+ "Example Chart" + ".rptdesign");
final IRunTask runTask = rengine.createRunTask(design);

// use the default locale
runTask.setLocale(Locale.getDefault());

runTask.run("C:/temp/tempDoc.rptDocument");
runTask.close();
} catch (final EngineException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public void shutdown() {
Platform.shutdown();
}
}