Skip to main content

Notice: this Wiki will be going read only early in 2024 and edits will no longer be possible. Please see: https://gitlab.eclipse.org/eclipsefdn/helpdesk/-/wikis/Wiki-shutdown-plan for the plan.

Jump to: navigation, search

XStream Tips

Revision as of 18:12, 12 August 2013 by Scott.fisher.oracle.com (Talk | contribs) (New page: == Registering a Custom Converter == Normally, you'd register converter to the class you are writing, and in that case the easiest thing to do is to write a nested type "ConverterImpl", t...)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Registering a Custom Converter

Normally, you'd register converter to the class you are writing, and in that case the easiest thing to do is to write a nested type "ConverterImpl", that gets picked up automatically. If you search by that class name, you'll see a number of implementations. Registering a Custom Converter without modifying the original class

If you want to register a custom XStream converter that will convert items that have already been persisted to disk, and you don't want to modify the source code for the class you want to convert, then you need to hook it in to Hudson before it reads in those items. Here's one way that works:

public class MyPlugin extends Plugin { 
   public void start() throws Exception {   
      Items.XSTREAM.registerConverter(new MyCoolConverter());
   }
}

The Items.XSTREAM portion should be adjusted to point to the right XStream instance (such as Hudson.XSTREAM), depending on which persistence your object participates. The converter would look something like this:

import com.thoughtworks.xstream.converters.Converter;

public class MyCoolConverter implements Converter {
    public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
        throw new UnsupportedOperationException("Sorry, no example for marshalling yet!.");
    }

    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
        // Traverse the reader to get structure and attributes of the thing you're converting from
        return new MyThing(some, attrs, etc);
    }

     public boolean canConvert(Class type) {
        return my.plugin.special.MyThing.class == type;
    }

}

Back to the top