论坛首页 Java企业应用论坛

SModel- 提供 XML , JSON , POJO 等结构化数据统一编程模型

浏览 8314 次
精华帖 (1) :: 良好帖 (4) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2010-04-20  
dengtl 写道
最近几月在闲暇时做了一款针对结构化模型查询及编辑的开源框架,大家可以在 http://code.google.com/p/smodel/得到相应源码及文档.

欢迎大家批评指正!

下载地址: http://smodel.googlecode.com/files/smodel-1.0.2-bin-dependencies.jar

源码: http://smodel.googlecode.com/files/smodel-1.0.2-src.jar

源码SVN:http://smodel.googlecode.com/svn/trunk/

SModel provides users a uniform way to access and manipulate structured model in the format of XML, JSON, POJO or other user defined data format from data source such as stream, database or others.

Base on SModel, Document Oriented Service(DOS) framework can employee a uniform set of APIs to read and manipulate different format of document.

Features
1) provides a uniform way to access and manipulate structure model, including: add, remove, query, move, update, and introspect data. SModel also provides mechanism to subscribe for the change event of the model manipulation.
2)supports to load model from XML, JSON, POJO, or user defined format.
3)supports to flush model to XML, JSON, POJO or user defined format.
4)supports to validate model according to SModel defined or user defined rule.
5)provides mechanism to extend the function of the model.
6)provides mechanism to subscribe for error or warning message of the SModel.

Two Minutes Reference
1)create a xml document
sample xml:
        <?xml version="1.0" encoding="UTF-8"?>
        <order id="order id 1" name="order name 1">
            <orderDate>2009-09-06 20:36:01.196</orderDate>
            <items>
                <item count="100" id="item id 1" name="item name 1" price="10.3" />
            </items>
        </order>

IXmlModel orderModel = new XmlModel("order");
      orderModel.setProperty("id", "order id 1");
      orderModel.setProperty("name", "order name 1");
      orderModel.setChildText("orderDate", Utils.buildTimestamp(new Timestamp(new Date().getTime())));
                
      IXmlModel items = (IXmlModel) orderModel.addChild("items");
      IXmlModel item = (IXmlModel) items.addChild("item");
      item.setProperty("id", "item id 1");
      item.setProperty("name", "item name 1");
      item.setProperty("price", 10.3);
      item.setProperty("count", 100);
                
      XmlModelService.flushToXml(orderModel, "d:/order.xml");

2)load from xml document
IXmlModel orderModel = XmlModelService.loadFromXml(new FileReader("d:/order.xml"));

3)create a json document
sample json:
{"order":
  {"$tag":"order",
    "items":
     {"item":
       {"$tag":"item",
        "$attr":{"price":"10.3","name":"item name 1","count":"100","id":"item id 1"}
       },
       "$tag":"items"
     },
     "orderDate":"2009-09-06 21:42:25.603",
     "$attr":{"name":"order name 1","id":"order id 1"}
  }
}

"$tag" and "$attr" are the kept words for JSON to XML mapping.

 //initialize orderModel
      IXmlModel orderModel= ...

      XmlModelService.flushToJson(orderModel, new FileWriter("d:/order.json"));

4)load from json document
IXmlModel orderModel = XmlModelService.loadFromJson(new FileReader("d:/order.json"));

5)flush to POJO
public class Order {
        private String id;
        private String name; 
        private Timestamp orderDate;
        private List<Item> items = Utils.newList();
        // ... default constructor and getter/setter methods
        //for the array field(items in this case), setter method is not mandatory if the add method exists
        //SModel(1.0.0) support the kind of array field includes:Object[],List,Set
    }

    public class Item {
        private String id;
        private String name;
        private double price;
        private int count;       
        // ... default constructor and getter/setter methods
    }     

       //define POJO channel
        BeanModelChannel orderChannel = new BeanModelChannel(Order.class, "order");
        orderChannel.propertyAsAttribute("id");
        orderChannel.propertyAsAttribute("name");
        orderChannel.propertyAsChildText("orderDate");
        
        BeanModelChannel itemChannel = new BeanModelChannel(Item.class, "item");
        itemChannel.propertyAsAttribute("id");
        itemChannel.propertyAsAttribute("name");
        itemChannel.propertyAsAttribute("price");
        itemChannel.propertyAsAttribute("count");
                
        orderChannel.arrayPropertyAs(itemChannel);
 

        //initialize orderModel
        IXmlModel orderModel = ...

        //flush to POJO
        Order order = (Order) XmlModelService.flushToBean(orderModel, orderChannel);

6)load from POJO
    Order order = ...//prepare POJO
    IXmlModel orderModel = XmlModelService.loadFromBean(order, orderChannel);

7)query model
//get first items/item element
IXmlModel itemModel = (IXmlModel) orderModel.queryFirstTreeChild("items/item");

//get the first element of items/item whose price equal 10.3
List<ITreeModel> itemModes = orderModel.queryTreeChild("items/item{price=10.3}[0]")

//get the element which price is more expensive than 10.3
Query priceQuery = new Query();
priceQuery.addExpression(new IExpression(){
    public boolean isMatched(IModel model) {
        double price = model.getDoubleProperty("price");
        return price > 10.3;
    }
});

List<ITreeModel> itemModels = orderModel.getTreeChild(NameHelper.buildFullName("items", "item"), priceQuery);

8)manipulate model
//change the order name to "order new name"
orderModel.setProperty("name", "order new name");

//set order date to "2009-09-07 20:36:01.196"
orderModel.setChildText("orderDate", "2009-09-07 20:36:01.196");

//add a new item
Map<String, Object> propValPairs = Utils.newMap();
propValPairs.put("id", "item id 2");
propValPairs.put("name", "item name 2");
propValPairs.put("count", "100");
propValPairs.put("price", 10.4);
orderModel.addChild("items/item", propValPairs); 

//move the index 1 of the items/item to index 0
orderModel.moveTreeChild("items/item", 1, 0);

//delete the item whose price is equal to 10.4
orderModel.removeTreeChild("items/item", Query.valueOf("price=10.4"));

9)introspect model attribute
int count = itemModel.getIntProperty("count", 0);
double price = itemModel.getDoubleProperty("price", 0.0);
     
//CustomizedClass is String, Boolean, Byte, Short, Integer, 
//Double, BigDecimal, BigInteger, URI, Date, Timestamp 
//and the class has the static method "public static Object valueOf(String str)" defined.
itemModel.getTypedProperty("id", CustomizedClass.class, defaultValue);

 
//get a typed value by employing a valueFactory
itemModel.getTypedProperty("id",
                            new IValueFactory<CustomizeObject>(){
                                public CustomizeObject valueOf(String value) {
                                     return new CustomizeObject(value);
                                }
                            }, 
                            defaultValue);

10)validate model
XmlModelDefinition orderModelDefinition = XmlModelDefinition.createDefaultXmlModelDefinition("root", null);

//the attribute id and name of element items/item is mandantory
orderModelDefinition.installRule(new PropertyMandantoryRule("items/item", IModelRule.SEVERITY_ERROR, "id", "name"));

//the count of items/item should at least be one
orderModelDefinition.installRule(new ChildCountRule(IModelRule.SEVERITY_ERROR, "items/item", ChildCountRule.ONE_TO_MANY));

ValidationResult validateRlt = orderModel.validate(orderModelDefinition); 
boolean isValid = validateRlt.isValid();
List<String> errMsgs = validateRlt.getErrMsgs();

0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics