<?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>Undocumented Matlab &#187; Java</title> <atom:link href="http://undocumentedmatlab.com/blog/category/java/feed/" rel="self" type="application/rss+xml" /><link>http://undocumentedmatlab.com</link> <description>Charting Matlab's unsupported hidden underbelly</description> <lastBuildDate>Thu, 17 May 2012 12:01:26 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.1.1</generator> <item><title>Customizing menu items part 3</title><link>http://undocumentedmatlab.com/blog/customizing-menu-items-part-3/</link> <comments>http://undocumentedmatlab.com/blog/customizing-menu-items-part-3/#comments</comments> <pubDate>Wed, 09 May 2012 18:00:05 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[GUI]]></category> <category><![CDATA[Icons]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[Medium risk of breaking in future versions]]></category> <category><![CDATA[Undocumented feature]]></category> <category><![CDATA[JavaFrame]]></category> <category><![CDATA[Menubar]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2909</guid> <description><![CDATA[Matlab menu items can easily display custom icons, using just a tiny bit of Java magic powder.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/customizing-menu-items-part-2/' rel='bookmark' title='Customizing menu items part 2'>Customizing menu items part 2</a> <small>Matlab menu items can be customized in a variety of useful ways using their underlying Java object. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-menu-items-part-1/' rel='bookmark' title='Customizing menu items part 1'>Customizing menu items part 1</a> <small>Matlab menus can be customized in a variety of undocumented manners - first article of a series. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-uitree-nodes/' rel='bookmark' title='Customizing uitree nodes &#8211; part 1'>Customizing uitree nodes &#8211; part 1</a> <small>This article describes how to customize specific nodes of Matlab GUI tree controls created using the undocumented uitree function...</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-uitree-nodes-2/' rel='bookmark' title='Customizing uitree nodes &#8211; part 2'>Customizing uitree nodes &#8211; part 2</a> <small>This article shows how Matlab GUI tree nodes can be customized with checkboxes and similar controls...</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>In the past weeks I&#8217;ve shown how Matlab menus can be customized in a variety of undocumented manners, using HTML, <a
target="_blank" href="http://undocumentedmatlab.com/blog/customizing-menu-items-part-1/">pure Matlab</a>, and <a
target="_blank" href="http://undocumentedmatlab.com/blog/customizing-menu-items-part-2/">Java</a>. Today I conclude this mini-series with an article that explains how to use the underlying Java object to customize menu item icons. Menu customizations are explored in depth in section 4.6 of my <a
target="_blank" href="http://undocumentedmatlab.com/matlab-java-book/">book</a>.</p><h3 id="underlying">A reminder: accessing the underlying Java object</h3><p>Matlab menus (<i><b>uimenu</b></i>) are basically simple wrappers for the much more powerful and flexible Java Swing <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/uiswing/components/menu.html"><code>JMenu</code> and <code>JMenuItem</code></a> on which they are based.  Many important functionalities that are available in Java menus are missing from the Matlab <i><b>uimenu</b></i>s.</p><p>Getting the Java reference for the figure window&#8217;s main menu is very easy:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">jFrame = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>handle<span style="color: #080;">&#40;</span>hFig<span style="color: #080;">&#41;</span>,<span style="color:#A020F0;">'JavaFrame'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">try</span>
    <span style="color: #228B22;">% R2008a and later</span>
    jMenuBar = jFrame.<span style="">fHG1Client</span>.<span style="">getMenuBar</span>;
<span style="color: #0000FF;">catch</span>
    <span style="color: #228B22;">% R2007b and earlier</span>
    jMenuBar = jFrame.<span style="">fFigureClient</span>.<span style="">getMenuBar</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p>There are many customizations that can only be done using the Java handle: setting icons, several dozen callback types, tooltips, background color, font, text alignment, and so on. etc. Interested readers may wish to <i><b>get</b></i>/<i><b>set</b></i>/<i><b>inspect</b></i>/<i><b>methodsview</b></i>/<i><b><a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/17935-uiinspect-display-methods-properties-callbacks-of-an-object">uiinspect</a></b></i> the <code>jSave</code> reference handle and/or to read the documentation for <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/6/docs/api/javax/swing/JMenuItem.html"><code>JMenuItem</code></a>. Today&#8217;s article will focus on icon customizations.</p><h3 id="simple">Setting simple menu item icons</h3><p>Many of Matlab&#8217;s icons reside in either the <i>[matlabroot '/toolbox/matlab/icons/']</i> folder or the <i>[matlabroot '/java/jar/mwt.jar']</i> file (a JAR file is simply a zip file that includes Java classes and resources such as icon images). Let us create icons from the latter, to keep a consistent look-and-feel with the rest of Matlab (we could just as easily use our own external icon files):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% External icon file example</span>
jSave.<span style="">setIcon</span><span style="color: #080;">&#40;</span>javax.<span style="">swing</span>.<span style="">ImageIcon</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'C:\Yair\save.gif'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% JAR resource example</span>
jarFile = <span style="color: #0000FF;">fullfile</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">matlabroot</span>,<span style="color:#A020F0;">'/java/jar/mwt.jar'</span><span style="color: #080;">&#41;</span>;
iconsFolder = <span style="color:#A020F0;">'/com/mathworks/mwt/resources/'</span>;
iconURI = <span style="color: #080;">&#91;</span><span style="color:#A020F0;">'jar:file:/'</span> jarFile <span style="color:#A020F0;">'!'</span> iconsFolder <span style="color:#A020F0;">'save.gif'</span><span style="color: #080;">&#93;</span>;
iconURI = java.<span style="">net</span>.<span style="">URL</span><span style="color: #080;">&#40;</span>iconURI<span style="color: #080;">&#41;</span>;  <span style="color: #228B22;">% not necessary for external files</span>
jSave.<span style="">setIcon</span><span style="color: #080;">&#40;</span>javax.<span style="">swing</span>.<span style="">ImageIcon</span><span style="color: #080;">&#40;</span>iconURI<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>Note that setting a menu item&#8217;s icon automatically re-aligns all other items in the menu, including those that do not have an icon (an internal bug that was introduced in R2010a causes a misalignment, as shown below):</p><p><center><div
class="wp-caption aligncenter" style="width: 240px"><img
alt="Menu item with a custom Icon (R2009b)" src="http://UndocumentedMatlab.com/images/uimenu3.png" title="Menu item with a custom Icon (R2009b)" width="230" height="120"/><p
class="wp-caption-text">Menu item with a custom <b>Icon</b> (R2009b)</p></div> &nbsp;&nbsp;&nbsp;<div
class="wp-caption aligncenter" style="width: 237px"><img
alt="...and the same in R2010a onward" src="http://UndocumentedMatlab.com/images/uimenu3b.png" title="...and the same in R2010a onward" width="227" height="120"/><p
class="wp-caption-text">...and the same in R2010a onward</p></div></center></p><h3 id="checkmark">Checkmark icon</h3><p>The empty space on the left of the menu is reserved for the check mark. Each Matlab menu item is check-able, since it is an object that extends the <code>com.mathworks.mwswing.MJCheckBoxMenuItem</code> class. I have not found a way to eliminate this empty space, which is really unnecessary in the File-menu case (it is only actually necessary in the View and Tools menus). Note that if an icon is set for the item, both the icon and the checkmark will be displayed, side by side.</p><p>The check mark is controlled by the <b>State</b> property of the Java object (which accepts logical true/false values), or the <b>Checked</b> property of the Matlab handle (which accepts the regular &#8216;on&#8217;/'off&#8217; string values):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Set the check mark at the Matlab level</span>
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>findall<span style="color: #080;">&#40;</span>hFig,<span style="color:#A020F0;">'tag'</span>,<span style="color:#A020F0;">'figMenuFileSave'</span><span style="color: #080;">&#41;</span>, <span style="color:#A020F0;">'Checked'</span>,<span style="color:#A020F0;">'on'</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Equivalent - set the checkmark at the Java level</span>
jSave.<span style="">setState</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">true</span><span style="color: #080;">&#41;</span>;</pre></div></div><p><center><div
class="wp-caption aligncenter" style="width: 195px"><img
alt="State = true, Icon = [ ]" src="http://UndocumentedMatlab.com/images/uimenu_save_checked1.png" title="State = true, Icon = [ ]" width="185" height="138"/><p
class="wp-caption-text"><b>State</b> = true, <b>Icon</b> = &#91; &#93;</p></div> &nbsp;&nbsp;&nbsp;<div
class="wp-caption aligncenter" style="width: 215px"><img
alt="State = true, Icon = custom" src="http://UndocumentedMatlab.com/images/uimenu_save_checked2.png" title="State = true, Icon = custom" width="205" height="137"/><p
class="wp-caption-text"><b>State</b> = true, <b>Icon</b> = custom</p></div></center></p><h3 id="custom">Customizing menu icons</h3><p>Icons can be customized: modify the gap between the icon and the label with the <b>IconTextGap</b> property (default = 4 [pixels]); place icons to the right of the label by setting <b>HorizontalTextPosition</b> to <code>jSave.LEFT</code> (=2), or centered using <code>jSave.CENTER</code> (=0). Note that the above-mentioned misalignment bug does not appear in these cases:</p><p><center><div
class="wp-caption aligncenter" style="width: 232px"><img
alt="jSave.setHorizontalTextPosition(jSave.LEFT)" src="http://UndocumentedMatlab.com/images/uimenu4.png" title="jSave.setHorizontalTextPosition(jSave.LEFT)" width="222" height="121"/><p
class="wp-caption-text"><code>jSave.setHorizontalTextPosition<br
/>(jSave.LEFT)</code></p></div> &nbsp;&nbsp;&nbsp;<div
class="wp-caption aligncenter" style="width: 233px"><img
alt="jSave.setHorizontalTextPosition(jSave.CENTER)" src="http://UndocumentedMatlab.com/images/uimenu5.png" title="jSave.setHorizontalTextPosition(jSave.CENTER)" width="223" height="120"/><p
class="wp-caption-text"><code>jSave.setHorizontalTextPosition<br
/>(jSave.CENTER)</code></p></div></center></p><p>Note how the label text can be seen through (or on top of) the icon when it is centered. This feature can be used to create stunning menu effects as shown below. Note how the width and height of the menu item automatically increased to accommodate my new 77&#215;31 icon size (icons are normally sized 16&#215;16 pixels):</p><p><center><div
class="wp-caption aligncenter" style="width: 295px"><img
alt="Overlaid icon (HorizontalTextPosition = CENTER)" src="http://UndocumentedMatlab.com/images/uimenu6.png" title="Overlaid icon (HorizontalTextPosition = CENTER)" width="285" height="136"/><p
class="wp-caption-text">Overlaid icon (<b>HorizontalTextPosition</b> = CENTER)</p></div></center></p><p>To resize an icon programmatically before setting it in a Java component, we can use the following example:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">myIcon = <span style="color: #0000FF;">fullfile</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">matlabroot</span>,<span style="color:#A020F0;">'/toolbox/matlab/icons/matlabicon.gif'</span><span style="color: #080;">&#41;</span>;
imageToolkit = java.<span style="">awt</span>.<span style="">Toolkit</span>.<span style="">getDefaultToolkit</span>;
iconImage = imageToolkit.<span style="">createImage</span><span style="color: #080;">&#40;</span>myIcon<span style="color: #080;">&#41;</span>;
iconImage = iconImage.<span style="">getScaledInstance</span><span style="color: #080;">&#40;</span><span style="color: #33f;">32</span>,<span style="color: #33f;">32</span>,iconImage.<span style="">SCALE_SMOOTH</span><span style="color: #080;">&#41;</span>;
jSave.<span style="">setIcon</span><span style="color: #080;">&#40;</span>javax.<span style="">swing</span>.<span style="">ImageIcon</span><span style="color: #080;">&#40;</span>iconImage<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>Remember when rescaling images, particularly small ones with few pixels, that it is always better to shrink than to enlarge images: enlarging a small icon image might introduce a significant pixelization effect:</p><p><center><div
class="wp-caption aligncenter" style="width: 100px"><img
alt="16x16 icon image resized to 32x32" src="http://UndocumentedMatlab.com/images/button_icon2.png" title="16x16 icon image resized to 32x32" width="90" height="90"/><p
class="wp-caption-text">16x16 icon image resized to 32x32</p></div></center></p><p>Separate icons can be specified for a different appearance during mouse hover (<b>RolloverIcon</b>; requires <b>RolloverEnabled</b>=1), item click/press (<b>PressedIcon</b>), item selection (<b>SelectedIcon</b>, <b>RolloverSelectedIcon</b>, <b>DisabledSelectedIcon</b>), and disabled menu item (<b>DisabledIcon</b>). All these properties are empty ([]) by default, which applies a predefined default variation (image color filter) to the main item&#8217;s Icon. For example, let us modify <b>DisabledIcon</b>:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">myIcon = <span style="color:#A020F0;">'C:\Yair\Undocumented Matlab\Images\save_disabled.gif'</span>;
jSaveAs.<span style="">setDisabledIcon</span><span style="color: #080;">&#40;</span>javax.<span style="">swing</span>.<span style="">ImageIcon</span><span style="color: #080;">&#40;</span>myIcon<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
jSaveAs.<span style="">setEnabled</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">false</span><span style="color: #080;">&#41;</span>;</pre></div></div><p><center><div
class="wp-caption aligncenter" style="width: 130px"><img
alt="Enabled, main Icon" src="http://UndocumentedMatlab.com/images/uimenu7a.png" title="Enabled, main Icon" width="120" height="135"/><p
class="wp-caption-text">Enabled, main <b>Icon</b></p></div> &nbsp;&nbsp;&nbsp;<div
class="wp-caption aligncenter" style="width: 170px"><img
alt="Disabled, default Icon variation" src="http://UndocumentedMatlab.com/images/uimenu7b.png" title="Disabled, default Icon variation" width="120" height="135"/><p
class="wp-caption-text">Disabled, default <b>Icon</b> variation</p></div> &nbsp;&nbsp;&nbsp;<div
class="wp-caption aligncenter" style="width: 180px"><img
alt="Disabled, custom DisabledIcon" src="http://UndocumentedMatlab.com/images/uimenu7c.png" title="Disabled, custom DisabledIcon" width="120" height="135"/><p
class="wp-caption-text">Disabled, custom <b>DisabledIcon</b></p></div></center></p><p>Note the automatic graying of disabled menu items, including their icon. This effect can also be achieved programmatically using the static methods in <code>com.mathworks.mwswing.IconUtils</code>: <i>changeIconColor(), createBadgedIcon(), createGhostedIcon()</i>, and <i>createSelectedIcon()</i>. When we use a non-default custom <b>DisabledIcon</b>, it is used instead of the gray icon variant.</p><p>This concludes my mini-series of customizing menus in Matlab. If you have used any nifty customization that I have not mentioned, please post a comment about it <a
href="http://undocumentedmatlab.com/blog/customizing-menu-items-part-3/#respond">below</a>.</p><p><span
class="alignleft"><img
alt="Ken &#038; Mike" src="http://UndocumentedMatlab.com/images/ken_and_mike.png" title="Ken &#038; Mike" width="98" height="83"/></span>In an unrelated note, I would like to extend good wishes to Mike Katz, who has left the MathWorks mobile development team to join Kinvey a few days ago. Mike has been with MathWorks since 2005 and has been responsible for maintaining the official <a
target="_blank" rel="nofollow" href="http://blogs.mathworks.com/desktop/">MATLAB Desktop blog</a>, together with <a
target="_blank" href="http://undocumentedmatlab.com/blog/gui-integrated-browser-control/">Ken Orr</a>. I&#8217;m not sure yet which direction the Desktop blog will take, and by whom, but in any case it won&#8217;t be the same. You&#8217;re both missed, Mike &#038; Ken!</p><p
/>&nbsp;</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/customizing-menu-items-part-2/' rel='bookmark' title='Customizing menu items part 2'>Customizing menu items part 2</a> <small>Matlab menu items can be customized in a variety of useful ways using their underlying Java object. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-menu-items-part-1/' rel='bookmark' title='Customizing menu items part 1'>Customizing menu items part 1</a> <small>Matlab menus can be customized in a variety of undocumented manners - first article of a series. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-uitree-nodes/' rel='bookmark' title='Customizing uitree nodes &#8211; part 1'>Customizing uitree nodes &#8211; part 1</a> <small>This article describes how to customize specific nodes of Matlab GUI tree controls created using the undocumented uitree function...</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-uitree-nodes-2/' rel='bookmark' title='Customizing uitree nodes &#8211; part 2'>Customizing uitree nodes &#8211; part 2</a> <small>This article shows how Matlab GUI tree nodes can be customized with checkboxes and similar controls...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/customizing-menu-items-part-3/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Customizing menu items part 2</title><link>http://undocumentedmatlab.com/blog/customizing-menu-items-part-2/</link> <comments>http://undocumentedmatlab.com/blog/customizing-menu-items-part-2/#comments</comments> <pubDate>Wed, 02 May 2012 11:57:38 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[GUI]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[Medium risk of breaking in future versions]]></category> <category><![CDATA[Undocumented feature]]></category> <category><![CDATA[Callbacks]]></category> <category><![CDATA[JavaFrame]]></category> <category><![CDATA[Menubar]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2902</guid> <description><![CDATA[Matlab menu items can be customized in a variety of useful ways using their underlying Java object.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/customizing-menu-items-part-3/' rel='bookmark' title='Customizing menu items part 3'>Customizing menu items part 3</a> <small>Matlab menu items can easily display custom icons, using just a tiny bit of Java magic powder. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-menu-items-part-1/' rel='bookmark' title='Customizing menu items part 1'>Customizing menu items part 1</a> <small>Matlab menus can be customized in a variety of undocumented manners - first article of a series. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-workspace-context-menu/' rel='bookmark' title='Customizing Workspace context-menu'>Customizing Workspace context-menu</a> <small>Matlab's Workspace table context-menu can be configured with user-defined actions - this article explains how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-uitree-nodes/' rel='bookmark' title='Customizing uitree nodes &#8211; part 1'>Customizing uitree nodes &#8211; part 1</a> <small>This article describes how to customize specific nodes of Matlab GUI tree controls created using the undocumented uitree function...</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>Last week I <a
target="_blank" href="http://undocumentedmatlab.com/blog/customizing-menu-items-part-1/">explained</a> how to customize Matlab&#8217;s menu items using some undocumented tricks that do not need Java. Today I will show how using just a tiny bit of Java magic powder we can add much more complex customizations to menu items. Menu customizations are explored in depth in section 4.6 of my <a
target="_blank" href="http://undocumentedmatlab.com/matlab-java-book/">book</a>.</p><h3 id="underlying">Accessing the underlying Java object</h3><p>Matlab menus (<i><b>uimenu</b></i>) are basically simple wrappers for the much more powerful and flexible Java Swing <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/uiswing/components/menu.html"><code>JMenu</code> and <code>JMenuItem</code></a> on which they are based.  Many important functionalities that are available in Java menus are missing from the Matlab <i><b>uimenu</b></i>s.</p><p>Getting the Java reference for the figure window&#8217;s main menu is very easy:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">jFrame = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>handle<span style="color: #080;">&#40;</span>hFig<span style="color: #080;">&#41;</span>,<span style="color:#A020F0;">'JavaFrame'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">try</span>
    <span style="color: #228B22;">% R2008a and later</span>
    jMenuBar = jFrame.<span style="">fHG1Client</span>.<span style="">getMenuBar</span>;
<span style="color: #0000FF;">catch</span>
    <span style="color: #228B22;">% R2007b and earlier</span>
    jMenuBar = jFrame.<span style="">fFigureClient</span>.<span style="">getMenuBar</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p>Note that we have used the figure handle&#8217;s hidden <a
target="_blank" href="http://undocumentedmatlab.com/blog/minimize-maximize-figure-window/#JavaFrame"><b>JavaFrame</b> property</a>, accessed through the reference&#8217;s <i><b>handle</b></i>() wrapper, to prevent an annoying warning message.</p><p>There are many customizations that can only be done using the Java handle: setting icons, several dozen callback types, tooltips, background color, font, text alignment, and so on. etc. Interested readers may wish to <i><b>get</b></i>/<i><b>set</b></i>/<i><b>inspect</b></i>/<i><b>methodsview</b></i>/<i><b><a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/17935-uiinspect-display-methods-properties-callbacks-of-an-object">uiinspect</a></b></i> the <code>jSave</code> reference handle and/or to read the documentation for <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/6/docs/api/javax/swing/JMenuItem.html"><code>JMenuItem</code></a>. Some useful examples are provided below.</p><h3 id="dynamic">Dynamic menu behavior</h3><p>As a first example of Java-based customization, let us add DHTML-like behavior to the menu, such that the menu items will automatically be displayed when the mouse hovers over the item, without waiting for a user mouse click. First, get the <code>jMenuBar</code> reference as described above. Now, set the <b>MouseEnteredCallback</b> to automatically simulate a user mouse click on each menu item using its <i>doClick()</i> method. Setting the callback should be done separately to each of the top-level menu components:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">for</span> menuIdx = <span style="color: #33f;">1</span> <span style="color: #F0F;">:</span> jMenuBar.<span style="">getComponentCount</span>
    jMenu = jMenuBar.<span style="">getComponent</span><span style="color: #080;">&#40;</span>menuIdx-<span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>;
    hjMenu = handle<span style="color: #080;">&#40;</span>jMenu,<span style="color:#A020F0;">'CallbackProperties'</span><span style="color: #080;">&#41;</span>;
    <span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>hjMenu,<span style="color:#A020F0;">'MouseEnteredCallback'</span>,<span style="color:#A020F0;">'doClick(gcbo)'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p>Note that using this mechanism may be awkward if the top-level menu does not have a sub-menu but is rather a stand-alone menu item. For example, if the top-level menu-item &#8220;Help&#8221; is a stand-alone menu button (i.e., there are no help menu-items, just the single Help item), then moving the mouse over this item will trigger the help event, although the user did not actually click on the item. To prevent this behavior, we should modify the code snippet above to only work on those menu items that have sub-items.</p><h3 id="accelerator">Custom accelerator shortcut keys</h3><p>As another example, Matlab automatically assigns a non-modifiable keyboard accelerator key modifier of <ctrl>, while JMenus allow any combination of Alt/Ctrl/Shift/Meta (depending on the platform). Let us modify the default File/Save accelerator key from &#8216;Ctrl-S&#8217; to &#8216;Alt-Shift-S&#8217; as an example. We need a reference for the &#8220;Save&#8221; menu item. Note that unlike regular Java components, menu items are retrieved using the <i>getMenuComponent()</i> method and not <i>getComponent()</i>:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% File main menu is the first main menu item =&gt; index=0</span>
jFileMenu = jMenuBar.<span style="">getComponent</span><span style="color: #080;">&#40;</span><span style="color: #33f;">0</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Save menu item is the 5th menu item (separators included)</span>
jSave = jFileMenu.<span style="">getMenuComponent</span><span style="color: #080;">&#40;</span><span style="color: #33f;">4</span><span style="color: #080;">&#41;</span>; <span style="color: #228B22;">%Java indexes start with 0!</span>
inspect<span style="color: #080;">&#40;</span>jSave<span style="color: #080;">&#41;</span> 	<span style="color: #228B22;">% just to be sure: label='Save' =&gt; good!</span>
&nbsp;
<span style="color: #228B22;">% Finally, set a new accelerator key for this menu item:</span>
jAccelerator = javax.<span style="">swing</span>.<span style="">KeyStroke</span>.<span style="">getKeyStroke</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'alt shift S'</span><span style="color: #080;">&#41;</span>;
jSave.<span style="">setAccelerator</span><span style="color: #080;">&#40;</span>jAccelerator<span style="color: #080;">&#41;</span>;</pre></div></div><p>That is all there is to it – the label is modified automatically to reflect the new keyboard accelerator key. More info on setting different combinations of accelerator keys and modifiers can be found in the official Java documentation for <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/6/docs/api/javax/swing/KeyStroke.html#getKeyStroke%28java.lang.String%29"><code>KeyStroke</code></a>.</p><p><center><div
class="wp-caption aligncenter" style="width: 212px"><img
alt="Modification of menu item accelerator and tooltip" src="http://UndocumentedMatlab.com/images/uimenu1.png" title="Modification of menu item accelerator and tooltip" width="202" height="200"/><p
class="wp-caption-text">Modification of menu item accelerator and tooltip</p></div></center></p><p>Note that the Save menu-item reference can only be retrieved after opening the File menu at least once earlier; otherwise, an exception will be thrown when trying to access the menu item. The File menu does NOT need to remain open – it only needs to have been opened sometime earlier, for its menu items to be rendered. This can be done either interactively (by selecting the File menu) or programmatically:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Simulate mouse clicks to force the File main-menu to open &amp; close</span>
jFileMenu.<span style="">doClick</span>; <span style="color: #228B22;">% open the File menu</span>
jFileMenu.<span style="">doClick</span>; <span style="color: #228B22;">% close the menu</span>
&nbsp;
<span style="color: #228B22;">% Now the Save menu is accessible:</span>
jSave = jFileMenu.<span style="">getMenuComponent</span><span style="color: #080;">&#40;</span><span style="color: #33f;">4</span><span style="color: #080;">&#41;</span>;</pre></div></div><h3 id="tooltip">Tooltip and highlight</h3><p>For some unknown reason, MathWorks did not include a tooltip property in its Matlab menu handle, contrary to all the other Matlab GUI components. So we must use the Java handle, specifically the <b>ToolTipText</b> property:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">jSave.<span style="">setToolTipText</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'modified menu item with tooltip'</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>Java menu items also contain a property called <b>Armed</b>, which is a logical value (default=false). When turned on, the menu item is highlighted just as when it is selected (see the <i>Save As&#8230;</i> menu item in the screenshot above). On a Windows system, this means a blue background:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">jSave.<span style="">setArmed</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">true</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>When the item is actually selected and then de-selected, <b>Armed</b> reverts to a false (off) value. Alternating the <b>Armed</b> property value can achieve an effect of flashing the menu item.</p><h3 id="callbacks">Callbacks</h3><p>In addition to the standard Swing control callbacks discussed in an <a
target="_blank" href="http://undocumentedmatlab.com/blog/uicontrol-callbacks/">earlier article</a>, menu items possess several additional callbacks that are specific to menu items, including:</p><ul><li><b>ActionPerformedCallback</b> – fired when the menu item is invoked</li><li><b>StateChangedCallback</b> – fired when the menu item is selected or deselected</li><li><b>MenuDragMouseXXXCallback</b> (XXX=Dragged/Entered/Exited/Released) – fired when the menu item is dragged, for the corresponding event</li><li><b>MenuKeyXXXCallback</b> (XXX=Pressed/Released/Typed) – fired when a keyboard click event occurs (the menu item&#8217;s accelerator was typed)</li></ul><p>Using these callbacks, together with the 30-odd standard Swing callbacks, we can control our menu&#8217;s behavior to a much higher degree than possible using the standard Matlab handle.</p><p>Next week, I will conclude this mini-series with an article explaining how to customize menu item icons.</ctrl></p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/customizing-menu-items-part-3/' rel='bookmark' title='Customizing menu items part 3'>Customizing menu items part 3</a> <small>Matlab menu items can easily display custom icons, using just a tiny bit of Java magic powder. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-menu-items-part-1/' rel='bookmark' title='Customizing menu items part 1'>Customizing menu items part 1</a> <small>Matlab menus can be customized in a variety of undocumented manners - first article of a series. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-workspace-context-menu/' rel='bookmark' title='Customizing Workspace context-menu'>Customizing Workspace context-menu</a> <small>Matlab's Workspace table context-menu can be configured with user-defined actions - this article explains how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-uitree-nodes/' rel='bookmark' title='Customizing uitree nodes &#8211; part 1'>Customizing uitree nodes &#8211; part 1</a> <small>This article describes how to customize specific nodes of Matlab GUI tree controls created using the undocumented uitree function...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/customizing-menu-items-part-2/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Extending a Java class with UDD</title><link>http://undocumentedmatlab.com/blog/extending-a-java-class-with-udd/</link> <comments>http://undocumentedmatlab.com/blog/extending-a-java-class-with-udd/#comments</comments> <pubDate>Thu, 29 Mar 2012 14:32:46 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Guest bloggers]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[Medium risk of breaking in future versions]]></category> <category><![CDATA[Undocumented feature]]></category> <category><![CDATA[Donn Shull]]></category> <category><![CDATA[schema]]></category> <category><![CDATA[schema.class]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2824</guid> <description><![CDATA[Java classes can easily be extended in Matlab, using pure Matlab code.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/creating-a-simple-udd-class/' rel='bookmark' title='Creating a simple UDD class'>Creating a simple UDD class</a> <small>This article explains how to create and test custom UDD packages, classes and objects...</small></li><li><a
href='http://undocumentedmatlab.com/blog/udd-and-java/' rel='bookmark' title='UDD and Java'>UDD and Java</a> <small>UDD provides built-in convenience methods to facilitate the integration of Matlab UDD objects with Java code - this article explains how...</small></li><li><a
href='http://undocumentedmatlab.com/blog/jmi-java-to-matlab-interface/' rel='bookmark' title='JMI &#8211; Java-to-Matlab Interface'>JMI &#8211; Java-to-Matlab Interface</a> <small>JMI enables calling Matlab functions from within Java. This article explains JMI's core functionality....</small></li><li><a
href='http://undocumentedmatlab.com/blog/fixing-a-java-focus-problem/' rel='bookmark' title='Fixing a Java focus problem'>Fixing a Java focus problem</a> <small>Java components added to Matlab GUIs do not participate in the standard focus cycle - this article explains how to fix this problem....</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p><i>Once again I welcome Donn Shull, with another article about Matlab&#8217;s internal UDD mechanism</i></p><h3 id="Introduction">Extending a Java class with UDD</h3><p>During the <a
target="_blank" href="http://undocumentedmatlab.com/?s=UDD">series on UDD</a>, we have mentioned the connection between UDD and Java. In <a
target="_blank" href="http://undocumentedmatlab.com/blog/udd-events-and-listeners/">UDD Events and Listeners</a> we described how in Matlab, each Java object can have a UDD companion. In <a
target="_blank" href="http://undocumentedmatlab.com/blog/hierarchical-systems-with-udd/">Hierarchical Systems with UDD</a> we briefly noted that a UDD hierarchy may be passed to Java. In the numerous posts on handle graphics and callbacks, Yair has discussed the UDD packages <code>javahandle</code> and <code>javahandle_withcallbacks</code>. Based on this information, it seems reasonable to speculate that it may be possible to extend a Java class with UDD using UDD&#8217;s class inheritance mechanism.</p><p>This can be extremely useful in two cases:</p><ul><li>You don&#8217;t know Java but found a Java class you would like to use in Matlab, it just needs minor modifications for your specific needs</li><li>You do know Java, but don&#8217;t have access to the original source code, and choose to extend the Java class with Matlab code, rather than Java code</li></ul><p>Today I will show how this can be done using a simple example. Our example will illustrate the following things:</p><ol><li>Subclassing a Java class with UDD</li><li>Adding UDD properties to the to the subclass</li><li>Overloading a Java method with Matlab code</li><li>Directly accessing the superclass methods</li></ol><p>The example will show extending Java socket classes to provide a simple method for communication between two Matlab sessions. The protocol has been kept purposely simple and is not robust. Additional work would need to be done to create a real-life socket-based communication between Matlab systems (see for example <a
rel="nofollow" target="_blank" href="http://www.mathworks.com/matlabcentral/fileexchange/24524-tcpip-communications-in-matlab">this</a> FEX submission).</p><p>Today&#8217;s example consists of two subclasses: a subclass of <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/6/docs/api/java/net/ServerSocket.html"><code>java.net.ServerSocket</code></a> and a subclass of <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/6/docs/api/java/net/Socket.html"><code>java.net.Socket</code></a>. The protocol will be sending strings back and forth between the two sessions. In each direction the information exchange will consist of two bytes containing the string length, followed by the actual string. The entire source code can be downloaded <a
target="_blank" href="http://UndocumentedMatlab.com/files/simple2.zip">from here</a>.</p><h3 id="ServerSocket">Creating the simple.ServerSocket class</h3><p>As in the UDD series, we will use the simple package for our classes and in this package create a <code>ServerSocket</code> class and a <code>Socket</code> class. Recall the simple package definition class is placed in a file named <i>schema.m</i> in a directory called <i>@simple</i>, placed somewhere on the Matlab path. <i>schema.m</i> consists of:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> schema<span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>
<span style="color: #228B22;">%SCHEMA  simple package definition function.</span>
   schema.<span style="">package</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'simple'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p>In our <code>ServerSocket</code> class we will add three UDD properties and overload two of the Java class methods. It is worth noting that our final class will have all the parent Java classes public properties and methods and if necessary we can access the parent or super class methods directly. As before, we create a subfolder of the <i>@simple</i> folder named <i>@ServerSocket</i>; in this folder we place four files:</p><ol><li><i>schema.m</i> &#8211; the class definition file</li><li><i>ServerSocket.m</i> &#8211; the class constructor</li><li><i>accept.m</i> &#8211; one of the Java methods that we will overload</li><li><i>bind.m</i> &#8211; the other Java method that we will overload</li></ol><p>At the beginning of our <i>schema.m</i> file, we will use the following code to subclass the Java class:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> schema.<span style="">m</span>
<span style="color: #228B22;">%SCHEMA  simple.ServerSocket class definition function.</span>
&nbsp;
    <span style="color: #228B22;">% parent schema.class definition</span>
    javaPackage = findpackage<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'javahandle'</span><span style="color: #080;">&#41;</span>;
    javaClass = findclass<span style="color: #080;">&#40;</span>javaPackage, <span style="color:#A020F0;">'java.net.ServerSocket'</span><span style="color: #080;">&#41;</span>;
&nbsp;
    <span style="color: #228B22;">% class package (schema.package)</span>
    simplePackage = findpackage<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'simple'</span><span style="color: #080;">&#41;</span>;
&nbsp;
    <span style="color: #228B22;">% class definition</span>
    simpleClass = schema.<span style="color: #0000FF;">class</span><span style="color: #080;">&#40;</span>simplePackage, <span style="color:#A020F0;">'ServerSocket'</span>, javaClass<span style="color: #080;">&#41;</span>;</pre></div></div><p>Here, we use <i><b>findpackage</b></i> and <i><b>findclass</b></i> to obtain the <i><b>schema.class</b></i> for the Java class that we are going to use as our parent. We then obtain a handle to the containing package, and finally use the subclass variation to define our <code>ServerSocket</code> as a variation of the Java parent&#8217;s <i><b>schema.class</b></i>.</p><p>Next, in the class definition file we place the code to define the signatures for the methods we are overloading:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">    <span style="color: #228B22;">% accept.m overloads java accept method and adds communication protocol</span>
    m = schema.<span style="">method</span><span style="color: #080;">&#40;</span>simpleClass, <span style="color:#A020F0;">'accept'</span><span style="color: #080;">&#41;</span>;
    s = m.<span style="">Signature</span>;
    s.<span style="color: #0000FF;">varargin</span>    = <span style="color:#A020F0;">'off'</span>;
    s.<span style="">InputTypes</span>  = <span style="color: #080;">&#123;</span><span style="color:#A020F0;">'handle'</span><span style="color: #080;">&#125;</span>;
    s.<span style="">OutputTypes</span> = <span style="color: #080;">&#123;</span><span style="color:#A020F0;">'string'</span><span style="color: #080;">&#125;</span>;
&nbsp;
    <span style="color: #228B22;">% bind.m overloads java bind method</span>
    m = schema.<span style="">method</span><span style="color: #080;">&#40;</span>simpleClass, <span style="color:#A020F0;">'bind'</span><span style="color: #080;">&#41;</span>;
    s = m.<span style="">Signature</span>;
    s.<span style="color: #0000FF;">varargin</span>    = <span style="color:#A020F0;">'off'</span>;
    s.<span style="">InputTypes</span>  = <span style="color: #080;">&#123;</span><span style="color:#A020F0;">'handle'</span><span style="color: #080;">&#125;</span>;
    s.<span style="">OutputTypes</span> = <span style="color: #080;">&#123;</span><span style="color: #080;">&#125;</span>;be</pre></div></div><p>Finally, we add three UDD properties to the class: The first will be used to hold a string representation of the address of our <code>ServerSocket</code>; the second will store the communication port number; the third is a handle property that will hold the reference to the socket used by the actual communication.</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">    <span style="color: #228B22;">% holds remote address as a matlab string</span>
    p = schema.<span style="">prop</span><span style="color: #080;">&#40;</span>simpleClass, <span style="color:#A020F0;">'address'</span>, <span style="color:#A020F0;">'string'</span><span style="color: #080;">&#41;</span>;
    p.<span style="">FactoryValue</span> = <span style="color:#A020F0;">'localhost'</span>;
&nbsp;
    <span style="color: #228B22;">% holds remote port as a matlab int</span>
    p = schema.<span style="">prop</span><span style="color: #080;">&#40;</span>simpleClass, <span style="color:#A020F0;">'port'</span>, <span style="color:#A020F0;">'int16'</span><span style="color: #080;">&#41;</span>;
    p.<span style="">FactoryValue</span> = <span style="color: #33f;">2222</span>;
&nbsp;
    <span style="color: #228B22;">% holds a handle reference to the socket created in the accept method</span>
    p = schema.<span style="">prop</span><span style="color: #080;">&#40;</span>simpleClass, <span style="color:#A020F0;">'socket'</span>, <span style="color:#A020F0;">'handle'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p>We now need to write our overloaded methods. The <i>bind</i> method is simple: it first creates a Java internet address using the new address and port properties; then it uses the standard Java class methods to call the superclass&#8217;s <i>bind</i> method with the specified internet address:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> bind<span style="color: #080;">&#40;</span>this<span style="color: #080;">&#41;</span>
    <span style="color: #228B22;">% use the object socket and port port properties to bind this instance</span>
    <span style="color: #228B22;">% to a address calling the superclass bind method</span>
    inetAddress = java.<span style="">net</span>.<span style="">InetSocketAddress</span><span style="color: #080;">&#40;</span>this.<span style="">address</span>, this.<span style="">port</span><span style="color: #080;">&#41;</span>;
    this.<span style="">java</span>.<span style="">bind</span><span style="color: #080;">&#40;</span>inetAddress<span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p>The overloaded <i>accept</i> method is a bit more complicated and crude: It starts by calling the superclass <i>accept</i> method to create a communication socket and stores the created socket in our class&#8217;s socket property. Then it goes into an infinite loop of waiting for incoming commands, uses <i><b>evalc</b></i> to execute them, and returns the captured result to the caller. The only way out of this loop is using Ctrl-C from the keyboard.</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> accept<span style="color: #080;">&#40;</span>this<span style="color: #080;">&#41;</span>
&nbsp;
    <span style="color: #228B22;">% use the superclass accept</span>
    this.<span style="">socket</span> = handle<span style="color: #080;">&#40;</span>this.<span style="">java</span>.<span style="">accept</span><span style="color: #080;">&#41;</span>;
&nbsp;
    <span style="color: #228B22;">% infinate loop use ctrl-c to exit</span>
    <span style="color: #0000FF;">while</span> <span style="color: #33f;">1</span>
        <span style="color: #228B22;">% wait for a command then execute it capturing output</span>
        <span style="color: #0000FF;">while</span> this.<span style="">socket</span>.<span style="">getInputStream</span>.<span style="">available</span> &lt; <span style="color: #33f;">2</span>
        <span style="color: #0000FF;">end</span>
&nbsp;
        msb = this.<span style="">socket</span>.<span style="">getInputStream</span>.<span style="">read</span>;
        lsb = this.<span style="">socket</span>.<span style="">getInputStream</span>.<span style="">read</span>;
&nbsp;
        numChar = <span style="color: #33f;">256</span> * msb + lsb;
        cmd = <span style="color: #0000FF;">uint8</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">zeros</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1</span>, numChar<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
&nbsp;
        <span style="color: #0000FF;">for</span> index = <span style="color: #33f;">1</span><span style="color: #F0F;">:</span>numChar
            cmd<span style="color: #080;">&#40;</span>index<span style="color: #080;">&#41;</span> = this.<span style="">socket</span>.<span style="">getInputStream</span>.<span style="">read</span>;
        <span style="color: #0000FF;">end</span>
        result = <span style="color: #0000FF;">evalc</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span>cmd<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
&nbsp;
        <span style="color: #228B22;">% send the result back to the calling system</span>
        len = numel<span style="color: #080;">&#40;</span>result<span style="color: #080;">&#41;</span>;
        msb = <span style="color: #0000FF;">uint8</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">floor</span><span style="color: #080;">&#40;</span>len/<span style="color: #33f;">256</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
        lsb = <span style="color: #0000FF;">uint8</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">mod</span><span style="color: #080;">&#40;</span>len,<span style="color: #33f;">256</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
&nbsp;
        this.<span style="">socket</span>.<span style="">getOutputStream</span>.<span style="">write</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">uint8</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#91;</span>msb, lsb, result<span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
    <span style="color: #0000FF;">end</span>
<span style="color: #0000FF;">end</span></pre></div></div><h3 id="Socket">Creating the simple.Socket class</h3><p>The <code>simple.Socket</code> class is created like <code>ServerSocket</code>, this time in the <i>@Socket</i> folder under the <i>@simple</i> folder. In this subclass we add properties for the address and port, just as in <code></code><code>ServerSocket</code>. We overload the superclass&#8217;s <i>connect</i> method with our own variant, and add a new method to make the remote calls to the <code>ServerSocket</code> running in another Matlab instance. Beginning with the <i>schema.m</i> file we have:</p> </pre><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> schema
<span style="color: #228B22;">%SCHEMA  simple.Socket class definition function.</span>
&nbsp;
    <span style="color: #228B22;">% package definition</span>
    simplePackage = findpackage<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'simple'</span><span style="color: #080;">&#41;</span>;
    javaPackage = findpackage<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'javahandle'</span><span style="color: #080;">&#41;</span>;
    javaClass = findclass<span style="color: #080;">&#40;</span>javaPackage, <span style="color:#A020F0;">'java.net.Socket'</span><span style="color: #080;">&#41;</span>;
&nbsp;
    <span style="color: #228B22;">% class definition</span>
    simpleClass = schema.<span style="color: #0000FF;">class</span><span style="color: #080;">&#40;</span>simplePackage, <span style="color:#A020F0;">'Socket'</span>, javaClass<span style="color: #080;">&#41;</span>;
&nbsp;
    <span style="color: #228B22;">% define class methods</span>
    <span style="color: #228B22;">% connect.m overloads java connect method</span>
    m = schema.<span style="">method</span><span style="color: #080;">&#40;</span>simpleClass, <span style="color:#A020F0;">'connect'</span><span style="color: #080;">&#41;</span>;
    s = m.<span style="">Signature</span>;
    s.<span style="color: #0000FF;">varargin</span>    = <span style="color:#A020F0;">'off'</span>;
    s.<span style="">InputTypes</span>  = <span style="color: #080;">&#123;</span><span style="color:#A020F0;">'handle'</span><span style="color: #080;">&#125;</span>;
    s.<span style="">OutputTypes</span> = <span style="color: #080;">&#123;</span><span style="color: #080;">&#125;</span>;
&nbsp;
    <span style="color: #228B22;">% remoteEval.m matlab method for remote evaluation of Matlab commands</span>
    m = schema.<span style="">method</span><span style="color: #080;">&#40;</span>simpleClass, <span style="color:#A020F0;">'remoteEval'</span><span style="color: #080;">&#41;</span>;
    s = m.<span style="">Signature</span>;
    s.<span style="color: #0000FF;">varargin</span>    = <span style="color:#A020F0;">'off'</span>;
    s.<span style="">InputTypes</span>  = <span style="color: #080;">&#123;</span><span style="color:#A020F0;">'handle'</span>, <span style="color:#A020F0;">'string'</span><span style="color: #080;">&#125;</span>;
    s.<span style="">OutputTypes</span> = <span style="color: #080;">&#123;</span><span style="color:#A020F0;">'string'</span><span style="color: #080;">&#125;</span>;
&nbsp;
    <span style="color: #228B22;">% add properties to this class</span>
    <span style="color: #228B22;">% holds remote address as a Matlab string</span>
    p = schema.<span style="">prop</span><span style="color: #080;">&#40;</span>simpleClass, <span style="color:#A020F0;">'address'</span>, <span style="color:#A020F0;">'string'</span><span style="color: #080;">&#41;</span>;
    p.<span style="">FactoryValue</span> = <span style="color:#A020F0;">'localhost'</span>;
&nbsp;
    <span style="color: #228B22;">% holds remote port as a Matlab int</span>
    p = schema.<span style="">prop</span><span style="color: #080;">&#40;</span>simpleClass, <span style="color:#A020F0;">'port'</span>, <span style="color:#A020F0;">'int16'</span><span style="color: #080;">&#41;</span>;
    p.<span style="">FactoryValue</span> = <span style="color: #33f;">2222</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p>The class constructor <i>Socket.m</i> is simply:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> skt = Socket
<span style="color: #228B22;">%SOCKET constructor for the simple.Socket class</span>
    skt = simple.<span style="">Socket</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p>The overloaded <i>connect</i> method is almost identical to the overloaded bind method we used for <code>ServerSocket</code>. We form a Java internet address from our new properties and then invoke the superclass's <i>connect</i> Java method:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> connect<span style="color: #080;">&#40;</span>this<span style="color: #080;">&#41;</span>
<span style="color: #228B22;">%CONNECT overload of the java.net.Socket connect method</span>
    <span style="color: #228B22;">% use the object address and port properties to connect to the remote</span>
    <span style="color: #228B22;">% session via the superclass connect method</span>
    inetAddress = java.<span style="">net</span>.<span style="">InetSocketAddress</span><span style="color: #080;">&#40;</span>this.<span style="">address</span>, this.<span style="">port</span><span style="color: #080;">&#41;</span>;
    this.<span style="">java</span>.<span style="">connect</span><span style="color: #080;">&#40;</span>inetAddress<span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p>Finally, our <i>remoteEval</i> method is very similar to the loop portion of the overloaded accept method we wrote for <code>simple.ServerSocket</code>. We take the command string input and convert it into a series of bytes prepended by the length of the string, send it to the other Matlab session and wait for a response:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">function</span> result = remoteEval<span style="color: #080;">&#40;</span>this, cmd<span style="color: #080;">&#41;</span>
<span style="color: #228B22;">%REMOTEEVAL evaluate a Matlab command on a remotely connected Matlab</span>
&nbsp;
    <span style="color: #228B22;">% The command string is sent as a series of bytes preceded by a pair of</span>
    <span style="color: #228B22;">% bytes which represents the length of the string  </span>
    cmd = <span style="color: #0000FF;">uint8</span><span style="color: #080;">&#40;</span>cmd<span style="color: #080;">&#41;</span>;
&nbsp;
    len = numel<span style="color: #080;">&#40;</span>cmd<span style="color: #080;">&#41;</span>;
    msb = <span style="color: #0000FF;">uint8</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">floor</span><span style="color: #080;">&#40;</span>len/<span style="color: #33f;">256</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
    lsb = <span style="color: #0000FF;">uint8</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">mod</span><span style="color: #080;">&#40;</span>len,<span style="color: #33f;">256</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
&nbsp;
    this.<span style="">getOutputStream</span>.<span style="">write</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#91;</span>msb, lsb, cmd<span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>;
&nbsp;
    <span style="color: #228B22;">% We will expect the remote session to return a string in the same format</span>
    <span style="color: #228B22;">% as the command</span>
    <span style="color: #0000FF;">while</span> this.<span style="">getInputStream</span>.<span style="">available</span> &lt; <span style="color: #33f;">2</span>
    <span style="color: #0000FF;">end</span>
&nbsp;
    msb = this.<span style="">getInputStream</span>.<span style="">read</span>;
    lsb = this.<span style="">getInputStream</span>.<span style="">read</span>;
&nbsp;
    numChar = <span style="color: #33f;">256</span> * msb + lsb;
&nbsp;
    result = <span style="color: #0000FF;">uint8</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">zeros</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1</span>, numChar<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
    <span style="color: #0000FF;">for</span> index = <span style="color: #33f;">1</span><span style="color: #F0F;">:</span>numChar
        result<span style="color: #080;">&#40;</span>index<span style="color: #080;">&#41;</span> = this.<span style="">getInputStream</span>.<span style="">read</span>;
    <span style="color: #0000FF;">end</span>
    result = <span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span>result<span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span></pre></div></div><h3 id="Usage">Using simple.ServerSocket and simple.Socket to communicate between Matlab sessions</h3><p>To use this example, add the zip contents to your Matlab path, then open an instance of Matlab and issue the following commands:</p> </pre><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; ss = simple.<span style="">ServerSocket</span>;
&gt;&gt; ss.<span style="">bind</span>;
&gt;&gt; ss.<span style="">accept</span>;</pre></div></div><p>Then open another Matlab instance and issue these commands:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; s = simple.<span style="">Socket</span>;
&gt;&gt; s.<span style="">connect</span>;</pre></div></div><p>At this point you can send commands from this Matlab instance (the client) to the first instance (the server) using the <i>remoteEval</i> method. The command will then be transmitted to the server, executed, and the server will return the captured string result to the client:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; remoteResult = s.<span style="">remoteEval</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'pi'</span><span style="color: #080;">&#41;</span>
remoteResult =
    <span style="color: #33f;">3.1416</span></pre></div></div><p>The defaults are for localhost and port 2222. These can be changed prior to using the server's <i>bind</i> method and the client's <i>connect</i> method. To keep things as simple as possible, error checking etc. has been left out, so this is just a demonstration and is far from robust.</p><p>There are some things to note about our new classes. If we type <i><b>methods</b>(s)</i> or <i>s.methods</i> at the Matlab command prompt in our <code>simple.Socket</code> session we obtain:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; s.<span style="color: #0000FF;">methods</span>
&nbsp;
<span style="color: #0000FF;">Methods</span> <span style="color: #0000FF;">for</span> <span style="color: #0000FF;">class</span> simple.<span style="">Socket</span><span style="color: #F0F;">:</span>
&nbsp;
Socket                     getOOBInline               isClosed                   setReuseAddress            
bind                       getOutputStream            isConnected                setSendBufferSize          
<span style="color: #0000FF;">close</span>                      getPort                    isInputShutdown            setSoLinger                
connect                    getReceiveBufferSize       isOutputShutdown           setSoTimeout               
equals                     getRemoteSocketAddress     java                       setSocketImplFactory       
getChannel                 getReuseAddress            notify                     setTcpNoDelay              
getClass                   getSendBufferSize          notifyAll                  setTrafficClass            
getInetAddress             getSoLinger                remoteEval                 shutdownInput              
getInputStream             getSoTimeout               sendUrgentData             shutdownOutput             
getKeepAlive               getTcpNoDelay              setKeepAlive               toString                   
getLocalAddress            getTrafficClass            setOOBInline               wait                       
getLocalPort               hashCode                   setPerformancePreferences  
getLocalSocketAddress      isBound                    setReceiveBufferSize</pre></div></div><p>This shows that our <code>simple.Socket</code> class has all of the methods of the Java superclass, plus our added <code>remoteEval</code> method and the <code>java</code> method that was automatically added by Matlab. This means that all of the Java methods are methods of our class instance and the added <code>java</code> means that we can access the superclass methods from our class instance if the need arises. If we use the <i><b>struct</b></i> function which Yair has <a
target="_blank" href="http://undocumentedmatlab.com/blog/matlab-java-memory-leaks-performance/#struct">previously discussed</a>, we obtain:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt;  <span style="color: #0000FF;">struct</span><span style="color: #080;">&#40;</span>s<span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">ans</span> = 
              OOBInline<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
                  Bound<span style="color: #F0F;">:</span> <span style="color: #33f;">1</span>
                Channel<span style="color: #F0F;">:</span> <span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span>
                  <span style="color: #0000FF;">Class</span><span style="color: #F0F;">:</span> <span style="color: #080;">&#91;</span>1x1 java.<span style="">lang</span>.<span style="color: #0000FF;">Class</span><span style="color: #080;">&#93;</span>
                 Closed<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
              Connected<span style="color: #F0F;">:</span> <span style="color: #33f;">1</span>
            InetAddress<span style="color: #F0F;">:</span> <span style="color: #080;">&#91;</span>1x1 java.<span style="">net</span>.<span style="">Inet4Address</span><span style="color: #080;">&#93;</span>
          InputShutdown<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
            InputStream<span style="color: #F0F;">:</span> <span style="color: #080;">&#91;</span>1x1 java.<span style="">net</span>.<span style="">SocketInputStream</span><span style="color: #080;">&#93;</span>
              KeepAlive<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
           LocalAddress<span style="color: #F0F;">:</span> <span style="color: #080;">&#91;</span>1x1 java.<span style="">net</span>.<span style="">Inet4Address</span><span style="color: #080;">&#93;</span>
              LocalPort<span style="color: #F0F;">:</span> <span style="color: #33f;">51269</span>
     LocalSocketAddress<span style="color: #F0F;">:</span> <span style="color: #080;">&#91;</span>1x1 java.<span style="">net</span>.<span style="">InetSocketAddress</span><span style="color: #080;">&#93;</span>
         OutputShutdown<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
           OutputStream<span style="color: #F0F;">:</span> <span style="color: #080;">&#91;</span>1x1 java.<span style="">net</span>.<span style="">SocketOutputStream</span><span style="color: #080;">&#93;</span>
      ReceiveBufferSize<span style="color: #F0F;">:</span> <span style="color: #33f;">8192</span>
    RemoteSocketAddress<span style="color: #F0F;">:</span> <span style="color: #080;">&#91;</span>1x1 java.<span style="">net</span>.<span style="">InetSocketAddress</span><span style="color: #080;">&#93;</span>
           ReuseAddress<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
         SendBufferSize<span style="color: #F0F;">:</span> <span style="color: #33f;">8192</span>
               SoLinger<span style="color: #F0F;">:</span> -<span style="color: #33f;">1</span>
              SoTimeout<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
             TcpNoDelay<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
           TrafficClass<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
                address<span style="color: #F0F;">:</span> <span style="color:#A020F0;">'localhost'</span>
                   port<span style="color: #F0F;">:</span> <span style="color: #33f;">2222</span></pre></div></div><p>We see that we have access to all of the public properties of the Java superclass, as well as the UDD properties that we have added.</p><h3 id="Conclusion">Conclusion</h3><p>At the beginning of this post I said that this would be a simple non-robust communications method. In order to make this anything more than that, a number of things would need to be implemented, for example:</p><ul><li>Improve the <i>accept</i> method to exit after a timeout or when a connection has been made and then terminated</li><li>Add checksums and timeouts for communication to determine the reliability of the communication</li><li>Add a retry request protocol for instances of communication failure</li><li>Add support for any serializable Matlab type, not just strings</li></ul><p>The intent here was just to show that extending Java classes with Matlab is possible, relatively simple, and can be extremely useful. After all, with over 10 million Java developers out there, chances are that somebody somewhere has already posted a Java class that answers your exact need, or at least close enough that it can be used in Matlab with only some small modifications.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/creating-a-simple-udd-class/' rel='bookmark' title='Creating a simple UDD class'>Creating a simple UDD class</a> <small>This article explains how to create and test custom UDD packages, classes and objects...</small></li><li><a
href='http://undocumentedmatlab.com/blog/udd-and-java/' rel='bookmark' title='UDD and Java'>UDD and Java</a> <small>UDD provides built-in convenience methods to facilitate the integration of Matlab UDD objects with Java code - this article explains how...</small></li><li><a
href='http://undocumentedmatlab.com/blog/jmi-java-to-matlab-interface/' rel='bookmark' title='JMI &#8211; Java-to-Matlab Interface'>JMI &#8211; Java-to-Matlab Interface</a> <small>JMI enables calling Matlab functions from within Java. This article explains JMI's core functionality....</small></li><li><a
href='http://undocumentedmatlab.com/blog/fixing-a-java-focus-problem/' rel='bookmark' title='Fixing a Java focus problem'>Fixing a Java focus problem</a> <small>Java components added to Matlab GUIs do not participate in the standard focus cycle - this article explains how to fix this problem....</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/extending-a-java-class-with-udd/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Expanding urlread capabilities</title><link>http://undocumentedmatlab.com/blog/expanding-urlreads-capabilities/</link> <comments>http://undocumentedmatlab.com/blog/expanding-urlreads-capabilities/#comments</comments> <pubDate>Wed, 21 Mar 2012 18:00:01 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Guest bloggers]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[Stock Matlab function]]></category> <category><![CDATA[Jim Hokanson]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2808</guid> <description><![CDATA[The built-in urlread functions has severe limitations. This article explains how to solve them.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/undocumented-xml-functionality/' rel='bookmark' title='Undocumented XML functionality'>Undocumented XML functionality</a> <small>Matlab's built-in XML-processing functions have several undocumented features that can be used by Java-savvy users...</small></li><li><a
href='http://undocumentedmatlab.com/blog/gui-automation-robot/' rel='bookmark' title='GUI automation using a Robot'>GUI automation using a Robot</a> <small>This article explains how Java's Robot class can be used to programmatically control mouse and keyboard actions...</small></li><li><a
href='http://undocumentedmatlab.com/blog/gui-automation-utilities/' rel='bookmark' title='GUI automation utilities'>GUI automation utilities</a> <small>This article explains a couple of Matlab utilities that use Java's Robot class to programmatically control mouse and keyboard actions...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p><i>I would like to welcome guest blogger <a
target="_blank" rel="nofollow" href="http://sites.google.com/site/jimhokanson/">Jim Hokanson</a>. Today, Jim will explain some of the limitations that at one time or another many of us have encountered with Matlab&#8217;s built-in <b>urlread</b> function. More importantly, Jim has spent a lot of time in creating an expanded-capabilities Matlab function, which he explains below. Note that while <b>urlread</b>&#8216;s internals are undocumented, the changes outlined below rely on pretty standard Java and HTTP, and should therefore be quite safe to use on multiple Matlab versions.</i></p><h3 id="Abstract">Abstract</h3><p>I recently tried to implement the <a
target="_blank" rel="nofollow" href="http://dev.mendeley.com">Mendeley</a> API but quickly found that <i><b>urlread</b></i> was not going to be sufficient for my needs. The first indication of this was my inability to send the proper authorization information for POST requests. It became even more obvious with the need to perform DELETE and PUT methods, since <i><b>urlread</b></i> only supports GET and POST. My implementation of <i><b>urlread</b></i>, which I refer to as <i><b>urlread2</b></i>, addresses these and a couple of other issues and can be <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/35693-urlread2">found on the Matlab File Exchange</a>. Other developers have tackled <i><b>urlread</b></i>&#8216;s shortcomings (<a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/8474-rewrites-of-urlread-and-urlwrite">this example</a> added timeout support, and <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/27189-urlreadpost-url-post-method-with-binary-file-uploading">this example</a> added support for binary file upload) &#8211; today&#8217;s article will focus on my solution, but others are obviously possible.</p><h3 id="Introduction">Introduction</h3><p><a
target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol">HTTP</a> is the underlying computer networking protocol that enables us to read webpages on the Internet. It consists of a request made by the user to an Internet server (typically located via <a
target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/Uniform_resource_locator">URL</a>), and a response from that server. Importantly, the request and response consist of three main parts: a resource line (for requests) or status line (for responses), followed by headers, and optionally a message body.</p><p>Matlab&#8217;s built-in <i><b>urlread</b></i> function enables Matlab users to easily read the server&#8217;s response text into a Matlab string:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">text = urlread<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'http://www.google.com'</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>This is done internally using Java code that connects to the specified URL and reads the information sent by the URL&#8217;s server (<a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/networking/urls/index.html">more on this</a>).</p><p><i><b>urlread</b></i> accepts optional additional inputs specifying the request type (&#8216;get&#8217; or &#8216;post&#8217;) and parameter values for the request.</p><p>Unfortunately, <i><b>urlread</b></i> has the following limitations:</p><ol><li>It does not allow specification of request headers</li><li>It makes assumptions as to the request headers needed based on the input method</li><li>It does not expose the response headers and status line</li><li>It assumes the response body contains text, and not a binary payload</li><li>It does not enable uploading binary contents to the server</li><li>It does not enable specifying a timeout in case the server is not responding</li></ol><h3 id="urlread2">urlread2</h3><p>The <i><b>urlread2</b></i> function addresses all of these problems. The overall design decision for this function was to make it more general, requiring more work up front to use in some cases, but more flexibility.</p><p>For reference, the following is the calling format for <i><b>urlread2</b></i> (which is reminiscent of <i><b>urlread</b></i>&#8216;s):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">urlread2<span style="color: #080;">&#40;</span>url,*method,*body,*headersIn, <span style="color: #0000FF;">varargin</span><span style="color: #080;">&#41;</span></pre></div></div><p>The * indicate optional inputs that must be spatially maintained.</p><ul><li>url &#8211; (string), url to request</li><li>method &#8211; (string, default GET) HTTP request method</li><li>body &#8211; (string, default &#8221;), body of the request</li><li>headersIn &#8211; (structure, default []), see the following section</li><li>varargin &#8211; extra properties that need to be specified via property/pair values</li></ul><h3 id="Headers">Addressing Problem 1 &#8211; Request header</h3><p><i><b>urlread</b></i> internally uses a Java object called <code>urlConnection</code> that is generally an instance of the class <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/1.5.0/docs/api/java/net/HttpURLConnection.html"><code>sun.net.www.protocol.http.HttpURLConnection</code></a>. The method <i>setRequestProperty()</i> can be used to set headers for the request. This method has two inputs, the header name and the value of that header. A simple example of this can be seen below:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">urlConnection.<span style="">setRequestProperty</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'Content-Type'</span>,<span style="color:#A020F0;">'application/x-www-form-urlencoded'</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>Here &#8216;Content-Type&#8217; is the header name and the second input is the value of that property. My function requires passing in nearly all headers as a structure array, with fields for the name and value. The preceding header would be created using a helper function <i><b>http_createHeader.m</b></i>:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">header = http_createHeader<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'Content-Type'</span>,<span style="color:#A020F0;">'application/x-www-form-urlencoded'</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>Multiple headers can be passed in to the function by concatenating header structures into a structure array.</p><h3 id="Parameters">Addressing Problem 2 &#8211; Request parameters</h3><p>When making a POST request, parameters are generally specified in the message body using the following format:</p><p><code>[property]=[value]&#038;[property]=[value]</code></p><p>The properties and values are also encoded in a particular way, generally termed <a
target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/Percent-encoding">urlencoded</a> (encoding and decoding can be done using Matlab&#8217;s built-in <i><b>urlencode</b></i> and <i><b>urldecode</b></i> functions). For GET requests this string is appended to the url with the &#8220;?&#8221; symbol. Since urlencoding methods can vary, and in the spirit of reducing assumptions, I use separate functions to generate these strings outside of <i><b>urlread2</b></i>, and then pass the result in either as the url (for GET) or as the body input (for POST). As an example, I might <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/?search_submit=fileexchange&#038;term=undocumented+matlab&#038;query=undocumented+matlab">search the Mathworks website</a> using the upper right search bar on its site for &#8220;undocumented matlab&#8221; under file exchange (<i>hmmm&#8230; pretty cute stuff there!</i>). Doing this performs a GET request with the following property/value pairs:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">params = <span style="color: #080;">&#123;</span><span style="color:#A020F0;">'search_submit'</span>,<span style="color:#A020F0;">'fileexchange'</span>, <span style="color:#A020F0;">'term'</span>,<span style="color:#A020F0;">'undocumented matlab'</span>, <span style="color:#A020F0;">'query'</span>,<span style="color:#A020F0;">'undocumented matlab'</span><span style="color: #080;">&#125;</span>;</pre></div></div><p>These property/value pairs are somewhat obvious from looking at the URL, but could also be determined by using programs such as <a
target="_blank" rel="nofollow" href="http://www.fiddler2.com/fiddler2/">Fiddler</a>, <a
target="_blank" rel="nofollow" href="http://getfirebug.com/">Firebug</a>, or <a
target="_blank" rel="nofollow" href="http://www.httpwatch.com/">HttpWatch</a>.</p><p>After urlencoding and concatenating, we would form the following string:</p><p><code>search_submit=fileexchange&#038;term=undocumented+matlab&#038;query=undocumented+matlab</code></p><p>This functionality is normally accomplished internally in <i><b>urlread</b></i>, but I use a function <i><b>http_paramsToString</b></i> to produce that result. That function also returns the required header for POST requests. The following is an example of both GET and POST requests:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #080;">&#91;</span>queryString,header<span style="color: #080;">&#93;</span> = http_paramsToString<span style="color: #080;">&#40;</span>params,<span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% For GET:</span>
url = <span style="color: #080;">&#91;</span>url <span style="color:#A020F0;">'?'</span> queryString<span style="color: #080;">&#93;</span>;
urlread2<span style="color: #080;">&#40;</span>url<span style="color: #080;">&#41;</span>
&nbsp;
<span style="color: #228B22;">% For POST:</span>
urlread2<span style="color: #080;">&#40;</span>url,<span style="color:#A020F0;">'POST'</span>,queryString,header<span style="color: #080;">&#41;</span></pre></div></div><h3 id="Response">Addressing Problem 3 &#8211; Response header</h3><p>According to the HTTP protocol, each server response starts with a simple header that indicates a numeric <a
target="_blank" rel="nofollow" href="http://en.wikipedia.org/wiki/List_of_HTTP_status_codes">response status</a>. The following Matlab code provides access to the status line using the <code>urlConnection</code> object:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">status = <span style="color: #0000FF;">struct</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'value'</span>,urlConnection.<span style="">getResponseCode</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>, <span style="color:#A020F0;">'msg'</span>,<span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span>urlConnection.<span style="">getResponseMessage</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
status = 
    value<span style="color: #F0F;">:</span> <span style="color: #33f;">200</span>
      msg<span style="color: #F0F;">:</span> <span style="color:#A020F0;">'OK'</span></pre></div></div><p><code>urlConnection</code>&#8216;s <i>getHeaderField()</i> and <i>getHeaderFieldKey()</i> methods enable reading the specific parts of the response header:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">headerValue = <span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span>urlConnection.<span style="">getHeaderField</span><span style="color: #080;">&#40;</span>headerIndex<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
headerName  = <span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span>urlConnection.<span style="">getHeaderFieldKey</span><span style="color: #080;">&#40;</span>headerIndex<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;</pre></div></div><p><code>headerIndex</code> starts at 0 and increases by 1 until both <code>headerValue</code> and <code>headerName</code> return empty.</p><p>It is important to note that header keys (names) can be repeated for different values. Sometimes this is desired, such as if there are multiple cookies being sent to the user. To generically handle this case, two header structures are returned. In both cases the header names are the field names in the structure, after <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/ref/genvarname.html">replacing hyphens with underscores</a>. In one case, allHeaders, the values are cell arrays of strings containing all values presented with the particular key. The other structure, firstHeaders, contains only the first instance of the header as a string to avoid needing to dereference a cell array.</p><h3 id="Body">Addressing Problem 4 &#8211; Response body</h3><p><i><b>urlread</b></i> assumes text output. This is fine for most webpages, which use HTML and are therefore text-based. However, <i><b>urlread</b></i> fails when trying to download any non-text resource such as an image, a ZIP file, or a PDF document. I have added a flag in <i><b>urlread2</b></i> called CAST_OUTPUT, which defaults to true, i.e. text response, just as <i><b>urlread</b></i> assumes. Using <i><b>varargin</b></i>, this flag can be set to false ({&#8216;CAST_OUTPUT&#8217;,false}) to indicate a binary response.</p><h3 id="Summary">Summary</h3><p><i><b>urlread2</b></i>&#8216;s functionality has been expanded to also address other limitations of <i><b>urlread</b></i>: It enables binary inputs, better character-set handling of the output, redirection following, and read timeouts.</p><p>The modifications described above provide direct access to the key components of the HTTP request and response messages. Its more generic nature lets <i><b>urlread2</b></i> focus on HTTP transmission, and leaves request formation and response interpretation up to the user. I think ultimately this approach is better than providing one-off modifications of the original <i><b>urlread</b></i> function to suit a particular need. <i><b>urlread2</b></i> and supporting files can be <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/35693-urlread2">found</a> on the Matlab File Exchange.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/undocumented-xml-functionality/' rel='bookmark' title='Undocumented XML functionality'>Undocumented XML functionality</a> <small>Matlab's built-in XML-processing functions have several undocumented features that can be used by Java-savvy users...</small></li><li><a
href='http://undocumentedmatlab.com/blog/gui-automation-robot/' rel='bookmark' title='GUI automation using a Robot'>GUI automation using a Robot</a> <small>This article explains how Java's Robot class can be used to programmatically control mouse and keyboard actions...</small></li><li><a
href='http://undocumentedmatlab.com/blog/gui-automation-utilities/' rel='bookmark' title='GUI automation utilities'>GUI automation utilities</a> <small>This article explains a couple of Matlab utilities that use Java's Robot class to programmatically control mouse and keyboard actions...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/expanding-urlreads-capabilities/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Java stack traces in Matlab</title><link>http://undocumentedmatlab.com/blog/java-stack-traces-in-matlab/</link> <comments>http://undocumentedmatlab.com/blog/java-stack-traces-in-matlab/#comments</comments> <pubDate>Wed, 07 Mar 2012 18:00:35 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Java]]></category> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[JMI]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2783</guid> <description><![CDATA[Matlab does not normally provide information about the Java calls on the stack trace. A simple trick can show us this information.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/jmi-java-to-matlab-interface/' rel='bookmark' title='JMI &#8211; Java-to-Matlab Interface'>JMI &#8211; Java-to-Matlab Interface</a> <small>JMI enables calling Matlab functions from within Java. This article explains JMI's core functionality....</small></li><li><a
href='http://undocumentedmatlab.com/blog/using-java-collections-in-matlab/' rel='bookmark' title='Using Java Collections in Matlab'>Using Java Collections in Matlab</a> <small>Java includes a wide selection of data structures that can easily be used in Matlab programs - this article explains how. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/converting-java-vectors-to-matlab-arrays/' rel='bookmark' title='Converting Java vectors to Matlab arrays'>Converting Java vectors to Matlab arrays</a> <small>Converting Java vectors to Matlab arrays is pretty simple - this article explains how....</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>When debugging Java events in Matlab callbacks, it is sometimes useful to check the stack trace of the originating Java code. Matlab&#8217;s built-in <i><b>dbstack</b></i> function only reports the stack-trace of Matlab code, and any prior Java code in the stack trace is not reported. Knowing this information is also extremely important when debugging Java components that are used in Matlab, especially when using the Java-to-Matlab Interface (<a
target="_blank" href="http://undocumentedmatlab.com/tag/JMI/">JMI</a>).</p><p>Let&#8217;s use a specific example to illustrate: Matlab&#8217;s <i><b>uitable</b></i> passes information back and forth between its underlying Java code and Matlab, via the <i><b>arrayviewfunc</b></i> Matlab function (<i>%matlabroot%/toolbox/matlab/codetools/arrayviewfunc.m</i>). If we place a breakpoint in <i><b>arrayviewfunc</b></i> and then update the table&#8217;s data, <i><b>dbstack</b></i> will only report the Matlab stack:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Prepare an empty uitable</span>
&gt;&gt; hTable = uitable<span style="color: #080;">&#40;</span><span style="color:#A020F0;">'ColumnName'</span>,<span style="color: #080;">&#123;</span><span style="color:#A020F0;">'a'</span>,<span style="color:#A020F0;">'b'</span>,<span style="color:#A020F0;">'c'</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Place a breakpoint in arrayviewfunc</span>
&gt;&gt; <span style="color: #0000FF;">dbstop</span> in arrayviewfunc at reportValuesCallback
&gt;&gt; <span style="color: #0000FF;">dbstatus</span>
Breakpoint <span style="color: #0000FF;">for</span> arrayviewfunc&gt;reportValuesCallback <span style="color: #0000FF;">is</span> on <span style="color: #0000FF;">line</span> <span style="color: #33f;">588</span>.
&nbsp;
<span style="color: #228B22;">% Update the table data and wait for the breakpoint to trigger</span>
&gt;&gt; <span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>hTable,<span style="color:#A020F0;">'Data'</span>,<span style="color: #0000FF;">magic</span><span style="color: #080;">&#40;</span><span style="color: #33f;">3</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% Check the Matlab stack trace – no sign of the invoking Java code</span>
K&gt;&gt; <span style="color: #0000FF;">dbstack</span>
&gt; In arrayviewfunc&gt;reportValuesCallback at <span style="color: #33f;">588</span>
  In arrayviewfunc at <span style="color: #33f;">42</span></pre></div></div><p>To see the originating Java stack trace, we can use <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html"><code>java.lang.Thread</code></a>&#8216;s static <i>dumpStack()</i> method, which spills the <a
target="_blank" rel="nofollow" href="http://java.sun.com/developer/technicalArticles/Programming/Stacktrace/">Java stack trace</a> onto the stderr console (will appear in red in Matlab&#8217;s Command Window):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">K&gt;&gt; java.<span style="">lang</span>.<span style="">Thread</span>.<span style="">dumpStack</span>
java.<span style="">lang</span>.<span style="">Exception</span><span style="color: #F0F;">:</span> Stack <span style="color: #0000FF;">trace</span>
   at java.<span style="">lang</span>.<span style="">Thread</span>.<span style="">dumpStack</span><span style="color: #080;">&#40;</span>Unknown Source<span style="color: #080;">&#41;</span>
   at com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">NativeMatlab</span>.<span style="">SendMatlabMessage</span><span style="color: #080;">&#40;</span>Native Method<span style="color: #080;">&#41;</span>
   at com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">NativeMatlab</span>.<span style="">sendMatlabMessage</span><span style="color: #080;">&#40;</span>NativeMatlab.<span style="">java</span><span style="color: #F0F;">:</span><span style="color: #33f;">219</span><span style="color: #080;">&#41;</span>
   at com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">MatlabLooper</span>.<span style="">sendMatlabMessage</span><span style="color: #080;">&#40;</span>MatlabLooper.<span style="">java</span><span style="color: #F0F;">:</span><span style="color: #33f;">121</span><span style="color: #080;">&#41;</span>
   at com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">Matlab</span>.<span style="">mtFeval</span><span style="color: #080;">&#40;</span>Matlab.<span style="">java</span><span style="color: #F0F;">:</span><span style="color: #33f;">1550</span><span style="color: #080;">&#41;</span>
   at com.<span style="">mathworks</span>.<span style="">hg</span>.<span style="">peer</span>.<span style="">ui</span>.<span style="">table</span>.<span style="">DefaultUIStyleTableModel</span>$UITableValueTableModel$1.<span style="">runOnMatlabThread</span><span style="color: #080;">&#40;</span>DefaultUIStyleTableModel.<span style="">java</span><span style="color: #F0F;">:</span><span style="color: #33f;">467</span><span style="color: #080;">&#41;</span>
   at com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">MatlabWorker</span>$2.<span style="">run</span><span style="color: #080;">&#40;</span>MatlabWorker.<span style="">java</span><span style="color: #F0F;">:</span><span style="color: #33f;">79</span><span style="color: #080;">&#41;</span>
   at com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">NativeMatlab</span>.<span style="">dispatchMTRequests</span><span style="color: #080;">&#40;</span>NativeMatlab.<span style="">java</span><span style="color: #F0F;">:</span><span style="color: #33f;">364</span><span style="color: #080;">&#41;</span></pre></div></div><p>To access and possibly parse the originating Java stack trace, we can use the <a
target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/1069066/get-current-stack-trace-in-java">following trick</a>:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">K&gt;&gt; st = java.<span style="">lang</span>.<span style="">Thread</span>.<span style="">currentThread</span>.<span style="">getStackTrace</span>;
K&gt;&gt; <span style="color: #0000FF;">for</span> idx = <span style="color: #33f;">2</span> <span style="color: #F0F;">:</span> <span style="color: #0000FF;">length</span><span style="color: #080;">&#40;</span>st<span style="color: #080;">&#41;</span>, <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>st<span style="color: #080;">&#40;</span>idx<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">end</span>
com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">NativeMatlab</span>.<span style="">SendMatlabMessage</span><span style="color: #080;">&#40;</span>Native Method<span style="color: #080;">&#41;</span>
com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">NativeMatlab</span>.<span style="">sendMatlabMessage</span><span style="color: #080;">&#40;</span>NativeMatlab.<span style="">java</span><span style="color: #F0F;">:</span><span style="color: #33f;">219</span><span style="color: #080;">&#41;</span>
com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">MatlabLooper</span>.<span style="">sendMatlabMessage</span><span style="color: #080;">&#40;</span>MatlabLooper.<span style="">java</span><span style="color: #F0F;">:</span><span style="color: #33f;">121</span><span style="color: #080;">&#41;</span>
com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">Matlab</span>.<span style="">mtFeval</span><span style="color: #080;">&#40;</span>Matlab.<span style="">java</span><span style="color: #F0F;">:</span><span style="color: #33f;">1550</span><span style="color: #080;">&#41;</span>
com.<span style="">mathworks</span>.<span style="">hg</span>.<span style="">peer</span>.<span style="">ui</span>.<span style="">table</span>.<span style="">DefaultUIStyleTableModel</span>$UITableValueTableModel$1.<span style="">runOnMatlabThread</span><span style="color: #080;">&#40;</span>DefaultUIStyleTableModel.<span style="">java</span><span style="color: #F0F;">:</span><span style="color: #33f;">467</span><span style="color: #080;">&#41;</span>
com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">MatlabWorker</span>$2.<span style="">run</span><span style="color: #080;">&#40;</span>MatlabWorker.<span style="">java</span><span style="color: #F0F;">:</span><span style="color: #33f;">79</span><span style="color: #080;">&#41;</span>
com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">NativeMatlab</span>.<span style="">dispatchMTRequests</span><span style="color: #080;">&#40;</span>NativeMatlab.<span style="">java</span><span style="color: #F0F;">:</span><span style="color: #33f;">364</span><span style="color: #080;">&#41;</span></pre></div></div><p>Each of the stack trace elements can be inspected, to get specific properties:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">K&gt;&gt; st<span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>.<span style="">getFileName</span>
<span style="color: #0000FF;">ans</span> =
     <span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span>		<span style="color: #228B22;">% empty = unknown</span>
&nbsp;
K&gt;&gt; st<span style="color: #080;">&#40;</span><span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>.<span style="color: #0000FF;">get</span>
	<span style="color: #0000FF;">Class</span> = <span style="color: #080;">&#91;</span> <span style="color: #080;">&#40;</span><span style="color: #33f;">1</span> by <span style="color: #33f;">1</span><span style="color: #080;">&#41;</span> java.<span style="">lang</span>.<span style="color: #0000FF;">Class</span> array<span style="color: #080;">&#93;</span>
	ClassName = com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">NativeMatlab</span>
	FileName = NativeMatlab.<span style="">java</span>
	LineNumber = <span style="color: #080;">&#91;</span>-<span style="color: #33f;">2</span><span style="color: #080;">&#93;</span>
	MethodName = SendMatlabMessage
	NativeMethod = on
&nbsp;
K&gt;&gt; st<span style="color: #080;">&#40;</span><span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>.<span style="">isNativeMethod</span>
<span style="color: #0000FF;">ans</span> =
     <span style="color: #33f;">1</span>		<span style="color: #228B22;">% 1 = true</span>
&nbsp;
K&gt;&gt; <span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span>st<span style="color: #080;">&#40;</span><span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>.<span style="">getFileName</span><span style="color: #080;">&#41;</span>  <span style="color: #228B22;">% cast java.lang.String to a Matlab char</span>
<span style="color: #0000FF;">ans</span> =
NativeMatlab.<span style="">java</span>
&nbsp;
K&gt;&gt; st<span style="color: #080;">&#40;</span><span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>.<span style="">getLineNumber</span>
<span style="color: #0000FF;">ans</span> =
    -<span style="color: #33f;">2</span>		<span style="color: #228B22;">% negative = unknown</span>
&nbsp;
K&gt;&gt; st<span style="color: #080;">&#40;</span><span style="color: #33f;">5</span><span style="color: #080;">&#41;</span>.<span style="color: #0000FF;">get</span>
	<span style="color: #0000FF;">Class</span> = <span style="color: #080;">&#91;</span> <span style="color: #080;">&#40;</span><span style="color: #33f;">1</span> by <span style="color: #33f;">1</span><span style="color: #080;">&#41;</span> java.<span style="">lang</span>.<span style="color: #0000FF;">Class</span> array<span style="color: #080;">&#93;</span>
	ClassName = com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">Matlab</span>
	FileName = Matlab.<span style="">java</span>
	LineNumber = <span style="color: #080;">&#91;</span><span style="color: #33f;">1550</span><span style="color: #080;">&#93;</span>
	MethodName = mtFeval
	NativeMethod = off</pre></div></div><p>This works well in JVM 1.5 (i.e., Matlab 7.04 or R14 SP2) and higher. In older Matlab releases you can use a slight modification:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">K&gt;&gt; t = java.<span style="">lang</span>.<span style="">Throwable</span>; st=t.<span style="">getStackTrace</span>;
K&gt;&gt; <span style="color: #0000FF;">for</span> idx = <span style="color: #33f;">1</span> <span style="color: #F0F;">:</span> <span style="color: #0000FF;">length</span><span style="color: #080;">&#40;</span>st<span style="color: #080;">&#41;</span>, <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>st<span style="color: #080;">&#40;</span>idx<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">end</span>
com.<span style="">mathworks</span>.<span style="">jmi</span>.<span style="">NativeMatlab</span>.<span style="">SendMatlabMessage</span><span style="color: #080;">&#40;</span>Native Method<span style="color: #080;">&#41;</span>
<span style="color: #F0F;">...</span> <span style="color: #080;">&#40;</span>etc.<span style="color: #080;">&#41;</span></pre></div></div><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/jmi-java-to-matlab-interface/' rel='bookmark' title='JMI &#8211; Java-to-Matlab Interface'>JMI &#8211; Java-to-Matlab Interface</a> <small>JMI enables calling Matlab functions from within Java. This article explains JMI's core functionality....</small></li><li><a
href='http://undocumentedmatlab.com/blog/using-java-collections-in-matlab/' rel='bookmark' title='Using Java Collections in Matlab'>Using Java Collections in Matlab</a> <small>Java includes a wide selection of data structures that can easily be used in Matlab programs - this article explains how. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/converting-java-vectors-to-matlab-arrays/' rel='bookmark' title='Converting Java vectors to Matlab arrays'>Converting Java vectors to Matlab arrays</a> <small>Converting Java vectors to Matlab arrays is pretty simple - this article explains how....</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/java-stack-traces-in-matlab/feed/</wfw:commentRss> <slash:comments>3</slash:comments> </item> <item><title>Using Java Collections in Matlab</title><link>http://undocumentedmatlab.com/blog/using-java-collections-in-matlab/</link> <comments>http://undocumentedmatlab.com/blog/using-java-collections-in-matlab/#comments</comments> <pubDate>Thu, 16 Feb 2012 13:58:49 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Java]]></category> <category><![CDATA[Low risk of breaking in future versions]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2725</guid> <description><![CDATA[Java includes a wide selection of data structures that can easily be used in Matlab programs - this article explains how.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/converting-java-vectors-to-matlab-arrays/' rel='bookmark' title='Converting Java vectors to Matlab arrays'>Converting Java vectors to Matlab arrays</a> <small>Converting Java vectors to Matlab arrays is pretty simple - this article explains how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events/' rel='bookmark' title='Matlab callbacks for Java events'>Matlab callbacks for Java events</a> <small>Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how...</small></li><li><a
href='http://undocumentedmatlab.com/blog/java-stack-traces-in-matlab/' rel='bookmark' title='Java stack traces in Matlab'>Java stack traces in Matlab</a> <small>Matlab does not normally provide information about the Java calls on the stack trace. A simple trick can show us this information....</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>In this blog, I posted numerous articles showing how built-in Java functionality can greatly increase Matlab programming productivity and the resulting program power. While not really &#8220;undocumented&#8221; in the true sense (most of the material is actually documented separately in Matlab and Java), in practice, such Java gems are unfortunately often overlooked by Matlab programmers. Many of these tricks are GUI related, but Java has a lot to offer in non-GUI aspects. Today I will show how we can leverage Java&#8217;s extensive Collections classes in non-GUI Matlab programming.</p><h3 id="Collections">Java Collections</h3><p>Java contains a wide variety of predefined data structures (specifically Collections and Maps), which can easily be adapted to fit most programming tasks. It is unfortunate that the Matlab programming language does not contain similar predefined collection types, apart from its basic cell, array and struct elements. Matlab R2008b (7.7) added <i><b>containers.Map</b></i>, which is a much-scaled-down Matlab version of the <code>java.util.Map</code> interface, but is a step in the right direction. Some Matlab programmers prepared their own implementations of data structures, which can be found on the File Exchange.</p><p>Matlab&#8217;s limitation can easily be overcome with Java&#8217;s out-of-the-box set of predefined classes, as described below. Java collections have many advantages over hand-coded Matlab equivalents, in addition to the obvious time saving: Java&#8217;s classes are extensively debugged and performance-tuned, which is especially important when searching large collections. Also, these classes provide a consistent interface, are highly configurable and extendable, enable easy cross-type interoperability and generally give Matlab programmers the full power of Java&#8217;s collections without needing to program the nuts-and-bolts.</p><p>To start using Java collections, readers should first be familiar with them. These classes are part of the core Java language, and are explained in any standard Java programming textbook. The official Java website provides a detailed online <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/collections/">tutorial</a> about these classes, their usage and differences, in addition to a <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/6/docs/technotes/guides/collections/">detailed reference</a> of these classes.</p><p>Java Collections include interfaces and implementation classes. As of Matlab R2011b, Java interfaces cannot be used directly – only the implementation classes. Of the many Collection classes, the following are perhaps most useful (all classes belong to the <code>java.util</code> package, unless otherwise noted):</p><ul><li><a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/6/docs/api/java/util/Set.html">Set</a>:  an interface that is implemented by classes characterized by their prevention of duplicate elements. Some notable implementation classes: <code>EnumSet</code>, <code>HashSet</code>, <code>LinkedHashSet</code>, <code>TreeSet</code>.</li><li><a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/6/docs/api/java/util/List.html">List</a>:  an interface that is implemented by classes characterized by ordered elements (a.k.a. sequences), which may be duplicates of each other and accessed based on their exact position within the list. Specially <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/collections/algorithms/">optimized internal algorithms</a> enable sorting, shuffling, reversing, rotating, and other modifications of the list. Some notable implementation classes: <code>Vector</code>, <code>Stack</code>, <code>LinkedList</code>.</li><li><a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/6/docs/api/java/util/Queue.html">Queue</a>:  an interface that is implemented by classes designed for holding elements prior to processing, in an ordered list accessible only at one (=<i>head</i>) or two (<i>head</i> and <i>tail</i>) positions. All classes include specialized insertion, extraction and inspection methods. Some notable implementation classes: <code>LinkedList</code>, <code>ArrayDeque</code>, <code>PriorityQueue</code>.</li><li><a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/6/docs/api/java/util/Map.html">Map</a>:  an interface that is implemented by classes characterized by elements of unique keys paired with associated values. Early Java versions used the <code>java.util.Dictionary</code> abstract superclass, but this was subsequently replaced by the <code>java.util.Map</code> interface class. Maps contain specialized algorithms for fast retrieval based on a supplied key. Some of the notable implementation classes: <code>EnumMap</code>, <code>HashMap</code>, <code>Hashtable</code>, <code>TreeMap</code>, <code>LinkedHashMap</code>.</li></ul><p>As noted, Matlab R2008b (7.7)&#8217;s new <i><b>containers.Map</b></i> class is a scaled-down Matlab version of the <code>java.util.Map</code> interface. It has the added benefit of seamless integration with all Matlab types (unlike Java Collections – see below), as well as the <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/ref/containers.mapclass.html">ability</a> since Matlab 7.10 (R2010a) to specify data types. Serious Matlab implementations requiring key-value maps/dictionaries should still use Java&#8217;s <code>Map</code> classes to gain access to their larger functionality if not performance. Matlab versions earlier than R2008b have no real alternative in any case and must use the Java classes. The reader may also be interested to examine pure-Matlab object-oriented (class-based) <code>Hashtable</code> implementations, available on the File Exchange (<a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/26778">example1</a>, <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/28586">example2</a>).</p><p>A potential limitation of using Java Collections is their <a
target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/436852/storing-matlab-structs-in-java-objects">inability</a> to contain non-primitive Matlab types such as structs. To overcome this, either down-convert the types to some simpler type (using the <i><b>struct2cell</b></i> function or programmatically), or create a separate Java object that holds the information and store this object in the Collection.</p><p>Many additional Collection classes offer implementation of specialized needs. For example, <code>java.util.concurrent.LinkedBlockingDeque</code> implements a <code>Queue</code> which is also a <code>LinkedList</code>, is a double-ended queue (<code>Deque</code>) and is blocking (meaning that extraction operations will block until at least one element is extractable).</p><h3 id="Interface">Programming interface</h3><p>All the Java Collections have intentionally similar interfaces, with additional methods specific to each implementation class based on its use and intent. Most Collections implement the following common self-explanatory methods (simplified interface):</p><div
class="wp_syntax"><div
class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">int</span> size<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000066; font-weight: bold;">int</span> hashCode<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000066; font-weight: bold;">boolean</span> isEmpty<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000066; font-weight: bold;">boolean</span> contains<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> element<span style="color: #009900;">&#41;</span>
<span style="color: #000066; font-weight: bold;">boolean</span> containsAll<span style="color: #009900;">&#40;</span><span style="color: #003399;">Collection</span> c<span style="color: #009900;">&#41;</span>
<span style="color: #003399;">Iterator</span> iterator<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000066; font-weight: bold;">boolean</span> add<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> element<span style="color: #009900;">&#41;</span>
<span style="color: #000066; font-weight: bold;">boolean</span> remove<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> element<span style="color: #009900;">&#41;</span>
<span style="color: #000066; font-weight: bold;">boolean</span> addAll<span style="color: #009900;">&#40;</span><span style="color: #003399;">Collection</span> c<span style="color: #009900;">&#41;</span>
<span style="color: #000066; font-weight: bold;">boolean</span> removeAll<span style="color: #009900;">&#40;</span><span style="color: #003399;">Collection</span> c<span style="color: #009900;">&#41;</span>
<span style="color: #000066; font-weight: bold;">boolean</span> retainAll<span style="color: #009900;">&#40;</span><span style="color: #003399;">Collection</span> c<span style="color: #009900;">&#41;</span>
<span style="color: #000066; font-weight: bold;">void</span> clear<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #003399;">Object</span> clone<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #003399;">Object</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> toArray<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #003399;">String</span> toString<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span></pre></div></div><p>The full list of supported methods in a specific Collection class can, as any other Java object/class, be inspected using Matlab&#8217;s <i><b>methods</b></i> or <i><b>methodsview</b></i> functions (or my utilities, <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/26947-checkclass"><i><b>checkClass</b></i></a> and <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/17935-uiinspect"><i><b>uiinspect</b></i></a>):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; <span style="color: #0000FF;">methods</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'java.util.Hashtable'</span><span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">Methods</span> <span style="color: #0000FF;">for</span> <span style="color: #0000FF;">class</span> java.<span style="">util</span>.<span style="">Hashtable</span><span style="color: #F0F;">:</span>
Hashtable	containsKey	  equals	<span style="color: #0000FF;">isEmpty</span>   notifyAll	<span style="color: #0000FF;">size</span> 
<span style="color: #0000FF;">clear</span>		containsValue	  <span style="color: #0000FF;">get</span>		keyset    put		toString
clone		elements	  getClass	keys      putAll	values
contains	entrySet	  hashCode	notify    remove	wait</pre></div></div><h3 id="Hashtable">Collections example: Hashtable</h3><p>A detailed Matlab example that utilizes Hashtable (actually, <code>java.util.Properties</code>, which is a subclass of <code>java.util.Hashtable</code>) for a phone-book application is <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/matlab_external/f18070.html">detailed</a> in Matlab&#8217;s External Interface/Java section. The following code snippet complements that example by showing some common characteristics of Collections:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; hash = java.<span style="">util</span>.<span style="">Hashtable</span>;
&gt;&gt; hash.<span style="">put</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'key #1'</span>,<span style="color:#A020F0;">'myStr'</span><span style="color: #080;">&#41;</span>;
&gt;&gt; hash.<span style="">put</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'2nd key'</span>,<span style="color: #0000FF;">magic</span><span style="color: #080;">&#40;</span><span style="color: #33f;">3</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
&gt;&gt; <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>hash<span style="color: #080;">&#41;</span>  <span style="color: #228B22;">% same as: hash.toString</span>
<span style="color: #080;">&#123;</span>2nd key=<span style="color: #080;">&#91;</span><span style="color: #080;">&#91;</span>D@59da0f, key #<span style="color: #33f;">1</span>=myStr<span style="color: #080;">&#125;</span>
&nbsp;
&gt;&gt; <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>hash.<span style="">containsKey</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'2nd key'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
     <span style="color: #33f;">1</span>                        <span style="color: #228B22;">% = true</span>
&nbsp;
&gt;&gt; <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>hash.<span style="color: #0000FF;">size</span><span style="color: #080;">&#41;</span>
     <span style="color: #33f;">2</span>
&nbsp;
&gt;&gt; <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>hash.<span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'key #2'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>   <span style="color: #228B22;">% key not found</span>
     <span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span>
&nbsp;
&gt;&gt; <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>hash.<span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'key #1'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>   <span style="color: #228B22;">% key found and value retrieved</span>
myStr
&nbsp;
&gt;&gt; <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>hash.<span style="">entrySet</span><span style="color: #080;">&#41;</span> <span style="color: #228B22;">% java.util.Collections$SynchronizedSet object</span>
<span style="color: #080;">&#91;</span>2nd key=<span style="color: #080;">&#91;</span><span style="color: #080;">&#91;</span>D@192094b, key #<span style="color: #33f;">1</span>=myStr<span style="color: #080;">&#93;</span>
&nbsp;
&gt;&gt; entries = hash.<span style="">entrySet</span>.<span style="">toArray</span>
entries =
java.<span style="">lang</span>.<span style="">Object</span><span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span><span style="color: #F0F;">:</span>
    <span style="color: #080;">&#91;</span>java.<span style="">util</span>.<span style="">Hashtable</span>$Entry<span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span>java.<span style="">util</span>.<span style="">Hashtable</span>$Entry<span style="color: #080;">&#93;</span>
&nbsp;
&gt;&gt; <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>entries<span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
2nd key=<span style="color: #080;">&#91;</span><span style="color: #080;">&#91;</span>D@192094b
&nbsp;
&gt;&gt; <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>entries<span style="color: #080;">&#40;</span><span style="color: #33f;">2</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>
key #<span style="color: #33f;">1</span>=myStr
&nbsp;
&gt;&gt; hash.<span style="">values</span>  <span style="color: #228B22;">% a java.util.Collections$SynchronizedCollection</span>
<span style="color: #0000FF;">ans</span> =
<span style="color: #080;">&#91;</span><span style="color: #080;">&#91;</span><span style="color: #080;">&#91;</span>D@59da0f, myStr<span style="color: #080;">&#93;</span>
&nbsp;
&gt;&gt; vals = hash.<span style="">values</span>.<span style="">toArray</span>
vals =
java.<span style="">lang</span>.<span style="">Object</span><span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span><span style="color: #F0F;">:</span>
    <span style="color: #080;">&#91;</span>3x3 <span style="color: #0000FF;">double</span><span style="color: #080;">&#93;</span>
    <span style="color:#A020F0;">'myStr'</span>
&nbsp;
&gt;&gt; vals<span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">ans</span> =
     <span style="color: #33f;">8</span>     <span style="color: #33f;">1</span>     <span style="color: #33f;">6</span>
     <span style="color: #33f;">3</span>     <span style="color: #33f;">5</span>     <span style="color: #33f;">7</span>
     <span style="color: #33f;">4</span>     <span style="color: #33f;">9</span>     <span style="color: #33f;">2</span>
&nbsp;
&gt;&gt; vals<span style="color: #080;">&#40;</span><span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">ans</span> =
myStr</pre></div></div><h3 id="Enumerators">Enumerators / Iterators</h3><p>Java Iterators (aka Enumerators), such as those returned by the <i>hash.keys()</i> method, are temporary memory constructs. A common pitfall is to directly chain such constructs. While legal from a syntax viewpoint, this would produce results that are repetitive and probably unintended, as the following code snippet shows:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; hash.<span style="">keys</span>
<span style="color: #0000FF;">ans</span> =
java.<span style="">util</span>.<span style="">Hashtable</span>$Enumerator@7b1d52    &lt; = enumerator reference
&gt;&gt; hash.<span style="">keys</span>
<span style="color: #0000FF;">ans</span> =
java.<span style="">util</span>.<span style="">Hashtable</span>$Enumerator@127d1b4   &lt; = new reference object
&nbsp;
&gt;&gt; <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>hash.<span style="">keys</span>.<span style="">nextElement</span><span style="color: #080;">&#41;</span>
2nd key   &lt; = 1st key enumerated in the hash
&gt;&gt; <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>hash.<span style="">keys</span>.<span style="">nextElement</span><span style="color: #080;">&#41;</span>
2nd key   &lt; = same key returned, because of the new enumeration obj
&nbsp;
&gt;&gt; <span style="color: #228B22;">% Wrong way: causes an endless loop since hash.keys regenerates</span>
&gt;&gt; <span style="color: #228B22;">% ^^^^^^^^^  so hash.keys.hasMoreElements is always true</span>
&gt;&gt; <span style="color: #0000FF;">while</span> hash.<span style="">keys</span>.<span style="">hasMoreElements</span>, doAbc<span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;  <span style="color: #0000FF;">end</span>   <span style="color: #228B22;">% endless loop</span>
&nbsp;
&gt;&gt; <span style="color: #228B22;">% Correct way: store the enumerator in a temporary variable</span>
&gt;&gt; hashKeys = hash.<span style="">keys</span>; 
&gt;&gt; <span style="color: #0000FF;">while</span> hashKeys.<span style="">hasMoreElements</span>,  doAbc<span style="color: #080;">&#40;</span><span style="color: #080;">&#41;</span>;  <span style="color: #0000FF;">end</span>
&nbsp;
&gt;&gt; hash.<span style="">keys</span>.<span style="color: #0000FF;">methods</span>
<span style="color: #0000FF;">Methods</span> <span style="color: #0000FF;">for</span> <span style="color: #0000FF;">class</span> java.<span style="">util</span>.<span style="">Hashtable</span>$Enumerator<span style="color: #F0F;">:</span>
equals            hasNext    nextElement   remove
getClass          hashCode   notify        toString
hasMoreElements   next       notifyAll     wait
&nbsp;
&gt;&gt; <span style="color: #228B22;">% And similarly for ArrayList iterators:</span>
&gt;&gt; jList = java.<span style="">util</span>.<span style="">ArrayList</span>;
&gt;&gt; jList.<span style="">add</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">pi</span><span style="color: #080;">&#41;</span>; jList.<span style="">add</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'text'</span><span style="color: #080;">&#41;</span>; jList.<span style="">add</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">magic</span><span style="color: #080;">&#40;</span><span style="color: #33f;">3</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>jList<span style="color: #080;">&#41;</span>
<span style="color: #080;">&#91;</span><span style="color: #33f;">3.141592653589793</span>, text, <span style="color: #080;">&#91;</span><span style="color: #080;">&#91;</span>D@1c8f959<span style="color: #080;">&#93;</span>
&nbsp;
&gt;&gt; iterator = jList.<span style="">iterator</span>
iterator =
java.<span style="">util</span>.<span style="">AbstractList</span>$Itr@1ab3929
&nbsp;
&gt;&gt; <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>iterator.<span style="">next</span><span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">fprintf</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'hasNext: %d\n'</span>,iterator.<span style="">hasNext</span><span style="color: #080;">&#41;</span>
          <span style="color: #33f;">3.14159265358979</span>
hasNext<span style="color: #F0F;">:</span> <span style="color: #33f;">1</span>
&nbsp;
&gt;&gt; <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>iterator.<span style="">next</span><span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">fprintf</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'hasNext: %d\n'</span>,iterator.<span style="">hasNext</span><span style="color: #080;">&#41;</span>
text
hasNext<span style="color: #F0F;">:</span> <span style="color: #33f;">1</span>
&nbsp;
&gt;&gt; <span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>iterator.<span style="">next</span><span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">fprintf</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'hasNext: %d\n'</span>,iterator.<span style="">hasNext</span><span style="color: #080;">&#41;</span>
     <span style="color: #33f;">8</span>     <span style="color: #33f;">1</span>     <span style="color: #33f;">6</span>
     <span style="color: #33f;">3</span>     <span style="color: #33f;">5</span>     <span style="color: #33f;">7</span>
     <span style="color: #33f;">4</span>     <span style="color: #33f;">9</span>     <span style="color: #33f;">2</span>
hasNext<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span></pre></div></div><p><i><b>More on this topic and other non-GUI Java libraries that can be used in Matlab, can be found in Chapter 2 of my <a
target="_blank" href="http://undocumentedmatlab.com/matlab-java-book/">Matlab-Java Programming book</a></b></i>.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/converting-java-vectors-to-matlab-arrays/' rel='bookmark' title='Converting Java vectors to Matlab arrays'>Converting Java vectors to Matlab arrays</a> <small>Converting Java vectors to Matlab arrays is pretty simple - this article explains how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events/' rel='bookmark' title='Matlab callbacks for Java events'>Matlab callbacks for Java events</a> <small>Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how...</small></li><li><a
href='http://undocumentedmatlab.com/blog/java-stack-traces-in-matlab/' rel='bookmark' title='Java stack traces in Matlab'>Java stack traces in Matlab</a> <small>Matlab does not normally provide information about the Java calls on the stack trace. A simple trick can show us this information....</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/using-java-collections-in-matlab/feed/</wfw:commentRss> <slash:comments>7</slash:comments> </item> <item><title>Using spinners in Matlab GUI</title><link>http://undocumentedmatlab.com/blog/using-spinners-in-matlab-gui/</link> <comments>http://undocumentedmatlab.com/blog/using-spinners-in-matlab-gui/#comments</comments> <pubDate>Wed, 25 Jan 2012 20:00:16 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[GUI]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[Internal component]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2679</guid> <description><![CDATA[Spinner controls can easily be added to Matlab GUI. This article explains how.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/customizing-matlab-labels/' rel='bookmark' title='Customizing Matlab labels'>Customizing Matlab labels</a> <small>Matlab's text uicontrol is not very customizable, and does not support HTML or Tex formatting. This article shows how to display HTML labels in Matlab and some undocumented customizations...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/advanced-jide-property-grids/' rel='bookmark' title='Advanced JIDE Property Grids'>Advanced JIDE Property Grids</a> <small>JIDE property grids can use complex cell renderer and editor components and can signal property change events asynchronously to Matlab callbacks...</small></li><li><a
href='http://undocumentedmatlab.com/blog/blurred-matlab-figure-window/' rel='bookmark' title='Blurred Matlab figure window'>Blurred Matlab figure window</a> <small>Matlab figure windows can be blurred using a semi-transparent overlaid window - this article explains how...</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>One of the few standard Java Swing controls that does not have any Matlab uicontrol counterpart is <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/uiswing/components/spinner.html"><code>JSpinner</code></a>. <code>JSpinner</code> is basically an editbox with two tiny adjacent up/down buttons. Spinners are similar in functionality to a combo-box (a.k.a. drop-down or pop-up menu), where a user can switch between several pre-selected values. They are often used when the list of possible values is too large to display in a combo-box menu. Like combo-boxes, spinners too can be editable (meaning that the user can type a value in the editbox) or not (the user can only &#8220;spin&#8221; the value using the up/down buttons).</p><p><code>JSpinner</code> uses an internal data model, similarly to <code>JTree</code>, <code>JTable</code> and other complex controls. The default model is <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/1.5.0/docs/api/javax/swing/SpinnerNumberModel.html"><code>SpinnerNumberModel</code></a>, which defines a min/max value (unlimited=[] by default) and step-size (1 by default). Additional predefined models are <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/1.5.0/docs/api/javax/swing/SpinnerListModel.html"><code>SpinnerListModel</code></a> (which accepts a cell array of possible string values) and <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/1.5.0/docs/api/javax/swing/SpinnerDateModel.html"><code>SpinnerDateModel</code></a> (which defines a date range and step unit).</p><p>Here&#8217;s a basic code snippet showing how to display a simple numeric spinner for numbers between 20 and 35, with an initial value of 24 and increments of 1:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">jModel = javax.<span style="">swing</span>.<span style="">SpinnerNumberModel</span><span style="color: #080;">&#40;</span><span style="color: #33f;">24</span>,<span style="color: #33f;">20</span>,<span style="color: #33f;">35</span>,<span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>;
jSpinner = javax.<span style="">swing</span>.<span style="">JSpinner</span><span style="color: #080;">&#40;</span>jModel<span style="color: #080;">&#41;</span>;
jhSpinner = javacomponent<span style="color: #080;">&#40;</span>jSpinner, <span style="color: #080;">&#91;</span><span style="color: #33f;">10</span>,<span style="color: #33f;">10</span>,<span style="color: #33f;">60</span>,<span style="color: #33f;">20</span><span style="color: #080;">&#93;</span>, <span style="color: #0000FF;">gcf</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>The spinner value can be set using the edit-box or by clicking on one of the tiny arrow buttons, or programmatically by setting the <b>Value</b> property. The spinner object also has related read-only properties <b>NextValue</b> and <b>PreviousValue</b>. The spinner&#8217;s model object has the corresponding <b>Value</b> (settable), <b>NextValue</b> (read-only) and <b>PreviousValue</b> (read-only) properties. In addition, the model also has the settable <b>Maximum</b>, <b>Minimum</b> and <b>StepSize</b> properties.</p><p>To attach a data-change callback, set the spinner&#8217;s <b>StateChangedCallback</b> property.</p><p>I have created a small Matlab demo, <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/26970-spinnerdemo"><i><b>SpinnerDemo</b></i></a>,  which demonstrates usage of <code>JSpinner</code> in Matlab figures. Each of the three predefined models (number, list, and date) is presented, and the spinner values are inter-connected via their callbacks. The Matlab code is modeled after the <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/uiswing/examples/components/SpinnerDemoProject/src/components/SpinnerDemo.java">Java code</a> that is used to document <code>JSpinner</code> in the official documentation. Readers are welcome to download this demo from the Matlab File Exchange and reuse its source code.</p><p><center><div
class="wp-caption aligncenter" style="width: 225px"><img
alt="Java's SpinnerDemo" src="http://UndocumentedMatlab.com/images/SpinnerDemoJava.png" title="Java's SpinnerDemo" width="215" height="134"/><p
class="wp-caption-text">Java's SpinnerDemo</p></div> &nbsp;&nbsp;<div
class="wp-caption aligncenter" style="width: 198px"><img
alt="My Matlab SpinnerDemo" src="http://UndocumentedMatlab.com/images/SpinnerDemoMatlab.png" title="My Matlab SpinnerDemo" width="188" height="184"/><p
class="wp-caption-text">My Matlab SpinnerDemo</p></div></center></p><p>As can be seen from the screenshot, <i><b>SpinnerDemo</b></i> also demonstrates how to attach a label to a GUI control with an associated accelerator key (Alt-D in the screenshot example, which sets the focus to the Date control).</p><p>An internal component in Matlab, namely <code>com.mathworks.mwswing.MJSpinner</code>, extends <code>javax.swing.JSpinner</code>, but in this particular case I cannot see any big advantage of using the internal <code>MJSpinner</code> rather than the standard <code>JSpinner</code>. On the contrary, using <code>JSpinner</code> will likely improve forward compatibility &#8211; MathWorks may well change <code>MJSpinner</code> in the future, but it cannot do anything to the standard Swing <code>JSpinner</code>. In other cases, internal Matlab controls do offer significant advantages over the standard Swing controls, but not here it would seem. In any case, the <i><b>SpinnerDemo</b></i> utility uses <code>MJSpinner</code>, but you can safely use <code>JSpinner</code> instead (line #86).</p><p>The internal Matlab controls are discussed in detail in Chapter 5 of my <a
target="_blank" href="http://undocumentedmatlab.com/matlab-java-book/">Matlab-Java book</a>, and <code>MJSpinner</code> is specifically discussed in section 5.2.1.</p><p>Another <code>JSpinner</code> derivative is JIDE&#8217;s <code>com.jidesoft.grid.SpinnerCellEditor</code>, which can be used as the cell-editor component in tables. An example of this was shown in the article about <a
target="_blank" href="http://undocumentedmatlab.com/blog/advanced-jide-property-grids/">Advanced JIDE Property Grids</a> (and section 5.7.5 in the book). You may also be interested in the <code>com.jidesoft.combobox.DateSpinnerComboBox</code>, which presents a control that includes both a date-selection combo-box and a spinner (section 5.7.2):</p><p><center><div
class="wp-caption aligncenter" style="width: 310px"><img
alt="A property grid with spinner control" src="http://UndocumentedMatlab.com/images/PropertyGrid_types.png" title="A property grid with spinner control" width="200" height="165" /><p
class="wp-caption-text">A property grid with spinner control</p></div> &nbsp;&nbsp;<div
class="wp-caption aligncenter" style="width: 289px"><img
alt="JIDE's DateSpinnerComboBox" src="http://UndocumentedMatlab.com/images/DateSpinnerComboBox.png" title="JIDE's DateSpinnerComboBox" width="279" height="228" /><p
class="wp-caption-text">JIDE's DateSpinnerComboBox</p></div></center></p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/customizing-matlab-labels/' rel='bookmark' title='Customizing Matlab labels'>Customizing Matlab labels</a> <small>Matlab's text uicontrol is not very customizable, and does not support HTML or Tex formatting. This article shows how to display HTML labels in Matlab and some undocumented customizations...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li><li><a
href='http://undocumentedmatlab.com/blog/advanced-jide-property-grids/' rel='bookmark' title='Advanced JIDE Property Grids'>Advanced JIDE Property Grids</a> <small>JIDE property grids can use complex cell renderer and editor components and can signal property change events asynchronously to Matlab callbacks...</small></li><li><a
href='http://undocumentedmatlab.com/blog/blurred-matlab-figure-window/' rel='bookmark' title='Blurred Matlab figure window'>Blurred Matlab figure window</a> <small>Matlab figure windows can be blurred using a semi-transparent overlaid window - this article explains how...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/using-spinners-in-matlab-gui/feed/</wfw:commentRss> <slash:comments>3</slash:comments> </item> <item><title>Matlab-Java memory leaks, performance</title><link>http://undocumentedmatlab.com/blog/matlab-java-memory-leaks-performance/</link> <comments>http://undocumentedmatlab.com/blog/matlab-java-memory-leaks-performance/#comments</comments> <pubDate>Fri, 20 Jan 2012 00:56:10 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Java]]></category> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[Memory]]></category> <category><![CDATA[Semi-documented feature]]></category> <category><![CDATA[Stock Matlab function]]></category> <category><![CDATA[Callbacks]]></category> <category><![CDATA[Performance]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2665</guid> <description><![CDATA[Internal fields of Java objects may leak memory - this article explains how to avoid this without sacrificing performance.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/profiling-matlab-memory-usage/' rel='bookmark' title='Profiling Matlab memory usage'>Profiling Matlab memory usage</a> <small>mtic and mtoc were a couple of undocumented features that enabled users of past Matlab releases to easily profile memory usage. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/preallocation-performance/' rel='bookmark' title='Preallocation performance'>Preallocation performance</a> <small>Preallocation is a standard Matlab speedup technique. Still, it has several undocumented aspects. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/performance-scatter-vs-line/' rel='bookmark' title='Performance: scatter vs. line'>Performance: scatter vs. line</a> <small>In many circumstances, the line function can generate visually-identical plots as the scatter function, much faster...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>There are several ways of retrieving information from a Java object into Matlab. On the face of it, all these methods look similar. But it turns out that there are important differences between them in terms of memory leakage and performance.</p><h3 id="Problem">The problem: &#8220;Matlab crashes&#8221; &#8211; now go figure&#8230;</h3><p>A client of one of my Matlab programs recently complained that Matlab crashes after several hours of extensive use of the program. The problem looked like something that is memory related (messages such as Matlab&#8217;s out-of-memory error or Java&#8217;s heap-space error). Apparently this happens even on 64-bit systems having lots of memory, where memory should never be a problem.</p><p>Well, we know that this is only in theory, but in practice Matlab&#8217;s internal memory management has problems that occasionally lead to such crashes. This is one of the reasons, by the way, that recent Matlab releases have added the preference option of increasing the default Java heap space (the previous way to do this was <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/support/solutions/en/data/1-18I2C/">a bit complex</a>). Still, even with a high Java heap space setting and lots of RAM, Matlab crashed after using my program for several hours.</p><p>Not pleasant at all, even a bit of an embarrassment for me. I&#8217;m used to crashing Matlab, but only as a result of my playing around with the internals &#8211; I would hate it to happen to my clients.</p><h3 id="Finding">Finding the leak</h3><p>While we can do little with Matlab&#8217;s internal memory manager, I started searching for the exact location of the memory leak and then to find a way to overcome it. I&#8217;ll save readers the description about the grueling task of finding out exactly where the memory leak occurred in a program that has thousands of lines of code and where events get fired asynchronously on a constant basis. <a
target="_blank" href="http://undocumentedmatlab.com/blog/undocumented-profiler-options/">Matlab Profiler&#8217;s undocumented memory profiling option</a> helped me quite a bit, as well as lots of intuition and trial-and-error. Detecting memory leak is never easy, and I consider myself somewhat lucky this time to have both detected the leak source and a workaround.</p><p>It turned out that the leakage happens in a callback that gets invoked multiple times per second by a Java object (see related articles <a
target="_blank" href="http://undocumentedmatlab.com/blog/uicontrol-callbacks/">here</a> and <a
target="_blank" href="http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events/">here</a>). Each time the Matlab callback function is invoked, it reads the event information from the supplied Java event-data (the callback&#8217;s second input parameter). Apparently, about 1KB of memory gets leaked whenever this event-data is being read. This may appear a very small leak, but multiply this by some 50-100K callback invocations per hour and you get a leakage of 50-100MB/hour. Not a small leak at all; more of a flood you could say&#8230;</p><h3 id="get">Using <i><b>get</b>()</i></h3><p>The leakage culprit turned out to be the following code snippet:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% 160 uSecs per call, with memory leak</span>
eventData  = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>hEventData,<span style="color: #080;">&#123;</span><span style="color:#A020F0;">'EventName'</span>,<span style="color:#A020F0;">'ParamNames'</span>,<span style="color:#A020F0;">'EventData'</span><span style="color: #080;">&#125;</span><span style="color: #080;">&#41;</span>;
eventName  = eventData<span style="color: #080;">&#123;</span><span style="color: #33f;">1</span><span style="color: #080;">&#125;</span>;
paramNames = eventData<span style="color: #080;">&#123;</span><span style="color: #33f;">2</span><span style="color: #080;">&#125;</span>;
paramData  = eventData<span style="color: #080;">&#123;</span><span style="color: #33f;">3</span><span style="color: #080;">&#125;</span>.<span style="color: #0000FF;">cell</span>;</pre></div></div><p>In this innocent-looking code, <code>hEventData</code> is a Java object that contains the <b>EventName, ParamNames, EventData</b> properties: <b>EventName</b> is a Java <code>String</code>, that is automatically converted by Matlab&#8217;s <i><b>get</b>()</i> function into a Matlab string (<i><b>char</b></i> array); <b>ParamNames</b> is a Java array of <code>String</code>s, that gets automatically converted into a Matlab cell-array of string; and <b>EventData</b> is a Java array of <code>Object</code>s that needs to be converted into a Matlab cell array using the built-in <i><b>cell</b></i> function, as <a
target="_blank" href="http://undocumentedmatlab.com/blog/converting-java-vectors-to-matlab-arrays/">described</a> in one of my recent articles.</p><p>The code is indeed innocent, works really well and is actually extremely fast: each invocation takes of this code segment takes less than 0.2 millisecs. Unfortunately, because of the memory leak I needed to find a better alternative.</p><h3 id="handle">Using <i><b>handle</b>()</i></h3><p>The first idea was to use the built-in <i><b>handle</b>()</i> function, under the assumption that it would solve the memory leak, as <a
target="_blank" rel="nofollow" href="http://mathforum.org/kb/message.jspa?messageID=5950839">reported here</a>. In fact, MathWorks specifically advises to use <i><b>handle</b>()</i> rather than to work with &#8220;naked&#8221; Java objects, when <a
target="_blank" href="http://undocumentedmatlab.com/blog/uicontrol-callbacks/#memory_leak">setting Java object callbacks</a>. The official documentation of the <i><b>set</b></i> function <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/ref/set.html#f67-433534">says</a>:</p><blockquote><p>Do not use the set function on Java objects as it will cause a memory leak.</p></blockquote><p>It stands to reason then that a similar memory leak happens with <i><b>get</b></i> and that a similar use of <i><b>handle</b></i> would solve this problem:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% 300 uSecs per call, with memory leak</span>
s = <span style="color: #0000FF;">get</span><span style="color: #080;">&#40;</span>handle<span style="color: #080;">&#40;</span>hEventData<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
eventName  = s.<span style="">EventName</span>;
paramNames = s.<span style="">ParamNames</span>;
paramData  = <span style="color: #0000FF;">cell</span><span style="color: #080;">&#40;</span>s.<span style="">EventData</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>Unfortunately, this variant, although working correctly, still leaks memory, and also performs almost twice as worse than the original version, taking some 0.3 milliseconds to execute per invocation. Looks like this is a dead end.</p><h3 id="accessor">Using Java accessor methods</h3><p>The next attempt was to use the Java object&#8217;s internal accessor methods for the requested properties. These are <code>public</code> methods of the form <i>getXXX(), isXXX(), setXXX()</i> that enable Matlab to treat XXX as a property by its <i><b>get</b></i> and <i><b>set</b></i> functions. In our case, we need to use the getter methods, as follows:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% 380 uSecs per call, no memory leak</span>
eventName  = <span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span>hEventData.<span style="">getEventName</span><span style="color: #080;">&#41;</span>;
paramNames = <span style="color: #0000FF;">cell</span><span style="color: #080;">&#40;</span>hEventData.<span style="">getParamNames</span><span style="color: #080;">&#41;</span>;
paramData  = <span style="color: #0000FF;">cell</span><span style="color: #080;">&#40;</span>hEventData.<span style="">getEventData</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>Here, the method <i>getEventName()</i> returns a Java <code>String</code>, that we convert into a Matlab string using the <i><b>char</b></i> function. In our previous two variants, the <i><b>get</b></i> function did this conversion for us automatically, but when we use the Java method directly we need to convert the results ourselves. Similarly, when we call <i>getParamNames()</i>, we need to use the <i><b>cell</b></i> function to convert the Java <code>String[]</code> array into a Matlab cell array.</p><p>This version at last doesn&#8217;t leak any memory. Unfortunately, it has an even worse performance: each invocation takes almost 0.4 milliseconds. The difference may seem insignificant. However, recall that this callback gets called dozens of times each second, so the total adds up quickly. It would be nice if there were a faster alternative that does not leak any memory.</p><h3 id="struct">Using <i><b>struct</b>()</i></h3><p>Luckily, I found just such an alternative. At 0.24 millisecs per invocation, it is almost as fast as the leaky best-performance original <i><b>get</b></i> version. Best of all, it leaks no memory, at least none that I could detect.</p><p>The mechanism relies on the little-known fact that public fields of Java objects can be retrieved in Matlab using the built-in <i><b>struct</b></i> function. For example:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; fields = <span style="color: #0000FF;">struct</span><span style="color: #080;">&#40;</span>java.<span style="">awt</span>.<span style="color: #0000FF;">Rectangle</span><span style="color: #080;">&#41;</span>
fields = 
             x<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
             y<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
         width<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
        height<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
      OUT_LEFT<span style="color: #F0F;">:</span> <span style="color: #33f;">1</span>
       OUT_TOP<span style="color: #F0F;">:</span> <span style="color: #33f;">2</span>
     OUT_RIGHT<span style="color: #F0F;">:</span> <span style="color: #33f;">4</span>
    OUT_BOTTOM<span style="color: #F0F;">:</span> <span style="color: #33f;">8</span>
&nbsp;
&gt;&gt; fields = <span style="color: #0000FF;">struct</span><span style="color: #080;">&#40;</span>java.<span style="">awt</span>.<span style="">Dimension</span><span style="color: #080;">&#41;</span>
fields = 
     width<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span>
    height<span style="color: #F0F;">:</span> <span style="color: #33f;">0</span></pre></div></div><p>Note that this useful mechanism is not mentioned in <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/matlab_external/f4873.html#f46643">the main documentation page for accessing Java object fields</a>, although it is indeed mentioned in <a
target="_blank" rel="nofollow" href="http://www.mathworks.com/help/techdoc/matlab_external/f6671.html#f61403">another doc-page</a> &#8211; I guess this is a documentation oversight.</p><p>In any case, I converted my Java object to use public (rather than private) fields, so that I could use this <i><b>struct</b></i> mechanism (Matlab can only access public fields). Yes I know that using private fields is a better programming practice and all that (I&#8217;ve programmed OOP for some 15 years&#8230;), but sometimes we need to do ugly things in the interest of performance. The latest version now looks like this:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% 240 uSecs per call, no memory leak</span>
s = <span style="color: #0000FF;">struct</span><span style="color: #080;">&#40;</span>hEventData<span style="color: #080;">&#41;</span>;
eventName  = <span style="color: #0000FF;">char</span><span style="color: #080;">&#40;</span>s.<span style="">eventName</span><span style="color: #080;">&#41;</span>;
paramNames = <span style="color: #0000FF;">cell</span><span style="color: #080;">&#40;</span>s.<span style="">paramNames</span><span style="color: #080;">&#41;</span>;
paramData  = <span style="color: #0000FF;">cell</span><span style="color: #080;">&#40;</span>s.<span style="">eventData</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>This solved the memory leakage issue for my client. I felt fortunate that I was not only able to detect Matlab&#8217;s memory leak but also find a working workaround without sacrificing performance or functionality.</p><p>In this particular case, I was lucky to have full control over my Java object, to be able to convert its fields to become public. Unfortunately, we do not always have similar control over the object that we use, because they were coded by a third party.</p><p>By the way, Matlab itself uses this <i><b>struct</b></i> mechanism in its code-base. For example, Matlab timers are implemented using Java objects (<code>com.mathworks.timer.TimerTask</code>). The timer callback in Matlab code converts the Java timer event data into a Matlab struct using the <i><b>struct</b></i> function, in <i>%matlabroot%/toolbox/matlab/iofun/@timer/timercb.m</i>. The users of the timer callbacks then get passed a simple Matlab EventData struct without ever knowing that the original data came from a Java object.</p><p>As an interesting corollary, this same <i><b>struct</b></i> mechanism can be used to detect internal properties of Matlab class objects. For example, in the timers again, we can get the underlying timer&#8217;s Java object as follows (note the highlighted warning, which I find a bit ironic given the context):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; timerObj = timerfind
&nbsp;
   Timer Object<span style="color: #F0F;">:</span> timer-<span style="color: #33f;">1</span>
&nbsp;
   Timer Settings
      ExecutionMode<span style="color: #F0F;">:</span> singleShot
             Period<span style="color: #F0F;">:</span> <span style="color: #33f;">1</span>
           BusyMode<span style="color: #F0F;">:</span> drop
            Running<span style="color: #F0F;">:</span> off
&nbsp;
   Callbacks
           TimerFcn<span style="color: #F0F;">:</span> @myTimerFcn
           ErrorFcn<span style="color: #F0F;">:</span> <span style="color:#A020F0;">''</span>
           StartFcn<span style="color: #F0F;">:</span> <span style="color:#A020F0;">''</span>
            StopFcn<span style="color: #F0F;">:</span> <span style="color:#A020F0;">''</span>
&nbsp;
&gt;&gt; timerFields = <span style="color: #0000FF;">struct</span><span style="color: #080;">&#40;</span>timerObj<span style="color: #080;">&#41;</span>
<span style="display:block;background-color: #ffc;"><span style="color: #0000FF;">Warning</span><span style="color: #F0F;">:</span> Calling <span style="color: #0000FF;">STRUCT</span> on an object prevents the object from hiding its implementation details and should thus be avoided.</span><span style="display:block;background-color: #ffc;"><span style="">Use</span> <span style="color: #0000FF;">DISP</span> or DISPLAY to see the visible public details of an object. <span style="">See</span> <span style="color:#A020F0;">'help struct'</span> <span style="color: #0000FF;">for</span> <span style="color: #0000FF;">more</span> information.</span><span style="display:block;background-color: #ffc;"><span style="color: #080;">&#40;</span><span style="color: #0000FF;">Type</span> &quot;warning off MATLAB<span style="color: #F0F;">:</span>structOnObject&quot; to suppress this <span style="color: #0000FF;">warning</span>.<span style="color: #080;">&#41;</span></span>timerFields = 
         ud<span style="color: #F0F;">:</span> <span style="color: #080;">&#123;</span><span style="color: #080;">&#125;</span>
    jobject<span style="color: #F0F;">:</span> <span style="color: #080;">&#91;</span>1x1 javahandle.<span style="">com</span>.<span style="">mathworks</span>.<span style="">timer</span>.<span style="">TimerTask</span><span style="color: #080;">&#93;</span></pre></div></div><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/profiling-matlab-memory-usage/' rel='bookmark' title='Profiling Matlab memory usage'>Profiling Matlab memory usage</a> <small>mtic and mtoc were a couple of undocumented features that enabled users of past Matlab releases to easily profile memory usage. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/preallocation-performance/' rel='bookmark' title='Preallocation performance'>Preallocation performance</a> <small>Preallocation is a standard Matlab speedup technique. Still, it has several undocumented aspects. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/performance-scatter-vs-line/' rel='bookmark' title='Performance: scatter vs. line'>Performance: scatter vs. line</a> <small>In many circumstances, the line function can generate visually-identical plots as the scatter function, much faster...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-interface-using-static-control/' rel='bookmark' title='Matlab-Java interface using a static control'>Matlab-Java interface using a static control</a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/matlab-java-memory-leaks-performance/feed/</wfw:commentRss> <slash:comments>20</slash:comments> </item> <item><title>Converting Java vectors to Matlab arrays</title><link>http://undocumentedmatlab.com/blog/converting-java-vectors-to-matlab-arrays/</link> <comments>http://undocumentedmatlab.com/blog/converting-java-vectors-to-matlab-arrays/#comments</comments> <pubDate>Wed, 14 Dec 2011 18:00:47 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[Java]]></category> <category><![CDATA[Low risk of breaking in future versions]]></category> <category><![CDATA[Performance]]></category> <category><![CDATA[Undocumented function]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2613</guid> <description><![CDATA[Converting Java vectors to Matlab arrays is pretty simple - this article explains how.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-memory-leaks-performance/' rel='bookmark' title='Matlab-Java memory leaks, performance'>Matlab-Java memory leaks, performance</a> <small>Internal fields of Java objects may leak memory - this article explains how to avoid this without sacrificing performance. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events/' rel='bookmark' title='Matlab callbacks for Java events'>Matlab callbacks for Java events</a> <small>Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how...</small></li><li><a
href='http://undocumentedmatlab.com/blog/java-stack-traces-in-matlab/' rel='bookmark' title='Java stack traces in Matlab'>Java stack traces in Matlab</a> <small>Matlab does not normally provide information about the Java calls on the stack trace. A simple trick can show us this information....</small></li><li><a
href='http://undocumentedmatlab.com/blog/jboost-integrating-an-external-java-library-in-matlab/' rel='bookmark' title='JBoost &#8211; Integrating an external Java library in Matlab'>JBoost &#8211; Integrating an external Java library in Matlab</a> <small>This article shows how an external Java library can be integrated in Matlab...</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>Matlab includes built-in support for automatic conversion of Matlab cell arrays into Java arrays. This is important in cases when we need to pass information to a Java function that expects an array (e.g., <code>String[]</code>).</p><h3 id="Numeric">Numeric data array</h3><p>In some cases, namely Java numeric arrays, Matlab also automatically converts the Java array into Matlab arrays. This is actually inconvenient when we would like to access the original Java reference in order to modify some value &#8211; since the Java reference is inaccessible from Matlab in this case, the data is immutable.</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; jColor = java.<span style="">awt</span>.<span style="">Color</span>.<span style="">red</span>
jColor =
java.<span style="">awt</span>.<span style="">Color</span><span style="color: #080;">&#91;</span>r=<span style="color: #33f;">255</span>,g=<span style="color: #33f;">0</span>,b=<span style="color: #33f;">0</span><span style="color: #080;">&#93;</span>
&nbsp;
&gt;&gt; matlabData = jColor.<span style="">getColorComponents</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>
matlabData =
     <span style="color: #33f;">1</span>
     <span style="color: #33f;">0</span>     <span style="color: #228B22;">% &lt; = immutable array of numbers, not a reference to int[]</span>
     <span style="color: #33f;">0</span></pre></div></div><h3 id="Nonnumeric">Non-numeric array</h3><p>Very often we encounter cases in Java where the information is stored in an array of non-numeric data. In such cases we need to apply a non-automatic conversion from Java into Matlab.</p><p>If the objects are of exactly the same type, then we could store them in a simple Matlab array; otherwise (as can be seen in the example below), we could store them in either a simple array of <i><b>handle</b></i>s, or in a simple cell array:</p> </pre><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; jFrames = java.<span style="">awt</span>.<span style="">Frame</span>.<span style="">getFrames</span>
jFrames =
java.<span style="">awt</span>.<span style="">Frame</span><span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span><span style="color: #F0F;">:</span>
    <span style="color: #080;">&#91;</span>javax.<span style="">swing</span>.<span style="">SwingUtilities</span>$SharedOwnerFrame <span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span>com.<span style="">mathworks</span>.<span style="">mde</span>.<span style="">desk</span>.<span style="">MLMainFrame</span>          <span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span>com.<span style="">mathworks</span>.<span style="">mde</span>.<span style="">desk</span>.<span style="">MLMultipleClientFrame</span><span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span>com.<span style="">mathworks</span>.<span style="">mwswing</span>.<span style="">MJFrame</span>               <span style="color: #080;">&#93;</span>
&nbsp;
<span style="color: #228B22;">% Alternative #1 - use a loop</span>
&gt;&gt; mFrames = handle<span style="color: #080;">&#40;</span><span style="color: #080;">&#91;</span><span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">for</span> idx = <span style="color: #33f;">1</span> <span style="color: #F0F;">:</span> <span style="color: #0000FF;">length</span><span style="color: #080;">&#40;</span>jFrames<span style="color: #080;">&#41;</span>; mFrames<span style="color: #080;">&#40;</span>idx<span style="color: #080;">&#41;</span>=handle<span style="color: #080;">&#40;</span>jFrames<span style="color: #080;">&#40;</span>idx<span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>; <span style="color: #0000FF;">end</span>
&gt;&gt; mFrames
mFrames =
	handle<span style="color: #F0F;">:</span> <span style="color: #33f;">1</span>-by-<span style="color: #33f;">4</span>
&gt;&gt; mFrames<span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">ans</span> =
	javahandle.<span style="">javax</span>.<span style="">swing</span>.<span style="">SwingUtilities</span>$SharedOwnerFrame
&gt;&gt; mFrames<span style="color: #080;">&#40;</span><span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>
<span style="color: #0000FF;">ans</span> =
	javahandle.<span style="">com</span>.<span style="">mathworks</span>.<span style="">mde</span>.<span style="">desk</span>.<span style="">MLMainFrame</span>
&nbsp;
<span style="color: #228B22;">% Alternative #2a - convert into a Matlab cell array</span>
&gt;&gt; mFrames = jFrames.<span style="color: #0000FF;">cell</span>
mFrames = 
    <span style="color: #080;">&#91;</span>1x1 javax.<span style="">swing</span>.<span style="">SwingUtilities</span>$SharedOwnerFrame <span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span>1x1 com.<span style="">mathworks</span>.<span style="">mde</span>.<span style="">desk</span>.<span style="">MLMainFrame</span>          <span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span>1x1 com.<span style="">mathworks</span>.<span style="">mde</span>.<span style="">desk</span>.<span style="">MLMultipleClientFrame</span><span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span>1x1 com.<span style="">mathworks</span>.<span style="">mwswing</span>.<span style="">MJFrame</span>               <span style="color: #080;">&#93;</span>
&nbsp;
<span style="color: #228B22;">% Alternative #2b - convert to a cell array (equivalent variant of alternative 2a)</span>
&gt;&gt; mFrames = <span style="color: #0000FF;">cell</span><span style="color: #080;">&#40;</span>jFrames<span style="color: #080;">&#41;</span>;</pre></div></div><p>Note that if we only need to access a particular item in the Java vector or array, we could do that directly, without needing to convert the entire data into Matlab first. Simply use <code>jFrames(1)</code> to directly access the first item in the <code>jFrames</code> array, for example.</p><p>(note: Java Frames are discussed in chapters 7 and 8 of my Matlab-Java book).</p><h3 id="Collections">Vectors and other Collections</h3><p>Very often we encounter cases in Java where the information is stored in a <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/tutorial/collections/index.html">Java Collection</a> rather than in a simple Java array. The basic mechanism for the conversion in this case is to first convert the Java data into a simple Java array (in cases it was not so in the first place), and then to convert this into a Matlab array using either the automated conversion (if the data is numeric), or using a for loop (ugly and slow!), or into a cell array using the <b><i>cell</i></b> function, as explained above.</p><p>Different Collections have different manners of converting into a Java array: some Collections return an Iterator/Enumerator that can be processed in a loop (be careful not to reset the iterator reference by re-reading it within the loop):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% Wrong way - causes an infinite loop</span>
idx = <span style="color: #33f;">1</span>;
props = java.<span style="">lang</span>.<span style="">System</span>.<span style="">getProperties</span>;
<span style="color: #0000FF;">while</span> props.<span style="">elements</span>.<span style="">hasMoreElements</span>
    mPropValue<span style="color: #080;">&#123;</span>idx<span style="color: #080;">&#125;</span> = props.<span style="">elements</span>.<span style="">nextElement</span>;
<span style="color: #0000FF;">end</span>
&nbsp;
<span style="color: #228B22;">% Right way</span>
idx = <span style="color: #33f;">1</span>;
propValues = java.<span style="">lang</span>.<span style="">System</span>.<span style="">getProperties</span>.<span style="">elements</span>;  <span style="color: #228B22;">% Enumerator</span>
<span style="color: #0000FF;">while</span> propValues.<span style="">hasMoreElements</span>
    mPropValue<span style="color: #080;">&#123;</span>idx<span style="color: #080;">&#125;</span> = propValues.<span style="">nextElement</span>;
<span style="color: #0000FF;">end</span></pre></div></div><p>(note: system properties are discussed in section 1.9 of my Matlab-Java book; Collections are discussed in section 2.1)</p><p>Other Collections, such as <a
target="_blank" rel="nofollow" href="http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Vector.html"><code>java.util.Vector</code></a>, have a <i>toArray()</i> method that directly converts into a Java array, and we can process from there as described above:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; jVector = java.<span style="">util</span>.<span style="">Vector</span>;
&gt;&gt; jVector.<span style="">add</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>; jVector.<span style="">add</span><span style="color: #080;">&#40;</span><span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>; jVector.<span style="">add</span><span style="color: #080;">&#40;</span><span style="color: #33f;">3</span><span style="color: #080;">&#41;</span>;
&gt;&gt; jVector.<span style="">addAll</span><span style="color: #080;">&#40;</span>jv<span style="color: #080;">&#41;</span>; jVector.<span style="">addAll</span><span style="color: #080;">&#40;</span>jv<span style="color: #080;">&#41;</span>;
&gt;&gt; jVector
jVector =
<span style="color: #080;">&#91;</span><span style="color: #33f;">1.0</span>, <span style="color: #33f;">2.0</span>, <span style="color: #33f;">3.0</span>, <span style="color: #33f;">1.0</span>, <span style="color: #33f;">2.0</span>, <span style="color: #33f;">3.0</span>, <span style="color: #33f;">1.0</span>, <span style="color: #33f;">2.0</span>, <span style="color: #33f;">3.0</span>, <span style="color: #33f;">1.0</span>, <span style="color: #33f;">2.0</span>, <span style="color: #33f;">3.0</span><span style="color: #080;">&#93;</span>
&nbsp;
<span style="color: #228B22;">% Now convert into a Matlab cell array via a Java simple array</span>
&gt;&gt; mCellArray = jVector.<span style="">toArray</span>.<span style="color: #0000FF;">cell</span>
mCellArray = 
    <span style="color: #080;">&#91;</span><span style="color: #33f;">1</span><span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span><span style="color: #33f;">2</span><span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span><span style="color: #33f;">3</span><span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span><span style="color: #33f;">1</span><span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span><span style="color: #33f;">2</span><span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span><span style="color: #33f;">3</span><span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span><span style="color: #33f;">1</span><span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span><span style="color: #33f;">2</span><span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span><span style="color: #33f;">3</span><span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span><span style="color: #33f;">1</span><span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span><span style="color: #33f;">2</span><span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span><span style="color: #33f;">3</span><span style="color: #080;">&#93;</span></pre></div></div><h3 id="Performance">Performance</h3><p>It so happens, that the undocumented built-in <a
target="_blank" href="http://undocumentedmatlab.com/blog/undocumented-feature-function/"><i><b>feature</b></i> function</a> (or its near-synonym <i><b>system_dependent</b></i>) enables improved performance in this conversion process. <i><b>feature</b></i>(44) accepts a <code>java.util.Vector</code> and converts it directly into a Matlab cell-array, in one third to one-half the time that it would take the equivalent <i>toArray.cell()</i> (the third input argument is the number of columns in the result - the reshaping is done automatically):</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">&gt;&gt; mCellArray = feature<span style="color: #080;">&#40;</span><span style="color: #33f;">44</span>,jVector,jVector.<span style="color: #0000FF;">size</span><span style="color: #080;">&#41;</span>   <span style="color: #228B22;">% jVector.size = 12</span>
mCellArray = 
    <span style="color: #080;">&#91;</span><span style="color: #33f;">1</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">2</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">3</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">1</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">2</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">3</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">1</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">2</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">3</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">1</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">2</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">3</span><span style="color: #080;">&#93;</span>
&nbsp;
&gt;&gt; mCellArray = feature<span style="color: #080;">&#40;</span><span style="color: #33f;">44</span>,jVector,<span style="color: #33f;">4</span><span style="color: #080;">&#41;</span>
mCellArray = 
    <span style="color: #080;">&#91;</span><span style="color: #33f;">1</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">1</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">1</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">1</span><span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span><span style="color: #33f;">2</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">2</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">2</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">2</span><span style="color: #080;">&#93;</span>
    <span style="color: #080;">&#91;</span><span style="color: #33f;">3</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">3</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">3</span><span style="color: #080;">&#93;</span>    <span style="color: #080;">&#91;</span><span style="color: #33f;">3</span><span style="color: #080;">&#93;</span></pre></div></div><p>The conversion process is pretty efficient: On my system, the regular <i>toArray.cell()</i> takes 0.45 seconds for a 100K vector, compared to 0.21 seconds for the <i><b>feature</b></i> alternative. However, this small difference could be important in cases where performance is crucial, for example in <a
target="_blank" href="http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events/">processing of highly-active Java events in Matlab callbacks</a>, or when retrieving data from a database. And this latter case is indeed where a sample usage of this <i><b>feature</b></i> can be found, namely in the <i><b>cursor.fetch.m</b></i> function (where it appears as <i><b>system_dependent(44)</b></i>).</p><p>Please note that both <i><b>feature</b></i> and <i><b>system_dependent</b></i> are highly prone to change without prior warning in some future Matlab release. On the other hand, the conversion methods that I presented above, excluding <i><b>feature</b></i>, will probably still be valid in all Matlab releases in the near future.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/matlab-java-memory-leaks-performance/' rel='bookmark' title='Matlab-Java memory leaks, performance'>Matlab-Java memory leaks, performance</a> <small>Internal fields of Java objects may leak memory - this article explains how to avoid this without sacrificing performance. ...</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events/' rel='bookmark' title='Matlab callbacks for Java events'>Matlab callbacks for Java events</a> <small>Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how...</small></li><li><a
href='http://undocumentedmatlab.com/blog/java-stack-traces-in-matlab/' rel='bookmark' title='Java stack traces in Matlab'>Java stack traces in Matlab</a> <small>Matlab does not normally provide information about the Java calls on the stack trace. A simple trick can show us this information....</small></li><li><a
href='http://undocumentedmatlab.com/blog/jboost-integrating-an-external-java-library-in-matlab/' rel='bookmark' title='JBoost &#8211; Integrating an external Java library in Matlab'>JBoost &#8211; Integrating an external Java library in Matlab</a> <small>This article shows how an external Java library can be integrated in Matlab...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/converting-java-vectors-to-matlab-arrays/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Common javacomponent problems</title><link>http://undocumentedmatlab.com/blog/common-javacomponent-problems/</link> <comments>http://undocumentedmatlab.com/blog/common-javacomponent-problems/#comments</comments> <pubDate>Wed, 07 Dec 2011 18:00:38 +0000</pubDate> <dc:creator>Yair Altman</dc:creator> <category><![CDATA[GUI]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[Medium risk of breaking in future versions]]></category> <category><![CDATA[Semi-documented function]]></category> <category><![CDATA[Callbacks]]></category> <category><![CDATA[GUIDE]]></category><guid
isPermaLink="false">http://undocumentedmatlab.com/?p=2607</guid> <description><![CDATA[The javacomponent function is very useful for placing Java components on-screen, but has a few quirks.<pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/javacomponent/' rel='bookmark' title='The javacomponent function'>The javacomponent function</a> <small>Matlab's built-in javacomponent function can be used to display Java components in Matlab application - this article details its usages and limitations...</small></li><li><a
href='http://undocumentedmatlab.com/blog/javacomponent-background-color/' rel='bookmark' title='Javacomponent background color'>Javacomponent background color</a> <small>This article explains how to align Java component background color with a Matlab color....</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-and-the-event-dispatch-thread-edt/' rel='bookmark' title='Matlab and the Event Dispatch Thread (EDT)'>Matlab and the Event Dispatch Thread (EDT)</a> <small>The Java Swing Event Dispatch Thread (EDT) is very important for Matlab GUI timings. This article explains the potential pitfalls and their avoidance using undocumented Matlab functionality....</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-uitree-nodes-2/' rel='bookmark' title='Customizing uitree nodes &#8211; part 2'>Customizing uitree nodes &#8211; part 2</a> <small>This article shows how Matlab GUI tree nodes can be customized with checkboxes and similar controls...</small></li></ol><pre> </pre>]]></description> <content:encoded><![CDATA[<p>The <i><b>javacomponent</b></i> function, which I described <a
target="_blank" href="http://UndocumentedMatlab.com/blog/javacomponent/">here</a> last year, is a very important built-in Matlab function that enables placing Java components in Matlab figure GUI. Using <i><b>javacomponent</b></i> is pretty straight-forward. However, there are a few quirks that users should be aware of. In today&#8217;s article I&#8217;ll try to highlight some of them and discuss workarounds.</p><h3 id="figure-vis">Figure visibility</h3><p>Java components can only be placed onscreen when their containing Matlab figure has been made visible. This means that calls to <i><b>javacomponent</b></i> cannot be placed at the GUIDE-created *_OpeningFcn() function, because that function is invoked <i>before</i> the figure window is made visible.</p><p>Of course, we can always force the figure to become visible by setting the figure&#8217;s <b>Visible</b> property to <code>'on'</code> in this function, before calling our <i><b>javacomponent</b></i>s. But IMHO, a better option would be to simply place the <i><b>javacomponent</b></i>s in the corresponding GUIDE-created *_OutputFcn() function, which is invoked <i>after</i> the figure window is made visible.</p><h3 id="parent-vis">Auto-hiding with parent container</h3><p>Java components are not automatically hidden with their ancestor container panel. This is also the root cause of the failure of Java components to disappear when switching tabs in a <i><b>uitab</b></i>.</p><p>One simple workaround for this that I often use is to link the <b>Visible</b> properties of the <i><b>javacomponent</b></i> container and the parent container:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">jButton = javax.<span style="">swing</span>.<span style="">JButton</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'click me!'</span><span style="color: #080;">&#41;</span>;
<span style="color: #080;">&#91;</span>jhButton, hContainer<span style="color: #080;">&#93;</span> = javacomponent<span style="color: #080;">&#40;</span>jButton, <span style="color: #080;">&#91;</span><span style="color: #33f;">100</span>,<span style="color: #33f;">100</span>,<span style="color: #33f;">60</span>,<span style="color: #33f;">30</span><span style="color: #080;">&#93;</span>, hParent<span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">setappdata</span><span style="color: #080;">&#40;</span>hParent, <span style="color:#A020F0;">'linked_props__'</span>, linkprop<span style="color: #080;">&#40;</span><span style="color: #080;">&#91;</span>hParent,hContainer<span style="color: #080;">&#93;</span>,<span style="color:#A020F0;">'Visible'</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>This has indeed been fixed in R2010b. If you ask me, this should have been standard behavior of <i><b>javacomponent</b></i> since the very beginning&#8230;</p><p>Although there is no need for the workaround in R2010b onward, I usually keep the workaround because it doesn&#8217;t hurt and enables backward compatibility for users who may have an older Matlab release.</p><h3 id="parent-types">Possible parent container types</h3><p><i><b>javacomponent</b></i> accepts parent handles that are figures, toolbars, <i><b>uipanel</b></i>s, or <a
target="_blank" href="http://UndocumentedMatlab.com/blog/matlab-layout-managers-uicontainer-and-relatives"><i><b>uicontainer</b></i>s</a> (some of these are not documented as possible parents in some Matlab releases, but they are). Since R2008a, parents of type <a
target="_blank" href="http://undocumentedmatlab.com/blog/uisplittool-uitogglesplittool/"><i><b>uisplittool</b></i> and <i><b>uitogglesplittool</b></i></a> can also be used. Unfortunately, frames are not <i><b>uicontainer</b></i>s and, therefore, cannot be used as <i><b>javacomponent</b></i> parents.</p><p>Note: Due to a bug in R2007a, <i><b>javacomponent</b></i>s cannot be added to <i><b>uicontainer</b></i>s, since <i>javacomponent.m</i> checks if <code>isa(hParent,'uicontainer')</code> (and similarly for <code>'uiflowcontainer', 'uigridcontainer'</code>), instead of <code>isa(hParent,'hg.uicontainer')</code> (and similarly for the others). If we modify <i>javacomponent.m</i> accordingly (add &#8220;hg.&#8221; in lines 98-100), this bug will be fixed. Since R2007b, <code>isa(…,'hg.uicontainer')</code> is equivalent to <code>isa(…,'uicontainer')</code>, so this fix is unnecessary.</p><h3 id="inputs">Input parameters</h3><p>Unlike many other Matlab functions, <i><b>javacomponent</b></i> does not accept optional parameter-value (P-V) pairs. If we want to customize the appearance of the Java component, it is better to create it , customize it, and only then to present it onscreen using <i><b>javacomponent</b></i>. If we first present the component and then customize it, there might be all sorts of undesirable flicker effects while the component is changing its properties.</p><p>One of the parameters that unfortunately cannot be customized before calling <i><b>javacomponent</b></i> is the component&#8217;s position onscreen. <i><b>javacomponent</b></i> only accepts a position vector in pixel units. To modify the component to use normalized units, we need to modify the container&#8217;s properties:</p><div
class="wp_syntax"><div
class="code"><pre class="matlab" style="font-family:monospace;">jButton = javax.<span style="">swing</span>.<span style="">JButton</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'click me!'</span><span style="color: #080;">&#41;</span>;
<span style="color: #080;">&#91;</span>jhButton, hContainer<span style="color: #080;">&#93;</span> = javacomponent<span style="color: #080;">&#40;</span>jButton, <span style="color: #080;">&#91;</span><span style="color: #33f;">100</span>,<span style="color: #33f;">100</span>,<span style="color: #33f;">60</span>,<span style="color: #33f;">30</span><span style="color: #080;">&#93;</span>, <span style="color: #0000FF;">gcf</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">set</span><span style="color: #080;">&#40;</span>hContainer, <span style="color:#A020F0;">'Units'</span>,<span style="color:#A020F0;">'norm'</span><span style="color: #080;">&#41;</span>;</pre></div></div><p>Similarly, we can set the container&#8217;s <b>UserData</b> and <b>ApplicationData</b> only after the call to <i><b>javacomponent</b></i>.</p><h3 id="bg-color">Background color</h3><p>The default background color of <i><b>javacomponent</b></i>s is a slightly different shade of gray than the default <i><b>uicontrol</b></i> background color. Please refer to my recent <a
target="_blank" href="http://UndocumentedMatlab.com/blog/javacomponent-background-color/">article</a> for a detailed discussion of this issue.</p><h3 id="alignment">Vertical alignment</h3><p>Java components are slightly mis-aligned vertically with combo-box (<b>Style</b>=&#8217;popup&#8217;) <i><b>uicontrol</b></i>s, even when positioned using the same Y position. This is actually due to an apparent bug in Matlab&#8217;s implementation of the combo-box <i><b>uicontrol</b></i>, and not in the Java component&#8217;s: Apparently, the Matlab control does not obey its specified height and uses some other default height.</p><p>If we place <i><b>javacomponent</b></i>s side-by-side with a regular Matlab popup <i><b>uicontrol</b></i>s and give them all the same Y position, we can see this mis-alignment. It is only a few pixels, but the effect is visible and disturbing. To fix it, we need to add a small offset to the <i><b>javacomponent</b></i>&#8216;s container&#8217;s <b>Position</b> property to make both the initial Y position slightly lower, and the height value slightly higher than the values for the corresponding Matlab combo-box control.</p><h3 id="callbacks">Callbacks</h3><p>Unlike Matlab <i><b>uicontrol</b></i> callbacks, Java callbacks are activated even when the affected value does not change. Therefore, setting a value in the component&#8217;s callback could well cause an infinite loop of invoked callbacks.</p><p>Matlab programmers often use the practice of modifying component value within the callback function, as a means of fixing user-entered values to be within a certain data range, or in order to format the displayed value. This is relatively harmless in Matlab (if done correctly) since updating a Matlab <i><b>uicontrol</b></i>&#8216;s value to the current value does not retrigger the callback. But since this is not the case with Java callbacks, users should beware not to use the same practice there. In cases where this cannot be avoided, users should at least implement some sort of <a
target="_blank" href="http://undocumentedmatlab.com/blog/controlling-callback-re-entrancy/">callback re-entrancy prevention logic</a>.</p><h3 id="EDT">EDT</h3><p>Java components typically need to use the independent Java Event processing Thread (EDT). EDT is very important for Matlab GUI, as explained in <a
target="_blank" href="http://undocumentedmatlab.com/blog/matlab-and-the-event-dispatch-thread-edt/">this article</a>. Failure to use EDT properly in Matlab can lead to unexpected GUI behavior and even Matlab hangs or crashes.</p><p>If the <i><b>javacomponent</b></i> function is called in a very specific syntax format where the first input arg is a string (the name of the Java class to be created), then the newly-created component is placed on the EDT. However, this is not the normal manner in which <i><b>javacomponent</b></i> is used: A much more typical use-case is where <i><b>javacomponent</b></i> is passed a reference handle to a previously-created Java component. In such cases, it is the user&#8217;s responsibility to place the component on the EDT. Until R2008a this should be done using the <i><b>awtcreate</b></i> function; since R2008b, we can use the much simpler <i><b>javaObjectEDT</b></i> function (<i><b>javaObjectEDT</b></i> actually existed since R2008a, but was buggy on that release so I suggest using it only starting in R2008b; it became documented starting in R2009a). In fact, modern <i><b>javacomponent</b></i> saves us the trouble, by automatically using <i><b>javaObjectEDT</b></i> to auto-delegate the component onto the EDT, even if we happen to have created it on the MT.</p><p>The paragraph above may lead us to believe that we only need to worry about EDT in R2008a and earlier. Unfortunately, this is not the case. Modern GUI requires using many sub-components, that are attached to their main component (e.g., CellRenderers and CellEditors). <i><b>javacomponent</b></i> only bothers to place the main component on the EDT &#8211; not any of the sub-components. We need to handle these separately. Liberally auto-delegating components to the EDT seems like a safe and painless habit to have.</p><p><pre> </pre>Related posts:<ol><li><a
href='http://undocumentedmatlab.com/blog/javacomponent/' rel='bookmark' title='The javacomponent function'>The javacomponent function</a> <small>Matlab's built-in javacomponent function can be used to display Java components in Matlab application - this article details its usages and limitations...</small></li><li><a
href='http://undocumentedmatlab.com/blog/javacomponent-background-color/' rel='bookmark' title='Javacomponent background color'>Javacomponent background color</a> <small>This article explains how to align Java component background color with a Matlab color....</small></li><li><a
href='http://undocumentedmatlab.com/blog/matlab-and-the-event-dispatch-thread-edt/' rel='bookmark' title='Matlab and the Event Dispatch Thread (EDT)'>Matlab and the Event Dispatch Thread (EDT)</a> <small>The Java Swing Event Dispatch Thread (EDT) is very important for Matlab GUI timings. This article explains the potential pitfalls and their avoidance using undocumented Matlab functionality....</small></li><li><a
href='http://undocumentedmatlab.com/blog/customizing-uitree-nodes-2/' rel='bookmark' title='Customizing uitree nodes &#8211; part 2'>Customizing uitree nodes &#8211; part 2</a> <small>This article shows how Matlab GUI tree nodes can be customized with checkboxes and similar controls...</small></li></ol></p><pre> </pre>]]></content:encoded> <wfw:commentRss>http://undocumentedmatlab.com/blog/common-javacomponent-problems/feed/</wfw:commentRss> <slash:comments>2</slash:comments> </item> </channel> </rss>

<!-- W3 Total Cache: Minify debug info:
Engine:             disk: basic
Theme:              b7666
Template:           category
-->
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Served from: undocumentedmatlab.com @ 2012-05-18 21:34:49 -->

<!-- W3 Total Cache: Page cache debug info:
Engine:             disk: enhanced
Cache key:          blog/category/java/feed/_index.xml_gzip
Caching:            enabled
Status:             not cached
Creation Time:      2.713s
Header info:
X-Pingback:         http://undocumentedmatlab.com/blog/xmlrpc.php
Set-Cookie:         wpgb_visit_last_php-default=1337402086; expires=Sun, 19-May-2013 04:34:46 GMT; path=/
Content-Type:       text/xml; charset=UTF-8
Last-Modified:      Sat, 19 May 2012 04:34:49 GMT
Vary:               Accept-Encoding, Cookie
Expires:            Sat, 19 May 2012 05:34:49 GMT
Pragma:             public
Cache-Control:      public, must-revalidate, proxy-revalidate
Etag:               93900c73aa625511c44d688568735fb5
Content-Encoding:   gzip
-->
