April 16, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Introducing Betwixt, Page 2

  • September 30, 2005
  • By Vikram Goyal
  • Send Email »
  • More Articles »

Converting XML to beans

On the other end of the bean --> XML spectrum is the XML --> bean process. It relies on the org.apache.commons.betwixt.io.BeanReader class, which is the primary class for reading an XML document and converting it to a tree of beans. BeanReader uses a subset of the Digester component to perform its functionality, and the BeanReader class extends the org.apache.commons.digester.Digester class. It makes sense, because Digester provides functionality to create beans read from an XML file. The Digester subset classes are placed in the package org.apache.commons.betwixt.digester.

You need to register the top-level element in the XML document as a JavaBean class with the BeanReader before you can parse a document. You can do this either by calling registerBeanClass(Class clazz) or by calling registerBeanClass(String path, Class clazz). The second method allows you to match the top-level element in case it differs from the name of the actual class, or if the top-level element isn't the element that you want created. In this case, the path is an XPath traversal to the actual element within the document. This rounds out our coverage of the Betwixt structure. It's time to look at some code and see Betwixt at work.

Betwixt in action

We'll start working with Betwixt by looking at a simple round-trip operation of converting a JavaBean to an XML representation and then back from that XML representation to the original JavaBean.

Note: Before you try any of these examples, make sure you have the commons-collections, commonslogging, commons-digester, and commons-beanutils libraries in your CLASSPATH, in addition to the Betwixt library.

Simple round trip

This example of using Betwixt will show how you can convert a bean --> XML and then use the same Betwixt-created XML representation to arrive at the original bean. For use within this example and the examples to follow, Listing 1 shows a simple class that models an ingredient for meal, Listing 2 shows a Meal class that uses the Ingredient class and finally Listing 3 shows a MealPlan class that uses the Meal class to model a meal plan for a week.

Listing 1. Ingredient class

package com.manning.commons.chapter05;
import java.util.Collection;
public class Ingredient {
   private String key;
   private String name;
   private String alternate;
   public String getKey() {
      return this.key;
   }
   public void setKey(String key) {
      this.key = key;
   }
   public String getName() {
      return this.name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getAlternate() {
      return this.alternate;
   }
   public void setAlternate(String alternate) {
      this.alternate = alternate;
   }
   public Ingredient() {
      this("Empty", "Empty", "Empty");
   }
   public Ingredient(String key, String name, String alternate) {
      this.key = key;
      this.name = name;
      this.alternate = alternate;
   }
   public String toString() {
      return "[Key=" + this.key + ", Name=" + this.name + ",
               Alternate=" + this.alternate + "]";
   }
}

Listing 2. A Meal Class

package com.manning.commons.chapter05;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
public class Meal {
   private int weekday;
   private int mealType;
   private String mealName;
   private Map ingredients;
   /** 0 - Sunday, 1 - Monday ..... 6 - Saturday */
   public int getWeekday() {
      return this.weekday;
   }
   public void setWeekday(int weekday) {
      this.weekday = weekday;
   }
   /** 0 - breakfast, 1 - lunch, 2 - dinner, 3 - other */
   public int getMealType() {
      return this.mealType;
   }
   public void setMealType(int mealType) {
      this.mealType = mealType;
   }
   public String getMealName() {
      return this.mealName;
   }
   public void setMealName(String mealName) {
      this.mealName = mealName;
   }
   public Map getIngredients() {
      return this.ingredients;
   }
   public void addIngredient(Ingredient ingredient) {
      addIngredient(ingredient.getKey(), ingredient);
   }
   public void addIngredient(String key, Ingredient ingredient) {
      ingredients.put(key, ingredient);
   }
   public Meal() {
      this(0, 0, "No meal");
   }
   public Meal(int weekday, int mealType, String mealName) {
      this.weekday = weekday;
      this.mealType = mealType;
      this.mealName = mealName;
      ingredients = new HashMap();
   }
   public String toString() {
      StringBuffer buffer = new StringBuffer(
         "Meal name: " + this.mealName + ", Meal Type: "
                       + this.mealType + " Meal Day: "
                       + this.weekday);
      buffer.append("rnIngredients:rn");
      Iterator itr = ingredients.values().iterator();
      while(itr.hasNext()) {
         buffer.append(itr.next() + "rn");
      }
      return buffer.toString();
   }
}

Listing 3. A MealPlan class

package com.manning.commons.chapter05;
import java.util.Map;
import java.util.Date;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Calendar;
import java.util.ArrayList;
import java.util.Collection;
import java.util.GregorianCalendar;
public class MealPlan {
   private Date startDate;
   private Date endDate;
   private Collection meals;
   private Meal snack;
   public Date getStartDate() {
      return this.startDate;
   }
   public void setStartDate(Date startDate) {
      this.startDate = startDate;
   }
   public Date getEndDate() {
      return this.endDate;
   }
   public void setEndDate(Date endDate) {
      this.endDate = endDate;
   }
   public Collection getMeals() {
      return this.meals;
   }
   public Meal getSnack() {
      return this.snack;
   }
   public void setSnack(Meal snack) {
      this.snack = snack;
   }
   public void addMeal(Meal meal) {
      if(meal == null)
         throw new IllegalArgumentException("Meal cannot be added
                                             null");
      meals.add(meal);
   }
   /** If this is called, it creates a MealPlan starting from now
     * till end of week */
   public MealPlan() {
      this(null, null);
   }
   public MealPlan(Date startDate, Date endDate) {
      if(startDate == null && endDate == null) {
         startDate = new Date();
         Calendar calendar = new GregorianCalendar();
         calendar.setTime(startDate);
         calendar.add(Calendar.WEEK_OF_YEAR, 1);
         endDate = calendar.getTime();
      }
      if(startDate == null || endDate
                   == null || startDate.after(endDate))
         throw new IllegalArgumentException("Please check the dates");
      this.startDate = startDate;
      this.endDate = endDate;
      meals = new ArrayList();
   }
   public String toString() {
      StringBuffer buffer =
         new StringBuffer(" **** Your Meal Plan **** ");
      buffer.append("rnStart Date: " + this.startDate);
      buffer.append("rnEnd Date: " + this.endDate + "rnrn");
      Iterator itr = meals.iterator();
      while(itr.hasNext()) {
         buffer.append(itr.next() + "rn");
      }
      buffer.append
         (" ----------------------------------------------rn");
      return buffer.toString();
   }
}

Listing 4. Simple round-trip conversion example

package com.manning.commons.chapter05;
import java.io.File;
import java.io.FileWriter;
import org.apache.commons.betwixt.io.BeanReader;
import org.apache.commons.betwixt.io.BeanWriter;
public class SimpleRoundTrip {
public static void main(String args[]) throws Exception {
FileWriter fWriter = new FileWriter("output.xml");
BeanWriter bWriter = new BeanWriter(fWriter);
Ingredient ingredient = new Ingredient("POT", "Potato", "None");
bWriter.write("ingredient", ingredient);
bWriter.flush();
BeanReader reader = new BeanReader();
reader.registerBeanClass("ingredient", Ingredient.class);
Ingredient ingReadFromFile =
(Ingredient)reader.parse(new File("output.xml"));
System.err.println(ingReadFromFile);
}
}




Page 2 of 4



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel