<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Javafact</title>
	<atom:link href="http://javafact.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://javafact.com</link>
	<description>a java development reference by Octavio Berlanga</description>
	<lastBuildDate>Sun, 18 Sep 2011 20:33:32 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Configuring JAAS in JBoss 6.1 and Eclipse RCP: Part 1</title>
		<link>http://javafact.com/2011/09/18/jaas-jboss-6-eclipse-rcp/</link>
		<comments>http://javafact.com/2011/09/18/jaas-jboss-6-eclipse-rcp/#comments</comments>
		<pubDate>Sun, 18 Sep 2011 20:20:57 +0000</pubDate>
		<dc:creator>Octavio Berlanga</dc:creator>
				<category><![CDATA[About]]></category>

		<guid isPermaLink="false">http://javafact.com/?p=673</guid>
		<description><![CDATA[In this post I explain how to setup Java Authentication and Authorization Service (JAAS) using JBoss AS 6.1 and an Eclipse RCP client that will be making calls on an EJB 3 Session Bean.

Part 1 will cover JBoss configuration and Part 2 will cover the code required in the Eclipse RCP client.
 <span style="color:#777"> . . . &#8594; Read More: <a href="http://javafact.com/2011/09/18/jaas-jboss-6-eclipse-rcp/">Configuring JAAS in JBoss 6.1 and Eclipse RCP: Part 1</a></span>]]></description>
			<content:encoded><![CDATA[<p>In this post I explain how to setup Java Authentication and Authorization Service (JAAS) using JBoss AS 6.1 and an Eclipse RCP client that will be making calls on an EJB 3 Session Bean.</p>
<p>Part 1 will cover JBoss configuration and Part 2 will cover the code required in the Eclipse RCP client.</p>
<hr />
<strong>Steps</strong><br />
Setting up JBoss for JAAS will involve the following steps:</p>
<ul>
<li>Setting up a datasource to validate user IDs and passwords.</li>
<li>Add an application policy.</li>
<li>Deploy a login config service</li>
<li>Deploy an ear with a security domain that matches the application policy.</li>
</ul>
<p></p>
<hr />
<strong>Setting up a Datasource to Validate User IDs and Passwords</strong></p>
<p>Setting up a datasource involves deploying an xml file using the -ds.xml naming convention, such as myAppJaas-ds.xml.  This file should be saved in the <strong>deploy</strong> directory of your Jboss server.</p>
<p>Assuming you have a local mysql database jaas and that you&#8217;ve already granted access to user JBossAS, the content of your file will read as follows:</p>
<blockquote><pre><code>
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE jboss-app PUBLIC "-//JBoss//DTD Java EE Application 5.0//EN" "http://www.jboss.org/j2ee/dtd/jboss-app_5_0.dtd"&gt; 

&lt;jboss-app&gt;
&lt;security-domain&gt;oxb-server&lt;/security-domain&gt;
&lt;/jboss-app&gt;
&lt;datasources&gt;
	&lt;local-tx-datasource&gt;
		&lt;jndi-name&gt;jaas-ds&lt;/jndi-name&gt;
		&lt;connection-url&gt;jdbc:mysql://localhost:3306/jaas&lt;/connection-url&gt;
		&lt;connection-property name="useUnicode"&gt;true
		&lt;/connection-property&gt;
		&lt;connection-property name="characterEncoding"&gt;utf8
		&lt;/connection-property&gt;
		&lt;driver-class&gt;com.mysql.jdbc.Driver&lt;/driver-class&gt;
		&lt;user-name&gt;jbossAS&lt;/user-name&gt;
		&lt;password&gt;secretPw&lt;/password&gt;
	&lt;/local-tx-datasource&gt;
&lt;/datasources&gt;
</code></pre>
</blockquote>
<p>JBoss will need access to the JDBC driver for mySQL.  The jar file containing the driver should be copied to directory [jboss-6.1.0.Final]/server/default/lib.  In this case. I&#8217;m using the default server configuration.</p>
<p></p>
<hr />
<strong>Add an Application Policy</strong><br />
The application policy is defined through a -config.xml file saved in your server <strong>conf</strong> directory.  The content of the file will be similar to the following myApp-config.xml file:</p>
<blockquote><pre><code>
&lt;?xml version='1.0'?&gt;
&lt;!DOCTYPE policy PUBLIC
      "-//JBoss//DTD JBOSS Security Config 3.0//EN"
      "http://www.jboss.org/j2ee/dtd/security_config.dtd"&gt;
&lt;policy&gt;
    &lt;application-policy name = "myApp"&gt;
       &lt;authentication&gt;
          &lt;login-module code = "org.jboss.security.auth.spi.DatabaseServerLoginModule"
             flag = "required"&gt;
             &lt;module-option name = "dsJndiName"&gt;java:jaas-ds&lt;/module-option&gt;
             &lt;module-option name = "principalsQuery"&gt;SELECT password FROM contact WHERE userId=?&lt;/module-option&gt;
             &lt;module-option name = "rolesQuery"&gt;SELECT role, 'Roles' FROM contact a JOIN roleset b on a.roleSet_id = b.id JOIN roleset_role c on b.id = c.roleset WHERE a.userId=?&lt;/module-option&gt;
          &lt;/login-module&gt;
       &lt;/authentication&gt;
    &lt;/application-policy&gt;
&lt;/policy&gt;
</code></pre>
</blockquote>
<p>As you can see, this file makes reference to the datasource that we defined in the prior step.  This application policy entry asumes you have already created the tables contact, roleset, and roleset_role.   Your table structures can be whatever makes sense for your application.  The important thing here is that you need a query that returns a password for a user id and another query that returns a result set with role name as the first column and the string Roles as the second column.</p>
<p>Another thing to keep in mind is that your application policy name will be used as the security domain in your ear file below.</p>
<p></p>
<hr />
<strong>Deploy a Login Config Service</strong><br />
The step above defined how passwords and roles should be checked.  In this step we tell the application server to start a JAAS service that makes use of the application policy defined in the previous step.  Here we will deploy a file myApp-login-config-service.xml.  The file name must end in -service.xml and the content will be as follows:</p>
<blockquote><pre><code>
 &lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE server&gt;

&lt;server&gt;
   &lt;mbean code="org.jboss.security.auth.login.DynamicLoginConfig"
      name="jboss:service=DynamicLoginConfig"&gt;
      &lt;attribute name="AuthConfig"&gt;myApp-config.xml&lt;/attribute&gt;
      &lt;depends optional-attribute-name="LoginConfigService"&gt;
         jboss.security:service=XMLLoginConfig
      &lt;/depends&gt;
      &lt;depends optional-attribute-name="SecurityManagerService"&gt;
         jboss.security:service=JaasSecurityManager
      &lt;/depends&gt;
   &lt;/mbean&gt;
 &lt;/server&gt;
</code></pre>
</blockquote>
<p>Notice that this file makes reference to the application policy file from the previous step.</p>
<p></p>
<hr />
<strong>Deploy an ear with a Security Domain that Matches the Application Policy</strong><br />
Your session beans should be deployed through and ear file with the following structure:<br />
<code><br />
yourEJB3.jar<br />
META-INF/application.xml<br />
META-INF/jboss-app.xml<br />
</code></p>
<p>The jboss-app.xml file will set the security domain with the following content.  The security domain should match the application policy name created above.</p>
<blockquote><pre><code>
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE jboss-app PUBLIC "-//JBoss//DTD Java EE Application 5.0//EN" "http://www.jboss.org/j2ee/dtd/jboss-app_5_0.dtd"&gt; 

&lt;jboss-app&gt;
&lt;security-domain&gt;myApp&lt;/security-domain&gt;
&lt;/jboss-app&gt;
</code></pre>
</blockquote>
<p></p>
<hr />
<strong>References</strong><br />
You should read the post <a href="http://www.ajka-andrej.com/2011/05/22/jboss-6-client-authentication-sd/" target="_new">JBoss 6: Client authentication, security domain</a> by Andrej.</p>
]]></content:encoded>
			<wfw:commentRss>http://javafact.com/2011/09/18/jaas-jboss-6-eclipse-rcp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Accessing a Database Connection Pool from a Session EJB in JBoss AS</title>
		<link>http://javafact.com/2011/02/15/accessing-a-database-connection-pool-from-a-session-ejb-in-jboss-as/</link>
		<comments>http://javafact.com/2011/02/15/accessing-a-database-connection-pool-from-a-session-ejb-in-jboss-as/#comments</comments>
		<pubDate>Wed, 16 Feb 2011 02:33:37 +0000</pubDate>
		<dc:creator>Octavio Berlanga</dc:creator>
				<category><![CDATA[About]]></category>
		<category><![CDATA[EJB]]></category>
		<category><![CDATA[Example]]></category>
		<category><![CDATA[JBoss]]></category>
		<category><![CDATA[Java EE]]></category>

		<guid isPermaLink="false">http://javafact.com/?p=653</guid>
		<description><![CDATA[There may be situations in which it makes sense to access data from an EJB session bean using JDBC.  Perhaps you are only reading values from a table and since you are not making any changes to the table, using an entity bean may seem like overkill.  In this post I cover setting up a database connection pool in JBoss and accessing the database using JDBC from an EJB session bean.

 <span style="color:#777"> . . . &#8594; Read More: <a href="http://javafact.com/2011/02/15/accessing-a-database-connection-pool-from-a-session-ejb-in-jboss-as/">Accessing a Database Connection Pool from a Session EJB in JBoss AS</a></span>]]></description>
			<content:encoded><![CDATA[<p>There may be situations in which it makes sense to access data from an EJB session bean using JDBC.  Perhaps you are only reading values from a table and since you are not making any changes to the table, using an entity bean may seem like overkill.  In this post I cover setting up a database connection pool in JBoss and accessing the database using JDBC from an EJB session bean.</p>
<p><strong>Configuring the Datasource</strong></p>
<p>Creating the connection pool requires copying a -ds.xml file to the deploy directory in your JBoss server.  This datasource XML file is no different from any other datasource file.  If you&#8217;ve been working with EJB, you&#8217;ve already done this, but here&#8217;s an example:</p>
<blockquote><pre>
&lt;datasources&gt;
	&lt;no-tx-datasource&gt;
		&lt;jndi-name&gt;jdbc/oxb-util&lt;/jndi-name&gt;
		&lt;connection-url&gt;jdbc:mysql://localhost:3306/utilDB&lt;/connection-url&gt;
		&lt;driver-class&gt;com.mysql.jdbc.Driver&lt;/driver-class&gt;
		&lt;user-name&gt;user123&lt;/user-name&gt;
		&lt;password&gt;abc123&lt;/password&gt;
		&lt;use-java-context&gt;false&lt;/use-java-context&gt;
		&lt;!--security-domain&gt;domainX&lt;/security-domain--&gt;
		&lt;idle-timeout-minutes&gt;5&lt;/idle-timeout-minutes&gt;

		&lt;!--Defaults --&gt;
		&lt;!--min-pool-size&gt;0&lt;/min-pool-size--&gt;
		&lt;!--max-pool-size&gt;20&lt;/max-pool-size--&gt;
	&lt;/no-tx-datasource&gt;
&lt;/datasources&gt;
</pre>
</blockquote>
<p><strong>Accessing the Connection Pool through a SessionContext from a Session EJB</strong><br />
One way to access the connection pool is by injecting a SessionContext into your Session EJB and then gaining access to the datasource connection.<br />
<br />
Injection of the session context is acomplished through the <code>@javax.annotation.Resource</code> annotation:</p>
<blockquote><pre>@Stateless(name = "SetupServiceEJB")
public class SetupServiceBean implements SetupServiceRemoteSession {
	@Resource
	SessionContext ejbContext;
	private Connection connection;
</pre>
</blockquote>
<p>You can then access a connection as follows:</p>
<blockquote><pre>	private Connection getConnection() throws SQLException {
		if (this.connection == null) {
			DataSource source = (DataSource) ejbContext.lookup("jdbc/oxb-util");
			connection = source.getConnection();
		}
		return this.connection;
	}
</pre>
</blockquote>
<p>Here&#8217;s an example of a method that performs a query using this getConnection() method:</p>
<blockquote><pre>	public void createLocations() {
		String query = "select * from country";
		try {
			Connection con = this.getConnection();
			Statement statement = con.createStatement();
			ResultSet set = statement.executeQuery(query);

			// do something with the result set...
</pre>
</blockquote>
<p><strong>Accessing the Connection Pool through a DataSource from a Session EJB</strong><br />
A second alternative is to inject into your session EJB a DataSource as follows:</p>
<blockquote><pre>@Stateless(name = "SetupServiceEJB")
public class SetupServiceBean implements SetupServiceRemoteSession {
	@Resource(name = "jdbc/oxb-util", type = DataSource.class, mappedName = "jdbc/oxb-util")
	DataSource datasource;
	private Connection connection;</pre>
</blockquote>
<p>Accessing the connection would then be done as follows:</p>
<blockquote><pre>		String query = "select * from country limit 20";

		try {
			Connection con = this.datasource.getConnection();
			Statement statement = con.createStatement();
			ResultSet set = statement.executeQuery(query);

			use result set here...
</pre>
</blockquote>
]]></content:encoded>
			<wfw:commentRss>http://javafact.com/2011/02/15/accessing-a-database-connection-pool-from-a-session-ejb-in-jboss-as/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Sample Business Document Created with the iText Library</title>
		<link>http://javafact.com/2010/09/25/sample-business-document-created-with-the-itext-library/</link>
		<comments>http://javafact.com/2010/09/25/sample-business-document-created-with-the-itext-library/#comments</comments>
		<pubDate>Sun, 26 Sep 2010 03:01:42 +0000</pubDate>
		<dc:creator>Octavio Berlanga</dc:creator>
				<category><![CDATA[Libraries]]></category>
		<category><![CDATA[iText]]></category>

		<guid isPermaLink="false">http://javafact.com/?p=615</guid>
		<description><![CDATA[This post provides sample code for creating a business PDF document using the iText library. <span style="color:#777"> . . . &#8594; Read More: <a href="http://javafact.com/2010/09/25/sample-business-document-created-with-the-itext-library/">Sample Business Document Created with the iText Library</a></span>]]></description>
			<content:encoded><![CDATA[<p><a href="http://javafact.com/wp-content/uploads/2010/09/SampleForm.png" target="_blank"><img src="http://javafact.com/wp-content/uploads/2010/09/SampleForm-300x175.png" alt="Sample Business Document" title="SampleForm.pdf" width="300" height="175" class="alignleft size-medium wp-image-621" /></a></p>
<p>The code below uses the iText Library to create the document <a href = "http://javafact.com/wp-content/uploads/2010/09/SampleForm.pdf"  target="_blank">SampleForm.pdf linked here.</a></p>
<p>For a detailed explanation of the code, read the post <a href = "http://javafact.com/2010/09/19/creating-a-pdf-document-with-itext/"  target="_blank">Creating a PDF Document in Java with iText</a>.<br />
</p>
<blockquote><pre>package explore.itext.form;

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

import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class FormPrintingService {
	private static FormPrintingService instance;
	private Font arial;
	private Font arialSmall;
	private Font arialMini;
	private Font courier;

	/**
	 * Private constructor, since this is a singleton. Fonts are initialized in
	 * the constructor.
	 */
	private FormPrintingService() {
		arial = FontFactory.getFont("Arial", 8);
		arial.setStyle(Font.BOLD);
		arialSmall = FontFactory.getFont("Arial", 6);
		arialSmall.setStyle(Font.BOLD);
		courier = FontFactory.getFont("Courier", 10);
		arialMini = FontFactory.getFont("Arial", 5);
	}

	/**
	 * Provides an access to the service instance
	 *
	 * @return
	 */
	public static FormPrintingService getInstance() {
		if (instance == null) {
			instance = new FormPrintingService();
		}
		return instance;
	}

	/**
	 * Creates the PDF document.
	 *
	 * @param domainObject
	 */
	public void createDocument(Object domainObject) {
		/**
		 * Assign the domainObject to an instance variable so that it can be
		 * used to populate the fields in the form
		 */

		try {
			Document document = new Document(PageSize.LETTER);
			document.setMargins(36f, 36f, 36f, 36f);
			FileOutputStream fos;
			fos = new FileOutputStream("I:\\trash\\SampleForm.pdf");
			PdfWriter.getInstance(document, fos);
			document.open();
			document.newPage();

			/**
			 * Only adding one element to the document. The element contains the
			 * entire form (which is just a table).
			 */
			Element mainElement = mainElement();
			document.add(mainElement);

			document.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * Builds and returns the main table.
	 *
	 * @return
	 */
	private Element mainElement() {

		PdfPTable table = new PdfPTable(2);
		table.setWidthPercentage(100f);
		table.getDefaultCell().setBorderWidth(0.5f);

		Element element;
		PdfPCell cell;

		element = this.firstElement();
		cell = this.createCell(1, 1);
		cell.setBorder(0);
		cell.setPadding(2f);
		cell.addElement(element);
		table.addCell(cell);

		element = this.secondElement();
		cell = this.createCell(1, 1);
		cell.setBorder(0);
		cell.setPadding(2f);
		cell.addElement(element);
		table.addCell(cell);

		element = this.thirdElement();
		cell = this.createCell(1, 1);
		cell.addElement(element);
		table.addCell(cell);

		element = this.fourthLogoElement();
		// You need to pass the image to the constructor.
		// If you add the image, it will be stretched to fill the cell.
		cell = new PdfPCell((Image)element);
		cell.setPadding(2);
		cell.setHorizontalAlignment(Element.ALIGN_CENTER);
		cell.setVerticalAlignment(Element.ALIGN_CENTER);
		cell.setBorderWidth(0.3f);
		table.addCell(cell);

		element = this.fifthElement();
		cell = this.createCell(1, 1);
		cell.addElement(element);
		table.addCell(cell);

		// This is a nested table
		PdfPTable acctTable = (PdfPTable) this.sixthElement();
		cell = new PdfPCell(acctTable);
		cell.setBorderWidth(0.3f);
		table.addCell(cell);

		element = this.seventhElement();
		cell = this.createCell(2, 1);
		cell.addElement(element);
		table.addCell(cell);

		PdfPTable wTable = (PdfPTable) this.eigthElement();
		cell = new PdfPCell(wTable);
		cell.setColspan(2);
		cell.setBorderWidth(0.3f);
		table.addCell(cell);

		element = this.ninethElement();
		cell = this.createCell(2, 1);
		cell.addElement(element);
		table.addCell(cell);

		return table;
	}

	/**
	 * Creates new cells
	 *
	 * @param colspan
	 * @param rowspan
	 * @return
	 */
	private PdfPCell createCell(int colspan, int rowspan) {
		PdfPCell cell = new PdfPCell();
		cell.setPadding(0);
		cell.setBorderWidth(0.3f);
		cell.setColspan(colspan);
		cell.setRowspan(rowspan);
		return cell;
	}

	private Element firstElement() {
		float leading = 9f;
		Phrase label = new Phrase("Ref. ", this.arial);
		Phrase ref = new Phrase("1239999 9999", courier);
		Paragraph info = new Paragraph();
		info.setLeading(leading);
		info.add(label);
		info.add(ref);
		return info;
	}

	private Element secondElement() {
		float leading = 9f;
		Phrase label = new Phrase("Doc ", this.arial);
		Phrase doc = new Phrase("1234567890", courier);
		Paragraph info = new Paragraph();
		info.setLeading(leading);
		info.add(label);
		info.add(doc);
		info.setAlignment(Element.ALIGN_RIGHT);
		return info;
	}

	private Element fourthLogoElement() {
		String path = "I:\\trash\\logo.jpg";
		Image image = null;
		try {
			image = Image.getInstance(path);
		} catch (BadElementException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return image;
	}

	private Element thirdElement() {
		float leading = 9f;
		PdfPTable table = new PdfPTable(1);
		table.setWidthPercentage(100f);
		PdfPCell cell;
		cell = new PdfPCell(new Paragraph("Company", arialSmall));
		cell.setPadding(2);
		cell.setGrayFill(0.85f);
		cell.setBorderWidth(0.3f);
		table.addCell(cell);

		cell = new PdfPCell();
		cell.setBorderWidth(0.3f);
		cell.setFixedHeight(72f);
		Paragraph info = new Paragraph(
				"Company info will go here\nMore here\nMore here\nMore here\nMore here",
				courier);
		info.setLeading(leading);
		cell.addElement(info);
		table.addCell(cell);

		return table;
	}

	private Element ninethElement() {
		String legal = "Legal Statement: Blah blah blah blah blah blah blah blah blah blah blah blah blah."
				+ "  Blah blah blah blah blah blah blah blah blah blah blah blah blah."
				+ "  Blah blah blah blah blah blah blah blah blah blah blah blah blah."
				+ "  Blah blah blah blah blah blah blah blah blah blah blah blah blah."
				+ "  Blah blah blah blah blah blah blah blah blah blah blah blah blah."
				+ "  Blah blah blah blah blah blah blah blah blah blah blah blah blah."
				+ "  Blah blah blah blah blah blah blah blah blah blah blah blah blah."
				+ "  Blah blah blah blah blah blah blah blah blah blah blah blah blah."
				+ "  Blah blah blah blah blah blah blah blah blah blah blah blah blah."
				+ "  Blah blah blah blah blah blah blah blah blah blah blah blah blah."
				+ "  Blah blah blah blah blah blah blah blah blah blah blah blah blah."
				+ "  Blah blah blah blah blah blah blah blah blah blah blah blah blah."
				+ "  Blah blah blah blah blah blah blah blah blah blah blah blah blah."
				+ "  Blah blah blah blah blah blah blah blah blah blah blah blah blah."
				+ "  Blah blah blah blah blah blah blah blah blah blah blah blah blah."
				+ "  Blah blah blah blah blah blah blah blah blah blah blah blah blah.";
		Paragraph element = new Paragraph(legal, this.arialMini);
		element.setAlignment(Element.ALIGN_JUSTIFIED);
		return element;
	}

	private Element fifthElement() {
		float leading = 9f;

		PdfPTable table = new PdfPTable(2);
		table.setWidthPercentage(100f);
		PdfPCell cell;

		cell = new PdfPCell(new Paragraph("Issuing Office Name and City",
				arialSmall));
		cell.setGrayFill(0.85f);
		cell.setBorderWidth(0.3f);
		cell.setColspan(2);
		table.addCell(cell);

		cell = new PdfPCell();
		cell.setBorderWidth(0.3f);
		cell.setFixedHeight(36f);
		cell.setColspan(2);
		Paragraph agentInfo = new Paragraph(
				"Some info will go here\nMore here\nMore here", courier);
		agentInfo.setLeading(leading);
		cell.addElement(agentInfo);
		table.addCell(cell);

		cell = new PdfPCell(new Paragraph("Code", arialSmall));
		cell.setPadding(2);
		cell.setGrayFill(0.85f);
		cell.setBorderWidth(0.3f);
		table.addCell(cell);

		cell = new PdfPCell(new Paragraph("Account No", arialSmall));
		cell.setPadding(2);
		cell.setGrayFill(0.85f);
		cell.setBorderWidth(0.3f);
		table.addCell(cell);

		cell = new PdfPCell();
		cell.setPadding(2);
		cell.setBorderWidth(0.3f);
		Paragraph iataInfo = new Paragraph("999999", courier);
		iataInfo.setLeading(leading);
		cell.addElement(iataInfo);
		table.addCell(cell);

		cell = new PdfPCell();
		cell.setPadding(2);
		cell.setBorderWidth(0.3f);
		Paragraph acctInfo = new Paragraph("888888888", courier);
		acctInfo.setLeading(leading);
		cell.addElement(acctInfo);
		table.addCell(cell);

		return table;
	}

	private Element sixthElement() {
		float leading = 9f;
		PdfPTable table = new PdfPTable(1);
		table.setWidthPercentage(100f);
		PdfPCell cell;
		cell = new PdfPCell(new Paragraph("Some Element Information", arialSmall));
		cell.setPadding(2);
		cell.setGrayFill(0.85f);
		cell.setBorderWidth(0.3f);
		table.addCell(cell);

		cell = new PdfPCell();
		cell.setBorderWidth(0.3f);
		Paragraph info = new Paragraph(
				"Some element info will go here\nMore here\nMore here\nMore here\nMore here",
				courier);
		info.setLeading(leading);
		cell.addElement(info);
		table.addCell(cell);

		return table;
	}

	private Element seventhElement() {
		float leading = 9f;

		PdfPTable table = new PdfPTable(1);
		table.setWidthPercentage(100f);
		PdfPCell cell;

		cell = new PdfPCell(new Paragraph("Handling Information", arialSmall));
		cell.setPadding(2);
		cell.setBorderWidth(0);
		table.addCell(cell);

		cell = new PdfPCell();
		cell.setPadding(2);
		cell.setBorderWidth(0);
		cell.setFixedHeight(36f);
		Paragraph info = new Paragraph(
				"Multiple lines \nof handling \ninformation", courier);
		info.setLeading(leading);
		cell.addElement(info);
		table.addCell(cell);

		return table;
	}

	private Element eigthElement() {
		float[] widths = { 3f, 6f, 6f, 6f, 6f, 9f, 25f };
		PdfPTable table = new PdfPTable(widths);
		table.setWidthPercentage(100f);

		PdfPCell cell;

		cell = new PdfPCell(new Paragraph(" # ", arialSmall));
		cell.setPadding(2);
		cell.setBorderWidth(0.3f);
		cell.setGrayFill(0.85f);
		cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
		cell.setHorizontalAlignment(Element.ALIGN_CENTER);
		table.addCell(cell);

		cell = new PdfPCell(new Paragraph("QT", arialSmall));
		cell.setPadding(2);
		cell.setBorderWidth(0.3f);
		cell.setGrayFill(0.85f);
		cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
		cell.setHorizontalAlignment(Element.ALIGN_CENTER);
		table.addCell(cell);

		cell = new PdfPCell(new Paragraph("Rate\nClass", arialSmall));
		cell.setPadding(2);
		cell.setBorderWidth(0.3f);
		cell.setGrayFill(0.85f);
		cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
		cell.setHorizontalAlignment(Element.ALIGN_CENTER);
		table.addCell(cell);

		cell = new PdfPCell(new Paragraph("Gross\nWeight", arialSmall));
		cell.setPadding(2);
		cell.setBorderWidth(0.3f);
		cell.setGrayFill(0.85f);
		cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
		cell.setHorizontalAlignment(Element.ALIGN_CENTER);
		table.addCell(cell);

		cell = new PdfPCell(new Paragraph("Rate", arialSmall));
		cell.setPadding(2);
		cell.setBorderWidth(0.3f);
		cell.setGrayFill(0.85f);
		cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
		cell.setHorizontalAlignment(Element.ALIGN_CENTER);
		table.addCell(cell);

		cell = new PdfPCell(new Paragraph("Total", arialSmall));
		cell.setPadding(2);
		cell.setBorderWidth(0.3f);
		cell.setGrayFill(0.85f);
		cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
		cell.setHorizontalAlignment(Element.ALIGN_CENTER);
		table.addCell(cell);

		cell = new PdfPCell(new Paragraph("Description", arialSmall));
		cell.setPadding(2);
		cell.setBorderWidth(0.3f);
		cell.setGrayFill(0.85f);
		cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
		cell.setHorizontalAlignment(Element.ALIGN_CENTER);
		table.addCell(cell);

		cell = new PdfPCell(new Paragraph("999", this.courier));
		cell.setPadding(2);
		cell.setFixedHeight(126);
		cell.setBorderWidth(0.3f);
		cell.setVerticalAlignment(Element.ALIGN_TOP);
		table.addCell(cell);

		cell = new PdfPCell(new Paragraph("9999", this.courier));
		cell.setPadding(2);
		cell.setFixedHeight(126);
		cell.setBorderWidth(0.3f);
		cell.setVerticalAlignment(Element.ALIGN_TOP);
		cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
		table.addCell(cell);

		cell = new PdfPCell(new Paragraph("GLD", this.courier));
		cell.setPadding(2);
		cell.setFixedHeight(126);
		cell.setBorderWidth(0.3f);
		cell.setVerticalAlignment(Element.ALIGN_TOP);
		table.addCell(cell);

		cell = new PdfPCell(new Paragraph("10125", this.courier));
		cell.setPadding(2);
		cell.setFixedHeight(126);
		cell.setBorderWidth(0.3f);
		cell.setVerticalAlignment(Element.ALIGN_TOP);
		table.addCell(cell);

		cell = new PdfPCell(new Paragraph("2.15 USD", this.courier));
		cell.setPadding(2);
		cell.setFixedHeight(126);
		cell.setBorderWidth(0.3f);
		cell.setVerticalAlignment(Element.ALIGN_TOP);
		table.addCell(cell);

		cell = new PdfPCell(new Paragraph("99999.99 USD", this.courier));
		cell.setPadding(2);
		cell.setFixedHeight(126);
		cell.setBorderWidth(0.3f);
		cell.setVerticalAlignment(Element.ALIGN_TOP);
		cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
		table.addCell(cell);

		float leading = 9f;
		Phrase description = new Phrase("INDUSTRIAL MACHINERY",
				courier);
		Phrase newLine = new Phrase("\n", courier);
		Phrase dims = new Phrase(
				"99@110x155x45 (Carton), 80@50x50x50 (Drum), 10@15x55x55 (Pallet), 3@100x100x80 (Crate)",
				courier);

		Paragraph info = new Paragraph();
		info.setLeading(leading);
		info.add(description);
		info.add(newLine);
		info.add(dims);

		cell = new PdfPCell(info);
		cell.setPadding(2);
		cell.setFixedHeight(126);
		cell.setBorderWidth(0.3f);
		cell.setVerticalAlignment(Element.ALIGN_TOP);
		table.addCell(cell);

		cell = new PdfPCell(new Paragraph("999", this.courier));
		cell.setPadding(2);
		cell.setBorderWidth(0.3f);
		table.addCell(cell);

		cell = new PdfPCell(new Paragraph("9999", this.courier));
		cell.setPadding(2);
		cell.setBorderWidth(0.3f);
		cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
		table.addCell(cell);

		cell = new PdfPCell();
		cell.setBorderWidth(0.3f);
		cell.setGrayFill(0.85f);
		table.addCell(cell);

		cell = new PdfPCell(new Paragraph("10125", this.courier));
		cell.setPadding(2);
		cell.setBorderWidth(0.3f);
		table.addCell(cell);

		cell = new PdfPCell();
		cell.setBorderWidth(0.3f);
		cell.setGrayFill(0.85f);
		table.addCell(cell);

		cell = new PdfPCell(new Paragraph("99999.99 USD", this.courier));
		cell.setPadding(2);
		cell.setBorderWidth(0.3f);
		cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
		table.addCell(cell);

		cell = new PdfPCell(new Paragraph("Total Volume: 99.9 CBM",
				this.courier));
		cell.setPadding(2);
		cell.setBorderWidth(0.3f);
		table.addCell(cell);
		return table;
	}

}</pre>
</blockquote>
]]></content:encoded>
			<wfw:commentRss>http://javafact.com/2010/09/25/sample-business-document-created-with-the-itext-library/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Creating a PDF document in Java with iText</title>
		<link>http://javafact.com/2010/09/19/creating-a-pdf-document-with-itext/</link>
		<comments>http://javafact.com/2010/09/19/creating-a-pdf-document-with-itext/#comments</comments>
		<pubDate>Mon, 20 Sep 2010 04:00:57 +0000</pubDate>
		<dc:creator>Octavio Berlanga</dc:creator>
				<category><![CDATA[Java SE]]></category>
		<category><![CDATA[Libraries]]></category>
		<category><![CDATA[iText]]></category>

		<guid isPermaLink="false">http://javafact.com/?p=572</guid>
		<description><![CDATA[A quick reference on how to create a PDF document using the iText library.
 <span style="color:#777"> . . . &#8594; Read More: <a href="http://javafact.com/2010/09/19/creating-a-pdf-document-with-itext/">Creating a PDF document in Java with iText</a></span>]]></description>
			<content:encoded><![CDATA[<p>This post is a quick reference on how to create a PDF document using the iText library.  If this is written correctly, you should be able to create a PDF document in minutes.  This entry is based on Bruno Lowagie&#8217;s book, iText in Action.</p>
<p>This post explains the details of how to create the sample document linked <a href = "http://javafact.com/wp-content/uploads/2010/09/SampleForm.pdf"  target="_blank">here</a>.  For the complete code that generated the sample document, check the entry <a href = "http://javafact.com/2010/09/25/sample-business-document-created-with-the-itext-library/"  target="_blank">Sample Business Document Created with the iText Library</a>.<br />
</p>
<p><a href="http://javafact.com/wp-content/uploads/2010/09/SampleForm.png"><img src="http://javafact.com/wp-content/uploads/2010/09/SampleForm.png" alt="Sample Business Document" title="SampleForm.pdf" width="1008" height="591" class="aligncenter size-full wp-image-621" /></a></p>
<hr />
<strong>References</strong></p>
<li><a href="http://api.itextpdf.com/" target="_blank">iText JavaDocs</a></li>
<li><a href="http://itextpdf.com/book/examples.php" target="_blank">iText in Action examples</a></li>
<hr />
<strong>Setup</strong><br />
Download the latest version of the itext jar from <a href="http://itextpdf.com/" target="_blank">itextpdf.com</a> and add it to your project&#8217;s build path.</p>
<hr />
<strong>Things to remember</strong><br />
Units. iText uses point as the typographic unit of measure.  One inch is equivallent to 72 points. One cm is equivallent to 28.35 points.</p>
<hr />
<strong>Steps</strong></p>
<li>Create a Document object</li>
<li>Instantiate a PdfWriter</li>
<li>Open the Document</li>
<li>Add content to the Document</li>
<li>Close the Document</li>
<p>The Document object is a representation of the PDF file.  The PdfWriter simply listens for events in the document object.  Most of the work involves adding elements or content to the document object.  The PdfWriter will interpret these document events to create the PDF file.  When you close the document the PdfWriter flushes all the changes to the PDF file itself.</p>
<hr />
<strong>Create a Document object</strong><br />
The following code creates a new document.  After this code executes you have no pages to write on (You need to add pages to the document).</p>
<blockquote><pre>// create a document object
Document document = new Document(PageSize.LETTER);
// set margins before opening the document
document.setMargins(36f, 36f, 36f, 36f);
</pre>
</blockquote>
<hr />
<strong>Instantiate a PdfWriter and open the document</strong></p>
<blockquote><pre>PdfWriter.getInstance(document, new FileOutputStream("c:\\myDir\\myDocument.pdf"));
document.open();</pre>
</blockquote>
<hr />
<strong>Adding Content to the Document</strong><br />
The iText library is quite extensive, but you should be able to create any type of business document by using just the following classes:<br />
<br />
<strong>Font and FontFactory from com.itextpdf.text:</strong><br />
Since fonts are used frequently throughout a document, it makes sense to set them up as instance variables and initialize them in a constructor, such as:</p>
<blockquote><pre>	private DocumentService() {
		arial = FontFactory.getFont("Arial", 8);
		arial.setStyle(Font.BOLD);
		arialSmall = FontFactory.getFont("Arial", 6);
		arialSmall.setStyle(Font.BOLD);
		courier = FontFactory.getFont("Courier", 10);
		arialMini = FontFactory.getFont("Arial", 5);
	}
</pre>
</blockquote>
<p><strong>Phrase and Paragraph from com.itextpdf.text:</strong><br />
A Paragraph can be instantiated with a String and a Font:</p>
<blockquote><pre>	private Element textElement() {
		Paragraph element = new Paragraph("Some Text for the paragraph.", this.arial);
		return element;
	}</pre>
</blockquote>
<p>You can also use Phrases to compose a Paragraph:</p>
<blockquote><pre>	private Element someElement() {
		float leading = 9f;
		Phrase label = new Phrase("Label ", this.arial);
		Phrase value = new Phrase("1234567890", courier);
		Paragraph info = new Paragraph();
		info.setLeading(leading);
		info.add(label);
		info.add(value);
		info.setAlignment(Element.ALIGN_RIGHT);
		return info;
	}
</pre>
</blockquote>
<p>Notice that the Element interface provides alignment constants.  Leading is used to define the space between lines within the paragraph.<br />
</p>
<p><strong>Image from com.itextpdf.text:</strong><br />
Assuming that you have an image file, the image object is created as follows:</p>
<blockquote><pre>	private Element fourthLogoElement() {
		String path = "I:\\trash\\logo.jpg";
		Image image = null;
		try {
			image = Image.getInstance(path);
		} catch (BadElementException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return image;
	}
</pre>
</blockquote>
<p>If you want to place the image in a PdfPCell, you will have to use the image as an argument for the PdfPCell constructor.  If you first instantiate the PdfPCell and then add the image, the image will be stretched.</p>
<blockquote><pre>		element = this.fourthLogoElement();
		// You need to pass the image to the constructor.
		// If you add the image, it will be stretched to fill the cell.
		cell = new PdfPCell((Image)element);
		cell.setPadding(2);
		cell.setHorizontalAlignment(Element.ALIGN_CENTER);
		cell.setVerticalAlignment(Element.ALIGN_CENTER);
		cell.setBorderWidth(0.3f);
		table.addCell(cell);
</pre>
</blockquote>
<p></p>
<p><strong>PdfPTable and PdfPCell from com.itextpdf.text.pdf</strong><br />
Tables will be used for layout purposes, the same way you would use them in html.  You can also use nested tables as you would in html.<br />
A table can be instantiated by indicating the number of columns&#8211;in which case all columns would have the same width&#8211; or by using an array of float values that indicate the relative width of the columns:</p>
<blockquote><pre>		// two columns, same width
		PdfPTable table = new PdfPTable(2);
		table.setWidthPercentage(100f);

		// 7 columns, multiple widths
		float[] widths = {3f,6f,6f,6f,6f,9f,25f};
		PdfPTable table = new PdfPTable(widths);
		table.setWidthPercentage(100f);
</pre>
</blockquote>
<p>PdfPCells added to the table are automatically positioned from left to right.  You can modify the rowspan and colspan as needed:</p>
<blockquote><pre>	private Element anotherElement() {
		float leading = 9f;
		// 2 columns
		PdfPTable table = new PdfPTable(2);
		table.setWidthPercentage(100f);
		PdfPCell cell;

		cell = new PdfPCell(new Paragraph("This is a label", arialSmall));
		cell.setGrayFill(0.85f);
		cell.setBorderWidth(0.3f);
		// A cell that spans 2 columns
		cell.setColspan(2);
		// add the cell to the table
		table.addCell(cell);

		cell = new PdfPCell();
		cell.setBorderWidth(0.3f);
		// to define the cell height
		cell.setFixedHeight(36f);
		cell.setColspan(2);
		Paragraph info = new Paragraph("Info will go here\nMore here\nMore here",
				courier);
		info.setLeading(leading);
		cell.addElement(info);
		table.addCell(cell);

		cell = new PdfPCell(new Paragraph("Another label", arialSmall));
		cell.setPadding(2);
		cell.setGrayFill(0.85f);
		cell.setBorderWidth(0.3f);
		table.addCell(cell);

		cell = new PdfPCell(new Paragraph("Last Label", arialSmall));
		cell.setPadding(2);
		cell.setGrayFill(0.85f);
		cell.setBorderWidth(0.3f);
		table.addCell(cell);

		cell = new PdfPCell();
		cell.setPadding(2);
		cell.setBorderWidth(0.3f);
		Paragraph someInfo = new Paragraph("99-9-9999", courier);
		someInfo.setLeading(leading);
		cell.addElement(someInfo);
		table.addCell(cell);

		cell = new PdfPCell();
		cell.setPadding(2);
		cell.setBorderWidth(0.3f);
		Paragraph acctInfo = new Paragraph("888888888", courier);
		acctInfo.setLeading(leading);
		cell.addElement(acctInfo);
		table.addCell(cell);

		return table;
	}
</pre>
</blockquote>
<p>The following PdfPCell methods are very usefull:</p>
<blockquote><pre>		// grey cell gackground:
		cell.setGrayFill(0.85f);

		// to set the border width:
		cell.setBorderWidth(0.3f);

		// A cell that spans 2 columns
		cell.setColspan(2);

		// to define the cell height
		cell.setFixedHeight(36f);

		// to add an element to the cell
		cell.addElement(info);

		// padding: the cell margins
		cell.setPadding(2);

		// set vertical alignment
		cell.setVerticalAlignment(Element.ALIGN_BOTTOM);

		// set horizontal alignment
		cell.setHorizontalAlignment(Element.ALIGN_CENTER);
</pre>
</blockquote>
<p>You can add any implementation of Element to a cell, including a PdfPTable (a nested table).  However, for nested tables to render as expected, you should use the table as a constructor parameter as follows:</p>
<blockquote><pre>		PdfPTable wTable = (PdfPTable) this.descriptionElement();
		cell = new PdfPCell(wTable);
		cell.setColspan(2);
		cell.setBorderWidth(0.3f);
		table.addCell(cell);
</pre>
</blockquote>
<hr />
<strong>Working with Tables</strong><br />
You can build an entire document in a single method, but your code will be cleaner if you divide the document in sections and you build each one of those sections using tables.  The following guidelines are useful:</p>
<li>Setup fonts as instance variables.</li>
<li>Use a private mainElement method to build the main table</li>
<li>Build each section in private methods that will be called from the mainElement method</li>
<li>Use a public createDocument method to add the mainElement to the document</li>
<p>Here&#8217;s what the createDocument method looks like:</p>
<blockquote><pre>	public void createDocument(DomainObject domainObject) {
		this.domainObject = domainObject;

		try {
			Document document = new Document(PageSize.LETTER);
			document.setMargins(36f, 36f, 36f, 36f);
			FileOutputStream fos;
			fos = new FileOutputStream("C:\\outputDir\\fileName.pdf");
			PdfWriter.getInstance(document, fos);
			document.open();
			document.newPage();

			// mainElement returns a PdfPTable
			Element mainElement = mainElement();
			document.add(mainElement);

			document.close();
		}
		catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		catch (DocumentException e) {
			e.printStackTrace();
		}
		catch (Exception e) {
			e.printStackTrace();
		}

	}</pre>
</blockquote>
]]></content:encoded>
			<wfw:commentRss>http://javafact.com/2010/09/19/creating-a-pdf-document-with-itext/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Example: TableViewer Events</title>
		<link>http://javafact.com/2010/08/07/example-tableviewer-events/</link>
		<comments>http://javafact.com/2010/08/07/example-tableviewer-events/#comments</comments>
		<pubDate>Sun, 08 Aug 2010 04:48:07 +0000</pubDate>
		<dc:creator>Octavio Berlanga</dc:creator>
				<category><![CDATA[Eclipse RCP]]></category>
		<category><![CDATA[JFace]]></category>

		<guid isPermaLink="false">http://javafact.com/?p=551</guid>
		<description><![CDATA[This example shows how to work with TableViewer events, such as selection changes, double-clicks, and clicks on column headers.  This example also shows a databinding implementation and the use of ViewerSorter. <span style="color:#777"> . . . &#8594; Read More: <a href="http://javafact.com/2010/08/07/example-tableviewer-events/">Example: TableViewer Events</a></span>]]></description>
			<content:encoded><![CDATA[<p>This example shows how to work with TableViewer events, such as selection changes, double-clicks, and clicks on column headers.  This example also shows a databinding implementation and the use of ViewerSorter.<br />
<br />
For a detailed explanation, read <a href="http://javafact.com/2010/07/26/working-with-jface-tableviewer/">Working with JFace TableViewer</a>.<br />
</p>
<blockquote><pre>package com.oxbsystems.study.table.app02;

import java.util.Set;

import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.beans.PojoObservables;
import org.eclipse.core.databinding.observable.Realm;
import org.eclipse.core.databinding.observable.map.IObservableMap;
import org.eclipse.core.databinding.observable.set.WritableSet;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.StatusLineManager;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.jface.databinding.viewers.ObservableMapLabelProvider;
import org.eclipse.jface.databinding.viewers.ObservableSetContentProvider;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.layout.TableColumnLayout;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;

import com.oxbsystems.study.domain.workgroup.Person;
import com.oxbsystems.study.domain.workgroup.Workgroup;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;

public class DatabindingTableApp extends ApplicationWindow {
	private static class FirstSorter extends ViewerSorter {
		public int compare(Viewer viewer, Object e1, Object e2) {
			Person item1 = (Person) e1;
			Person item2 = (Person) e2;
			String s1 = item1.getFirst();
			String s2 = item2.getFirst();
			return s1.compareTo(s2);
		}
	}
	private static class LastSorter extends ViewerSorter {
		public int compare(Viewer viewer, Object e1, Object e2) {
			Person item1 = (Person) e1;
			Person item2 = (Person) e2;
			String s1 = item1.getLast();
			String s2 = item2.getLast();
			return s1.compareTo(s2);
		}
	}
	@SuppressWarnings("unused")
	private DataBindingContext m_bindingContext;
	private Table table;
	private TableViewer tableViewer;
	@SuppressWarnings("unused")
	private Workgroup workgroup;
	private Set<Person> memberSet;
	private Action clearSelectionAction;

	/**
	 * Create the application window.
	 */
	public DatabindingTableApp() {
		super(null);
		createActions();
		addToolBar(SWT.FLAT | SWT.WRAP);
		addMenuBar();
		addStatusLine();
	}

	/**
	 * Create contents of the application window.
	 *
	 * @param parent
	 */
	@Override
	protected Control createContents(Composite parent) {
		Composite container = new Composite(parent, SWT.NONE);
		container.setLayout(new GridLayout(1, false));

		// Create the composite
		Composite composite = new Composite(container, SWT.NONE);
		composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1,
				1));

		// Add TableColumnLayout
		TableColumnLayout layout = new TableColumnLayout();
		composite.setLayout(layout);

		tableViewer = new TableViewer(composite, SWT.BORDER
				| SWT.FULL_SELECTION);
		tableViewer.setSorter(new FirstSorter());
		tableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
			public void selectionChanged(SelectionChangedEvent event) {
				IStructuredSelection sel = (IStructuredSelection) tableViewer.getSelection();
				Person person = (Person) sel.getFirstElement();
				if(person != null){
					System.out.println("Selected : "+ person.getFirst() + " " + person.getLast());
					// call a method that will do something
					// useful with person
				}
				else{
					MessageDialog.openInformation(getShell(), "Message", "Selection cleared!");
				}
			}
		});
		tableViewer.addDoubleClickListener(new IDoubleClickListener() {
			public void doubleClick(DoubleClickEvent event) {
				IStructuredSelection sel = (IStructuredSelection) event.getSelection();
				Person person = (Person) sel.getFirstElement();
				if(person != null){
					System.out.println("Double-click on : "+ person.getFirst() + " " + person.getLast());
				}
			}
		});
		table = tableViewer.getTable();
		table.setHeaderVisible(true);
		table.setLinesVisible(true);

		TableViewerColumn tableViewerColumn = new TableViewerColumn(
				tableViewer, SWT.NONE);
		TableColumn tblclmnFirst = tableViewerColumn.getColumn();
		tblclmnFirst.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				tableViewer.setSorter(new FirstSorter());
			}
		});
		layout.setColumnData(tblclmnFirst, new ColumnWeightData(2,
				ColumnWeightData.MINIMUM_WIDTH, true));
		tblclmnFirst.setText("First");

		TableViewerColumn tableViewerColumn_1 = new TableViewerColumn(
				tableViewer, SWT.NONE);
		TableColumn tblclmnLast = tableViewerColumn_1.getColumn();
		tblclmnLast.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				tableViewer.setSorter(new LastSorter());
			}
		});
		// Specify width using weights
		layout.setColumnData(tblclmnLast, new ColumnWeightData(2,
				ColumnWeightData.MINIMUM_WIDTH, true));
		tblclmnLast.setText("Last");

		TableViewerColumn tableViewerColumn_2 = new TableViewerColumn(
				tableViewer, SWT.NONE);
		TableColumn tblclmnTitle = tableViewerColumn_2.getColumn();
		// Specify width using weights
		layout.setColumnData(tblclmnTitle, new ColumnWeightData(4,
				ColumnWeightData.MINIMUM_WIDTH, true));
		tblclmnTitle.setText("Title");

		TableViewerColumn tableViewerColumn_3 = new TableViewerColumn(
				tableViewer, SWT.NONE);
		TableColumn tblclmnEmail = tableViewerColumn_3.getColumn();
		// Specify width using weights
		layout.setColumnData(tblclmnEmail, new ColumnWeightData(6,
				ColumnWeightData.MINIMUM_WIDTH, true));
		tblclmnEmail.setText("Email");

		initWorkgroup();
		m_bindingContext = initDataBindings();

		return container;
	}

	private void initWorkgroup() {
		Workgroup w = new Workgroup();
		Person p = new Person();
		p.setId(1);
		p.setFirst("John");
		p.setLast("Smith");
		p.setTitle("Manager");
		p.setEmail("jsmith@somecompany.com");
		w.add(p);
		p = new Person();
		p.setId(2);
		p.setFirst("Sam");
		p.setLast("Johnson");
		p.setTitle("Supervisor");
		p.setEmail("sjohnson@somecompany.com");
		w.add(p);
		this.setWorkgroup(w);
	}

	private void setWorkgroup(Workgroup workgroup) {
		this.workgroup = workgroup;
		this.memberSet = workgroup.getMemberSet();
	}

	/**
	 * Create the actions.
	 */
	private void createActions() {
		// Create the actions
		{
			clearSelectionAction = new Action("Clear Selection") {
				@Override
				public void run() {
					StructuredSelection sel = new StructuredSelection();
					tableViewer.setSelection(sel);
					super.run();
				}

			};
		}
	}

	/**
	 * Create the menu manager.
	 *
	 * @return the menu manager
	 */
	@Override
	protected MenuManager createMenuManager() {
		MenuManager menuManager = new MenuManager("menu");
		return menuManager;
	}

	/**
	 * Create the toolbar manager.
	 *
	 * @return the toolbar manager
	 */
	@Override
	protected ToolBarManager createToolBarManager(int style) {
		ToolBarManager toolBarManager = new ToolBarManager(style);
		toolBarManager.add(clearSelectionAction);
		return toolBarManager;
	}

	/**
	 * Create the status line manager.
	 *
	 * @return the status line manager
	 */
	@Override
	protected StatusLineManager createStatusLineManager() {
		StatusLineManager statusLineManager = new StatusLineManager();
		return statusLineManager;
	}

	/**
	 * Launch the application.
	 *
	 * @param args
	 */
	public static void main(String args[]) {
		Display display = Display.getDefault();
		Realm.runWithDefault(SWTObservables.getRealm(display), new Runnable() {
			public void run() {
				try {
					DatabindingTableApp window = new DatabindingTableApp();
					window.setBlockOnOpen(true);
					window.open();
					Display.getCurrent().dispose();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Configure the shell.
	 *
	 * @param newShell
	 */
	@Override
	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setText("TableViewer with Databinding");
	}

	/**
	 * Return the initial size of the window.
	 */
	@Override
	protected Point getInitialSize() {
		return new Point(450, 300);
	}

	protected DataBindingContext initDataBindings() {
		DataBindingContext bindingContext = new DataBindingContext();
		//
		ObservableSetContentProvider setContentProvider = new ObservableSetContentProvider();
		tableViewer.setContentProvider(setContentProvider);
		//
		IObservableMap[] observeMaps = PojoObservables.observeMaps(
				setContentProvider.getKnownElements(), Person.class,
				new String[] { "first", "last", "title", "email" });
		tableViewer
				.setLabelProvider(new ObservableMapLabelProvider(observeMaps));
		//
		WritableSet writableSet = new WritableSet(memberSet, Person.class);
		tableViewer.setInput(writableSet);
		//
		return bindingContext;
	}
}</pre>
</blockquote>
]]></content:encoded>
			<wfw:commentRss>http://javafact.com/2010/08/07/example-tableviewer-events/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Example: TableViewer with Databinding</title>
		<link>http://javafact.com/2010/08/04/example-tableviewer-with-databinding/</link>
		<comments>http://javafact.com/2010/08/04/example-tableviewer-with-databinding/#comments</comments>
		<pubDate>Thu, 05 Aug 2010 03:36:49 +0000</pubDate>
		<dc:creator>Octavio Berlanga</dc:creator>
				<category><![CDATA[Eclipse RCP]]></category>
		<category><![CDATA[JFace]]></category>

		<guid isPermaLink="false">http://javafact.com/?p=545</guid>
		<description><![CDATA[An example that demonstrates how to use a Jface TableViewer with Databinding. <span style="color:#777"> . . . &#8594; Read More: <a href="http://javafact.com/2010/08/04/example-tableviewer-with-databinding/">Example: TableViewer with Databinding</a></span>]]></description>
			<content:encoded><![CDATA[<p>The following code demonstrates how to use a TableViewer with Databinding.  For a detailed explanation of the code, check the post <a href="http://javafact.com/2010/07/26/working-with-jface-tableviewer/">Working with JFace TableViewer</a>.</p>
<blockquote><pre>package com.oxbsystems.study.table.app02;

import java.util.Set;

import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.beans.PojoObservables;
import org.eclipse.core.databinding.observable.Realm;
import org.eclipse.core.databinding.observable.map.IObservableMap;
import org.eclipse.core.databinding.observable.set.WritableSet;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.StatusLineManager;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.jface.databinding.viewers.ObservableMapLabelProvider;
import org.eclipse.jface.databinding.viewers.ObservableSetContentProvider;
import org.eclipse.jface.layout.TableColumnLayout;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;

import com.oxbsystems.study.domain.workgroup.Person;
import com.oxbsystems.study.domain.workgroup.Workgroup;

public class DatabindingTableApp extends ApplicationWindow {
	private static class Sorter extends ViewerSorter {
		public int compare(Viewer viewer, Object e1, Object e2) {
			Person item1 = (Person) e1;
			Person item2 = (Person) e2;
			String s1 = item1.getLast()+item1.getFirst();
			String s2 = item2.getLast()+item2.getFirst();
			return s1.compareTo(s2);
		}
	}
	@SuppressWarnings("unused")
	private DataBindingContext m_bindingContext;
	private Table table;
	private TableViewer tableViewer;
	@SuppressWarnings("unused")
	private Workgroup workgroup;
	private Set<Person> memberSet;
	private Action clearSelectionAction;

	/**
	 * Create the application window.
	 */
	public DatabindingTableApp() {
		super(null);
		createActions();
		addToolBar(SWT.FLAT | SWT.WRAP);
		addMenuBar();
		addStatusLine();
	}

	/**
	 * Create contents of the application window.
	 *
	 * @param parent
	 */
	@Override
	protected Control createContents(Composite parent) {
		Composite container = new Composite(parent, SWT.NONE);
		container.setLayout(new GridLayout(1, false));

		// Create the composite
		Composite composite = new Composite(container, SWT.NONE);
		composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1,
				1));

		// Add TableColumnLayout
		TableColumnLayout layout = new TableColumnLayout();
		composite.setLayout(layout);

		tableViewer = new TableViewer(composite, SWT.BORDER
				| SWT.FULL_SELECTION);
		tableViewer.setSorter(new Sorter());
		tableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
			public void selectionChanged(SelectionChangedEvent event) {
				IStructuredSelection sel = (IStructuredSelection) tableViewer.getSelection();
				Person person = (Person) sel.getFirstElement();
				if(person != null){
					System.out.println("Selected : "+ person.getFirst() + " " + person.getLast());
				}
				else{
					System.out.println("Selection cleared!");
				}
			}
		});
		tableViewer.addDoubleClickListener(new IDoubleClickListener() {
			public void doubleClick(DoubleClickEvent event) {
				IStructuredSelection sel = (IStructuredSelection) event.getSelection();
				Person person = (Person) sel.getFirstElement();
				if(person != null){
					System.out.println("Double-click on : "+ person.getFirst() + " " + person.getLast());
				}
			}
		});
		table = tableViewer.getTable();
		table.setHeaderVisible(true);
		table.setLinesVisible(true);

		TableViewerColumn tableViewerColumn = new TableViewerColumn(
				tableViewer, SWT.NONE);
		TableColumn tblclmnFirst = tableViewerColumn.getColumn();
		layout.setColumnData(tblclmnFirst, new ColumnWeightData(2,
				ColumnWeightData.MINIMUM_WIDTH, true));
		tblclmnFirst.setText("First");

		TableViewerColumn tableViewerColumn_1 = new TableViewerColumn(
				tableViewer, SWT.NONE);
		TableColumn tblclmnLast = tableViewerColumn_1.getColumn();
		// Specify width using weights
		layout.setColumnData(tblclmnLast, new ColumnWeightData(2,
				ColumnWeightData.MINIMUM_WIDTH, true));
		tblclmnLast.setText("Last");

		TableViewerColumn tableViewerColumn_2 = new TableViewerColumn(
				tableViewer, SWT.NONE);
		TableColumn tblclmnTitle = tableViewerColumn_2.getColumn();
		// Specify width using weights
		layout.setColumnData(tblclmnTitle, new ColumnWeightData(4,
				ColumnWeightData.MINIMUM_WIDTH, true));
		tblclmnTitle.setText("Title");

		TableViewerColumn tableViewerColumn_3 = new TableViewerColumn(
				tableViewer, SWT.NONE);
		TableColumn tblclmnEmail = tableViewerColumn_3.getColumn();
		// Specify width using weights
		layout.setColumnData(tblclmnEmail, new ColumnWeightData(6,
				ColumnWeightData.MINIMUM_WIDTH, true));
		tblclmnEmail.setText("Email");

		initWorkgroup();
		m_bindingContext = initDataBindings();

		return container;
	}

	private void initWorkgroup() {
		Workgroup w = new Workgroup();
		Person p = new Person();
		p.setId(1);
		p.setFirst("John");
		p.setLast("Smith");
		p.setTitle("Manager");
		p.setEmail("jsmith@somecompany.com");
		w.add(p);
		p = new Person();
		p.setId(2);
		p.setFirst("Sam");
		p.setLast("Johnson");
		p.setTitle("Supervisor");
		p.setEmail("sjohnson@somecompany.com");
		w.add(p);
		this.setWorkgroup(w);
	}

	private void setWorkgroup(Workgroup workgroup) {
		this.workgroup = workgroup;
		this.memberSet = workgroup.getMemberSet();
	}

	/**
	 * Create the actions.
	 */
	private void createActions() {
		// Create the actions
		{
			clearSelectionAction = new Action("Clear Selection") {
				@Override
				public void run() {
					StructuredSelection sel = new StructuredSelection();
					tableViewer.setSelection(sel);
					super.run();
				}

			};
		}
	}

	/**
	 * Create the menu manager.
	 *
	 * @return the menu manager
	 */
	@Override
	protected MenuManager createMenuManager() {
		MenuManager menuManager = new MenuManager("menu");
		return menuManager;
	}

	/**
	 * Create the toolbar manager.
	 *
	 * @return the toolbar manager
	 */
	@Override
	protected ToolBarManager createToolBarManager(int style) {
		ToolBarManager toolBarManager = new ToolBarManager(style);
		toolBarManager.add(clearSelectionAction);
		return toolBarManager;
	}

	/**
	 * Create the status line manager.
	 *
	 * @return the status line manager
	 */
	@Override
	protected StatusLineManager createStatusLineManager() {
		StatusLineManager statusLineManager = new StatusLineManager();
		return statusLineManager;
	}

	/**
	 * Launch the application.
	 *
	 * @param args
	 */
	public static void main(String args[]) {
		Display display = Display.getDefault();
		Realm.runWithDefault(SWTObservables.getRealm(display), new Runnable() {
			public void run() {
				try {
					DatabindingTableApp window = new DatabindingTableApp();
					window.setBlockOnOpen(true);
					window.open();
					Display.getCurrent().dispose();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Configure the shell.
	 *
	 * @param newShell
	 */
	@Override
	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setText("TableViewer with Databinding");
	}

	/**
	 * Return the initial size of the window.
	 */
	@Override
	protected Point getInitialSize() {
		return new Point(450, 300);
	}

	protected DataBindingContext initDataBindings() {
		DataBindingContext bindingContext = new DataBindingContext();
		//
		ObservableSetContentProvider setContentProvider = new ObservableSetContentProvider();
		tableViewer.setContentProvider(setContentProvider);
		//
		IObservableMap[] observeMaps = PojoObservables.observeMaps(
				setContentProvider.getKnownElements(), Person.class,
				new String[] { "first", "last", "title", "email" });
		tableViewer
				.setLabelProvider(new ObservableMapLabelProvider(observeMaps));
		//
		WritableSet writableSet = new WritableSet(memberSet, Person.class);
		tableViewer.setInput(writableSet);
		//
		return bindingContext;
	}
}
</pre>
</blockquote>
]]></content:encoded>
			<wfw:commentRss>http://javafact.com/2010/08/04/example-tableviewer-with-databinding/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Example: TableViewer with a ContentProvider and a LabelProvider</title>
		<link>http://javafact.com/2010/08/01/example-tableviewer-with-a-contentprovider-and-a-labelprovider/</link>
		<comments>http://javafact.com/2010/08/01/example-tableviewer-with-a-contentprovider-and-a-labelprovider/#comments</comments>
		<pubDate>Sun, 01 Aug 2010 21:58:57 +0000</pubDate>
		<dc:creator>Octavio Berlanga</dc:creator>
				<category><![CDATA[Eclipse RCP]]></category>
		<category><![CDATA[Example]]></category>
		<category><![CDATA[JFace]]></category>

		<guid isPermaLink="false">http://javafact.com/?p=530</guid>
		<description><![CDATA[This example demonstrates how to populate a TableViewer using a ContentProvider and a LabelProvider <span style="color:#777"> . . . &#8594; Read More: <a href="http://javafact.com/2010/08/01/example-tableviewer-with-a-contentprovider-and-a-labelprovider/">Example: TableViewer with a ContentProvider and a LabelProvider</a></span>]]></description>
			<content:encoded><![CDATA[<p>The following code demonstrates how to create a TableViewer using TableColumnLayout, a ContentProvider and a LabelProvider.</p>
<p>For a detailed explanation, check the post <a href="http://javafact.com/2010/07/26/working-with-jface-tableviewer/">Working With JFace TableViewer</a>.</p>
<div id="attachment_533" class="wp-caption aligncenter" style="width: 624px"><a href="http://javafact.com/wp-content/uploads/2010/08/tableViewer.png"><img class="size-full wp-image-533" title="TableViewer" src="http://javafact.com/wp-content/uploads/2010/08/tableViewer.png" alt="" width="614" height="293" /></a><p class="wp-caption-text">TableViewer Example</p></div>
<p> </p>
<blockquote>
<pre>package com.oxbsystems.study.table.app01;

import java.awt.Dimension;
import java.awt.Toolkit;

import org.eclipse.jface.action.CoolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.StatusLineManager;
import org.eclipse.jface.layout.TableColumnLayout;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;

import com.oxbsystems.study.domain.workgroup.Person;
import com.oxbsystems.study.domain.workgroup.Workgroup;

public class TableApp extends ApplicationWindow {
	private class TableLabelProvider extends LabelProvider implements ITableLabelProvider {
		public Image getColumnImage(Object element, int columnIndex) {
			return null;
		}
		public String getColumnText(Object element, int columnIndex) {
			Person p = (Person) element;
			String result = "";
			switch(columnIndex){
			case 0:
				result = p.getFirst();
				break;
			case 1:
				result = p.getLast();
				break;
			case 2:
				result = p.getTitle();
				break;
			case 3:
				result = p.getEmail();
				break;
			default:
				//should not reach here
				result = "";
			}
			return result;
		}
	}
	private static class ContentProvider implements IStructuredContentProvider {
		public Object[] getElements(Object inputElement) {
			Workgroup w = (Workgroup) inputElement;
			return w.getMemberSet().toArray();
		}
		public void dispose() {
		}
		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
		}
	}
	private Table table;
	private TableViewer tableViewer;
	private Workgroup workgroup;
	/**
	 * Create the application window,
	 */
	public TableApp() {
		super(null);
		setShellStyle(SWT.CLOSE | SWT.MIN | SWT.MAX | SWT.RESIZE);
		createActions();
		addCoolBar(SWT.FLAT);
		addMenuBar();
		addStatusLine();
	}

	/**
	 * Create contents of the application window.
	 * @param parent
	 */
	@Override
	protected Control createContents(Composite parent) {
		Composite container = new Composite(parent, SWT.NONE);
		container.setLayout(new GridLayout(1, false));

		//Create the composite
		Composite composite = new Composite(container, SWT.NONE);
		composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

		//Add TableColumnLayout
		TableColumnLayout layout = new TableColumnLayout();
		composite.setLayout(layout);

		tableViewer = new TableViewer(composite, SWT.BORDER | SWT.FULL_SELECTION);
		table = tableViewer.getTable();
		table.setHeaderVisible(true);
		table.setLinesVisible(true);

		TableViewerColumn tableViewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
		TableColumn tblclmnFirst = tableViewerColumn.getColumn();
		layout.setColumnData(tblclmnFirst, new ColumnWeightData(2, ColumnWeightData.MINIMUM_WIDTH, true));
		tblclmnFirst.setText("First");

		TableViewerColumn tableViewerColumn_1 = new TableViewerColumn(tableViewer, SWT.NONE);
		TableColumn tblclmnLast = tableViewerColumn_1.getColumn();
		//Specify width using weights
		layout.setColumnData(tblclmnLast, new ColumnWeightData(2, ColumnWeightData.MINIMUM_WIDTH, true));
		tblclmnLast.setText("Last");

		TableViewerColumn tableViewerColumn_2 = new TableViewerColumn(tableViewer, SWT.NONE);
		TableColumn tblclmnTitle = tableViewerColumn_2.getColumn();
		//Specify width using weights
		layout.setColumnData(tblclmnTitle, new ColumnWeightData(4, ColumnWeightData.MINIMUM_WIDTH, true));
		tblclmnTitle.setText("Title");

		TableViewerColumn tableViewerColumn_3 = new TableViewerColumn(tableViewer, SWT.NONE);
		TableColumn tblclmnEmail = tableViewerColumn_3.getColumn();
		//Specify width using weights
		layout.setColumnData(tblclmnEmail, new ColumnWeightData(6, ColumnWeightData.MINIMUM_WIDTH, true));
		tblclmnEmail.setText("Email");
		tableViewer.setLabelProvider(new TableLabelProvider());
		tableViewer.setContentProvider(new ContentProvider());
		initWorkgroup();
		return container;
	}

	private void initWorkgroup() {
		Workgroup w = new Workgroup();
		Person p = new Person();
		p.setFirst("John");
		p.setLast("Smith");
		p.setTitle("Manager");
		p.setEmail("jsmith@somecompany.com");
		w.add(p);
		this.setWorkgroup(w);
	}

	private void add(Person person){
		workgroup.add(person);
		this.tableViewer.add(person);
		this.tableViewer.refresh();
	}

	private void remove(Person person){
		workgroup.remove(person);
		this.tableViewer.remove(person);
		this.tableViewer.refresh();
	}

	public void setWorkgroup(Workgroup workgroup){
		this.workgroup = workgroup;
		this.tableViewer.setInput(workgroup);
	}

	/**
	 * Create the actions.
	 */
	private void createActions() {
		// Create the actions
	}

	/**
	 * Create the menu manager.
	 * @return the menu manager
	 */
	@Override
	protected MenuManager createMenuManager() {
		MenuManager menuManager = new MenuManager("menu");
		return menuManager;
	}

	/**
	 * Create the coolbar manager.
	 * @return the coolbar manager
	 */
	@Override
	protected CoolBarManager createCoolBarManager(int style) {
		CoolBarManager coolBarManager = new CoolBarManager(style);
		return coolBarManager;
	}

	/**
	 * Create the status line manager.
	 * @return the status line manager
	 */
	@Override
	protected StatusLineManager createStatusLineManager() {
		StatusLineManager statusLineManager = new StatusLineManager();
		return statusLineManager;
	}

	/**
	 * Launch the application.
	 * @param args
	 */
	public static void main(String args[]) {
		try {
			TableApp window = new TableApp();
			window.setBlockOnOpen(true);
			window.open();
			Display.getCurrent().dispose();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Configure the shell.
	 * @param newShell
	 */
	@Override
	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setText("TableApp");
	}

	/**
	 * Return the initial size of the window.
	 */
	@Override
	protected Point getInitialSize() {
		Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
		return new Point(dim.width,dim.height);
	}
}</pre>
</blockquote>
]]></content:encoded>
			<wfw:commentRss>http://javafact.com/2010/08/01/example-tableviewer-with-a-contentprovider-and-a-labelprovider/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Working with JFace TableViewer</title>
		<link>http://javafact.com/2010/07/26/working-with-jface-tableviewer/</link>
		<comments>http://javafact.com/2010/07/26/working-with-jface-tableviewer/#comments</comments>
		<pubDate>Tue, 27 Jul 2010 03:15:42 +0000</pubDate>
		<dc:creator>Octavio Berlanga</dc:creator>
				<category><![CDATA[Eclipse RCP]]></category>
		<category><![CDATA[JFace]]></category>

		<guid isPermaLink="false">http://javafact.com/?p=452</guid>
		<description><![CDATA[How to use a JFace TableViewer step by step. <span style="color:#777"> . . . &#8594; Read More: <a href="http://javafact.com/2010/07/26/working-with-jface-tableviewer/">Working with JFace TableViewer</a></span>]]></description>
			<content:encoded><![CDATA[<hr /><strong>Overview</strong><br />
The following sections provide a concise explanation of how to work with TableViewer, including: </p>
<li>Instantiating a TableViewer and its columns</li>
<li>Using a ContentProvider, a LabelProvider and a Sorter</li>
<li>Using eclipse databinding</li>
<li>Ways to manage column width</li>
<li>Managing updates</li>
<li>Using event listeners</li>
<li>Trouble-shooting</li>
<li>Limitations</li>
<hr /><strong>Instantiating a TableViewer</strong></p>
<p style="text-align: left;">The order of operations for creating a TableViewer is, perhaps, not what you would expect. You can simply instantiate the TableViewer and then its TableViewerColumns and then you could add the columns to the viewer. That would work, but your columns would not fill the entire width of the container. Rather, you would have a table with a blank column to the right.</p>
<p style="text-align: center;"><a href="http://javafact.com/wp-content/uploads/2010/07/simpleTable.png"><img class="size-full wp-image-510   aligncenter" style="border: black 1px solid;" title="Simple Table" src="http://javafact.com/wp-content/uploads/2010/07/simpleTable.png" alt="" width="447" height="296" /></a></p>
<p>To avoid the blank column at the end of the TableViewer you need to use TableColumnLayout. Using that layout requires a composite that only holds your TableViewer, so first you create the composite, then you add the layout to the composite, and then you create and add the TableViewer to the composite.</p>
<p>The following code shows how this is done: </p>
<blockquote>
<pre>		<span style="color: #ff0000;">//Create the composite</span>
		Composite composite = new Composite(container, SWT.NONE);
		composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

		<span style="color: #ff0000;">//Add TableColumnLayout</span>
		TableColumnLayout layout = new TableColumnLayout();
		composite.setLayout(layout);

		<span style="color: #ff0000;">//Instantiate TableViewer</span>
		TableViewer tableViewer = new TableViewer(composite, SWT.BORDER | SWT.FULL_SELECTION);
		table = tableViewer.getTable();
		table.setHeaderVisible(true);
		table.setLinesVisible(true);

		TableViewerColumn tableViewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
		TableColumn tblclmnPixel100 = tableViewerColumn.getColumn();
		<span style="color: #ff0000;"><strong>//Specify width using pixels</strong>
</span>		layout.setColumnData(tblclmnPixel100, new ColumnPixelData(100, true, true));
		tblclmnPixel100.setText("Pixel 100");

		TableViewerColumn tableViewerColumn_1 = new TableViewerColumn(tableViewer, SWT.NONE);
		TableColumn tblclmnWeight2 = tableViewerColumn_1.getColumn();
		<strong><span style="color: #ff0000;">//Specify width using weights</span></strong>
		layout.setColumnData(tblclmnWeight2, new ColumnWeightData(2, ColumnWeightData.MINIMUM_WIDTH, true));
		tblclmnWeight2.setText("Weight 2");

		TableViewerColumn tableViewerColumn_2 = new TableViewerColumn(tableViewer, SWT.NONE);
		TableColumn tblclmnWeight4 = tableViewerColumn_2.getColumn();
		<span style="color: #ff0000;">//Specify width using weights</span>
		layout.setColumnData(tblclmnWeight4, new ColumnWeightData(4, ColumnWeightData.MINIMUM_WIDTH, true));
		tblclmnWeight4.setText("Weight 4");

		TableViewerColumn tableViewerColumn_3 = new TableViewerColumn(tableViewer, SWT.NONE);
		TableColumn tblclmnWeight6 = tableViewerColumn_3.getColumn();
		<span style="color: #ff0000;">//Specify width using weights</span>
		layout.setColumnData(tblclmnWeight6, new ColumnWeightData(6, ColumnWeightData.MINIMUM_WIDTH, true));
		tblclmnWeight6.setText("Weight 6");

		TableViewerColumn tableViewerColumn_4 = new TableViewerColumn(tableViewer, SWT.NONE);
		TableColumn tblclmnWeight12 = tableViewerColumn_4.getColumn();
		<span style="color: #ff0000;">//Specify width using weights</span>
		layout.setColumnData(tblclmnWeight12, new ColumnWeightData(12, ColumnWeightData.MINIMUM_WIDTH, true));
		tblclmnWeight12.setText("Weight 12");</pre>
</blockquote>
<p>Notice how the first column differs from the rest as it uses pixels to define width; the other columns use a weight value and will adjust their width based on the space that is available for the entire TableViewer. The code may seem a bit involved if you are writing the code by hand; however, if you use RCP Developer or SWT Designer from <a href="http://instantiations.com" target="_blank">Instantiations</a>, generating the code above will only take a few seconds. The resulting TableViewer will no longer have the blank column to the right:</p>
<p style="text-align: center;"> </p>
<p><a href="http://javafact.com/wp-content/uploads/2010/07/TableColumnLayout.png"><img class="aligncenter size-full wp-image-513" style="border: black 1px solid;" title="TableColumnLayout" src="http://javafact.com/wp-content/uploads/2010/07/TableColumnLayout.png" alt="" width="905" height="453" /></a></p>
<hr /><strong>Populating a table with a ContentProvider and a LabelProvider</strong><br />
There are two ways to populate a TableViewer. You can use a ContentProvider and a LabelProvider or you can use databinding, which I&#8217;ll explain in the next section. SWT Designer makes both methods relatively easy to implement, but if a column should display a string that must be built on the fly by combining several input object properties (such as [first name][space][last name]), then your only option will be to use a ContentProvider and a LabelProvider.</p>
<p>Assuming you have the layout ready, ie, you&#8217;ve setup the TableViewer with the columns that you need, you will create the ContentProvider and the LabelProvider as inner classes. In this section we assume we will use a workgroup object that has a member set and will display first name, last name, title, and email address. The ContentPorvider will only return an array of objects that will be displayed in each row, so it would be implemented as follows:</p>
<blockquote>
<pre>	private static class ContentProvider implements IStructuredContentProvider {
		public Object[] getElements(Object inputElement) {
			Workgroup w = (Workgroup) inputElement;
			return w.getMemberSet().toArray();
		}
		public void dispose() {
		}
		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
		}
	}</pre>
</blockquote>
<p> </p>
<p>The label provider will return the icons and strings that will be used in each column:</p>
<blockquote>
<pre>	private class TableLabelProvider extends LabelProvider implements ITableLabelProvider {
		public Image getColumnImage(Object element, int columnIndex) {
			return null;
		}
		public String getColumnText(Object element, int columnIndex) {
			Person p = (Person) element;
			String result = "";
			switch(columnIndex){
			case 0:
				result = p.getFirst();
				break;
			case 1:
				result = p.getLast();
				break;
			case 2:
				result = p.getTitle();
				break;
			case 3:
				result = p.getEmail();
				break;
			default:
				//should not reach here
				result = "";
			}
			return result;
		}
	}</pre>
</blockquote>
<p> </p>
<p>These two providers must be added to the tableViewer as follows:</p>
<blockquote>
<pre>		tableViewer.setLabelProvider(new TableLabelProvider());
		tableViewer.setContentProvider(new ContentProvider());</pre>
</blockquote>
<p> </p>
<p>The table will get populated with a call to the tableViewer.setInput method:</p>
<blockquote>
<pre>	public void setWorkgroup(Workgroup workgroup){
		this.workgroup = workgroup;
		this.tableViewer.setInput(workgroup);
	}</pre>
</blockquote>
<p> </p>
<p>As you add and remove members, you will have to update the table programatically as the table will not reflect changes automatically:</p>
<blockquote>
<pre>	private void add(Person person){
		workgroup.add(person);
		this.tableViewer.add(person);
		this.tableViewer.refresh();
	}

	private void remove(Person person){
		workgroup.remove(person);
		this.tableViewer.remove(person);
		this.tableViewer.refresh();
	}</pre>
</blockquote>
<p>Here&#8217;s the complete <a href="http://javafact.com/2010/08/01/example-tableviewer-with-a-contentprovider-and-a-labelprovider/">example</a>. </p>
<hr /><strong>Populating a table with Databinding</strong><br />
If you are using SWT Designer, the databinding tool would generate the following initDatabinding method.  You will note that there is a WritableSet that is constructed with the memberSet and is passed as viewer input.  One very important thing to note is that in this case changes to memberSet will not be reflected in the WritableSet, so the term &#8220;databinding&#8221; is perhaps not entirely true.  If you add or delete members from the memberSet, those changes will not be reflected automatically in the tableViewer.  You will still have to call tableViewer add or remove methods.  However, if the objects in the set provide support for property listeners, changes in these objects will be reflected in the tableviewer automatically.</p>
<blockquote>
<pre>	protected DataBindingContext initDataBindings() {
		DataBindingContext bindingContext = new DataBindingContext();
		//
		ObservableSetContentProvider setContentProvider = new ObservableSetContentProvider();
		tableViewer.setContentProvider(setContentProvider);
		//
		IObservableMap[] observeMaps = PojoObservables.observeMaps(
				setContentProvider.getKnownElements(), Person.class,
				new String[] { "first", "last", "title", "email" });
		tableViewer
				.setLabelProvider(new ObservableMapLabelProvider(observeMaps));
		//
		WritableSet writableSet = new WritableSet(memberSet, Person.class);
		tableViewer.setInput(writableSet);
		//
		return bindingContext;
	}</pre>
</blockquote>
<p>This initDatabindings method is called from the createContents method and the UI class will keep a reference to the DatabindingContext through an instance variable.  The DatabindingContext could then be used to update the target tableViewer or the model.  Or, if you are re-loading the UI with a new model, you can use the DatabindingContext to call Dispose and then you can recreate the databinding by simply calling initDataBindings().</p>
<blockquote>
<pre>	protected Control createContents(Composite parent) {
		Composite container = new Composite(parent, SWT.NONE);
		container.setLayout(new GridLayout(1, false));

		// Create the composite
		// Add TableColumnLayout
		// Create tableViewer its columns

		initWorkgroup();
		m_bindingContext = initDataBindings();

		return container;
	}
</pre>
</blockquote>
<p>Here&#8217;s the complete <a href="http://javafact.com/2010/08/04/example-tableviewer-with-databinding/">example</a>.</p>
<hr /><strong>TableViewer Events</strong><br />
Two events that are commonly tracked on a TableViewer are selection changes and mouse double-clicks on a TableViewer item.  In both cases you will use the getSelection() method to determine the current selection.  This method will always return a StructuredSelection object, which implements ISelection, and it will never return null.  Most of the time you will cast to either StructuredSelection or IStructuredSelection as follows:</p>
<blockquote><pre>IStructuredSelection sel = (IStructuredSelection) tableViewer.getSelection();
Person person = (Person) sel.getFirstElement(); // this can return null
if(person != null){
	System.out.println("Selected : "+ person.getFirst() + " " + person.getLast());
	// call a method that will do something
	// useful with person
}
else{
	MessageDialog.openInformation(getShell(), "Message", "Selection cleared!");
}</pre>
</blockquote>
<p>Selection changes will be monitored through an ISelectionChangedListener which will tipically be implemented as an inner class:</p>
<blockquote><pre>tableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
	public void selectionChanged(SelectionChangedEvent event) {
		IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
		// ... Do something with selection
	}
});</pre>
</blockquote>
<p>Likewise, double-clicks will be monitored through an IDoubleClickListener:</p>
<blockquote><pre>tableViewer.addDoubleClickListener(new IDoubleClickListener() {
	public void doubleClick(DoubleClickEvent event) {
		IStructuredSelection selection = (IStructuredSelection) event.getSelection();
		// Do something with selection here
	}
});</pre>
</blockquote>
<p>It is also common to change the sorting order on a TableViewer when a column header is clicked.  This is acheived by adding a selection adapter to a column and changing the TableViewer sorter from within the adapter&#8217;s widgetSelected method:</p>
<blockquote><pre>
tblclmnFirst.addSelectionListener(new SelectionAdapter() {
	@Override
	public void widgetSelected(SelectionEvent e) {
		tableViewer.setSorter(new FirstSorter());
	}
});</pre>
</blockquote>
<p>The sorter itself is most commonly implemented a private class that extends ViewerSorter:</p>
<blockquote><pre>private static class FirstSorter extends ViewerSorter {
	public int compare(Viewer viewer, Object e1, Object e2) {
		Person item1 = (Person) e1;
		Person item2 = (Person) e2;
		String s1 = item1.getFirst();
		String s2 = item2.getFirst();
		return s1.compareTo(s2);
	}
}</pre>
</blockquote>
<p>Here&#8217;s the complete <a href="http://javafact.com/2010/08/07/example-tableviewer-events/">example of TableViewer events</a>.<br />
</p>
<hr /><strong>Trouble-shooting</strong><br />
Here are a few conditions that will cause the TableViewer to not act as you would expect:<br />
<br />
<strong>Databinding a Set.</strong>  Window Builder Pro or SWT Designer will generate databinding code that makes use of a WritableSet, such as:</p>
<blockquote><pre>
WritableSet writableSet = new WritableSet(codeDescriptor.getDescriptorSet(), Descriptor.class);
tableViewer.setInput(writableSet);
</pre>
</blockquote>
<p>The problem with this databinding approach is that it creates a completely new Set.  Changes in the original set&#8211;changes in your model&#8211; are not reflected in the writableSet because it is a completely different set.  As a result, the TableViewer will not get updated as you would expect after making a change to your model.  The following statement comes from the JavaDoc for the constructor: &#8220;Constructs a new instance in the default realm containing the elements of the given collection. Changes to the given collection after calling this method do not affect the contents of the created WritableSet.&#8221;</p>
<p>WritableList does not present this update problem because the WritableList wraps the list that you provide in the constructor (which would be a list from your model).  So a coding approach that works perfectly fine when you are working with Lists will &#8220;fail silently&#8221; when you are working with Sets.</p>
<p>So, how do you work around this problem?  If you add or remove items from your model set, also add or remove them from the WritableSet.  Obtain the writableSet by using the getInput method in the tableViewer.  Once you have gained access to the WritableSet, make the additions and removals as you normally would on any set and, finally, call the refresh method on the tableViewer.</p>
<blockquote><pre>
	WritableSet set = (WritableSet) this.tableViewer.getInput();
	set.add(descriptor);
	this.tableViewer.refresh();</pre>
</blockquote>
<p>If you are making changes to an item, follow the change with a call to bindingContext.updateTargets().</p>
]]></content:encoded>
			<wfw:commentRss>http://javafact.com/2010/07/26/working-with-jface-tableviewer/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>The Role of Eclipse RCP Application Advisors</title>
		<link>http://javafact.com/2010/07/12/the-role-of-eclipse-rcp-application-advisors/</link>
		<comments>http://javafact.com/2010/07/12/the-role-of-eclipse-rcp-application-advisors/#comments</comments>
		<pubDate>Tue, 13 Jul 2010 00:52:18 +0000</pubDate>
		<dc:creator>Octavio Berlanga</dc:creator>
				<category><![CDATA[Eclipse RCP]]></category>

		<guid isPermaLink="false">http://javafact.com/?p=446</guid>
		<description><![CDATA[When you create a new Rich Client Platform application, the eclipse wizard will create an Application class and several advisors that work with the Application class.  This post provides an overview of the classes that you will find after creating a new RCP application. <span style="color:#777"> . . . &#8594; Read More: <a href="http://javafact.com/2010/07/12/the-role-of-eclipse-rcp-application-advisors/">The Role of Eclipse RCP Application Advisors</a></span>]]></description>
			<content:encoded><![CDATA[<hr />
<strong>Introduction</strong><br />
When you create a new Eclipse RCP application, the wizard will create an Application class that implements IApplication and the following advisor classes:</p>
<li>ApplicationWorkbenchAdvisor, which extends WorkbenchAdvisor and will be responsible for loading the initial perspective</li>
<li>ApplicationWorkbenchWindowAdvisor, which extends WorkbenchWindowAdvisor and is responsible for configuring the application window</li>
<li>ApplicationActionBarAdvisor, which extends ActionBarAdvisor and will be responsible for populating the action bar</li>
<p>The Application class that the wizard creates has a start method and a stop method. I&#8217;ve never had the need to make changes to this Application class. How is this Application class used? In essence, the application class in RCP will have a role similar to a main class in a standard executable jar file. In a standard jar file the JVM will search the jar manifest to determine which class has the main method where the program begins. In RCP, the Eclipse platform checks the plugin.xml file to determine the run class that implements IApplication.</p>
<p>So the RCP application will execute under a Run Configuration. Within that configuration, there will be a reference to the plug-in that you are developing. The plugin.xml file will show the Application class as the run class:</p>
<blockquote><pre>      &lt;application
            icon="icons/branding/branding16.gif"
            visible="true"&gt;
         &lt;run
              class="com.oxbsystems.client.application.Application"&gt;
         &lt;/run&gt;
      &lt;/application&gt;</pre>
</blockquote>
<p>In short, the sequence of events for application start-up is:</p>
<li>The Eclipse platform loads and determines the plug-in that should be executed</li>
<li>Eclipse inspects the plugin.xml file for the plug-in to resolve the run class name.</li>
<li>Eclipse calls the start method in the run class (which implements IApplication)</li>
<li>The start method in the run class will create an instance of ApplicationWorkbenchAdvisor</li>
<li>ApplicationWorkbenchAdvisor will instantiate an ApplicationWorkbenchWindowAdvisor, which in turn will instantiate ApplicationActionBarAdvisor.</li>
<hr />
<strong>ApplicationWorkbenchAdvisor</strong><br />
The ApplicationWorkbenchAdvisor does two things: it instantiates an ApplicationWorkbenchWindowAdvisor (explained below) and will set the initial perspective.</p>
<blockquote>
<pre>public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor {
	private static final String PERSPECTIVE_ID = "com.oxbsystems.client.perspective.login.LoginPerspective";

	public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
		return new ApplicationWorkbenchWindowAdvisor(configurer);
	}

	public String getInitialWindowPerspectiveId() {
		return PERSPECTIVE_ID;
	}
}</pre>
</blockquote>
<hr />
<p><strong>ApplicationWorkbenchWindowAdvisor</strong><br />
ApplicationWorkbenchWindowAdvisor will have a constructor that takes an IWorkbenchWindowConfigurer that will be supplied by the platform. This class will typically have the following methods:</p>
<li>createActionBarAdvisor will instantiate and return an ApplicationActionBarAdvisor.</li>
<li>preWindowOpen will modify the IWorkbenchWindowConfigurer. Screen size will be calculated in this method as shown in the next snippet.</li>
<li>postWindowOpen will modify the configurer after the application window opens.</li>
<blockquote>
<pre>public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor {

	public ApplicationWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
		super(configurer);
	}

	public ActionBarAdvisor createActionBarAdvisor(IActionBarConfigurer configurer) {
		return new ApplicationActionBarAdvisor(configurer);
	}

	public void preWindowOpen() {
		IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
		Rectangle r = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
		configurer.setInitialSize(new Point(r.width, r.height));
		configurer.setShowCoolBar(true);
		configurer.setShowStatusLine(false);
		PlatformUI.getPreferenceStore().setValue(
				IWorkbenchPreferenceConstants.SHOW_TRADITIONAL_STYLE_TABS, false);
	}

	@Override
	public void postWindowOpen() {
		super.postWindowOpen();
		IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
		configurer.getWindow().getShell().setMaximized(true);

	}

}</pre>
</blockquote>
<hr />
<strong>ApplicationActionBarAdvisor</strong><br />
The ApplicationActionBarAdvisor creates actions and adds them to the toolbar. In the following example this class also listens for changes in a Session object to enable or disable items in the toolbar.</p>
<blockquote>
<pre>public class ApplicationActionBarAdvisor extends ActionBarAdvisor implements SessionListener{
	private OpenCompanyCatalogPerspectiveAction openCompanyPerspectiveAction;
	private OpenServiceCatalogPerspectiveAction openServicePerspectiveAction;
	private Session session;
	private IWorkbenchAction quitAction;
	private ToolBarManager toolBarManager;

    public ApplicationActionBarAdvisor(IActionBarConfigurer configurer) {
		super(configurer);
		session = Session.getInstance();
		session.register(this);
    }

    protected void makeActions(IWorkbenchWindow window) {
		quitAction = ActionFactory.QUIT.create(window);
		quitAction.setImageDescriptor(	Activator.getImageDescriptor( "icons/action/perspective/exit.png"));
		register(quitAction);

		openCompanyPerspectiveAction = new OpenCompanyCatalogPerspectiveAction(window);
		register(openCompanyPerspectiveAction);

		openServicePerspectiveAction = new OpenServiceCatalogPerspectiveAction(window);
		register(openServicePerspectiveAction);
    }

	protected void fillMenuBar(IMenuManager menuBar) {
	}

	protected void fillCoolBar(ICoolBarManager coolBar) {
		toolBarManager = new ToolBarManager(SWT.FLAT);
		coolBar.add(toolBarManager);
		this.populateToolbar();
	}

	private void populateToolbar() {
		this.toolBarManager.removeAll();
		if(session.isValid()){
			this.toolBarManager.add(openConfigurationPerspectiveAction);
			this.toolBarManager.add(openCompanyPerspectiveAction);
		}
		this.toolBarManager.add(quitAction);
	}

	/* (non-Javadoc)
	 * @see com.oxbsystems.client.service.jaas.SessionListener#sessionChanged()
	 */
	@Override
	public void sessionChanged() {
		this.populateToolbar();
		this.toolBarManager.update(true);
	}
}</pre>
</blockquote>
]]></content:encoded>
			<wfw:commentRss>http://javafact.com/2010/07/12/the-role-of-eclipse-rcp-application-advisors/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java Enumerations</title>
		<link>http://javafact.com/2010/07/12/java-enumerations/</link>
		<comments>http://javafact.com/2010/07/12/java-enumerations/#comments</comments>
		<pubDate>Tue, 13 Jul 2010 00:04:02 +0000</pubDate>
		<dc:creator>Octavio Berlanga</dc:creator>
				<category><![CDATA[Java SE]]></category>

		<guid isPermaLink="false">http://javafact.com/?p=442</guid>
		<description><![CDATA[An explanation of Java Enumerations, including the use of constructors, variables, and methods. <span style="color:#777"> . . . &#8594; Read More: <a href="http://javafact.com/2010/07/12/java-enumerations/">Java Enumerations</a></span>]]></description>
			<content:encoded><![CDATA[<p><strong>Usage</strong><br />
Sometimes an object will have a property that can only take a limited set of values, such as male/female. You could simply use a String to represent those values, but you could also use int values. Using Strings may lead to errors. Using int values could lead to errors but will also make the code more difficult to read.</p>
<p>With enumerations we can specify male/female values as Gender.Male and Gender.Female. Enumerations will let you obtain String and numeric representations of these values if that is what you need at some point in your application.</p>
<p><strong>Declaration</strong><br />
The simplest declaration would be something like this:</p>
<blockquote>
<pre>public enum Gender{
	Male, Female;
}</pre>
</blockquote>
<p>But in addition to declaring final values, an enumeration can have a constructor and can also have methods:</p>
<blockquote>
<pre>public enum Gender{
	Male("Masculino"), Female("Femenino");

	private String spanish;

	// the constructor
	Gender(String spanish){
		this.spanish = spanish;
	}

	// a method
	public String toSpanish(){
		return this.spanish;
	}
}</pre>
</blockquote>
<p>This Gender enumeration could be used as follows:</p>
<blockquote><p><code><br />
Person p = new Person();<br />
p.setGender(Gender.Male);</code></p>
<p>String text = &#8220;The person&#8217;s gender in Spanish is: &#8221; + p.getGender().toSpanish();</p></blockquote>
<p>You can think of an enumeration as a Collection for which the JVM initializes all the collection objects and for which additions and removals are not allowed at run time. These collection objects are accessed statically.</p>
<p>In the example above Gender is the collection and its elements are accessed without having to instantiate Gender.</p>
<p><strong>Switch Statement Using Enumerations</strong><br />
If you use enumerations, sooner or later you will have the need to control program logic based on an enum value through a switch statement. The following code illustrates a switch statement using a TransportMode enumeration with values Air, Ocean, and Truck.</p>
<blockquote>
<pre>	private void processMode(TransportMode mode) {
		switch (mode) {
		case Air:
			// Do something here for Air
			break;
		case Ocean:
			// Do something here for Ocean
			break;
		case Truck:
			// Do something here for Truck
			break;
		default:
			// You will never reach this point.
			// The statement will throw a NullPointerException if mode == null
		}
	}</pre>
</blockquote>
<p>If you use Eclipse, code completion will help you write the statement by pressing Control-Space after &#8220;case &#8220;:</p>
<p style="text-align: center;"><a href="http://javafact.com/wp-content/uploads/2010/07/switchCompletion.gif"><img class="aligncenter size-full wp-image-507" style="border: black 1px solid;" title="switchCompletion" src="http://javafact.com/wp-content/uploads/2010/07/switchCompletion.gif" alt="Eclipse code completion" width="408" height="259" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://javafact.com/2010/07/12/java-enumerations/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>

