<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>ytoh's blog</title>
	<atom:link href="http://ytoh.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://ytoh.wordpress.com</link>
	<description></description>
	<lastBuildDate>Thu, 10 Nov 2011 09:31:33 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='ytoh.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>ytoh's blog</title>
		<link>http://ytoh.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://ytoh.wordpress.com/osd.xml" title="ytoh&#039;s blog" />
	<atom:link rel='hub' href='http://ytoh.wordpress.com/?pushpress=hub'/>
		<item>
		<title>@Flow &#8211; accessing Webflow data in Spring MVC controllers</title>
		<link>http://ytoh.wordpress.com/2011/09/07/flow-accessing-webflow-data-in-spring-mvc-controllers/</link>
		<comments>http://ytoh.wordpress.com/2011/09/07/flow-accessing-webflow-data-in-spring-mvc-controllers/#comments</comments>
		<pubDate>Wed, 07 Sep 2011 19:28:49 +0000</pubDate>
		<dc:creator>ytoh</dc:creator>
				<category><![CDATA[howto]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://ytoh.wordpress.com/?p=104</guid>
		<description><![CDATA[At the company I work at we are presently in the middle of replacing JSF with Spring Webflow + a yet undecided templating technology. We have grown tired of the problems associated with JSF and are ready to replace them with a different set of problems (as every technology has). Since we do not have &#8230;<p><a href="http://ytoh.wordpress.com/2011/09/07/flow-accessing-webflow-data-in-spring-mvc-controllers/" class="more-link">Read More</a></p><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ytoh.wordpress.com&amp;blog=3728656&amp;post=104&amp;subd=ytoh&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>At the company I work at we are presently in the middle of replacing JSF with Spring Webflow + a yet undecided templating technology. We have grown tired of the problems associated with JSF and are ready to replace them with a different set of problems <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  (as every technology has).</p>
<p>Since we do not have a full analysis on a suitable templating technology we decided to use JSF for rendering of HTML but use Spring Webflow to handle the postback. Using Facelets to handle HTML templating and leaving out JSF components produces nice and plain HTML ideal for jQuery (or any other JavaScript framework) on the client.</p>
<p>Using Webflow to handle the postback proved to hold much less surprises than when we used JSF. Most of the tasks required just work. But there is one thing that was missing. There was no way of accessing flow scoped (or view scoped) variables in Spring MVC controller methods handling ajax calls.</p>
<p>Why not use the Webflow&#8217;s ajax abstraction? Webflow&#8217;s ajax abstraction is based on re-rendering page fragments which is not suitable for retrieving pure data from the server. On the other hand Spring 3 introduced a very appealing ajax simplification (<a title="Spring 3's ajax simplification" href="http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/" target="_blank">as described here</a>) which significantly cuts down server and client side ajax handling code.</p>
<h2>Problem statement</h2>
<p>I want to have all data related to the process defined in (and handled by) Webflow conveniently accessible from my MVC controller methods handling ajax calls. While I do not want to define the flow data outside the flow definition xml.</p>
<p><strong>Example:</strong> Imagine a user registering an account. The process of creating an account spans several screens and it is defined in a flow. Inside this flow there is a flow scoped variable of type <em>Account</em>. On one of the screens you need to provide a list of available products using an ajax call. The available products depend on data entered on previous screens (this means they are already stored in flow scope) and on data on the current screen (sent via ajax).</p>
<h2>Solution proposal</h2>
<p>A prefered solution would be to have Spring MVC inject data stored in flow scope as handler method parameters. You could denote these parameters by adding a <em>@Flow</em> annotation to them.</p>
<p><pre class="brush: java; wrap-lines: false;">
@RequestMapping(&quot;/data/availableProducts&quot;)
public @ResponseBody List getProducts(@Flow Account account, @RequestParam(&quot;query&quot;) String query) {
    List&lt;Product&gt; products = // filter using a query and data from the account being created
    return products;
}
</pre></p>
<h2>Solution implementation</h2>
<p>The concept behind the implementation is to expose the current flow execution to the <em>AnnotationMethodHandlerAdapter</em> (adapter handling our ajax requests) in similar fashion as it is done in <em>FlowHandlerAdapter</em> (adapter handling flow requests) and resolve arguments using a custom <em>WebArgumentResolver</em>.</p>
<p>For the <em>@Flow</em> annotation to work we 3 classes:</p>
<ol>
<li>The <em>@Flow</em> annotation itself</li>
<li>A custom implementation of the <em>WebArgumentResolver</em> interface (a Spring SPI interface). Implementations of this interface are responsible for resolving arguments of handler methods</li>
<li>A custom implementation of the <em>HandlerInterceptor</em> interface (another Spring SPI interface)</li>
</ol>
<h3>@Flow</h3>
<p><pre class="brush: java; wrap-lines: false;">
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Flow {

    /**
     * Name under which the annotated parameter is registered in Flow scope.
     */
    String value() default &quot;&quot;;
}
</pre></p>
<h3>FlowArgumentResolver</h3>
<p>This class does all the work. It contains one &#8220;hack&#8221; without which all of this would not work. It accesses <em>FlowExecutorImpl</em> the implementation of the <em>FlowExecutor</em> to retrieve the execution repository. If you cannot stomach this, tread no further <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
<p><pre class="brush: java; wrap-lines: false;">
public class FlowArgumentResolver implements WebArgumentResolver, InitializingBean {

    private FlowExecutor flowExecutor;
    private FlowExecutionRepository executionRepository;

    @Override
    public void afterPropertiesSet() throws Exception {
        executionRepository = ((FlowExecutorImpl) flowExecutor).getExecutionRepository();
        //...
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) throws Exception {
        if(isFlowParameter(methodParameter)) {
            return resolveFlowArgument(methodParameter, webRequest);
        }

        return UNRESOLVED;
    }

    private boolean isFlowParameter(MethodParameter methodParameter) {
        return getParameterAnnotation(methodParameter) != null;
    }

    private Flow getParameterAnnotation(MethodParameter methodParameter) {
        return methodParameter.getParameterAnnotation(Flow.class);
    }

    private Object resolveFlowArgument(MethodParameter methodParameter, NativeWebRequest webRequest) {
        FlowExecution flowExecution = getFlowExecution(executionRepository, (HttpServletRequest) webRequest.getNativeRequest());

        Flow parameterAnnotation = getParameterAnnotation(methodParameter);
        if(&quot;&quot;.equals(parameterAnnotation.value())) {
            return resolveByType(methodParameter, flowExecution);
        } else {
            return resolveByName(methodParameter, parameterAnnotation.value(), flowExecution);
        }
    }

    private Object resolveByName(MethodParameter methodParameter, String name, FlowExecution flowExecution) {
        MutableAttributeMap flowAttributes = flowExecution.getActiveSession().getScope();
        return flowAttributes.get(name);
    }

    private Object resolveByType(MethodParameter methodParameter, FlowExecution flowExecution) {
        Map flowAttributes = filterValues(flowExecution.getActiveSession().getScope().asMap(), instanceOf(methodParameter.getParameterType()));
        return ((Map.Entry) flowAttributes.entrySet().iterator().next()).getValue();
    }

    private FlowExecution getFlowExecution(FlowExecutionRepository executionRepository, HttpServletRequest request) {
        String flowExecutionKeyParameter = // from flowUrlHandler
        FlowExecutionKey executionKey = executionRepository.parseFlowExecutionKey(flowExecutionKeyParameter);
        return executionRepository.getFlowExecution(executionKey);
    }

    // ...
}
</pre></p>
<h3>FlowHandlerInterceptor</h3>
<p>This is only a helper class that initializes ExternalContextHolder. Without this the FlowArgumentResolver would not work.</p>
<p><pre class="brush: java; wrap-lines: false;">
public class FlowHandlerInterceptor extends HandlerInterceptorAdapter implements ServletContextAware, InitializingBean {

    private ServletContext servletContext;
    private FlowUrlHandler flowUrlHandler;

    @Override
    public void afterPropertiesSet() throws Exception {
        if (flowUrlHandler == null) {
            flowUrlHandler = new DefaultFlowUrlHandler();
        }
        //...
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        ExternalContextHolder.setExternalContext(createServletExternalContext(request, response));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ExternalContextHolder.setExternalContext(null);
    }
    private ExternalContext createServletExternalContext(HttpServletRequest request, HttpServletResponse response) {
        ServletExternalContext context = new MvcExternalContext(servletContext, request, response, flowUrlHandler);
        context.setAjaxRequest(ajaxHandler.isAjaxRequest(request, response));
        return context;
    }

    // ...
}
</pre></p>
<h3>Configuration</h3>
<p>After we have these three things we register the <em>FlowArgumentResolver</em> and <em>FlowHandlerInterceptor</em> and arguments annotated with <em>@Flow</em> are automagically resolved from the current flow execution.</p>
<p><pre class="brush: xml; wrap-lines: false;">
&lt;bean class=&quot;org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping&quot;&gt;
    &lt;property name=&quot;interceptors&quot;&gt;
        &lt;list&gt;
            &lt;ref local=&quot;flowHandlerInterceptor&quot;/&gt;
        &lt;/list&gt;
    &lt;/property&gt;
&lt;/bean&gt;
&lt;bean class=&quot;org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter&quot;&gt;
    &lt;property name=&quot;customArgumentResolvers&quot;&gt;
        &lt;list&gt;
            &lt;bean class=&quot;com.company.flow.FlowArgumentResolver&quot;&gt;
                &lt;property name=&quot;flowExecutor&quot; ref=&quot;flowExecutor&quot; /&gt;
            &lt;/bean&gt;
        &lt;/list&gt;
    &lt;/property&gt;
&lt;/bean&gt;

&lt;bean id=&quot;flowHandlerInterceptor&quot; class=&quot;com.company.flow.FlowHandlerInterceptor&quot;/&gt;
</pre></p>
<h2>Conclusion</h2>
<p>There is one (IMHO fortunate) side-effect here. Since Webflow stores snapshots of flow scoped objects when flow pauses in view states you always access a deserialized copy of your data in Spring MVC handlers. The consequence of this is that you cannot really change flow scoped variables in MVC ajax handlers. And since changing server-side state using ajax calls can get really tricky really fast this is a not as big of a problem as it might seem. (Actions that change data should be recorded in the flow definition as event handlers if needed)</p>
<p>Using these 3 rather short classes and couple of lines of configuration we are able to access flow scoped variables very conveniently just by a simple annotation. Furthermore a similar approach can be adopted to access view scoped variables as well.</p>
<p>/Enjoy</p>
<p>Edit: the full code and a showcase can be found at <a href="http://code.google.com/p/webflow-mvc-bridge/">http://code.google.com/p/webflow-mvc-bridge/</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ytoh.wordpress.com/104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ytoh.wordpress.com/104/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ytoh.wordpress.com/104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ytoh.wordpress.com/104/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/ytoh.wordpress.com/104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/ytoh.wordpress.com/104/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/ytoh.wordpress.com/104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/ytoh.wordpress.com/104/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ytoh.wordpress.com/104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ytoh.wordpress.com/104/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ytoh.wordpress.com/104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ytoh.wordpress.com/104/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ytoh.wordpress.com/104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ytoh.wordpress.com/104/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ytoh.wordpress.com&amp;blog=3728656&amp;post=104&amp;subd=ytoh&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ytoh.wordpress.com/2011/09/07/flow-accessing-webflow-data-in-spring-mvc-controllers/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d6074b6508685d183b68532b45e9d294?s=96&#38;d=http%3A%2F%2Fs0.wp.com%2Fi%2Fmu.gif" medium="image">
			<media:title type="html">ytoh</media:title>
		</media:content>
	</item>
		<item>
		<title>Simple mixins in Java need simple IDE support</title>
		<link>http://ytoh.wordpress.com/2009/02/19/simple-mixins-in-java-need-simple-ide-support/</link>
		<comments>http://ytoh.wordpress.com/2009/02/19/simple-mixins-in-java-need-simple-ide-support/#comments</comments>
		<pubDate>Thu, 19 Feb 2009 09:56:20 +0000</pubDate>
		<dc:creator>ytoh</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[delegator pattern]]></category>
		<category><![CDATA[IDE]]></category>
		<category><![CDATA[mixin]]></category>

		<guid isPermaLink="false">http://ytoh.wordpress.com/?p=87</guid>
		<description><![CDATA[Java doesn&#8217;t provide a mixin functionality in its language core . But you can think of a mixin as an interface together with an implementation and then it is possible to use the concept of a mixin in java and use it as a means of promoting code reuse. Like everyone during development I find &#8230;<p><a href="http://ytoh.wordpress.com/2009/02/19/simple-mixins-in-java-need-simple-ide-support/" class="more-link">Read More</a></p><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ytoh.wordpress.com&amp;blog=3728656&amp;post=87&amp;subd=ytoh&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p style="text-align:justify;">Java doesn&#8217;t provide a mixin functionality in its language core <img src='http://s0.wp.com/wp-includes/images/smilies/icon_sad.gif' alt=':-(' class='wp-smiley' /> . But you can think of a mixin as an interface together with an implementation and then it is possible to use the <em>concept</em> of a mixin in java and use it as a means of promoting code reuse.</p>
<p style="text-align:justify;">Like everyone during development I find myself writing classes that share a certain set of functionalities. In other words they share the same small number of methods. If you prefer object composition over inheritance (as you should <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ) you define an interface and make all the classes implement this interface. But then another thing jumps up. You end up writing the same method bodies in every class. So you create <em>one</em> implementation of this interface and let every class use this implementation and just delegate the method calls. And now you&#8217;ve effectively created a simple mixin using the delegator pattern and one interface implementation and ended up with a lot of builerplate code. Like this:</p>
<p style="text-align:justify;">
<p><pre class="brush: java;">
// simple interface
public interface Description {

    String getName();

    String getDescription();

    String getVersion();

    void setName(String name);

    void setDescription(String description);

    void setVersion(String version);
}

// one implementation
public final class DescriptionImpl implements Description {
    private String name;
    private String description;
    private String version;

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    @Override
    public String toString() {
        return &quot;&quot; + name + &quot; \&quot;&quot; + description + &quot;\&quot; (&quot; + version + &quot;)&quot;;
    }
}

// mixin usage
public class Bean implements Description {
    // mixing in the description to this bean
    private final Description description = new DescriptionImpl();

    // HERE IS THE BOILERPLATE DELEGATION CODE
    public void setVersion(String version) { description.setVersion(version); }

    public void setName(String name) { description.setName(name); }

    public void setDescription(String description) { this.description.setDescription(description); }

    public String getVersion() { return description.getVersion(); }

    public String getName() { return description.getName(); }

    public String getDescription() { return description.getDescription(); }

    @Override
    public String toString() { return description.toString(); }
}
</pre></p>
<p style="text-align:justify;">I know that this is a really simplistic example but just try to imagine some complex operations taking place in the default interface implementation or possibly some generic code. Wouldn&#8217;t it be nice if with the help of an IDE you would be able to write this and end up with the same thing as in the above code fragment?</p>
<p style="text-align:justify;">
<p><pre class="brush: java;">
public class Bean implements Description {

    @Mixin private final Description description = new DescriptionImpl();

// and here imagine the collapsed auto-generated builderplate code here
}
</pre></p>
<p style="text-align:justify;">The mixin can depend on the object that mixes it in:</p>
<p style="text-align:justify;">
<p><pre class="brush: java;">
public interface Upcase {

    String toUpcaseString();
}

public final class UpcaseImpl implements Upcase {
    private Object object;

    public UpcaseImpl(Object object) {
        this.object = object;
    }

    public String toUpcaseString() {
        return object.toString().toUpperCase();
    }
}

public class Bean implements Upcase {
    @Mixin private final Upcase upcase = new UpcaseImpl(this);

// and here imagine the collapsed auto-generated builderplate code here
}
</pre></p>
<p style="text-align:justify;">The technology is present in (all) modern IDEs but I haven&#8217;t seen anything like this yet. Has anybody seen something similar in their IDE? Another question is: does anyone care? (Or is it just me <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> )</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ytoh.wordpress.com/87/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ytoh.wordpress.com/87/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ytoh.wordpress.com/87/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ytoh.wordpress.com/87/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/ytoh.wordpress.com/87/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/ytoh.wordpress.com/87/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/ytoh.wordpress.com/87/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/ytoh.wordpress.com/87/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ytoh.wordpress.com/87/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ytoh.wordpress.com/87/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ytoh.wordpress.com/87/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ytoh.wordpress.com/87/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ytoh.wordpress.com/87/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ytoh.wordpress.com/87/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ytoh.wordpress.com&amp;blog=3728656&amp;post=87&amp;subd=ytoh&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ytoh.wordpress.com/2009/02/19/simple-mixins-in-java-need-simple-ide-support/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d6074b6508685d183b68532b45e9d294?s=96&#38;d=http%3A%2F%2Fs0.wp.com%2Fi%2Fmu.gif" medium="image">
			<media:title type="html">ytoh</media:title>
		</media:content>
	</item>
		<item>
		<title>Creating a span table in Swing</title>
		<link>http://ytoh.wordpress.com/2009/02/06/creating-a-span-table-in-swing/</link>
		<comments>http://ytoh.wordpress.com/2009/02/06/creating-a-span-table-in-swing/#comments</comments>
		<pubDate>Fri, 06 Feb 2009 10:35:52 +0000</pubDate>
		<dc:creator>ytoh</dc:creator>
				<category><![CDATA[howto]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[swing]]></category>

		<guid isPermaLink="false">http://ytoh.wordpress.com/?p=43</guid>
		<description><![CDATA[SpanTable = JTable + Cell span While Swing provides a wide range of ready made components that cover a wide range of use cases most of the time if you find yourself needing something more you have to resort to writing it from scratch. After a couple of afternoons of searching the web for a &#8230;<p><a href="http://ytoh.wordpress.com/2009/02/06/creating-a-span-table-in-swing/" class="more-link">Read More</a></p><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ytoh.wordpress.com&amp;blog=3728656&amp;post=43&amp;subd=ytoh&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h2>SpanTable = JTable + Cell span</h2>
<p style="text-align:justify;">While <a title="Swing (Java)" href="http://en.wikipedia.org/wiki/Java_Swing" target="_blank">Swing</a> provides a wide range of ready made components that cover a wide range of use cases most of the time if you find yourself needing something more you have to resort to writing it from scratch. After a couple of afternoons of searching the web for a decent open source solution I gave up and started looking for a tutorial that would help me understand the concepts underneath JTable and help me extend it to allow cell spanning. I found <a title="column_spanning" href="http://www.swingwiki.org/howto:column_spanning" target="_blank">this tutorial</a> which builds a fully functional JTable with cells that can span multiple columns. This was a nice start but I needed a little more.</p>
<h3>Concepts</h3>
<p style="text-align:justify;">Adopting the division of cells from the above mentioned tutorial, there are 4 types of cells: hidden, visible, spanned and logical cells.</p>
<ul>
<li>Visible cell &#8211; a cell that gets rendered</li>
<li>Hidden cells &#8211; a cell not rendered because it is spanned by another cell</li>
<li>Spanned cells &#8211; a cell which spans atleast 2 columns or rows (thereby hiding other cells)</li>
<li>Logical cells &#8211; every cell is a logical cell, a logical cell is used to query the model</li>
</ul>
<p style="text-align:justify;">A model holds information that the table displays, using an UI component, including the information about visible and hidden cells and cell spans. A custom UI object filters out the hidden cells to display only the visible ones.</p>
<h3>Implementation</h3>
<div id="attachment_46" class="wp-caption center" style="width: 465px"> <a href="http://ytoh.files.wordpress.com/2009/02/spantable1.png"><img class="size-full wp-image-46" title="Span table" src="http://ytoh.files.wordpress.com/2009/02/spantable1.png?w=545" alt="Span table class diagram"   /></a><p class="wp-caption-text">Span table and its dependencies</p></div>
<h3>A SpanModel implementation</h3>
<p style="text-align:justify;"><em>DefaultSpanModel</em> is a basic implementation of the <em>SpanModel</em> interface. It uses <em>java.util.Map</em>s to store information about cell spans and hidden cells.</p>
<p><pre class="brush: java;">
public class DefaultSpanModel extends ForwardingTableModel implements SpanModel {
    // decorated model
    private Map&lt;Integer, Map&lt;Integer, Integer&gt;&gt; rowSpans;
    private Map&lt;Integer, Map&lt;Integer, Integer&gt;&gt; columnSpans;
    private Map&lt;Integer, Map&lt;Integer, Cell&gt;&gt;    hiddenCells;

    /**
     * Constructs a new &lt;code&gt;DefaultSpanModel&lt;/code&gt; backed by the supplied
     * &lt;code&gt;model&lt;/code&gt;.
     *
     * @param model to be extended
     */
    public DefaultSpanModel(TableModel model) {
        super(model);

        Factory hashMapFactory = new Factory() {
            public Map&lt;Integer, Integer&gt; create() {
                return new HashMap&lt;Integer, Integer&gt;();
            }
        };

        rowSpans = MapUtils.lazyMap(new HashMap&lt;Integer, Map&lt;Integer, Integer&gt;&gt;(), hashMapFactory);
        columnSpans = MapUtils.lazyMap(new HashMap&lt;Integer, Map&lt;Integer, Integer&gt;&gt;(), hashMapFactory);
        hiddenCells = MapUtils.lazyMap(new HashMap&lt;Integer, Map&lt;Integer, Cell&gt;&gt;(), new Factory() {
            public Object create() {
                return new HashMap&lt;Integer, Cell&gt;();
            }
        });
    }

    // ...
}</pre></p>
<p style="text-align:justify;">Keep in mind that this is not the most efficient implementation as after the first rendering you&#8217;ll have (2 *(# of rows) + (# of columns)) of map instances but it does simplify the implementation of functionality and should keep rendering time independent of the number of spanned cells. Its a start <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> .</p>
<p style="text-align:justify;">The most important trick to it is the custom UI object that filters hidden cells and only displays the visible ones. (Swing components delegate their rendering to utility UI objects to facilitate flexible look and feel as the above tutorial explains). This can be a bit of a problem to the generality of the solution. Because to render the span table you need a custom UI object but if someone changes the UI object then you don&#8217;t render the span table correctly. The good news is that most of the look and feels don&#8217;t change the rendering of tables (mostly only headers). As a precaution I set the UI object in the contructor and ignore any other UI component setting.</p>
<p><pre class="brush: java;">
public class SpanTable extends JTable {
    private boolean isSpanModel;

    public SpanTable(TableModel model) {
        super(model);
        // the table UI has to be set to &lt;code&gt;SpanTableUI&lt;/code&gt;
        this.setUI(new SpanTableUI());
    }

    @Override
    public Rectangle getCellRect(int row, int column, boolean includeSpacing) {
        if (isSpanModel) {
            // if the model is a span model, we have to check if the cell is spanned or not
            // and expand the area of the cell to reflect it
            Rectangle cellRect = super.getCellRect(row, column, includeSpacing);

            for (int i = 1, n = ((SpanModel) getModel()).getRowSpan(row, column); i &lt; n; i++) {
                // expand the area of the visible cell
                cellRect.height += getRowHeight(row + i);
            }

            for (int i = 1, n = ((SpanModel) getModel()).getColumnSpan(row, column); i &lt; n; i++) {
                // expand the area of the visible cell
                cellRect.width += getColumnModel().getColumn(column + i).getWidth();
            }

            return cellRect;
        }

        return super.getCellRect(row, column, includeSpacing);
    }

    @Override
    public void setUI(TableUI ui) { }

    @Override
    public void setModel(TableModel dataModel) {
        isSpanModel = dataModel instanceof SpanModel;
        super.setModel(dataModel);
    }

    @Override
    public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend) {
        // only needed for correct repaint behavior
        super.changeSelection(rowIndex, columnIndex, toggle, extend);
        repaint();
    }

    @Override
    public int columnAtPoint(Point point) {
        if(isSpanModel) {
           int row = super.rowAtPoint(point);
           int column = super.columnAtPoint(point);

           // return the column of the hiding cell
           return ((SpanModel) getModel()).getVisibleCell(row, column).getColumn();
        }

        return super.columnAtPoint(point);
    }

    @Override
    public int rowAtPoint(Point point) {
        if(isSpanModel) {
           int row = super.rowAtPoint(point);
           int column = super.columnAtPoint(point);

           // return the row of the hiding cell
           return ((SpanModel) getModel()).getVisibleCell(row, column).getRow();
        }

        return super.rowAtPoint(point);
    }
}
</pre></p>
<p style="text-align:justify;">The most importat thing here is the expansion of the spanned cell rectangle in getCellRect().</p>
<p style="text-align:justify;">Here is a simple usage example:</p>
<p><pre class="brush: java;">
// DATA
String[][] data = new String[][] {
    {&quot;a1&quot;, &quot;a2&quot;, &quot;a3&quot;, &quot;a4&quot;},
    {&quot;b1&quot;, &quot;b2&quot;, &quot;b3&quot;, &quot;b4&quot;},
    {&quot;c1&quot;, &quot;c2&quot;, &quot;c3&quot;, &quot;c4&quot;},
    {&quot;d1&quot;, &quot;d2&quot;, &quot;d3&quot;, &quot;d4&quot;},
    {&quot;e1&quot;, &quot;e2&quot;, &quot;e3&quot;, &quot;e4&quot;}
};

// SPAN TABLE INITIALIZATION
DefaultTableModel model = new DefaultTableModel(data, new String[] { &quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot; });
DefaultSpanModel spanModel = new DefaultSpanModel(model);

aFrame.getContentPane().add(new JScrollPane(new SpanTable(spanModel)), BorderLayout.CENTER);

spanModel.setColumnSpan(0, 0, 3);
spanModel.setRowSpan(1, 1, 2);
spanModel.setColumnSpan(1, 1, 2);
spanModel.setRowSpan(2, 0, 3);
</pre></p>
<p style="text-align:justify;">This is the final result:</p>
<div id="attachment_63" class="wp-caption aligncenter" style="width: 465px"><a href="http://ytoh.files.wordpress.com/2009/02/picture-1.png"><img class="size-full wp-image-63" title="span table" src="http://ytoh.files.wordpress.com/2009/02/picture-1.png?w=545" alt="A table with 3 spanned cells"   /></a><p class="wp-caption-text">A table with 3 spanned cells</p></div>
<div id="attachment_64" class="wp-caption aligncenter" style="width: 465px"><a href="http://ytoh.files.wordpress.com/2009/02/picture-2.png"><img class="size-full wp-image-64" title="3 column span" src="http://ytoh.files.wordpress.com/2009/02/picture-2.png?w=545" alt="A cell spanning 3 columns (edit)"   /></a><p class="wp-caption-text">A cell spanning 3 columns (edit)</p></div>
<div id="attachment_65" class="wp-caption aligncenter" style="width: 465px"><a href="http://ytoh.files.wordpress.com/2009/02/picture-3.png"><img class="size-full wp-image-65" title="2 column 2 row span" src="http://ytoh.files.wordpress.com/2009/02/picture-3.png?w=545" alt="A cell spanning 2 columns and 2 rows (edit)"   /></a><p class="wp-caption-text">A cell spanning 2 columns and 2 rows (edit)</p></div>
<div id="attachment_66" class="wp-caption aligncenter" style="width: 465px"><a href="http://ytoh.files.wordpress.com/2009/02/picture-4.png"><img class="size-full wp-image-66" title="3 row span" src="http://ytoh.files.wordpress.com/2009/02/picture-4.png?w=545" alt="A cell spanning 3 rows (edit)"   /></a><p class="wp-caption-text">A cell spanning 3 rows (edit)</p></div>
<div id="attachment_67" class="wp-caption aligncenter" style="width: 465px"><br />
<a href="http://ytoh.files.wordpress.com/2009/02/picture-5.png"><img class="size-full wp-image-67" title="span table highlighted" src="http://ytoh.files.wordpress.com/2009/02/picture-5.png?w=545" alt="Span table"   /></a><p class="wp-caption-text">Span table</p></div>
<h2 style="text-align:justify;">Resources</h2>
<p><a title="Span table source code" href="http://www.filefactory.com/file/afg20f0/n/SpanTable_zip" target="_blank">source code</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ytoh.wordpress.com/43/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ytoh.wordpress.com/43/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ytoh.wordpress.com/43/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ytoh.wordpress.com/43/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/ytoh.wordpress.com/43/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/ytoh.wordpress.com/43/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/ytoh.wordpress.com/43/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/ytoh.wordpress.com/43/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ytoh.wordpress.com/43/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ytoh.wordpress.com/43/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ytoh.wordpress.com/43/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ytoh.wordpress.com/43/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ytoh.wordpress.com/43/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ytoh.wordpress.com/43/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ytoh.wordpress.com&amp;blog=3728656&amp;post=43&amp;subd=ytoh&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ytoh.wordpress.com/2009/02/06/creating-a-span-table-in-swing/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d6074b6508685d183b68532b45e9d294?s=96&#38;d=http%3A%2F%2Fs0.wp.com%2Fi%2Fmu.gif" medium="image">
			<media:title type="html">ytoh</media:title>
		</media:content>

		<media:content url="http://ytoh.files.wordpress.com/2009/02/spantable1.png" medium="image">
			<media:title type="html">Span table</media:title>
		</media:content>

		<media:content url="http://ytoh.files.wordpress.com/2009/02/picture-1.png" medium="image">
			<media:title type="html">span table</media:title>
		</media:content>

		<media:content url="http://ytoh.files.wordpress.com/2009/02/picture-2.png" medium="image">
			<media:title type="html">3 column span</media:title>
		</media:content>

		<media:content url="http://ytoh.files.wordpress.com/2009/02/picture-3.png" medium="image">
			<media:title type="html">2 column 2 row span</media:title>
		</media:content>

		<media:content url="http://ytoh.files.wordpress.com/2009/02/picture-4.png" medium="image">
			<media:title type="html">3 row span</media:title>
		</media:content>

		<media:content url="http://ytoh.files.wordpress.com/2009/02/picture-5.png" medium="image">
			<media:title type="html">span table highlighted</media:title>
		</media:content>
	</item>
		<item>
		<title>Ruby-like collection handling in verbose Java = CollectionUtils</title>
		<link>http://ytoh.wordpress.com/2008/07/17/ruby-like-collection-handling-in-verbose-java-collectionutils/</link>
		<comments>http://ytoh.wordpress.com/2008/07/17/ruby-like-collection-handling-in-verbose-java-collectionutils/#comments</comments>
		<pubDate>Wed, 16 Jul 2008 22:06:41 +0000</pubDate>
		<dc:creator>ytoh</dc:creator>
				<category><![CDATA[howto]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://ytoh.wordpress.com/?p=21</guid>
		<description><![CDATA[each, select, reject, collect, detect, inject, include?, compact &#8211; translated into Java I have compiled this little cheat sheet for those who like working with arrays in Ruby but not just for Ruby&#8217;s expressivness as a language but mostly for the idioms behind it. If you like the way Ruby (and also Smalltalk and others, &#8230;<p><a href="http://ytoh.wordpress.com/2008/07/17/ruby-like-collection-handling-in-verbose-java-collectionutils/" class="more-link">Read More</a></p><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ytoh.wordpress.com&amp;blog=3728656&amp;post=21&amp;subd=ytoh&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h3>each, select, reject, collect, detect, inject, include?, compact &#8211; translated into Java</h3>
<p>I have compiled this little cheat sheet for those who like working with arrays in Ruby but not just for Ruby&#8217;s expressivness as a language but mostly for the idioms behind it. If you like the way Ruby (and also Smalltalk and others, but I like Ruby the best <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  ) handles arrays but you cannot use Ruby in your projects directly &#8212; CollectionUtils from the Apache Commons-Collections library (version 3.0 and above) can maybe be <em>the</em> answer you are looking for. For the price of added Java&#8217;s verbosity (compared to Ruby) you can find yourself on familiar ground with your Java collections.</p>
<h3>Cheat sheet</h3>
<h4>each</h4>
<p><pre class="brush: ruby;">
[1, 2, 3, 4].each { |x| print x }
# &gt;&gt; 1
# &gt;&gt; 2
# &gt;&gt; 3
# &gt;&gt; 4
</pre></p>
<p>one possibility how to translate Ruby&#8217;s each to Java</p>
<p><pre class="brush: java;">
List&lt;Integer&gt; i = Arrays.asList(1,2,3,4);
CollectionUtils.forAllDo(i, new Closure() {
    public void execute(Object i) {
        System.out.println(i);
    }
});
</pre></p>
<h4>select</h4>
<p><pre class="brush: ruby;">
[1, 2, 3, 4].select { |x| x % 2 == 0 }
# &gt;&gt; [2, 4]
</pre></p>
<p>one possibility how to translate Ruby&#8217;s select to Java</p>
<p><pre class="brush: java;">
List&lt;Integer&gt; i = Arrays.asList(1,2,3,4);
System.out.println(CollectionUtils.select(i, new Predicate() {
    public boolean evaluate(Object o) {
        return (Integer)o % 2 == 0;
    }
}));
</pre></p>
<h4>reject</h4>
<p><pre class="brush: ruby;">
digits = (1..10).to_a
digits.reject { |x| i &lt; 5 }
# &gt;&gt; [5, 6, 7, 8, 9, 10]
</pre></p>
<p>one possibility how to translate Ruby&#8217;s reject to Java</p>
<p><pre class="brush: java;">
List&lt;Integer&gt; i = new ArrayList&lt;Integer&gt;(10);
for (int j = 1; j &lt;= 10; j++) {
    i.add(j);
}
System.out.println(CollectionUtils.selectRejected(i, new Predicate() {
    public boolean evaluate(Object o) {
        return (Integer)o &lt; 5;
    }
}));
</pre></p>
<h4>collect</h4>
<p><pre class="brush: ruby;">
[1, 2, 3].collect { |x| x + 1 }
# &gt;&gt; [2, 3, 4]
</pre></p>
<p>one possibility how to translate Ruby&#8217;s collect to Java</p>
<p><pre class="brush: java;">
List&lt;Integer&gt; i = Arrays.asList(1,2,3);
System.out.println(CollectionUtils.collect(i, new Transformer() {
    public Object transform(Object input) {
        return (Integer)input + 1;
    }
}));
</pre></p>
<h4>detect</h4>
<p><pre class="brush: ruby;">
(1..100).to_a.detect { |i| i % 5 == 0 and i % 7 == 0 }
# &gt;&gt; 35
</pre></p>
<p>one possibility how to translate Ruby&#8217;s detect to Java</p>
<p><pre class="brush: java;">
List&lt;Integer&gt; i = new ArrayList&lt;Integer&gt;(100);
for (int j = 1; j &lt;= 100; j++) {
    i.add(j);
}
System.out.println(CollectionUtils.find(i, new Predicate() {
    public boolean evaluate(Object o) {
        return (Integer)o % 5 == 0 &amp;&amp; (Integer)o % 7 == 0;
    }
}));
</pre></p>
<h4>inject</h4>
<p><pre class="brush: ruby;">
[1, 2, 3, 4, 5].inject(0) { |sum, x| sum += x }
# &gt;&gt; 15
</pre></p>
<p>Translating inject is a little tricky because of the anonymous classes involved and the final value retrieval. Here is one possible way how to translate Ruby&#8217;s inject to Java. Probably not the best way to do it but still a working solution <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p><pre class="brush: java;">
List&lt;Integer&gt; i = new ArrayList&lt;Integer&gt;(5);
for (int j = 1; j &lt;= 5; j++) {
    i.add(j);
}
CollectionUtils.transform(i, new Transformer() {
    int sum = 0;
    public Object transform(Object input) {
        sum += (Integer)input;
        return sum;
    }
});
System.out.println(i.get(i.size() - 1));
</pre><br />
<strong>update:</strong> A better solution, as Daniel suggested, would be to use <em>Closure</em> instead of a <em>Transformer</em> with combination with <em>CollectionUtils#forAllDo()</em></p>
<p><pre class="brush: java;">
// lets use an inner class to do the work:
private static class SumAccumulator implements Closure {
    private int sum;

    public void execute(Object o) {
        sum += (Integer)o;
    }

    public int getSum() {
        return sum;
    }
}

// then the sum accumulation would look something like this:
SumAccumulator accumulator = new SumAccumulator();
CollectionUtils.forAllDo(i, accumulator);
System.out.println(accumulator.getSum());
</pre></p>
<h4>include?</h4>
<p><pre class="brush: ruby;">
digits = (1..10).to_a
digits.include? 5
# &gt;&gt; true
</pre></p>
<p>one possibility how to translate Ruby&#8217;s include? to Java</p>
<p><pre class="brush: java;">
List&lt;Integer&gt; i = new ArrayList&lt;Integer&gt;(100);
    for (int j = 1; j &lt;= 10; j++) {
        i.add(j);
    }
System.out.println(CollectionUtils.exists(i, PredicateUtils.identityPredicate(5)));
</pre></p>
<h4>compact</h4>
<p><pre class="brush: ruby;">
[&quot;a&quot;, null, &quot;b&quot;, null, &quot;c&quot;, null].compact
# &gt;&gt; [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;]
</pre></p>
<p>one possibility how to translate Ruby&#8217;s compact to Java</p>
<p><pre class="brush: java;">
List&lt;String&gt; s = new ArrayList&lt;String&gt;();
s.add(&quot;a&quot;);
s.add(null);
s.add(&quot;b&quot;);
s.add(null);
s.add(&quot;c&quot;);
CollectionUtils.filter(s, PredicateUtils.notNullPredicate());
System.out.println(s);
</pre></p>
<p>As you can see the added finger typing with &#8216;translated&#8217; Ruby into Java is in orders of hundreds of percent for small examples like these. But these constructs should stay unchanged and the more business logic you have the more efficient they will get. The added bonus is in being able to work with Java collections in somewhat familiar way to Ruby&#8217;s array. You could even make your own List interface implementation with each(), select(), reject(), collect(), detect(), inject(), include(), compact() methods added to the mix. And you could end up with something like this:</p>
<p><pre class="brush: java;">
class MyList extends ArrayList {
    public void each(Closure closure) {
        CollectionUtils.forAllDo(this, closure);
    }

    public MyList select(Predicate predicate) {
        return MyList(CollectionUtils.select(this, predicate));
    }

    // ... and so on ... you get the idea
}
</pre></p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/ytoh.wordpress.com/21/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/ytoh.wordpress.com/21/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ytoh.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ytoh.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ytoh.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ytoh.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/ytoh.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/ytoh.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/ytoh.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/ytoh.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ytoh.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ytoh.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ytoh.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ytoh.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ytoh.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ytoh.wordpress.com/21/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ytoh.wordpress.com&amp;blog=3728656&amp;post=21&amp;subd=ytoh&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ytoh.wordpress.com/2008/07/17/ruby-like-collection-handling-in-verbose-java-collectionutils/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d6074b6508685d183b68532b45e9d294?s=96&#38;d=http%3A%2F%2Fs0.wp.com%2Fi%2Fmu.gif" medium="image">
			<media:title type="html">ytoh</media:title>
		</media:content>
	</item>
		<item>
		<title>Windows networking concepts</title>
		<link>http://ytoh.wordpress.com/2008/05/22/windows-networking-concepts/</link>
		<comments>http://ytoh.wordpress.com/2008/05/22/windows-networking-concepts/#comments</comments>
		<pubDate>Thu, 22 May 2008 20:04:37 +0000</pubDate>
		<dc:creator>ytoh</dc:creator>
				<category><![CDATA[lessons]]></category>
		<category><![CDATA[windows]]></category>
		<category><![CDATA[windows networking]]></category>
		<category><![CDATA[windows server]]></category>

		<guid isPermaLink="false">http://ytoh.wordpress.com/?p=17</guid>
		<description><![CDATA[Domain, Domain tree, Forest, Domain Controller, Active Directory Q: What are the basics concepts of a corporate network on the Windows platform? When you imagine a basic computer network (for example: a home or small office network) you usually think of a bunch of computers connected via switches, that probably have a router connecting them &#8230;<p><a href="http://ytoh.wordpress.com/2008/05/22/windows-networking-concepts/" class="more-link">Read More</a></p><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ytoh.wordpress.com&amp;blog=3728656&amp;post=17&amp;subd=ytoh&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h3>Domain, Domain tree, Forest, Domain Controller, Active Directory</h3>
<p><strong>Q:</strong> What are the basics concepts of a corporate network on the Windows platform?</p>
<p style="text-align:justify;">When you imagine a basic computer network (for example: a home or small office network) you usually think of a bunch of computers connected via switches, that probably have a router connecting them to the internet and maybe some printers or scanners that they can share among them selves.</p>
<p style="text-align:justify;">Now when I say that &#8220;the computers share&#8221; printers and scanners I of course mean that one user sitting at a computer with a printer (scanner) lets another user sitting at another computer use his/hers printer (scanner). I say that computers share to illustrate one point: home and small office networks users mostly don&#8217;t interchange or share computers. They authenticate only locally (against the username and password stored on the local computer) and have mostly full access to the computer.</p>
<p style="text-align:justify;">Aside from internet access and file/printer/scanner sharing there is usually not much else going on in these networks.</p>
<p style="text-align:justify;"><strong>Q:</strong> How are the corporate networks different?</p>
<p style="text-align:justify;">There are some obvious and some not so obvious ways. They are obviously <em>bigger</em>. Not only <em>workstations</em> (personal computers) but also <em>servers</em> &#8212; computes dedicated to providing services to the network (e.g. File servers, Print servers, <acronym title="Domain Name System">DNS</acronym> servers, etc.) are on the network. The size of the network can vary &#8212; <em>laptop</em> users coming and going. And the security on corporate networks must be stricter assuming that the <em>data</em> handled are <em>more sensitive</em> than data handled on a home network <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  also when it provides some sort of <em>access</em> to it <em>from the internet</em> for example a Web server hosting the corporate web applications or the network provides Remote Desktop Connection.</p>
<p style="text-align:justify;">The less obvious reasons can be that the corporate network does not only host a lot of computers (be it workstations or servers) but also <em>can span</em> not only floor in a building or buildings but also <em>cities and even continents</em>. Company specific services (physically located on one side of the globe) have to be accessible to <em>authorized users</em> (even on the other side of the globe). Workstation users can interchange their computers (free-seating). A corporate network has to accommodate companies with complex inner structure without forcing their structure to change and has to be <em>flexible</em> for example in an event of one company buying another.</p>
<p style="text-align:justify;">Now with this in mind we can ask how does the Windows platform accomplish these things?</p>
<p style="text-align:justify;"><strong>Q:</strong> What do you mean by &#8216;these things&#8217;?</p>
<ul>
<li>user authentication &#8211; controlling user access to the network</li>
<li>user authorization &#8211; controlling authenticated user access to network resources (data, servers, printers, etc.)</li>
<li>user account management &#8211; controlling user account security (by forcing secure passwords or restricting user local machine privileges like disallowing changes to hardware or network settings)</li>
<li>network resources management (providing names and lookup services for those names &#8211; physical resource location transparency)</li>
<li>logical grouping of user and network resources to simplify their management</li>
</ul>
<p>The Windows platform provides many more features but for now lets focus on the above.</p>
<p><strong>Q:</strong> So how do I build a network solution on the Windows platform?</p>
<p style="text-align:justify;">First of all you have to understand that your network and its resources are on the Windows platform network solution managed by a service called <em>Active Directory</em>. The Active Directory directory service is provided with Windows servers. So to build a network on the Windows platform you will need a Windows server for example a <a href="http://www.microsoft.com/windowsserver2003/default.mspx">Windows Server 2003</a>. So lets assume that you have one. What is next? Next you&#8217;ll need to understand a little bit about Active Directory and the structures it manages.</p>
<h4>Active Directory</h4>
<p>We said that Active Directory is a directory service. From <a href="http://en.wikipedia.org/wiki/Directory_service">Wikipedia</a>:</p>
<blockquote><p>A directory service (DS) is a software application — or a set of applications — that stores and organizes information about a computer network&#8217;s users and network resources, and that allows network administrators to manage users&#8217; access to the resources. Additionally, directory services act as an abstraction layer between users and shared resources.</p></blockquote>
<p style="text-align:justify;">And more specifically it&#8217;s Microsoft&#8217;s implementation of the Lightweight Directory Access Protocol or LDAP and was first released with Windows 2000 Server edition.</p>
<p style="text-align:justify;">Active Directory is simply a database of objects which represent users, computers, network resources and groupings of each of them. On the top level Active Directory manages a domain forest which is a grouping of domain trees. A domain forest can also consist of a single domain tree. The picture below shows a more general version of a domain forest.</p>
<p style="text-align:justify;"><a href="http://ytoh.files.wordpress.com/2008/05/domain_forest.jpg"><img class="alignnone size-medium wp-image-19" src="http://ytoh.files.wordpress.com/2008/05/domain_forest.jpg?w=300&#038;h=215" alt="" width="300" height="215" /></a></p>
<p style="text-align:justify;">To understand what a domain forest is and what it is good for lets first discuss what is a domain.</p>
<h4>Domain</h4>
<p style="text-align:justify;">A domain is a logical grouping of objects (just like the domain forest) but something like a second level grouping. And by second level I mean a more specific grouping. The objects managed in a single domain have the same distinguished name suffix (the domain component part).</p>
<p style="text-align:justify;"><strong>Q:</strong> What are distinguished names?</p>
<p style="text-align:justify;">Distinguished name (DN) is a notion from LDAP &#8212; Active Directory is an implementation of LDAP remember? As you might have guessed DNs are used in Active Directory to identify the specific objects stored in it. Everything in Active Directory has a distinguished name &#8212; users, computers, groups, organization units and so on.</p>
<p style="text-align:justify;">The best way to explain this is to look at an example.</p>
<p style="text-align:justify;">Lets say we have our own organization called awesome organization <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  , you are part of the management of the organization and your name is John Doe. Then your distinguished name (the name given to you by Active Directory) would be something like this:</p>
<pre>CN="John Doe", CN="management", DC="awesome", DC="org"</pre>
<p style="text-align:justify;">Where CN stands for <em>Common Name</em> and DC stands for <em>Domain Component</em>. You can see that the naming in Active Directory is hierarchical. Another thing you can notice is that the domain has a name! And as we&#8217;ve discussed above the domain manages objects with the same distinguished name suffices. In the above example that would mean objects whose distinguished names end with <em>DC=&#8221;awesome&#8221;, DC=&#8221;org&#8221;</em>.</p>
<p style="text-align:justify;"><strong>Q:</strong> Do I have to buy a domain called awesome.org to be able to use it with Active Directory?</p>
<p style="text-align:justify;">No you don&#8217;t. Domain names in Active Directory are completely independent of domain names on the Internet. You can call you domain <em>local</em> or <em>business</em> or <em>whatever</em> you like. If it bothers you that they look the same it&#8217;s just because the method used to resolve domain names on the Internet and in Windows domains is the same namely <acronym title="Domain Name System">DNS</acronym>.</p>
<p style="text-align:justify;">With the notion of domains as a collection of objects with the same distinguished name suffix we can return to the domain forest and see its function. The domain forest is a grouping of domains (domain trees) and that means that a domain forest can manage objects without the need for them to have the same distinguished name suffix.</p>
<h4>Domain tree</h4>
<p style="text-align:justify;">A domain tree is actually a more general term for a domain. You can think of a domain tree as a domain with zero or more subdomains.</p>
<p style="text-align:justify;"><a href="http://ytoh.files.wordpress.com/2008/05/domain_forest.jpg"><img class="alignnone size-medium wp-image-19" src="http://ytoh.files.wordpress.com/2008/05/domain_forest.jpg?w=300&#038;h=215" alt="" width="300" height="215" /></a></p>
<p style="text-align:justify;">If from our previous example (awesome.org) we wanted to make our management department a whole subdomain its name would be management.awesome.org. And then your DN would be:</p>
<pre>CN="John Doe", DC="management", DC="awesome", DC="org"</pre>
<p style="text-align:justify;">The CN in front of management changed to DC.</p>
<h4>Domain Controllers</h4>
<p style="text-align:justify;">OK, so we know a bit about Active Directory. We know that it&#8217;s a database of some sorts. It manages objects that represent users, computers, user groups, computer groups, organizational units (more on these later). But where is this database stored physically? The answer is (as the title of this section suggests) <em>Domain Controllers</em>. A domain controller is a piece of software shipped with Windows servers that manages the authentication requests in a windows domain. If a computer is a part of a domain and a user wants to log in he/she provides the username and password. The computer instead of checking that information against something stored locally it contacts a domain controller and asks if it can do the authentication instead. If the domain controller authenticates the user the user is granted access to the local machine and the domain.</p>
<p style="text-align:justify;">Three things to remember:</p>
<ol>
<li>the computer must be part of a domain</li>
<li>the computer uses the domain controller to check the users credentials</li>
<li>the domain controller does the authentication not the authorization</li>
</ol>
<h3>Resource and user/machine management concepts</h3>
<p style="text-align:justify;">There are two concepts: one for managing network resources (access to servers, share files, printers, etc.) and one for managing the user workstations and user accounts.</p>
<h4>Access Control Lists</h4>
<p style="text-align:justify;">To manage network resources windows domains use Access Control Lists or ACLs. ACL is just an enumeration of users or groups with their rights to use a particular resource. The important thing is that the ACL are stored with the resources. Active Directory does not store them. For example:</p>
<p style="text-align:justify;">You have a File server in your domain. A File server provides the users of the domain with the access to certain folders in its directory structure. On each of those folders you can set an ACL saying which users can read/write/delete(/and many more options) these folders, subfolder and so on. Here is a concrete example setting permissions to Read &amp; Execute, List Folder Contents and Read for the group named Managers on the folder named DATA.</p>
<p style="text-align:justify;"><a href="http://ytoh.files.wordpress.com/2008/05/acl.jpg"><img class="alignnone size-medium wp-image-20" src="http://ytoh.files.wordpress.com/2008/05/acl.jpg?w=232&#038;h=300" alt="" width="232" height="300" /></a></p>
<p style="text-align:justify;">You can imagine that setting permissions for every individual user would be a daunting task. The solution? Groups! Group users, group machines, group groups, group everything and set ACLs on groups instead of individual users.</p>
<h4>Group Policies</h4>
<p style="text-align:justify;">To manage user accounts and machines you use a <em>Group Policy</em> (GP). Group policies are rules applied to the users workstation at computer startup (Computer configuration) and/or at logon (User configuration). There are around 1000 individual setting you can apply to the users workstation with Group Policies. From the complexity of passwords needed to logon, the contents of the Start menu, access to the Control Panel to write permission of the local hard drive or profile folder redirections.</p>
<p style="text-align:justify;">You can even use GPs to <a href="http://ytoh.wordpress.com/2008/05/15/clean-up-your-windows-desktop/">remove the pesky Recycle Bin desktop icon</a> if you don&#8217;t want it there <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p style="text-align:justify;"><strong>Q:</strong> I really don&#8217;t want to set all 1000 individual setting. Is there no easier way?</p>
<p style="text-align:justify;">YES, THERE IS! And thank God for that! Microsoft developed the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=354b9f45-8aa6-4775-9208-c681a7043292&amp;DisplayLang=en">Common Desktop Scenarios</a> which are implementation if GPs for some common types of users and workstations. The scenarios contain GPs for:</p>
<ul>
<li>Lightly managed
<ul>
<li>Power users</li>
<li>Laptop users</li>
</ul>
</li>
<li>Highly managed
<ul>
<li>Application station</li>
<li>Multi-user station</li>
<li>Task stations</li>
<li>Kiosk station</li>
</ul>
</li>
</ul>
<p>In most cases only minor adjustments to those scenarios are necessary to get the desired result.</p>
<h4>Additional useful links</h4>
<p><a href="http://www.windowsnetworking.com/articles_tutorials/Networking-Basics-Part1.html">http://www.windowsnetworking.com/articles_tutorials/Networking-Basics-Part1.html</a><br />
<a href="http://web2.blogtells.com/">http://web2.blogtells.com/</a><a></a></p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/ytoh.wordpress.com/17/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/ytoh.wordpress.com/17/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ytoh.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ytoh.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ytoh.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ytoh.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/ytoh.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/ytoh.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/ytoh.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/ytoh.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ytoh.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ytoh.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ytoh.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ytoh.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ytoh.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ytoh.wordpress.com/17/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ytoh.wordpress.com&amp;blog=3728656&amp;post=17&amp;subd=ytoh&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ytoh.wordpress.com/2008/05/22/windows-networking-concepts/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d6074b6508685d183b68532b45e9d294?s=96&#38;d=http%3A%2F%2Fs0.wp.com%2Fi%2Fmu.gif" medium="image">
			<media:title type="html">ytoh</media:title>
		</media:content>

		<media:content url="http://ytoh.files.wordpress.com/2008/05/domain_forest.jpg?w=300" medium="image" />

		<media:content url="http://ytoh.files.wordpress.com/2008/05/domain_forest.jpg?w=300" medium="image" />

		<media:content url="http://ytoh.files.wordpress.com/2008/05/acl.jpg?w=232" medium="image" />
	</item>
		<item>
		<title>Ruby metaprogramming step-by-step</title>
		<link>http://ytoh.wordpress.com/2008/05/17/ruby-metaprogramming-step-by-step/</link>
		<comments>http://ytoh.wordpress.com/2008/05/17/ruby-metaprogramming-step-by-step/#comments</comments>
		<pubDate>Sat, 17 May 2008 19:53:12 +0000</pubDate>
		<dc:creator>ytoh</dc:creator>
				<category><![CDATA[lessons]]></category>
		<category><![CDATA[metaprogramming]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://ytoh.wordpress.com/?p=12</guid>
		<description><![CDATA[Instance, class, superclass, metaclass Q: What does metaprogramming mean exactly? It means writing programs which modify them selves and/or write other programs. At runtime! In Ruby the most common example of metaprogramming is the shorthand for creating attribute readers/writers/accessors (i.e. getters/setters) The attr_accessor is an ordinary class method which accepts symbols (or strings) and based &#8230;<p><a href="http://ytoh.wordpress.com/2008/05/17/ruby-metaprogramming-step-by-step/" class="more-link">Read More</a></p><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ytoh.wordpress.com&amp;blog=3728656&amp;post=12&amp;subd=ytoh&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h3>Instance, class, superclass, metaclass</h3>
<p style="text-align:justify;"><strong>Q:</strong> What does metaprogramming mean exactly?</p>
<p style="text-align:justify;">It means writing programs which modify them selves and/or write other programs. At runtime! In Ruby the most common example of metaprogramming is the shorthand for creating attribute readers/writers/accessors (i.e. getters/setters)</p>
<p><pre class="brush: ruby;">
class Person
  attr_accessor :name
end

# is extended to (and therefore is equivalent to)
class Person
  def name=(val)
    @name = val
  end
  def name
    @name
  end
end
</pre></p>
<p style="text-align:justify;">The <em>attr_accessor</em> is an ordinary class method which accepts symbols (or strings) and based on those symbols defines the methods like <em>name=</em> and <em>name</em>. That is it modifies itself!</p>
<p style="text-align:justify;"><strong>Q:</strong> Is this it? Is this all we can do with it?</p>
<p style="text-align:justify;">Not at all. Pretty much anything you can do statically (before compilation) you can also do dynamically (at runtime). This includes declaring new classes, adding class and instance methods to those classes, setting their instance variables and so on.</p>
<p style="text-align:justify;">But if you want to do that you need to understand a few things about the inner workings of Ruby. Specifically:</p>
<ol>
<li>How to create new classes at runtime</li>
<li>Where are method stored</li>
<li>How to programmatically define a method</li>
<li>Understand instance_eval, class_eval</li>
</ol>
<h3>How to create new classes at runtime</h3>
<p>Creating new classes at runtime is actually the easiest thing of the above four. It&#8217;s just a call to the class method of the class Class (that&#8217;s quite a mouthful).</p>
<p><pre class="brush: ruby;">
Person = Class::new

# is equivalent to
class Person
end
</pre></p>
<p style="text-align:justify;">Notice the double colons ( :: ) after Class. It&#8217;s there to remind us that we are calling a class method. <em>Class::new</em> creates an anonymous class. When we assign it to a constant we effectively give it a name. We can also supply a superclass to the <em>Class::new</em> method to create a subclass of that superclass.</p>
<h3>Where are method stored</h3>
<p style="text-align:justify;"><strong>Q:</strong> Creating classes is great and all but we would really like them to do something useful not just to sit around. So how to we define methods?</p>
<p style="text-align:justify;">The <span style="text-decoration:underline;">real</span> question is &#8212; which methods? Instance methods or class methods? This is a crucial point because instance method actually reside elsewhere then class methods. The picture below (is just an approximation) illustrates the process of resolution of method calls.</p>
<p><a href="http://ytoh.files.wordpress.com/2008/05/ruby_metaprogramming_model.jpg"><img class="alignnone size-medium wp-image-13" src="http://ytoh.files.wordpress.com/2008/05/ruby_metaprogramming_model.jpg?w=300&#038;h=174" alt="" width="300" height="174" /></a></p>
<h4>Instance method call</h4>
<p style="text-align:justify;">Instance method &#8220;source codes&#8221; reside in classes. In order for an instance of a class to run such a method the instance needs to reach in to its class, find out if the class has the method and then run the method. Imagine we want to call the instance method <em>im</em> on the <em>instanceOfCustom</em> (which is our custom class, duh):</p>
<ol>
<li>instanceOfCustom follows the klass pointer to its class</li>
<li>searches for the method im in the repository of methods inside the class</li>
<li>invokes the method</li>
</ol>
<h4>Class method call</h4>
<p><strong>Q:</strong> So if the class holds the instance methods where are the class methods?</p>
<p style="text-align:justify;">Good question. Lets look in the superclass of our <em>Custom</em> class. Nope, not there &#8230; just more instance methods. So what if we would follow the same procedure like with the instance method call? We (and by we we mean our <em>Custom</em> class) get a request to run the class method <em>cm</em>:</p>
<ol>
<li> We follow our klass pointer to <em>something</em></li>
<li>then search that <em>somethings</em> repository of methods and are surprised that it actually has one</li>
<li>invoke the method</li>
</ol>
<p style="text-align:justify;">What is that <em>something</em> that lets Ruby have such elegantly similar (i.e. the same) procedure for calling instance and class methods? Well it behaves something like a class but is not quite a class and in fact it&#8217;s a <strong>metaclass</strong>. It&#8217;s kinda like a new class hierarchy (see the above picture). Metaclasses are virtual (notice the flag V, you cannot make instance of them) and are created by the interpreter on demand and are not visible in the class hierarchy as you cannot reach them using the superclass reference. The metaclass concept can be hard to understand so try reading <a href="http://whytheluckystiff.net/articles/seeingMetaclassesClearly.html">why&#8217;s seeing metaclasses clearly</a> for more insight.</p>
<p style="text-align:justify;">OK, now that we know where the individual methods reside lets see how can we actually put them there our selves programmatically.</p>
<h3>How to programmatically define a method</h3>
<p style="text-align:justify;">Now that we know where methods need to be stored to take the property of being instance or class methods we can try to create our own method programmatically. One way to do so is to use <em>instance_eval</em> and <em>class_eval</em> methods and inside their body define the method we want to add. Lets focus on <em>class_eval</em> first.</p>
<p style="text-align:justify;">With <em>class_eval</em> you can run code in the context of a class (it&#8217;s just like being inside class &#8230; end).</p>
<p><pre class="brush: ruby;">
# we'll use the above defined Person class
Person.class_eval do
  def name
    @name
  end
  def name=(val)
    @name = val
  end
end

p = Person.new
p.name = 'John'
p.name
# =&gt; &quot;John&quot;
</pre></p>
<p style="text-align:justify;">This way you can add the instance and class methods <em>name</em> and <em>name=</em> to whatever class you wish. For example:</p>
<p><pre class="brush: ruby;">
def add_name(klass)
  klass.class_eval do
    def name; @name; end
    def name=(val); @name = val; end
    def self.name; self.to_s; end
  end
end

add_name(String)
a = 'hello'
a.name = 'John'
a.name
# =&gt; &quot;John&quot;
a.class.name
# =&gt; &quot;String&quot;
</pre></p>
<p><strong>Q:</strong> So what is <em>instance_eval</em> for then? And why did we bother learning about metaclasses?</p>
<p style="text-align:justify;">Good questions. Before answering them lets make it a bit more confusing than it is now but after that the explanation will make more sense. Lets try the same example but change the <em>class_eval</em> for <em>instance_eval</em>.</p>
<p><pre class="brush: ruby;">
def add_name(klass)
  klass.instance_eval do
    def name; @name; end
    def name=(val); @name = val; end
    def self.name; self.to_s; end
  end
end

add_name(String)
a = 'hello'
a.name = 'John'
a.name
# =&gt; &quot;John&quot;
a.class.name
# =&gt; &quot;String&quot;
</pre></p>
<p style="text-align:justify;">We get the same result! Surprised? There is no reason to be and this is why: <em>classes are just instances of the class Class</em>. That is why we get the same results with <em>instance_eval</em> and <em>class_eval</em> called on a class.</p>
<p style="text-align:justify;"><strong>Q:</strong> So what is instance_eval for again?</p>
<p style="text-align:justify;">The reason that you can use <em>instance_eval</em> on classes is a side effect of the fact that classes are instances themselves. The really cool thing about <em>instance_eval</em> is that you can call <em>instance_eval</em> on objects and execute code in their context. So we can for example &#8220;cheat&#8221; and display private attributes using <em>instance_eval</em>.</p>
<p><pre class="brush: ruby;">
class C
  def initialize
    @a = 1
  end
end
C.new.instance_eval { @a }
# =&gt; 1
</pre></p>
<p style="text-align:justify;">Or even add singleton (object specific) methods to objects!</p>
<p><pre class="brush: ruby;">
p1 = Person.new
p2 = Person.new
p1.instance_eval do
  def say_hello
    p 'hello'
  end
end
p1.say_hello
# =&gt; &quot;hello&quot;
p2.say_hello
# =&gt; NoMethodError: undefined method `say_hello' for #&lt;Person:0x2b8462c&gt;
#            from (irb):9
</pre></p>
<p style="text-align:justify;">How cool is that! Only the polite person (<em>p1</em>) can <em>say_hello</em> and the other one (<em>p2</em>) is just rude. The <em>instance_eval</em> method is defined in class Object so everyone can use it but <em>class_eval</em> method is defined in Module and can be used only by modules an classes.</p>
<p style="text-align:justify;"><strong>Q:</strong> I still don&#8217;t see how the metaclasses fit in.</p>
<p style="text-align:justify;">The above examples of adding instance and class methods are perfectly valid but there are things that you cannot accomplish by explicitly defining methods. Sometimes you need to pass stuff from outside into the method definition like symbols, string, blocks and so on. And by starting a definition you effectively cut yourself off from the surrounding scope. For instance you cannot access variables assigned in the outer scope. Understanding variable scope, blocks and Procs takes a longer discussion that&#8217;s why I wrote <a href="http://ytoh.wordpress.com/2008/05/17/ruby-blocks-lambda-and-procs/">a whole post about this topic</a>.</p>
<p style="text-align:justify;">So assuming you have an idea about variable scope, blocks and Procs you should be able to see the shortcomings of the metaprogramming using explicit method definitions. The way Ruby does metaprogramming without explicit definitions is by providing the <em>define_method</em> private method in the Object class. We can call this method passing it the method name (a symbol) as argument and associate a block with it which will be the method&#8217;s body and Ruby defines the method for us. Thanks to this we don&#8217;t have to start a new method definition and we have access to variables in the surrounding scope. As the block of the method body is transformed into a Proc (more on this in the post I mentioned above) the context in which it&#8217;s defined is associated with it so the block will have access to variables defined in that scope even in a different context (in the context of a class or a instance, etc.). Lets look at an example.</p>
<p><pre class="brush: ruby;">
Person = Class::new
var = 5
Person.class_eval do
  def age
    @age ||= var
  end
end
Person.new.age
# =&gt; NameError: undefined local variable or method `age' for #&lt;Person:0x2b78764&gt;
#            from (irb):4:in `age'
#            from (irb):8

Person.class_eval do
  define_method(:age) do
    @age ||= var
  end
end
Person.new.age
# =&gt; 5
</pre></p>
<p style="text-align:justify;">The first time we tried calling the method age we got an error because Ruby cannot find the variable <em>var</em> because it&#8217;s not a local variable. But thanks to block turning to Procs the second time everything works fine.</p>
<p style="text-align:justify;"><strong>Q:</strong> Neat, so we can define instance methods without explicit definition. What about class methods?</p>
<p style="text-align:justify;">The <em>define_method</em> adds a new method definition to a class which has the effect of a new instance method (because the class is the repository of instance methods remember?). Do you see them now?</p>
<p style="text-align:justify;">Metaclasses to the rescue! By now it should be clear that calling the <em>define_method</em> method in a metaclass of a class should add a new method to the method repository of the metaclass a thus effectively making the new method a class method. Yes, it&#8217;s exactly the same as with instance methods! There is a little snag though. There is no direct way of getting to the metaclass of a class (presently at least). The way people do it is to open the metaclass&#8217; definition and return a reference to it.</p>
<p><pre class="brush: ruby;">
class Person
  def self.metaclass
    class &lt;&lt; self
      self
    end
  end
end

# now we can use the metaclass to define a class method
Person.metaclass.class_eval do
  define_method(:max_age) do
    125
  end
end
Person.max_age
# =&gt; 125
</pre></p>
<p style="text-align:justify;">Piece of cake!</p>
<p style="text-align:justify;"><strong>Q:</strong> How does the method self.metaclass work?</p>
<p style="text-align:justify;">Two reasons.</p>
<p style="text-align:justify;">First because Ruby allows us to get to so-called per-object classes. The notation <em>class &lt;&lt; self</em> is used to open this per-object (singleton) class associated with an object. (You can use this notation as another way of adding methods to a single object.)  And since classes are objects too we can access their per-object class the same way but in reality what we get we call the class&#8217; metaclass.</p>
<p style="text-align:justify;">The second reason is that Ruby is a dynamic language. And therefore you can return values from the definition of a class.</p>
<p><pre class="brush: ruby;">
class C
  10
end
# =&gt; 10
</pre></p>
<p style="text-align:justify;"><strong>Q:</strong> This is all interesting and all but what  can I do with it?</p>
<p style="text-align:justify;">Metaprogramming is best suited for automating repetitive tasks (like creating attribute readers/writters), developing frameworks (a great example is ActiveRecord in Rails and how it gets metadata from the database and then builds up your model classes without you having to do anything) and having lots and lots of fun!!!</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/ytoh.wordpress.com/12/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/ytoh.wordpress.com/12/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ytoh.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ytoh.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ytoh.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ytoh.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/ytoh.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/ytoh.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/ytoh.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/ytoh.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ytoh.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ytoh.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ytoh.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ytoh.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ytoh.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ytoh.wordpress.com/12/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ytoh.wordpress.com&amp;blog=3728656&amp;post=12&amp;subd=ytoh&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ytoh.wordpress.com/2008/05/17/ruby-metaprogramming-step-by-step/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d6074b6508685d183b68532b45e9d294?s=96&#38;d=http%3A%2F%2Fs0.wp.com%2Fi%2Fmu.gif" medium="image">
			<media:title type="html">ytoh</media:title>
		</media:content>

		<media:content url="http://ytoh.files.wordpress.com/2008/05/ruby_metaprogramming_model.jpg?w=300" medium="image" />
	</item>
		<item>
		<title>Ruby blocks, lambda and Procs</title>
		<link>http://ytoh.wordpress.com/2008/05/17/ruby-blocks-lambda-and-procs/</link>
		<comments>http://ytoh.wordpress.com/2008/05/17/ruby-blocks-lambda-and-procs/#comments</comments>
		<pubDate>Sat, 17 May 2008 19:49:12 +0000</pubDate>
		<dc:creator>ytoh</dc:creator>
				<category><![CDATA[lessons]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://ytoh.wordpress.com/?p=16</guid>
		<description><![CDATA[Block Ruby code block are chunks of code surrounded by do and end keywords (or single line block with curly braces). Blocks can take arguments. The arguments are declared surrounding variable names by pipe symbols. They can be associated with method calls and evaluated using yield. Passing arguments is accomplished by passing arguments to yield. &#8230;<p><a href="http://ytoh.wordpress.com/2008/05/17/ruby-blocks-lambda-and-procs/" class="more-link">Read More</a></p><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ytoh.wordpress.com&amp;blog=3728656&amp;post=16&amp;subd=ytoh&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h3>Block</h3>
<p style="text-align:justify;">Ruby code block are chunks of code surrounded by <strong><em>do</em> </strong>and <strong><em>end</em> </strong>keywords (or single line block with curly braces). Blocks can take arguments. The arguments are declared surrounding variable names by pipe symbols. They can be associated with method calls and evaluated using <strong>yield</strong>. Passing arguments is accomplished by passing arguments to yield. Any method can be called with a block as an implicit argument. So for example:</p>
<p><pre class="brush: ruby;">
# implicit block evaluation
def m1
  yield
end

# passing arguments to implicit block
def m2( param )
  yield param
end

# assigning a name to an implicit block
def m3( param, &amp;block )
  block.call param
end

m1 { puts 'hello' }
# =&gt; &quot;hello&quot;

m2( 'hello' ) { |x| puts x }
# =&gt; &quot;hello&quot;

m3( 'hello' ) do |x|
  3.times { puts x }
end
# =&gt; &quot;hello&quot;
# =&gt; &quot;hello&quot;
# =&gt; &quot;hello&quot;
</pre></p>
<p style="text-align:justify;">In the above example we can see how are blocks associated with method calls and how are blocks evaluated inside a method. In the <em>m3</em> method call we can see how multi line blocks are associated with method calls.</p>
<p style="text-align:justify;"><strong>Q:</strong> Whoa! Where is the yield in m3, hmm? And what is the meaning of the ampersand before the parameter block?</p>
<p style="text-align:justify;">You got me <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  The yield is replaced by <em>block.call</em> because we supplied a name for the block being associated (and a very unimaginative one: <em>block</em>) and thanks to that by the time the block gets to the method body it&#8217;s no longer a block. It&#8217;s actually a Proc. In <em>m1</em> and <em>m2</em> the block is anonymous and we evaluate it by calling <em>yield</em>. If we want to give a name to the block (by putting an ampersand before the name of the methods <em><span style="text-decoration:underline;"><strong>last</strong></span></em> parameter) we get a reference to it wrapped in a Proc object. And to evaluate a Proc you need to call it&#8217;s <em>call</em> method.</p>
<p style="text-align:justify;">The <em>m3 </em>example is interesting in another way also. It shows how blocks handle scope of variables. The block sees the variables in the context (scope) it was declared in. The block <em>{ puts x }</em> sees the variable <em>x</em> declared outside of its scope and therefore can print it. And blocks are generous and can provide that kind of scope transcending service to anyone &#8212; but only if they go through a self sacrifice and change into a Proc!</p>
<h3>Proc</h3>
<p style="text-align:justify;">A Proc can be created by associating a block to the call of Proc.new (actually associating a block with <em>any </em>method call does the trick). Proc is a block associated with a context. So for example if we have a local variable say <em>foo</em> and we use it in a block and send the block to a method which automatically converts the block to a Proc then the formally local variable <em>foo</em> can be accessed in the new scope of the method. Pretty cool, huh?</p>
<p><pre class="brush: ruby;">
def bar
  yield( 10 )
  puts var # bam! this throws an error
end

var = 1
bar { |value| var = value }
# =&gt; 10
# =&gt; NameError: undefined local variable or method `var' for main:Object
#            from (irb):3:in `bar'
#            from (irb):6
</pre></p>
<p style="text-align:justify;">In the above example we declare a method bar which cannot access the variable <em>var</em> which is defined later in the scope but using a block we can assign a value to it without being able to access it directly (hence the NameError). Since the start of a method (or class) definition opens a new context we cannot assign the value of <em>var</em> in a method and see it change in the outer scope without the cool goodness of Procs. So only an &#8220;insane&#8221; person would try something like this:</p>
<p><pre class="brush: ruby;">
var = 1
def bar
  var = 10
end
bar
puts var
# =&gt; 1
</pre></p>
<p>And expect <em>var</em> to be 10.</p>
<h3>Lambda</h3>
<p>Lambda is a Kernel method (so we should write it with a lowercase l &#8211; <em>lambda</em>) a call to which is equivalent to Proc.new. Except that a <em>lambda</em> returns a Proc which checks the number of parameters passed when called. If the number of parameters is wrong you get a warning.</p>
<p><pre class="brush: ruby;">
l = lambda {|x| 3.times {puts x}}
l.call &quot;hi&quot;,&quot;you&quot;
# =&gt; (irb):2: warning: multiple values for a block parameter (2 for 1)
# =&gt; &quot;hi&quot;
# =&gt; &quot;you&quot;
# =&gt; &quot;hi&quot;
# =&gt; &quot;you&quot;
# =&gt; &quot;hi&quot;
# =&gt; &quot;you&quot;
</pre></p>
<h3>Lambda vs Proc</h3>
<p>From <a href="http://en.wikipedia.org/wiki/Closure_(computer_science)">Wikipedia</a></p>
<blockquote><p>Both <code>Proc.new</code> and <code>lambda</code> in this example are ways to create a closure, but semantics of the closures thus created are different with respect to the <code>return</code> statement.</p></blockquote>
<p><pre class="brush: ruby;">
def foo
  f = Proc.new { return &quot;return from foo from inside proc&quot; }
  f.call # control leaves foo here
  return &quot;return from foo&quot;
end

def bar
  f = lambda { return &quot;return from lambda&quot; }
  f.call # control does not leave bar here
  return &quot;return from bar&quot;
end

puts foo # prints &quot;return from foo from inside proc&quot;
puts bar # prints &quot;return from bar&quot;
</pre></p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/ytoh.wordpress.com/16/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/ytoh.wordpress.com/16/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ytoh.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ytoh.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ytoh.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ytoh.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/ytoh.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/ytoh.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/ytoh.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/ytoh.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ytoh.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ytoh.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ytoh.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ytoh.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ytoh.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ytoh.wordpress.com/16/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ytoh.wordpress.com&amp;blog=3728656&amp;post=16&amp;subd=ytoh&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ytoh.wordpress.com/2008/05/17/ruby-blocks-lambda-and-procs/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d6074b6508685d183b68532b45e9d294?s=96&#38;d=http%3A%2F%2Fs0.wp.com%2Fi%2Fmu.gif" medium="image">
			<media:title type="html">ytoh</media:title>
		</media:content>
	</item>
		<item>
		<title>Clean up your windows desktop</title>
		<link>http://ytoh.wordpress.com/2008/05/15/clean-up-your-windows-desktop/</link>
		<comments>http://ytoh.wordpress.com/2008/05/15/clean-up-your-windows-desktop/#comments</comments>
		<pubDate>Thu, 15 May 2008 13:11:31 +0000</pubDate>
		<dc:creator>ytoh</dc:creator>
				<category><![CDATA[howto]]></category>
		<category><![CDATA[customization]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://ytoh.wordpress.com/?p=6</guid>
		<description><![CDATA[If for whatever reason you want your windows desktop to contain no icons you have probably tried deleting the Recycle Bin icon from your desktop. And I mean hitting the delete button while you have the Recycle Bin icon selected. But that didn&#8217;t do anything. My reason for doing this was I got tired of &#8230;<p><a href="http://ytoh.wordpress.com/2008/05/15/clean-up-your-windows-desktop/" class="more-link">Read More</a></p><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ytoh.wordpress.com&amp;blog=3728656&amp;post=6&amp;subd=ytoh&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p style="text-align:justify;">If for whatever reason you want your windows desktop to contain no icons you have probably tried deleting the Recycle Bin icon from your desktop. And I mean hitting the delete button while you have the Recycle Bin icon selected. But that didn&#8217;t do anything. My reason for doing this was I got tired of minimizing all my opened windows (<a href="http://ytoh.files.wordpress.com/2008/05/windows-key.png"><img class="alignnone size-full wp-image-8" src="http://ytoh.files.wordpress.com/2008/05/windows-key.png?w=545" alt=""   /></a> + M) when I tried to get to the desktop icons. Since I always have Firefox, an IDE or a shell window opened this tended to happen a lot.</p>
<p>I decided to use <a title="RocketDock is a smoothly animated, alpha blended application launcher." href="http://rocketdock.com/">RocketDock</a> instead of the desktop icons utilizing its very nice (and free) AutoHide feature.</p>
<p style="text-align:justify;">Being a &#8220;purist&#8221; I spotted a duplication. RocketDock contains built in icons for My Computer, My Network Places and Recycle Bin and so does my desktop (because I prefer the classic windows start menu). That is why I decided to remove these icons from my desktop.</p>
<h3>The cleanup</h3>
<p>Removing the My Computer and My Network Places is easy. Delete works just fine. The hard part is removing the Recycle Bin. There are multiple ways how to get rid of the Recycle Bin icon actually:</p>
<ul>
<li>A third-party program was used to hide the Recycle 				Bin.</li>
<li>The TweakUI program was used to hide the Recycle Bin.</li>
<li>The registry information for the Recycle Bin was 				deleted.</li>
<li>A Group Policy setting was used to hide the Recycle Bin.</li>
</ul>
<p>I used my Local Computer <a title="Group Policy FAQ" href="http://technet2.microsoft.com/windowsserver/en/technologies/featured/gp/faq.mspx">Group Policy</a> to do the job.<br />
<strong>NOTE:</strong> Windows XP Home Edition does not support Group Policy.</p>
<h3>The procedure</h3>
<ol>
<li>Open the Group Policy Object Editor</li>
<li>Enable the &#8216;Remove Recycle Bin icon from the desktop&#8217; option</li>
<li>Restart your computer</li>
<li>Delete the Recycle Bin icon</li>
</ol>
<h4>Open the Group Policy Object Editor</h4>
<p>From the <strong>Start</strong> menu select <strong>Run</strong>, type <em>gpedit.msc</em> and press <strong>OK</strong>.</p>
<p><a href="http://ytoh.files.wordpress.com/2008/05/gpedit.png"><img class="alignnone size-medium wp-image-9" src="http://ytoh.files.wordpress.com/2008/05/gpedit.png?w=300&#038;h=154" alt="" width="300" height="154" /></a></p>
<p>The Group Policy Object Editor shows up.</p>
<h4>Enable the &#8216;Remove Recycle Bin icon from the desktop&#8217; option</h4>
<p>In the <strong>Group Policy Object Editor</strong> navigate to:</p>
<p>Local Computer Policy -&gt; User Configuration -&gt; Administrative Templates -&gt; Desktop<br />
and double click <strong>Remove Recycle Bin icon from desktop</strong> option and change from Not configured to <strong>Enabled</strong>.</p>
<p><a href="http://ytoh.files.wordpress.com/2008/05/group-policy.png"><img class="alignnone size-medium wp-image-10" src="http://ytoh.files.wordpress.com/2008/05/group-policy.png?w=300&#038;h=160" alt="" width="300" height="160" /></a></p>
<h4>Restart your computer</h4>
<p style="text-align:justify;">Group policies are applied when a user logs in or the computer boots up. The easiest way to ensure that the new policies have been applied is to simply restart your computer. If you prefer not to you can run the <em>gpupdate /force</em> command which can update most of the changes to policies. But as my windows administration teacher says:</p>
<blockquote><p>&#8220;with windows there are never enough restarts&#8221;</p></blockquote>
<h4>Delete the Recycle Bin icon</h4>
<p>Now you should be able to select the Recycle Bin desktop icon and delete it out of your clean, icon free, spotless desktop.</p>
<p><a href="http://ytoh.files.wordpress.com/2008/05/clean-desktop.jpg"><img class="aligncenter size-medium wp-image-11" src="http://ytoh.files.wordpress.com/2008/05/clean-desktop.jpg?w=300&#038;h=187" alt="clean desktop" width="300" height="187" /></a></p>
<p>For information on how to reverse the removal of the Recycle Bin desktop icon check out this <a href="http://support.microsoft.com/kb/810869">Microsoft&#8217;s Help and Support page</a>.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/ytoh.wordpress.com/6/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/ytoh.wordpress.com/6/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ytoh.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ytoh.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ytoh.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ytoh.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/ytoh.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/ytoh.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/ytoh.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/ytoh.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ytoh.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ytoh.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ytoh.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ytoh.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ytoh.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ytoh.wordpress.com/6/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ytoh.wordpress.com&amp;blog=3728656&amp;post=6&amp;subd=ytoh&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ytoh.wordpress.com/2008/05/15/clean-up-your-windows-desktop/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d6074b6508685d183b68532b45e9d294?s=96&#38;d=http%3A%2F%2Fs0.wp.com%2Fi%2Fmu.gif" medium="image">
			<media:title type="html">ytoh</media:title>
		</media:content>

		<media:content url="http://ytoh.files.wordpress.com/2008/05/windows-key.png" medium="image" />

		<media:content url="http://ytoh.files.wordpress.com/2008/05/gpedit.png?w=300" medium="image" />

		<media:content url="http://ytoh.files.wordpress.com/2008/05/group-policy.png?w=300" medium="image" />

		<media:content url="http://ytoh.files.wordpress.com/2008/05/clean-desktop.jpg?w=300" medium="image">
			<media:title type="html">clean desktop</media:title>
		</media:content>
	</item>
	</channel>
</rss>
