<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Jayway Team Blog » Embedded</title>
	
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<pubDate>Wed, 18 Mar 2009 10:13:15 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.7</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/jayway/posts/embedded" /><feedburner:info uri="jayway/posts/embedded" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>iPhone OS and the Lowest Common Denominator</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/embedded/~3/BotKwlXIdXk/</link>
		<comments>http://blog.jayway.com/2009/03/18/iphone-os-and-the-lowest-common-denominator/#comments</comments>
		<pubDate>Wed, 18 Mar 2009 10:04:00 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
		
		<category><![CDATA[Architecture]]></category>

		<category><![CDATA[Embedded]]></category>

		<category><![CDATA[Innovation]]></category>

		<category><![CDATA[apple]]></category>

		<category><![CDATA[iphone]]></category>

		<category><![CDATA[java]]></category>

		<category><![CDATA[sdk]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1178</guid>
		<description><![CDATA[Nishant wrote a good piece on why Apple continue to outdo it's rivals, he used a variant of a quote by Canadian hockey player Wayne Gretzky to make his point:
A good hockey player plays where the puck is. A great hockey player plays where the puck is going to be.
This is true as it stands, [...]]]></description>
			<content:encoded><![CDATA[<p>Nishant wrote a good piece on <a href="http://news.worldofapple.com/archives/2009/03/17/wayne-gretzky-and-why-apple-continues-to-outdo-its-rivals/">why Apple continue to outdo it's rivals</a>, he used a variant of a quote by Canadian hockey player Wayne Gretzky to make his point:</p>
<blockquote><p>A good hockey player plays where the puck is. A great hockey player plays where the puck is going to be.</p></blockquote>
<p>This is true as it stands, but I think the main reason why Apple can keep a pace and a high standard of inovation is because of how they manage the Lowest Common Denominator. And iPhone OS with App Store is the crown jewel.</p>
<h3>Technology vs. User Base</h3>
<p>The lowest common denominator is always of interest when developing applications and services for the end user with profit interests. The lowest common denominator is what defines your user base, and it is a hard game of balance. Sticking to the newest technology will allow you to progress faster with more elegant solutions, whereas using a more commonly available technology will give you a larger user base.</p>
<p>So the lowest common denominator should be as high as possible, while still economical. With Java ME a bold effort to rise the bar of the lowest common denominator is the <a href="http://jcp.org/en/jsr/detail?id=248">MSA JSR-248</a>. An effort to give Java ME developers a guarantee minimum of features. A noble effort, but in reality up to a year ago only Sony Ericsson was MSA compliant, making the aged MIDP 2.0 the de-facto lowest common denominator for any developer targeting a the majority of Java ME devices.</p>
<p>The lowest common denominator for an average Java ME developer is the MIDP 2.0 spec from 2002.</p>
<h3>iTunes as a Hub</h3>
<p>Apple has a different situation, largely due to it's decision to use iTunes as the hub for all mobile devices, iPods as well as iPhones. All iPods and iPhones charges the battery by plugging in the USB-cable to your computer, this have some large but not obvious benefits.</p>
<p>Most notably Apple knows with 100% certainty that all users will have their devices on a reliable and controlled connection often, in most cases on a daily basis. As the users also use iTunes to synchronize their media, any other synchronization is not a hassle but rather a bonus on top of something they already requested.</p>
<p>Adding software updates on top of synchronizing media and data content through iTunes is just genius. It is a two click operation for the user, and as a result Apple virtually guaranteed that all iPod and iPhone users have <a href="http://www.theiphoneblog.com/2009/03/14/iphone-firmware-running/">the very latest software installed</a> on their device.</p>
<h3>Back-porting Software</h3>
<p>Apart from the technology decision with iTunes as a hub, Apple have also made a business decision by always back porting their latest software to all iPhone OS powered devices. iPhone OS 2.0 can be installed on any first generation iPod Touch or iPhone, and with iPhone OS 3.0 this summer all three generations will be supported.</p>
<p>This back-porting model is the total oposite of almost all competitors, where instead new features are explicitly locked to the latest hardware in order to sell devices. So if the end users can get all the new iPhone 3.0 as a free download, why should they buy new hardware? Will not Apple loose revenue on unsold third generation iPhone devices? </p>
<p>In short term probably will, but the big win is <strong>the Lowest Common Denominator</strong>. Whereas the competition have a common lowest denominator of several years, almost a decade, Apple and all of Apple's third party developers have a lowest common denominator of virtually weeks.</p>
<h3>Conclusion</h3>
<p>With a simple software distribution model that guarantees the lowest common denominator Apple has guaranteed that the common lowest denominator is the current software, period. This allows Apple, and all third party developer creating applications and services for their devices, the luxury of discarding all effort for backward compatibility, and technological compromises.</p>
<p>Apple and we are allowed to innovate with full steam ahead.</p>
<img src="http://feeds.feedburner.com/~r/jayway/posts/embedded/~4/BotKwlXIdXk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/03/18/iphone-os-and-the-lowest-common-denominator/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.jayway.com/2009/03/18/iphone-os-and-the-lowest-common-denominator/</feedburner:origLink></item>
		<item>
		<title>Hidden methods in Sony Ericsson Java Platform</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/embedded/~3/DBKOXppdusk/</link>
		<comments>http://blog.jayway.com/2009/03/09/hidden-methods-in-sony-ericsson-java-platform/#comments</comments>
		<pubDate>Mon, 09 Mar 2009 07:58:00 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
		
		<category><![CDATA[Embedded]]></category>

		<category><![CDATA[Frameworks]]></category>

		<category><![CDATA[java]]></category>

		<category><![CDATA[mobile]]></category>

		<category><![CDATA[tips]]></category>

		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1069</guid>
		<description><![CDATA[It is no secret that the published interfaces for MIDP classes in any JavaME Platform is only a subset of what in reality is there. Most of the native calls needed to interact with the underlying native platform, and other helper methods, are hidden from us. Mostly for good, and sometimes for bad...
The Anecdotal History
We [...]]]></description>
			<content:encoded><![CDATA[<p>It is no secret that the published interfaces for MIDP classes in any JavaME Platform is only a subset of what in reality is there. Most of the native calls needed to interact with the underlying native platform, and other helper methods, are hidden from us. Mostly for good, and sometimes for bad...</p>
<h3>The Anecdotal History</h3>
<p>We are developing a custom application framework on top of MIDP, adding a MVC application model, and modern interface components with touch and animation support. All this is build on top of a shared subclass of <code>Canvas</code>, and our own custom drawing with screen transitions, etc. is implemented on top of that.</p>
<p>An interface component is called a <code>View</code>, and any interface component that can host other interface components implements the <code>ViewParent</code> interface. Simple until I introduces the method <code>hasFocus()</code>. All of a sudden the application refused to run on target Sony Ericsson device. The emulator worked nice, our P1i worked, even the Xperia X1 run. But none of the cybershots, or walkmans with JP-7 or JP-8.</p>
<p><em>"Application error</em>". Oh well, that means that something threw an exception during the MIDlet constructor or <code>appStart()</code> call. So add pedantic catches, and display the error in an <code>Alert</code>; <em>"NoClassDefFoundError"</em>.</p>
<h3>The Problem</h3>
<p><code>NoClassDefFoundError</code> on the OSE phones, but no other installed with the same jad/jar-files, that is strange. Unfortunately Sony Ericsson has a policy of removing all error messages from exceptions, so no clue as to what class is missing either. Turn off Proguard optimization, still does not work, still <code>NoClassDefFoundError</code>. Head back to the Subversion logs and binary search, what is the latest revision that worked? And what was changed?</p>
<p>Turnes out that the shared <code>Canvas</code> subclass that implement the aforementioned interface <code>ViewParent</code> got the new method <code>hasFocus()</code>, and that is the only change from the working revision, to the broken revision.</p>
<p><em>- "I'm pretty sure that is working."</em>, one of the half dozen bug-hunting team member said looking at:
<pre class="java"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">boolean</span> hasFocus<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">true</span>;
<span style="color: #66cc66;">&#125;</span></pre>
<p>As it turns out the platform implementation of the MIDP class <code>Canvas</code> has a hidden method named <code>hasFocus()</code>. It is not <code>private</code>, but declared as <code>public</code> and <code>final</code>, but not exposed in the public API. So when our subclass is loaded, our <code>public hasFocus()</code> method clashes with the unexposed <code>public final hasFocus()</code> of the platform's implementation.</p>
<h3>Solution, and Lesson Learned</h3>
<p>The method <code>hasFocus()</code> was renamed to <code>isInFocus()</code>, and now everything works again.</p>
<p>From now on we will:</p>
<ul>
<li>Never trust subclasses of MIDP classes.</li>
<li>Test on device early and often, also for obvious changes.</li>
<li>Always keep commits small and atomic.</li>
</ul>
<img src="http://feeds.feedburner.com/~r/jayway/posts/embedded/~4/DBKOXppdusk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/03/09/hidden-methods-in-sony-ericsson-java-platform/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.jayway.com/2009/03/09/hidden-methods-in-sony-ericsson-java-platform/</feedburner:origLink></item>
		<item>
		<title>Proxy Based AOP for Cocoa Touch</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/embedded/~3/5u937TTStAE/</link>
		<comments>http://blog.jayway.com/2009/03/06/proxy-based-aop-for-cocoa-touch/#comments</comments>
		<pubDate>Fri, 06 Mar 2009 14:46:33 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
		
		<category><![CDATA[Embedded]]></category>

		<category><![CDATA[Frameworks]]></category>

		<category><![CDATA[Programming]]></category>

		<category><![CDATA[aop]]></category>

		<category><![CDATA[iphone]]></category>

		<category><![CDATA[objective-c]]></category>

		<category><![CDATA[proxy]]></category>

		<category><![CDATA[reflection]]></category>

		<category><![CDATA[tips]]></category>

		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1041</guid>
		<description><![CDATA[UITabBarController is generally used as is, no subclassing required. It creates a UITabBar and manages a list of UIViewControllers, keeping track of the tab in focus, UI creation and everything nice. UITabBarController has a delegate, the UITabBarControllerDelegate protocol. Unfortunately this is not a superset of the UITabBarDelegate protocol, and UITabBarController already implements the UITabBarDelegate protocol [...]]]></description>
			<content:encoded><![CDATA[<p><code>UITabBarController</code> is generally used as is, no subclassing required. It creates a <code>UITabBar</code> and manages a list of <code>UIViewControllers</code>, keeping track of the tab in focus, UI creation and everything nice. <code>UITabBarController</code> has a delegate, the <code>UITabBarControllerDelegate</code> protocol. Unfortunately this is not a superset of the <code>UITabBarDelegate</code> protocol, and <code>UITabBarController</code> already implements the <code>UITabBarDelegate</code> protocol itself. So how can I hook into and respond to delegate calls from the managed <code>UITabBar</code>?</p>
<p>Simply replacing the original delegate will break the default functionality. We need to somehow insert our own code to execute before the original delegates call. Or in AOP speak; a before advice.</p>
<h3>The Wanted Solution</h3>
<p>What we want is a proxy that can forward invocations both to our own delegate, and to the original delegate. The interface for said class looks looks like this:</p>
<pre class="objc"><span style="color: #0000ff;">@protocol</span> CWDelegateOverrideProxyDelegate
@required
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">BOOL</span><span style="color: #002200;">&#41;</span>shouldCallOriginalImplementationForSelector:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector;
<span style="color: #0000ff;">@end</span>
&nbsp;
<span style="color: #0000ff;">@interface</span> CWDelegateOverrideProxy : <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSProxy.html"><span style="color: #0000ff;">NSProxy</span></a> <span style="color: #002200;">&#123;</span>
<span style="color: #0000ff;">@private</span>
  id&lt;NSObject&gt; _originalDelegate;
  id&lt;NSObject&gt; _overrideingDelegate;
  id&lt;CWDelegateOverrideProxyDelegate&gt; _delegate;
<span style="color: #002200;">&#125;</span>
&nbsp;
@property<span style="color: #002200;">&#40;</span>nonatomic, retain, readonly<span style="color: #002200;">&#41;</span> id&lt;NSObject&gt; originalDelegate;
@property<span style="color: #002200;">&#40;</span>nonatomic, retain, readonly<span style="color: #002200;">&#41;</span> id&lt;NSObject&gt; overridingDelegate;
@property<span style="color: #002200;">&#40;</span>nonatomic, assign<span style="color: #002200;">&#41;</span> id&lt;CWDelegateOverrideProxyDelegate&gt; delegate;
&nbsp;
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>initWithOriginalDelegate:<span style="color: #002200;">&#40;</span>id&lt;NSObject&gt;<span style="color: #002200;">&#41;</span>originalDelegate
     overridingDelegate:<span style="color: #002200;">&#40;</span>id&lt;NSObject&gt;<span style="color: #002200;">&#41;</span>overridingDelegate;
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<p>And then we could use this class to replace an existing delegate with a short piece fo code like this:</p>
<pre class="objc">UITabBar* tabBar = <span style="color: #002200;">&#40;</span>UITabBar*<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#91;</span>self.tabBarController.view
    viewWithKindOfClass:<span style="color: #002200;">&#91;</span>UITabBar <span style="color: #0000ff;">class</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
CWDelegateOverrideProxy* proxy = <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>CWDelegateOverrideProxy alloc<span style="color: #002200;">&#93;</span>
    initWithOriginalDelegate:tabBar.delegate overridingDelegate:self<span style="color: #002200;">&#93;</span>;
tabBar.delegate = <span style="color: #002200;">&#40;</span>id&lt;UITabBarDelegate&gt;<span style="color: #002200;">&#41;</span>proxy;</pre>
<p>See <a href="http://blog.jayway.com/2009/02/24/finding-subview-of-a-particular-class-in-cocoa/">my previous post</a> for the implementation of <code>viewWithKindOfClass:</code>.</p>
<p>Easy enough to use, only thing left is to implement <code>CWDelegateOverrideProxy</code>.</p>
<h3>Enter <code>NSProxy</code></h3>
<p>Java only have one root class; <code>java.lang.Object</code>. Objective-C can have many, and Cocoa defines two; <code>NSObject</code> and <code>NSProxy</code>. Both of them conforms to the protocol <code>NSObject</code>, wich can be confusing. What we need to know is that class names, and protocol names have two different name spaces in Objective-C. Imagine it as if you could have a class and an interface with the same name in Java; in Objective-C you can. <code>NSObject</code> class is the root class for all concrete classes, and <code>NSProxy</code> class is the root class for proxies, both implements <code>NSObject</code> protocol allowing them to be interchangeable.</p>
<p>Without much ado, here is the base implementation for the initializer:</p>
<pre class="objc"><span style="color: #339900;">#import &quot;CWDelegateOverrideProxy.h&quot;</span>
&nbsp;
<span style="color: #0000ff;">@implementation</span> CWDelegateOverrideProxy
&nbsp;
@synthesize originalDelegate = _originalDelegate;
@synthesize overridingDelegate = _overridingDelegate;
@synthesize delegate = _delegate;
&nbsp;
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>initWithOriginalDelegate:<span style="color: #002200;">&#40;</span>id&lt;NSObject&gt;<span style="color: #002200;">&#41;</span>originalDelegate
     overridingDelegate:<span style="color: #002200;">&#40;</span>id&lt;NSObject&gt;<span style="color: #002200;">&#41;</span>overridingDelegate;
<span style="color: #002200;">&#123;</span>
  _originalDelegate = <span style="color: #002200;">&#91;</span>originalDelegate retain<span style="color: #002200;">&#93;</span>;
  _overridingDelegate = <span style="color: #002200;">&#91;</span>overridingDelegate retain<span style="color: #002200;">&#93;</span>;
  <span style="color: #0000ff;">return</span> self;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #ff0000;">// More code goes here!</span>
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<h3>Introspection</h3>
<p>In Objective-C, just as in Java, an instance can be queried for its class, and conformance to protocols (interface in Java speak). But as a bonus an instance can also be queried for specific methods per instance.</p>
<p>Our <code>CWDelegateOverrideProxy</code> class inherits from <code>NSProxy</code>. And it makes a simple assumption; if the original delegate, or the overriding delegate is capable of something, then so it is. So if queried for type of class, protocol conformance, or implemented methods, then we reply with whatever our managed delegates replies.</p>
<p>The <code>NSObject</code> protocol defines methods, equivalent of the <code>java.lang.reflect</code> package, that allows us to implement this as such:</p>
<pre class="objc"><span style="color: #339900;">#pragma mark --- Testing Object Behavior, and Conformance</span>
&nbsp;
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">BOOL</span><span style="color: #002200;">&#41;</span>isKindOfClass:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">Class</span><span style="color: #002200;">&#41;</span>aClass;
<span style="color: #002200;">&#123;</span>
  <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#91;</span>self.overridingDelegate isKindOfClass:aClass<span style="color: #002200;">&#93;</span> ||
         <span style="color: #002200;">&#91;</span>self.originalDelegate isKindOfClass:aClass<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">BOOL</span><span style="color: #002200;">&#41;</span>conformsToProtocol:<span style="color: #002200;">&#40;</span>Protocol *<span style="color: #002200;">&#41;</span>aProtocol;
<span style="color: #002200;">&#123;</span>
  <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#91;</span>self.overridingDelegate conformsToProtocol:aProtocol<span style="color: #002200;">&#93;</span> ||
         <span style="color: #002200;">&#91;</span>self.originalDelegate conformsToProtocol:aProtocol<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">BOOL</span><span style="color: #002200;">&#41;</span>respondsToSelector:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector;
<span style="color: #002200;">&#123;</span>
  <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#91;</span>self.overridingDelegate respondsToSelector:aSelector<span style="color: #002200;">&#93;</span> ||
         <span style="color: #002200;">&#91;</span>self.originalDelegate respondsToSelector:aSelector<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre>
<h3>Invocation Forwarding</h3>
<p>The <code>NSObject</code> protocol also defines methods for functionality equivalent of <code>java.lang.reflect.InvocationHandler</code> and hooks to act as a <code>java.lang.reflect.Proxy</code>. The details are different as Objective-C do not enforce calls to only known methods at compile time, which means that at run-time unimplemented methods can be called.</p>
<p>When an unimplemented method is called the run-time will call <code>methodSignatureForSelector:</code>, that can return a <code>NSMethodSignature</code> instance, sort of the equivalent of a <code>java.lang.reflect.Method</code>. The run-time will then use the information from the <code>NSMethodSignature</code> instance to create a correct <code>NSInvocation</code> (other half of a <code>java.lang.reflect.Method</code>) instance, and set the correct arguments. This NSInvocation instance is then used as argument to call <code>forwardInvocation:</code>.</p>
<p>And thus our implementation is completed with:</p>
<pre class="objc"><span style="color: #339900;">#pragma mark --- Handling Proxy Methods</span>
&nbsp;
-<span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSMethodSignature.html"><span style="color: #0000ff;">NSMethodSignature</span></a>*<span style="color: #002200;">&#41;</span>methodSignatureForSelector:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector;
<span style="color: #002200;">&#123;</span>
  <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>self.overridingDelegate respondsToSelector:aSelector<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#91;</span>self.overridingDelegate methodSignatureForSelector:aSelector<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#125;</span> <span style="color: #0000ff;">else</span> <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>self.originalDelegate respondsToSelector:aSelector<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#91;</span>self.originalDelegate methodSignatureForSelector:aSelector<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#125;</span> <span style="color: #0000ff;">else</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#91;</span>super methodSignatureForSelector:aSelector<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>forwardInvocation:<span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSInvocation.html"><span style="color: #0000ff;">NSInvocation</span></a>*<span style="color: #002200;">&#41;</span>anInvocation;
<span style="color: #002200;">&#123;</span>
  <span style="color: #0000ff;">BOOL</span> shouldCallOriginal = YES;
  <span style="color: #0000ff;">SEL</span> aSelector = <span style="color: #002200;">&#91;</span>anInvocation selector<span style="color: #002200;">&#93;</span>;
  <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>self.overridingDelegate respondsToSelector:aSelector<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>anInvocation setTarget:self.overridingDelegate<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>anInvocation invoke<span style="color: #002200;">&#93;</span>;
    <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>self.delegate != <span style="color: #0000ff;">nil</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
      shouldCallOriginal = <span style="color: #002200;">&#91;</span>self.delegate shouldCallOriginalImplementationForSelector:aSelector<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
  <span style="color: #002200;">&#125;</span>
  <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>shouldCallOriginal &amp;&amp; <span style="color: #002200;">&#91;</span>self.originalDelegate respondsToSelector:aSelector<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>anInvocation setTarget:self.originalDelegate<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>anInvocation invoke<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre>
<p>And that rounds up how to implement a class that handles proxy based AOP, in order to introduce a before advice for delegate methods. For a more complex code base you can look at <a href="http://sourceforge.net/projects/hessiankit/">HessianKit</a>, a framework that uses proxies, invocation forwarding and dynamic class creation in order to use a web service as distributed objects.</p>
<img src="http://feeds.feedburner.com/~r/jayway/posts/embedded/~4/5u937TTStAE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/03/06/proxy-based-aop-for-cocoa-touch/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.jayway.com/2009/03/06/proxy-based-aop-for-cocoa-touch/</feedburner:origLink></item>
		<item>
		<title>Finding Subview of a Particular Class in Cocoa</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/embedded/~3/WKUU7SNDf6k/</link>
		<comments>http://blog.jayway.com/2009/02/24/finding-subview-of-a-particular-class-in-cocoa/#comments</comments>
		<pubDate>Tue, 24 Feb 2009 16:52:17 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
		
		<category><![CDATA[Embedded]]></category>

		<category><![CDATA[Frameworks]]></category>

		<category><![CDATA[Programming]]></category>

		<category><![CDATA[iphone]]></category>

		<category><![CDATA[mobile]]></category>

		<category><![CDATA[objective-c]]></category>

		<category><![CDATA[tips]]></category>

		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1008</guid>
		<description><![CDATA[Many of the UIView subclasses in Cocoa, and especially Cocoa Touch are created by combining many different simple views into a more complex view. UITableViewCell is a good example, concisting of almost a dozen subviews, UIImageView for the image, UILabel for the text, etc.
It is often nice to be able to reuse existing functionality when [...]]]></description>
			<content:encoded><![CDATA[<p>Many of the <code>UIView</code> subclasses in Cocoa, and especially Cocoa Touch are created by combining many different simple views into a more complex view. <code>UITableViewCell</code> is a good example, concisting of almost a dozen subviews, <code>UIImageView</code> for the image, <code>UILabel</code> for the text, etc.</p>
<p>It is often nice to be able to reuse existing functionality when you subclass <code>UITableViewCell</code>. Properties such as image and <code>textColor</code> maps directly to the embedded <code>UILabel</code> and <code>UIImageView</code> subviews, and reimplementing them all when introducing a custom layout is tedious and error prone. Would it not be better to be able to get access to the original subview instances and just add a custom layout to them?</p>
<h3>You can find subviews by class</h3>
<p>Would it not be nice if the Cocoa Touch framework had a method such as this:</p>
<pre class="objc">- <span style="color: #002200;">&#40;</span>UIView*<span style="color: #002200;">&#41;</span>viewWithKindOfClass:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">Class</span><span style="color: #002200;">&#41;</span>aClass;</pre>
<p>Kind of like what <code>viewWithTag:</code>, does but instead of searching for a subview matching a tag, it searches for a subview matching a class.</p>
<p>Good news for us is that this is very easy to implement, by just adding a new category to <code>UIView</code>. Add a new .h/.m file pair to your Xcode project and type this down in the header file:</p>
<pre class="objc"><span style="color: #339900;">#import &lt;UIKit/UIKit.h&gt;</span>
&nbsp;
<span style="color: #0000ff;">@interface</span> UIView <span style="color: #002200;">&#40;</span>CWViewWithKindOfClass<span style="color: #002200;">&#41;</span>
&nbsp;
- <span style="color: #002200;">&#40;</span>UIView*<span style="color: #002200;">&#41;</span>viewWithKindOfClass:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">Class</span><span style="color: #002200;">&#41;</span>aClass;
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<p>Now we have to implement it. The existing <code>viewWithTag:</code> method is not documented as such, but my experimentation tells me that it uses a breadth first search algorithm. Quite logical as the wanted subview most commonly is close to the root view, and we want to find it fast. Since <code>viewWithTag:</code> always returns the first found matching view, we can do the same assumption.</p>
<p>The quite short implementation goes like this:</p>
<pre class="objc"><span style="color: #339900;">#import &quot;UIView+CWViewWithKindOfClass.h&quot;</span>
&nbsp;
<span style="color: #0000ff;">@implementation</span> UIView <span style="color: #002200;">&#40;</span>CWViewWithKindOfClass<span style="color: #002200;">&#41;</span>
&nbsp;
- <span style="color: #002200;">&#40;</span>UIView*<span style="color: #002200;">&#41;</span>viewWithKindOfClass:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">Class</span><span style="color: #002200;">&#41;</span>aClass;
<span style="color: #002200;">&#123;</span>
  <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSMutableArray.html"><span style="color: #0000ff;">NSMutableArray</span></a>* nodeQueue = <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSMutableArray.html"><span style="color: #0000ff;">NSMutableArray</span></a> arrayWithObject:self<span style="color: #002200;">&#93;</span>;
  <span style="color: #0000ff;">while</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>nodeQueue count<span style="color: #002200;">&#93;</span> &gt; <span style="color: #0000dd;">0</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    UIView* node = <span style="color: #002200;">&#91;</span>nodeQueue objectAtIndex:<span style="color: #0000dd;">0</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>nodeQueue removeObjectAtIndex:<span style="color: #0000dd;">0</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>node isKindOfClass:aClass<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
      <span style="color: #0000ff;">return</span> node;
    <span style="color: #002200;">&#125;</span> <span style="color: #0000ff;">else</span> <span style="color: #002200;">&#123;</span>
      <span style="color: #002200;">&#91;</span>nodeQueue addObjectsFromArray:node.subviews<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
  <span style="color: #002200;">&#125;</span>
  <span style="color: #0000ff;">return</span> <span style="color: #0000ff;">nil</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<p>And that is it, not you can use it with something like for example this:</p>
<pre class="objc">UITabBar* tabBar = <span style="color: #002200;">&#91;</span>myTabBarController.view viewWithKindOfClass:<span style="color: #002200;">&#91;</span>UITabBar <span style="color: #0000ff;">class</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;</pre>
<p>Wich is an introduction to a future post, where I will discuss how to access the managed <code>UITabBar</code> of a <code>UITabBarController</code>, and introduce a <code>UITabBarDelegate</code> without interfering with the delegate already in place from the Cocoa Touch framework.</p>
<img src="http://feeds.feedburner.com/~r/jayway/posts/embedded/~4/WKUU7SNDf6k" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/02/24/finding-subview-of-a-particular-class-in-cocoa/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.jayway.com/2009/02/24/finding-subview-of-a-particular-class-in-cocoa/</feedburner:origLink></item>
		<item>
		<title>Fixing Image#getRGB()</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/embedded/~3/dREH6cYdDA0/</link>
		<comments>http://blog.jayway.com/2009/01/17/fixing-imagegetrgb/#comments</comments>
		<pubDate>Sat, 17 Jan 2009 11:47:25 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
		
		<category><![CDATA[Embedded]]></category>

		<category><![CDATA[Programming]]></category>

		<category><![CDATA[java]]></category>

		<category><![CDATA[midp]]></category>

		<category><![CDATA[mobile]]></category>

		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=813</guid>
		<description><![CDATA[I have encountered a problem when implementing a nine-patch painter for MIDP 2.0, most of my graphics where left transparent for no-reason. A nine-patch is an image with a flexible center row, and a flexible center column. Most useful when doing themed UI, as a single image can be used to draw buttons, and boxes [...]]]></description>
			<content:encoded><![CDATA[<p>I have encountered a problem when implementing a nine-patch painter for MIDP 2.0, most of my graphics where left transparent for no-reason. A nine-patch is an image with a flexible center row, and a flexible center column. Most useful when doing themed UI, as a single image can be used to draw buttons, and boxes of any sizes. </p>
<p>The four corners are coped as is, the four borders scaled in a single direction, and the center is scaled in both directions. Since MIDP do not support image scaling this must be implemented by hand using the ARGB values fetched using <code>Image#getRGB()</code>. The documentation is quite straight forward, but fail to mention one pecularity in many implementation...</p>
<h3>Clearing unwanted data</h3>
<p>I want to create the target image in a single <code>int[]</code> array to reduce memory usage. No problem copying image data into this structure, it is just what the quite straightforward API is designed to do:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> getRGB<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> rgbData,
                   <span style="color: #993333;">int</span> offset, <span style="color: #993333;">int</span> scanlength,
                   <span style="color: #993333;">int</span> x, <span style="color: #993333;">int</span> y,
                   <span style="color: #993333;">int</span> width, <span style="color: #993333;">int</span> height<span style="color: #66cc66;">&#41;</span></pre>
<p>Unfortunately the documentation fails to mention that many implementations will not as expected just ignore data in <code>rgbData</code> that is not copied. Instead zeroes, or transparent pixels, will be filled in for any image data that has not been requested on a per row basis. I dare anyone to find where this is mentioned in the <a href="http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Image.html">MIDP spec</a>.</p>
<h3>A solution</h3>
<p>The solution is to write your own wrapper method for <code>Image#getRGB()</code> that copies just a single row of image data at a time, and the requested scanline length must be lied about to avoid having the remainder of lines filled with zeroes. Here is tho code ready for copy and paste:</p>
<pre class="java"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ImageUtils <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #993333;">void</span> getRGBFromImage<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AImage+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Image</span></a> image, <span style="color: #993333;">int</span><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> argbData, <span style="color: #993333;">int</span> offset,
            <span style="color: #993333;">int</span> scanline, <span style="color: #993333;">int</span> x, <span style="color: #993333;">int</span> y, <span style="color: #993333;">int</span> width, <span style="color: #993333;">int</span> height<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> row = <span style="color: #cc66cc;">0</span>; row &lt; height; row++<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
            image.<span style="color: #006600;">getRGB</span><span style="color: #66cc66;">&#40;</span>argbData, offset, width, x, y + row, width, <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>;
            offset += scanline;
        <span style="color: #66cc66;">&#125;</span>
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre>
<img src="http://feeds.feedburner.com/~r/jayway/posts/embedded/~4/dREH6cYdDA0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/01/17/fixing-imagegetrgb/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.jayway.com/2009/01/17/fixing-imagegetrgb/</feedburner:origLink></item>
		<item>
		<title>UIButton troubles, a better solution</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/embedded/~3/_pRQCa1Fyjo/</link>
		<comments>http://blog.jayway.com/2008/12/17/uibutton-troubles-a-better-solution/#comments</comments>
		<pubDate>Wed, 17 Dec 2008 17:10:33 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
		
		<category><![CDATA[Architecture]]></category>

		<category><![CDATA[Design Patterns]]></category>

		<category><![CDATA[Embedded]]></category>

		<category><![CDATA[Frameworks]]></category>

		<category><![CDATA[Programming]]></category>

		<category><![CDATA[iphone]]></category>

		<category><![CDATA[java]]></category>

		<category><![CDATA[objective-c]]></category>

		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=651</guid>
		<description><![CDATA[I described in my previous post how you can change the class of a live object instance. The use-case was a workaround for bug in Cocoa Touch's UIKit. What if I could fix the bug, instead of applying a work around in my sub-class?
Update: Buttons created with UIButtonTypeRoundedRect is a special case returning a private [...]]]></description>
			<content:encoded><![CDATA[<p>I described in my <a href="http://blog.jayway.com/2008/12/12/uibutton-troubles-and-obj-c-magic/">previous post</a> how you can change the class of a live object instance. The use-case was a workaround for bug in Cocoa Touch's UIKit. What if I could fix the bug, instead of applying a work around in my sub-class?</p>
<p><strong>Update:</strong> Buttons created with <code>UIButtonTypeRoundedRect</code> is a special case returning a private subclass of <code>UIButton</code>, this bugfix can therefor not safely be used with rounded buttons. Good news is that they already have a large nice touch area.</p>
<h3>With Objective-C you can</h3>
<p>In short the problem is that the implementation of the factory method <code>buttonWithType:</code> in <code>UIButton</code> do not respect subclasses, so it will always return instances of <code>UIButton</code>. This is bad since it is the only method available to use to get custom buttons. Without access to the source code for <code>UIButton</code> changes can not be made to the implementation, so in order to fix the bug in UIKit we must wrap the original implementation of <code>buttonWithType:</code> with our own method that applies the bugfix. </p>
<p>Adding a category with a new implementation will not work, since that would shadow the original implementation. What is need is some sort of <a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming">AOP</a>, and Objective-C gives us enough of this but under the name of <a href="http://www.cocoadev.com/index.pl?MethodSwizzling">method-swizzling</a>.</p>
<p>We can intercept method calls to <code>buttonWithType</code>: by swizzling the implementation with the implementation of our own method. In Objective-C all method implementations are called by name, that name is what is know as a selector. By swizzling the implementations we can make messages with the old selector call our new implementation, and vice versa.</p>
<p>We do this by adding a category to UIButton with this class method:</p>
<pre class="objc"><span style="color: #339900;">#import &lt;objc/runtime.h&gt;</span>
+<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>load;
<span style="color: #002200;">&#123;</span>
  Method oldMethod = class_getClassMethod<span style="color: #002200;">&#40;</span>self, <span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>buttonWithType:<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
  Method newMethod = class_getClassMethod<span style="color: #002200;">&#40;</span>self, <span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>__buttonWithType:<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
  method_exchangeImplementations<span style="color: #002200;">&#40;</span>oldMethod, newMethod<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre>
<p>The class method <code>load</code> is called once for each class and category as they are loaded into the run-time, and is the optimal place to add initialization code. Think of it as static initializer blocks in Java.</p>
<p>And that is it, apart from implementing the actual bugfix in our <code>__buttonWithType:</code> method.</p>
<h3>A better bugfix</h3>
<p>The fix I did in my previous post only worked if the new subclass of <code>UIBUtton</code> did not introduce any new instance variables. This is a limitation, and not quite as obvious to new users of our bugfix, so this time around the bugfix will work with any subclass.</p>
<p>The trick here is allocate a new instance of the correct subclass if needed, and copy over the instance variables. Implementation:</p>
<pre class="objc">+<span style="color: #002200;">&#40;</span>UIButton*<span style="color: #002200;">&#41;</span>__buttonWithType:<span style="color: #002200;">&#40;</span>UIButtonType<span style="color: #002200;">&#41;</span>type;
<span style="color: #002200;">&#123;</span>
  UIButton* button = <span style="color: #002200;">&#91;</span>self __buttonWithType:type<span style="color: #002200;">&#93;</span>;
  <span style="color: #0000ff;">Class</span> buttonClass = <span style="color: #002200;">&#91;</span>button <span style="color: #0000ff;">class</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>button &amp;&amp; buttonClass != self &amp;&amp; buttonClass == <span style="color: #002200;">&#91;</span>UIButton <span style="color: #0000ff;">class</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #0000ff;">size_t</span> oldSize = class_getInstanceSize<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>button <span style="color: #0000ff;">class</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
    <span style="color: #0000ff;">size_t</span> newSize = class_getInstanceSize<span style="color: #002200;">&#40;</span>self<span style="color: #002200;">&#41;</span>;
    button-&gt;isa = self;
    <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>oldSize &lt; newSize<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
      UIButton* newButton = <span style="color: #002200;">&#91;</span>self alloc<span style="color: #002200;">&#93;</span>;
      <a href="http://www.opengroup.org/onlinepubs/009695399/functions/memcpy.html"><span style="color: #0000dd;">memcpy</span></a><span style="color: #002200;">&#40;</span>newButton, button, oldSize<span style="color: #002200;">&#41;</span>;
      button = <span style="color: #002200;">&#91;</span>newButton autorelease<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
  <span style="color: #002200;">&#125;</span>
  <span style="color: #0000ff;">return</span> button;
<span style="color: #002200;">&#125;</span></pre>
<p>At first glance the first statement might look like a recursive call, but remember that we have swizzled the implementations so it will call the original implementation of <code>buttonWithType:</code>.</p>
<p>Also note that we must autorelease the new instance that we allocated, and that we must not release the original instance as that one is already owned by an auto release pool.</p>
<p>And that is how you go about fixing bugs in Objective-C for code that you do not have access to the source code for.</p>
<img src="http://feeds.feedburner.com/~r/jayway/posts/embedded/~4/_pRQCa1Fyjo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/12/17/uibutton-troubles-a-better-solution/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.jayway.com/2008/12/17/uibutton-troubles-a-better-solution/</feedburner:origLink></item>
		<item>
		<title>Java ME Logging over Bluetooth using MicroLog</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/embedded/~3/byTDFashA5M/</link>
		<comments>http://blog.jayway.com/2008/12/17/java-me-logging-over-bluetooth-using-microlog/#comments</comments>
		<pubDate>Wed, 17 Dec 2008 16:17:25 +0000</pubDate>
		<dc:creator>Henrik Larne</dc:creator>
		
		<category><![CDATA[Embedded]]></category>

		<category><![CDATA[bluetooth]]></category>

		<category><![CDATA[java]]></category>

		<category><![CDATA[logging]]></category>

		<category><![CDATA[mobile]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=604</guid>
		<description><![CDATA[When developing in Java ME and wanting to support several different devices, you wil no doubt run into problems with devices behaving differently. In some cases it is only the appearance that changes and in others the actual functionality varies or breaks. The first step in solving this is to run your Midlet in the [...]]]></description>
			<content:encoded><![CDATA[<p>When developing in Java ME and wanting to support several different devices, you wil no doubt run into problems with devices behaving differently. In some cases it is only the appearance that changes and in others the actual functionality varies or breaks. The first step in solving this is to run your Midlet in the emulators for the devices that you want to support and hopefully you will be able to solve some of the problems here, but unless you are really lucky there will be some problems remaining that needs to be debugged on the actual device. Depending on which device it is you might be able to run On Device Debugging  to solve it, but in many cases you don't have that option or the On Device Debugger is not stable enough. So now you are left with logging as your only tool to debug the midlet. Logging on a small screen device with very limited ram is not trivial however. </p>
<p>What you really want is to have the midlet write the log to your development PC instantaneously and free of charge, then you can log whatever you want to pinpoint your bug. This could be accomplished by logging over Bluetooth. Previously you had to write your own code to handle the logging and Bluetooth communication as well as a server to which the midlet connects and sends the log messages, but now there is a powerful logging framework for Java ME that offers this support out of the box. The framework is <a href="http://microlog.sourceforge.net">MicroLog</a> and is open source under the Apache Software License, so it is free to use as you see fit. MicroLog can be configured with one or more appenders that takes care of the logging messages and sends them to the right destination and each appender can have its own formatter to format the messages appropriately. This is very similar to log4j, so if you have used log4j before, MicroLog is very easy to learn. If you are using Maven 2 you will be happy to know that MicroLog is built using Maven 2 and is available in a public repository.</p>
<p>Setting up MicroLog to use Bluetooth and log to your PC is simple. It only requires that you setup your Logger:</p>
<pre>
private final static Logger log = Logger.getLogger(TestMidlet.class);
</pre>
<p>and that you configure it to use a <code>BluetoothSerialAppender</code>, which is done like this:</p>
<pre>
log.addAppender(new BluetoothSerialAppender());
</pre>
<p>Now your midlet is all set to start logging over Bluetooth. For a full midlet example see the following code:</p>
<pre>
package se.jayway.me;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

import net.sf.microlog.Logger;
import net.sf.microlog.bluetooth.BluetoothSerialAppender;

public class TestMidlet extends MIDlet
{

	private final static Logger log = Logger.getLogger(TestMidlet.class);

	public TestMidlet()
	{
		configureMicroLog();
	}

	protected void destroyApp(boolean arg0) throws MIDletStateChangeException
	{
		log.info("Destroying application...");
	}

	protected void pauseApp()
	{
		log.info("Pausing application...");
	}

	protected void startApp() throws MIDletStateChangeException
	{
		log.info("Starting application...");
		final TextBox textBox = new TextBox("Text", "My text", 100, 0);
		textBox.addCommand(new Command("Log", Command.SCREEN, 0));
		textBox.setCommandListener(new CommandListener() {
			private int counter;

			public void commandAction(Command c, Displayable d)
			{
				log.debug("You clicked " + counter++);
				log.debug(textBox.getString());
			}
		});
		Display.getDisplay(this).setCurrent(textBox);
	}

	private void configureMicroLog()
	{
		log.addAppender(new BluetoothSerialAppender());
	}
}
</pre>
<p>Build and deploy this midlet to your Bluetooth enabled device, supporting JSR-82, the Bluetooth API and make sure that Bluetooth is turned on.</p>
<p>Next you need to get the Bluetooth server that will receive and print the logging messages to standard out. The server is also available in a public <a href="http://microlog.sourceforge.net/repo/m2-snapshot-repository/net/sf/microlog-servers/">Maven repository</a>. Just download the version that ends with -jar-with-dependencies.jar. This file contains all its dependencies. Now make sure that your Bluetooth unit is on and discoverable on your PC. Then start the server with the following command:</p>
<pre>
java -cp microlog-servers-1.1.0-SNAPSHOT-jar-with-dependencies.jar net.sf.microlog.server.btspp.MicrologBtsppServer
</pre>
<p>You might have to change the jar file name if it is not the same as the one you downloaded, then just replace it with the file name of your own microlog-server jar file.</p>
<p>The server starts up and registers a logging service with a unique UUID that the phone will try to locate and connect to. Now start the midlet and see how it will start logging over the Bluetooth connection.</p>
<p>The first phone I tested was a SonyEricsson C905 and it worked perfectly from the start. Then I tried to use a SonyEricsson P990i and for some reason it failed to locate the logging server with the unique UUID. I was unable to determine the reason why it failed to locate the service, so instead I added support to the <code>BluetoothSerialAppender</code> to specify the url of the Bluetooth logger server. Using this and setting the server url to my PC it connected flawlessly to it and started logging. So if you experience problems when your midlet connects to the PC or if you are using multiple logger servers within the Bluetooth range of your device try specifying the server url that the <code>BluetoothSerialAppender</code> should connect to. The url of the server is shown when starting the logger server. This url does however contain a channel that is not possible to determine through the used API's, but it does start on 1 and increases. For each session I always got the same channel and it was only the next day that it changed and I got channel 2 instead, so try with 1 to start with and if that does not work increase it by one and try again. It will most likely work first or second time.</p>
<p>Now you are free to log as much as you want and do not have to restrict your logging during the development phase of your project. Neither is there a reason for writing your own Bluetooth logger, just use MicroLog.</p>
<img src="http://feeds.feedburner.com/~r/jayway/posts/embedded/~4/byTDFashA5M" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/12/17/java-me-logging-over-bluetooth-using-microlog/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.jayway.com/2008/12/17/java-me-logging-over-bluetooth-using-microlog/</feedburner:origLink></item>
		<item>
		<title>iPhone Tech Talks - Stockholm</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/embedded/~3/KV9dFz4qfNs/</link>
		<comments>http://blog.jayway.com/2008/12/09/iphone-tech-talks-stockholm/#comments</comments>
		<pubDate>Tue, 09 Dec 2008 08:03:51 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
		
		<category><![CDATA[Embedded]]></category>

		<category><![CDATA[Events]]></category>

		<category><![CDATA[Frameworks]]></category>

		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Usability]]></category>

		<category><![CDATA[apple]]></category>

		<category><![CDATA[design]]></category>

		<category><![CDATA[iphone]]></category>

		<category><![CDATA[mobile]]></category>

		<category><![CDATA[sdk]]></category>

		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=535</guid>
		<description><![CDATA[Apple has arranged a world tour of iPhone Tech Talks, and in cold december it was Scandinavia's turn and a crew of software evangelists from Apple turned up at KTH in Stockholm for a full day of sessions.
The sessions are confidential so I will keep this post vague on the technical parts, not revealing any [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.apple.com">Apple</a> has arranged a world tour of <a href="http://developer.apple.com/events/iphone/techtalks/">iPhone Tech Talks</a>, and in cold december it was Scandinavia's turn and a crew of software evangelists from Apple turned up at <a href="http://www.kth.se/">KTH</a> in Stockholm for a full day of sessions.</p>
<p>The sessions are confidential so I will keep this post vague on the technical parts, not revealing any thing that might or might not come to an iPhone or iPod touch near you in the future. And I can not mention any specific sales numbers, but I do can say that any predicted numbers you might have seen; is probably an underestimation with a margin and then some.</p>
<p>The sessions where on a high level, not going too deep on technical details. Instead the sessions concentrated on the overall design philosophies, and common gotchas. For the nitty gritty details Apple engineers where available, and I missed half a session discussing the ins and outs of the UIToolbar class with Alberto Arauz. Alberto is one of the european software evangelist, and was most impressed, and interested, when I described the successful <a href="http://www.oredev.org/topmenu/program/trackmobile20.4.2c4b8bee11a31fca49e8000319.html">Mobile 2.0 track</a> at <a href="http://www.oredev.org">Øredev 2008</a>. Apple's overall impression with Scandinavia has so far been a mostly cold hand regarding anything with Apple, going as far as only six people registering for a Tech Talk in Oslo two years ago.</p>
<p>Apart from the speakers and engineers, Apple also brought a video-team. So yours truly has been intervjued about the <a href="http://www.peylow.se/">applications I have</a> on App Store, and my experience with the iPhone SDK. The video will be cut and edited for promotional purposes, and hopefully me mentioning both Malmö and Jayway will not be cut out. The odds of my short talk being included is quite good, as most developers seems to be focusing on games, not utilities as I and Jayway has done.</p>
<p>The best part to take home is not technical, just solid advice for any development, not even under NDA, and the sole point repeated by Apple over and over: <strong>Developing great applications is not about adding features!</strong> The trick is not to cram in as many features as you can, the trick is to know what features to leave out, so that time can be well spend on the key features that do make the cut. And this is tenfold as important on a mobile device where real estate is limited. A quote from Mark Twain:</p>
<blockquote><p>I apologize for writing you a long letter, but I did not have the time to write a short.</p></blockquote>
<p>Writing short, and cutting features is hard. How to decide on the features to drop or implement? Apple uses a simple technique, called a product statement. The product statement for the Photos application is for example; <em>"An easy to use photo sharing application for all iPhone users"</em>. Any feature that do not help fulfilling this statement do not make it. How about simple photo-editing? Nope, does not comply with statement. The wording of the product statement is important, by simply changing it to <em>"An easy to use photo sharing application for <u>professional photographers</u>"</em>, would be a completely new application. Only when the product statement is agreed upon, can an approved list of features be made. An omnipresent Steve Jobs approving and dismissing features, is an exaggeration, this simple method is what do the trick.</p>
<p>Now this might sound both obvious, and counterintuitive. Surely adding that last nice feature would add value? Not at the expense of a cluttered user interface, that is meant to be used while standing in line for 30 seconds. Features thought to be must haves, most of the time are not. Some features thought to be must haves are MMS and video recording. Looking at the raging success of the iPhone, it is very obvious that they are not must haves. We as software engineers must at long last learn that it truly is quality over quantity.</p>
<p>And lastly a personal reflection; from a developer's point of view the best part about iPhone SDK is that it is not an UI framework, it is an Application framework. It do not settle with providing the tools for collections, persisting data, displaying a UI, and then leave the rest of the architecture to the developers. The iPhone SDK supports all three parts of the Model-View-Controller paradigm equally well, and that is what makes it so productive.</p>
<img src="http://feeds.feedburner.com/~r/jayway/posts/embedded/~4/KV9dFz4qfNs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/12/09/iphone-tech-talks-stockholm/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.jayway.com/2008/12/09/iphone-tech-talks-stockholm/</feedburner:origLink></item>
		<item>
		<title>Accelerometer and Vibration on the iPhone</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/embedded/~3/YF94CqWx3bo/</link>
		<comments>http://blog.jayway.com/2008/11/25/accelerometer-and-vibration-on-the-iphone/#comments</comments>
		<pubDate>Tue, 25 Nov 2008 06:48:47 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
		
		<category><![CDATA[Embedded]]></category>

		<category><![CDATA[Frameworks]]></category>

		<category><![CDATA[Programming]]></category>

		<category><![CDATA[accelerometer]]></category>

		<category><![CDATA[android]]></category>

		<category><![CDATA[iphone]]></category>

		<category><![CDATA[objective-c]]></category>

		<category><![CDATA[oredev]]></category>

		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=464</guid>
		<description><![CDATA[Last friday I attended an excellent session at Øredev 2008, on Android by Mike Jennings from Google. At the end of the presentation Mike show the code for a simple application with a bouncing blue ball, controlled by the accelerometer. What stroke me was that the git of the application was 85 lines of code, [...]]]></description>
			<content:encoded><![CDATA[<p>Last friday I attended an excellent session at <a href="http://www.oredev.org">Øredev 2008</a>, on <a href="http://code.google.com/android/">Android</a> by Mike Jennings from Google. At the end of the presentation Mike show the code for a simple application with a bouncing blue ball, controlled by the accelerometer. What stroke me was that the git of the application was 85 lines of code, and Mike told us most of the physics and life cycle code was hidden away. I have never used the accelerometer on the iPhone, but my gut told me that 85 lines was allot of code.</p>
<p>So I took out my laptop during the next 60 minutes of Panel Debate, and wrote an iPhone app, and as I expected the code landed on 46 lines of code for the actual application logic, physics, grits and all. Or 112 lines of code if headers and boiler-plate should be counted as well.</p>
<p>This blog post will describe what I did, in a quite nice model-view-controller fashion <em>(Model and Controller is implemented in the same class)</em>.</p>
<ul>
<li>First of all I needed a view to display my bouncing ball on, I choose to subclass UIViewController to handle this view.</li>
<li>A standard UIView instance with a UIImageView sub-view for the ball is all I need for my view, this I setup using Interface Builder.</li>
<li>And the model/logic is handled by one CGPoint for the current location, and one CGPoint with the current delta movement of the ball.</li>
</ul>
<p>First the custom view controller sets up itself as the accelerometer delegate when awakening from it's nib-file.</p>
<pre class="objc">-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>awakeFromNib;
<span style="color: #002200;">&#123;</span>
  self.location = CGPointMake<span style="color: #002200;">&#40;</span><span style="color: #0000dd;">160</span>, <span style="color: #0000dd;">230</span><span style="color: #002200;">&#41;</span>;
  UIAccelerometer* accelerometer = <span style="color: #002200;">&#91;</span>UIAccelerometer sharedAccelerometer<span style="color: #002200;">&#93;</span>;
  accelerometer.updateInterval = <span style="color: #0000dd;">0.02</span>;
  accelerometer.delegate = self;
<span style="color: #002200;">&#125;</span></pre>
<p>Then comes a private function for the <em>quite faked physics</em>, it is responsible for detecting if a value with a given delta movement has hit a min or max edge. If it do hits an edge, it flips it's delta movement with some deceleration, and corrects it's value.</p>
<pre class="objc"><span style="color: #0000ff;">static</span> inline <span style="color: #0000ff;">BOOL</span> bounce<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">float</span>* val, <span style="color: #0000ff;">float</span>* delta, <span style="color: #0000ff;">float</span> min, <span style="color: #0000ff;">float</span> max<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
<span style="color: #339900;">#define FLIP(val, c) (c - (val - c))</span>
  <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>*val &lt; min || *val &gt; max<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    *delta = -<span style="color: #002200;">&#40;</span>*delta * <span style="color: #0000dd;">0.75</span><span style="color: #002200;">&#41;</span>;
    <span style="color: #0000ff;">float</span> loc = *val &lt; min ? min : max;
    *val = FLIP<span style="color: #002200;">&#40;</span>*val, loc<span style="color: #002200;">&#41;</span>;
    <span style="color: #0000ff;">return</span> YES;
  <span style="color: #002200;">&#125;</span>
  <span style="color: #0000ff;">return</span> NO;
<span style="color: #002200;">&#125;</span></pre>
<p>And lastly the delegate method that is called by the accelerometer. Here we update the delta movement, and use the bounce-function to detect and compensate location+delta when the ball hits any edges. If an edge it hit, a vibration is also triggered.</p>
<pre class="objc">-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>accelerometer:<span style="color: #002200;">&#40;</span>UIAccelerometer*<span style="color: #002200;">&#41;</span>accelerometer
       didAccelerate:<span style="color: #002200;">&#40;</span>UIAcceleration*<span style="color: #002200;">&#41;</span>acceleration;
<span style="color: #002200;">&#123;</span>
<span style="color: #339900;">#define CAP(val, max) (val &lt; -max ? -max : (val &gt; max ? max : val))</span>
  CGPoint delta = CGPointMake<span style="color: #002200;">&#40;</span>CAP<span style="color: #002200;">&#40;</span>self.delta.x + acceleration.x, <span style="color: #0000dd;">32</span><span style="color: #002200;">&#41;</span>,
                              CAP<span style="color: #002200;">&#40;</span>self.delta.y - acceleration.y, <span style="color: #0000dd;">32</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
  CGPoint location = CGPointMake<span style="color: #002200;">&#40;</span>self.location.x + delta.x,
                                 self.location.y + delta.y<span style="color: #002200;">&#41;</span>;
  <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>bounce<span style="color: #002200;">&#40;</span>&amp;location.x, &amp;delta.x, <span style="color: #0000dd;">8</span>, self.view.bounds.size.width - <span style="color: #0000dd;">8</span> <span style="color: #002200;">&#41;</span> ||
      bounce<span style="color: #002200;">&#40;</span>&amp;location.y, &amp;delta.y, <span style="color: #0000dd;">8</span>, self.view.bounds.size.height - <span style="color: #0000dd;">8</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>
  <span style="color: #002200;">&#123;</span>
      AudioServicesPlayAlertSound<span style="color: #002200;">&#40;</span>kSystemSoundID_Vibrate<span style="color: #002200;">&#41;</span>;
  <span style="color: #002200;">&#125;</span>
  self.delta = delta;
  self.location = location;
  self.ballView.center = self.location;
<span style="color: #002200;">&#125;</span></pre>
<p>In conclusion Cocoa Touch requires surprisingly little code for accessing and using the accelerometer and trigger a vibration. Triggering a vibration is literary done with a single line of code. The lines of code needed to setup and listen to the accelerometer can literary be counted on the fingers of one hand.</p>
<p>On the downside there is no finer control of the vibration, and if you like to have the rotation angles of the device instead of simple gravity forces of the x, y and z axis, then you must do the math for yourself. Simple enough, but it would had been nice to have to current rotations around each axis as well. </p>
<p>The full source code can be downloaded <a href="http://www.peylow.se/BouncyBall.zip">here</a>.</p>
<p>ps. I dare Mike Jennings to best this :). ds.</p>
<img src="http://feeds.feedburner.com/~r/jayway/posts/embedded/~4/YF94CqWx3bo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/11/25/accelerometer-and-vibration-on-the-iphone/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.jayway.com/2008/11/25/accelerometer-and-vibration-on-the-iphone/</feedburner:origLink></item>
		<item>
		<title>Android on the FreeRunner</title>
		<link>http://feedproxy.google.com/~r/jayway/posts/embedded/~3/UXdnoG8nbtc/</link>
		<comments>http://blog.jayway.com/2008/11/21/android-on-the-freerunner/#comments</comments>
		<pubDate>Fri, 21 Nov 2008 16:01:48 +0000</pubDate>
		<dc:creator>Peter Neubauer</dc:creator>
		
		<category><![CDATA[Embedded]]></category>

		<category><![CDATA[Linux]]></category>

		<category><![CDATA[Open Source]]></category>

		<category><![CDATA[Programming]]></category>

		<category><![CDATA[android]]></category>

		<category><![CDATA[java]]></category>

		<category><![CDATA[mobile]]></category>

		<category><![CDATA[oredev]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=450</guid>
		<description><![CDATA[Hi there,
Öredev was great success, especially all the people and the organization - a big Thank You to Michael and Emily for making this possible, you rock!
Now, it was really awesome to exchange Android games with Mike Jennings fro the Android team, and get him excited over the recent Android port to the Neo FreeRunner! [...]]]></description>
			<content:encoded><![CDATA[<p>Hi there,</p>
<p>Öredev was great success, especially all the people and the organization - a big Thank You to Michael and Emily for making this possible, you rock!</p>
<p>Now, it was really awesome to exchange Android games with Mike Jennings fro the Android team, and get him excited over the recent Android port to the Neo FreeRunner! Thanks Anders Hedberg for coming over to fix the FR, and to all the OpenMoko enthusiasts doing the hard work!</p>
<p><a href="https://blog.jayway.com/wp-content/uploads/2008/11/1227281553155.jpg"><img class="alignnone size-medium wp-image-451" title="Android on the NeoFreerunner" src="https://blog.jayway.com/wp-content/uploads/2008/11/1227281553155-225x300.jpg" alt="" width="225" height="300" /></a></p>
<p>/peter neubauer</p>
<img src="http://feeds.feedburner.com/~r/jayway/posts/embedded/~4/UXdnoG8nbtc" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/11/21/android-on-the-freerunner/feed/</wfw:commentRss>
		<feedburner:origLink>http://blog.jayway.com/2008/11/21/android-on-the-freerunner/</feedburner:origLink></item>
	</channel>
</rss>
