<?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>ProcessWorks Blog &#187; Java</title>
	<atom:link href="http://www.processworks.de/blog/tag/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.processworks.de/blog</link>
	<description>About teams and technology</description>
	<lastBuildDate>Mon, 26 Jul 2010 07:35:19 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.5</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Add Undo/Redo functionality to a Java app</title>
		<link>http://www.processworks.de/blog/2009/08/add-undoredo-functionality-to-a-java-app/</link>
		<comments>http://www.processworks.de/blog/2009/08/add-undoredo-functionality-to-a-java-app/#comments</comments>
		<pubDate>Tue, 04 Aug 2009 04:59:38 +0000</pubDate>
		<dc:creator>Dominik</dc:creator>
				<category><![CDATA[Patterns]]></category>
		<category><![CDATA[Sofware]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://processworks.wordpress.com/?p=33</guid>
		<description><![CDATA[Learn how to add undo/redo functionality to an existing Java application.]]></description>
			<content:encoded><![CDATA[<p>Recently I had to figure out a way to add undo/redo functionality to an existing Java application. Searching the web for some guidance I got a bit scared by finding posts that gave the impression that undo in Java is an overly complex thing that requires 10+ mysterious classes, best combined with reflection and modified GoF patterns.</p>
<p>I write this post to show you how simple undo in Java is and how it can be easily added to an existing application. You do not need to study Command patterns or rebuild half of your app, just follow the pragmatic approach described below and add a few simple classes to your application!</p>
<p>In our concrete case the requirement was to add undo functionality to an existing Excel-like spreadsheet application that had a horrible menu management and no patterns in it at all.<span id="more-33"></span></p>
<h2>Step 1: Determine what to undo</h2>
<p>To undo user actions, you absolutely need to know what actions you want to become undoable. In a spreadsheet application, you probably would like to undo cell modifications and row or column inserts, but not save or open operations. And it&#8217;s up to you to include visualization changes like modification of column width or sorting in the undoable operations. Every undoable action will add one small class to your project.</p>
<p>Let&#8217;s capture some examples of undoable operations for our spreadsheet:</p>
<p>- Cell Value change<br />
- Row insert<br />
- Row delete<br />
- Change column width<br />
- Sort rows</p>
<p>I will show how to implement the first of these undoable edits.</p>
<h2>Step 2: Tools of trade</h2>
<p>So now, from those 10+ magic classes that you can find in some descriptions on the net, where is the real magic?</p>
<p>It is the <a href="http://java.sun.com/javase/6/docs/api/javax/swing/undo/UndoManager.html" target="_blank">javax.swing.undo.UndoManager</a></p>
<div id="attachment_40" class="wp-caption alignnone" style="width: 268px"><img class="size-full wp-image-40" title="UndoManager" src="http://www.processworks.de/blog/wp-content/uploads/2009/08/UndoManager.png" alt="UndoManager" width="258" height="461" /><p class="wp-caption-text">The UndoManager class</p></div>
<p>This class is the heart of the undo functionality. It is responsible for managing the list of undoable operations and &#8216;manages&#8217; everything you need to undo an action.</p>
<p>Please be aware that UndoManager is in the Swing package, but this does not mean that you must have a Swing GUI to use it!</p>
<p>You will need usually one UndoManager in your application (it is designed to be a singleton); it provides you with:</p>
<p>- the possibility to register information about the changes an user action produces, those are called &#8216;Edits&#8217;<br />
- the ability to undo a previously registered Edit<br />
- the ability to redo a previously undone Edit<br />
- the functionality to invalidate all edits.</p>
<p>As you may expect, the UndoManager manages the undoable operation as &#8216;Edits&#8217;. An Edit is an object of a class you have to create, that implements the <a href="http://java.sun.com/javase/6/docs/api/javax/swing/undo/UndoableEdit.html" target="_blank">javax.swing.undo.UndoableEdit</a> interface.</p>
<div id="attachment_39" class="wp-caption alignnone" style="width: 214px"><img class="size-full wp-image-39" title="UndoableEditInterface" src="http://www.processworks.de/blog/wp-content/uploads/2009/08/UndoableEditInterface.png" alt="Interface UndoableEdit" width="204" height="225" /><p class="wp-caption-text">Interface UndoableEdit</p></div>
<h2>Step 3: Building your Edits</h2>
<p>Now let&#8217;s build a class implementing the Edit for value changes in our Excel-like table. We base our Edit on the <em>AbstractUndoableEdit</em> class provided by the Java framework, so we need to override only a few methods.</p>
<div id="attachment_41" class="wp-caption alignnone" style="width: 261px"><img class="size-full wp-image-41" title="Custom class TableCellEdit" src="http://www.processworks.de/blog/wp-content/uploads/2009/08/TableCellEditClass.png" alt="Custom class TableCellEdit" width="251" height="122" /><p class="wp-caption-text">Custom class TableCellEdit</p></div>
<p>TableCellEdit implements the UndoableEdit interface (actually AbstracrUndoableEdit does). It&#8217;s operations are the following:</p>
<pre><em>public TableCellEdit(IUndoableTableModel tableModel, Object oldValue, Object newValue, int row, int column)</em></pre>
<p>This constructor takes all information required for the undo. We want to be able to restore the previous value of a table cell, so we need the TableModel, the old value, the new value (for redo), and the row/column position in the model where value goes.</p>
<pre><em>public String getPresentationName()</em></pre>
<p>This returns a String to be presented to the user in the edit menu, for example “Cell Edit”, which will be presented as “Undo Cell Edit” or “Redo Cell Edit” respectively.</p>
<pre><em>public void undo() throws CannotUndoException</em></pre>
<p>This operation actually performs the undo operation. For undoing a value change in a TableModel, will set the cell at position row/column the oldValue (given in the constructor).<br />
The required housekeeping of the undo/redo stack will be done automatically by the UndoManager and UndoableEdit classes. Implementation of the undo usually will be something as simple as</p>
<pre> // Call the UndoableEdit class for housekeeping
 super.undo();</pre>
<pre> // set the old value, excluding all undo activity
 tableModel.setValueAt(oldValue, row, column, false)</pre>
<pre><em>public void redo() throws CannotRedoException</em></pre>
<p>Same as undo(), except that we would set the newValue to the cell.</p>
<p>We will see in a moment, how to merge the Edit-classes in your existing code. Stay tuned.</p>
<h3>Extending the basic Edit</h3>
<p>The TableCellEdit class illustrated above provides the required functionality for undoing and redoing edits. But wait – what about cursor movements? Shouldn&#8217;t they be treated as edits as well?<br />
Without handling cursor movements as UndoableEdits, an undo of a cell value change would result in the substitution of the value, but leave the cursor in it&#8217;s current position. That would be quite irritating to the user since he was at the changed cell position when he entered the new value.<br />
While cursor movements usually do not represent any information of value to the user and should not be undoable, the repositioning to the point where the undo happened is important because it is the behavior the user expects. Thus we move the cursor to the field/position where the undo/redo happens.</p>
<p>To implement this, we capture the on screen position for every cell that gets edited. Here we must pay attention to the Swing specific fact that TableModel and the shown JTable on screen may not be the same. Our solution was simply to convert the model position to the View position (JTable&#8217;s convertRowIndexToView()) and set the position in the undo and redo operations (editCellAt()). To do this, every TableCellEdit receives a reference to the edited Jtable (See below in the &#8216;Listeners&#8217; paragraph how we inject this reference).</p>
<h2>Step 4: Plugging it in</h2>
<p>Now that you have seen, what the main parts of the undo/redo implementation are, we can complete the setup by adding the required &#8216;glue&#8217; to the points where existing code needs to be modified for adding undo functionality.</p>
<h3>UndoManager</h3>
<p>You need at least one UndoManager class. We decided to have only one UndoManager in the whole application and to use a specialization of the Java-Provided UndoManager that updates our application menu and toolbar with every undo/redo operation.</p>
<h3>TableModel</h3>
<p>We use a form containing a Jtable in which we track edits. The JTable is backened by it&#8217;s TableModel. To capture cell value changes, we modify the TableModel&#8217;s setValueAt() method. For every new value set, a new TableCellEditObject is created and call to undoSupport.postEdit() is performed. UndoableEditSupport is provided by Swing and manages a list of undo event listeners (you will see below, why this is useful).</p>
<pre>// Add undo support to TableModel
 private UndoableEditSupport undoSupport = new UndoableEditSupport();
 ...</pre>
<pre>// in setValueAt(): if anything changed -&gt; announce edit
 if(oldValue!=null &amp;&amp; !oldValue.equals(newValue)
      || newValue != null &amp;&amp; !newValue.equals(oldValue)) {
    TableCellEdit cellEdit = new TableCellEdit(this, oldValue, newValue, modelRow, modelColumn);
    undoSupport.postEdit(cellEdit);
 }</pre>
<p>You must pay attention here to the fact that <em>setValueAt() </em>is called when the user edits a cell and also when we restore an old value during undo. We implemented a second <em>setValueAt()</em> that does <span style="text-decoration: underline;">not</span> create a <em>TableCellEdit</em> onject for the latter case.</p>
<h3>MenuActions</h3>
<p>To actually perform an undo when the user selects undo from the application menu, all you have to do is to call your UpdateManager&#8217;s <em>undo()</em> operation. The UpdateManager picks the last undoable Edit from it&#8217;s undo stack and executes it&#8217;s undo() operation.<br />
With our global solution, we do just:</p>
<pre> PCSUndoManager manager = Globals.getInstance().getUndoManager();
 manager.undo();</pre>
<h3>Listeners</h3>
<p>The Java undo facility provides an UndoableEditListener interface to capture notifications on every edit. You must define a listener that decides what to do with an UndoableEdit that gets advertised with the call to <em>UpdateManager.postEdit()</em>.<br />
Usually you just want to add it to the undo queue:</p>
<pre> public void undoableEditHappened(UndoableEditEvent e) {
    undoManager.addEdit(e.getEdit());
 }</pre>
<p>You register a class implementing just this with the <em>UndoableEditSupport</em> (in our TableModel). Fortunally the  UndoManager class implements the UndoableEditListener interface and provides exactly this as a default implementation. We do not need any customization here, so we use it as the listener.</p>
<pre>tableModel.getUndoSupport().addUndoableEditListener(undoManager);</pre>
<p>As mentioned above, we have a special need to track on-screen cursor positions inside the table. To do this our edits need to know to which table they belong, because the table provides the model-to-view conversion. Since we create our edits in the TableMODEL and do not want to spoil the design by adding a dependency of the model on the table (Swing is designed vice versa),  UndoableEditListeners come in handy. We used a listener to inject the current table edited into the TableCellEdit objects. Note that this is just a feature required by our design, you will do without, unless implementing undo in JTables.</p>
<p>Register our Form containing model and JTable as a listener:</p>
<pre>// Form implements UndoableEditListener
 public class PEForm implements UndoableEditListener
 ...</pre>
<pre>// in the Form's setup code, install the listener
 tableModel.getUndoSupport().addUndoableEditListener(this);
 ...</pre>
<pre>// Inject reference to current table in every edit inside our TableModel
 public void undoableEditHappened(UndoableEditEvent e) {
     UndoableEdit edit = e.getEdit();</pre>
<pre>     IPEEdit tce = (IPEEdit) edit;
     tce.setTable(theTable);
 }</pre>
<p>Note: The IPEEdit interface defines only the setTable(JTable) operation shown.</p>
<h3>Step 5: Try it</h3>
<p>Above I have illustrated in 4 simple steps how to add undo/redo functionality to your Java appplication. You are now prepared to apply it on your own application. They are</p>
<p>- add an UndoManager to your application (eventually derive your own class to include automatic menubar updates)</p>
<p>For each action you want to be undoable:<br />
- add class implementing the UndoAbleEdit interface (derive it from AbstractUndoableEdit)<br />
- where the to-be-undone operation is performed, create a new Edit object and call UndoManager&#8217;s postEdit(edit) method.</p>
<p>Below you find some sample classes attached, be aware that it is not a running example, but intended to give you a more complete context.</p>
<p>Now let&#8217;s have a final look on some details in the process.</p>
<h3>How does this &#8216;magic&#8217; stuff actually work?</h3>
<p>You may wonder what exactly happens when you implement the mechanism described above. This is best explained looking at a sequence diagram.</p>
<div id="attachment_45" class="wp-caption alignnone" style="width: 310px"><a href="http://www.processworks.de/blog/wp-content/uploads/2009/08/undosequence.png"><img class="size-medium wp-image-45 " title="undosequence" src="http://www.processworks.de/blog/wp-content/uploads/2009/08/undosequence-300x143.png" alt="Sequence diagram for a cell edit and a successive undo" width="300" height="143" /></a><p class="wp-caption-text">Sequence diagram for a cell edit and a successive undo</p></div>
<p>the first part of the diagram shows the creation of a TableCellEdit, the second part  shows what happens when the user selects Undo from the menu.</p>
<h3>How many UndoManagers do I need?</h3>
<p>In the sample shown above I said that one UndoManager is good enough. Actually  there are use cases where you would have more than one UndoManager. One scenario might be an application handling multiple open files; if you do not make file switching undoable, you will need one UndoManager per open file to make sure that undos are limited to the currently active file and do not impact invisible data.</p>
<h3>How many undo steps are available?</h3>
<p>The UpdateManager has a built in limit of 100 un-/redoable edits. You may change this value by calling setLimit(). There is also a discardAllEdits() operation available that you might want to call for example when a new file is opened.</p>
<h3>Why are ther two setValueAt() in the TableModel?</h3>
<p>You typically will set the value changes you want to be undoable in some kind of model object. When you do an undo or redo, you have to set the old (or new) value the same place. A pitfall is to call the same set operation in the Edit&#8217;s undo() as the one used to set a new value given by the user. This would produce a new Edit for each undo() and leave the currently undone operation on top of the undo stack &#8211; you would be able do undo once, but never be able to get to the previous step.</p>
<h3>Where to get more information?</h3>
<p>As stated above, I did not find very much useful information on the topic. You may try <a href="http://gondtalan.com/blog/?p=42" target="_blank">Neil Weber&#8217;s Blog</a> for an additional view on the topic. <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html#undo" target="_blank">Sun&#8217;s Java tutorial</a> gives some very basic advice on how to implement undo with standard text components.</p>
<p>Read the <a href="http://java.sun.com/javase/6/docs/api/index.html?javax/swing/undo/package-summary.html" target="_blank">Javadocs for the involved classes</a>.</p>
<h3>Can you provide complete source code please?</h3>
<p>No I can&#8217;t. The described solution was implemented in a not very well designed legacy application and it would be a headache to extract a running example.</p>
<p>Yes I can. Please find the source files for the example given above in the <a href="http://www.processworks.de/blog/wp-content/uploads/2009/08/JavaUndoRedoFiles.zip">downloadable JavaUndoRedoFiles.zip</a><br />
It is not runnable code but it may help you to better understand what exacty you need and where.</p>
<p>Have fun!<br />
Dominik</p>
]]></content:encoded>
			<wfw:commentRss>http://www.processworks.de/blog/2009/08/add-undoredo-functionality-to-a-java-app/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Export from Displaytag inside a Portlet</title>
		<link>http://www.processworks.de/blog/2008/12/export-from-displaytag-inside-a-portlet/</link>
		<comments>http://www.processworks.de/blog/2008/12/export-from-displaytag-inside-a-portlet/#comments</comments>
		<pubDate>Sun, 14 Dec 2008 17:38:29 +0000</pubDate>
		<dc:creator>Dominik</dc:creator>
				<category><![CDATA[Sofware]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Portlet]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Struts2]]></category>

		<guid isPermaLink="false">http://processworks.wordpress.com/?p=18</guid>
		<description><![CDATA[This article describes an easy workaround to get the export function of Displaytag working inside a portlet.
Environment: Displaytag 1.1.1, Liferay 5.1.2, Struts2 2.1.3-SNAPSHOT]]></description>
			<content:encoded><![CDATA[<p><span style="text-decoration:underline;">The Problem:</span><br />
When using Displaytag inside a Prortlet, the export functionality will not work because the portlet has no way to produce other than it&#8217;s portlet content for display (see <a href="http://jira.codehaus.org/browse/DISPL-344" target="_blank">http://jira.codehaus.org/browse/DISPL-344</a>).<br />
Since Displaytag export functionality produces downloadable content that the portlet container will interpret as a portlet render result, you will see the Displaytag output as HTML-rubbish.</p>
<p><span style="text-decoration:underline;">The Solution:</span><br />
When we came over this problem, a promising solution seemed to be the one described in this post:  <a href="http://www.jroller.com/hakan/entry/liferay_portal_4_1_2" target="_blank">http://www.jroller.com/hakan/entry/liferay_portal_4_1_2</a>,  but nobody was able to get it running.<br />
Based on the concept in this post I came up with the following simple idea: If the problem is, that the output is produced by something inside the portlet, than the solution is to produce the export result outside of the portlet. And it works.</p>
<p>It works like this:</p>
<ol>
<li>Disable the standard Displaytag export functionality</li>
<li>Create a copy of your page and place it somewhere outside the portlet</li>
<li>Add manually links to the copied page, providing the parameters required by Displaytag</li>
</ol>
<p>Let&#8217;s look at this in detail on a concrete example:</p>
<p><span id="more-18"></span></p>
<p>I have a page containing the Displaytag</p>
<pre>/WEB-INF
   /view
      /cercaaree.jsp<strong> </strong>(original)</pre>
<p>and create a copy of this under</p>
<pre>/export
  /cercaaree.jsp (copy)</pre>
<p>Essential is that /export is not inside WEB-INF, besides that, it could be placed anywhere.</p>
<p>Now I add manually the required export links below the display-tag in the original file, csv and excel in this case:</p>
<pre>...
&lt;/display:table&gt;
&lt;div class="exportlinks"&gt;Export:
    &lt;a href="&lt;%=currentPagePath%&gt;?d-16544-e=1&amp;d-49243-e=1&amp;6578706f7274=1"&gt;
              &lt;span class="export csv"&gt; CSV &lt;/span&gt;
    &lt;/a&gt;
    |
    &lt;a href="&lt;%=currentPagePath%&gt;?d-16544-e=2&amp;d-49243-e=2&amp;6578706f7274=1"&gt;
        &lt;span class="export excel"&gt; Excel &lt;/span&gt;
    &lt;/a&gt;
&lt;/div&gt;</pre>
<p>Where currentPagePath is defined to point to the copy of the page, in this case.:</p>
<pre>&lt;%</pre>
<pre>   String currentPagePath =  "http://" + request.getServerName() + ":"
       + request.getServerPort()
       + request.getContextPath()
       + "/export/cercaaree.jsp";
%&gt;</pre>
<p>Note that  the constructed absolute path &#8220;/export&#8221;  <span style="text-decoration:underline;">is not </span>below &#8220;/WEB-INF&#8221;.</p>
<p>You must include all the displaytag parameters as shown, the number given to in the d-16544-e parameter determines the result type (1=CSV, 2=EXCEL &#8230;).</p>
<p>The copied cercaaree.jsp lays outside our Struts2 web application, so there will be no Struts2 support. That&#8217;s fine for the export, but we need a way to access the data to export. We do this through the HttpSession which is easily accessible from Struts2 and plain jsp.</p>
<p>The original jsp gets the the data to display from the session:</p>
<pre>&lt;%
  List areeProduttive = (List) PortletActionContext.getRequest().getPortletSession().getAttribute("areeProduttive");
  request.setAttribute("areaList", areeProduttive);
%&gt;
&lt;display:table name="areaList" pagesize="8" id="area" export="false"&gt;
...</pre>
<p>In the copy, this fails since we are outside the portlet code and there are no Portlet Resources available. What we can do instead is to look in the standard HTTPSession of the jsp page for the data (&#8221;areaList&#8221;). The Session is the same as the one underlying the portlet functionality, but the portlet data is &#8216;encoded&#8217;. In Liferay Portal, the key will be something like:</p>
<pre>javax.portlet.p.AreeIndustrialiPortlet_WAR_conextname_LAYOUT_11901?areeProduttuve</pre>
<p>I access this simply searching the session data:</p>
<pre>&lt;%
// reload the data from the session
List&lt;AreaProduttiva&gt;  areeProduttive = null;
Enumeration names =  session.getAttributeNames();
while (names.hasMoreElements()) {
   String name = (String) names.nextElement();
  if (name.contains("areeProduttive")) {
    areeProduttive = (List&lt;AreaProduttiva&gt;) request.getSession().getAttribute(name);
    break;
  }
}
request.setAttribute("areaList", areeProduttive);
%&gt;</pre>
<p>This is, how we access the data for export. Note that this works with Liferay, but I have not tested how other portals encode portlet session data.</p>
<p>The copied page will produce the desired export output without doing any rendering. Having to copy the page might be a drawback, but it has also the nice side effect that you can change the columns included in the export.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.processworks.de/blog/2008/12/export-from-displaytag-inside-a-portlet/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
