'Betwixt'에 해당되는 글 2건

  1. 2008/03/08 Bywoong Commons Betwixt : Turning beans into XML
  2. 2008/02/26 Bywoong 데이터 인터페이스를 위한 XML-RPC(Java) 테스트1.0 (1)
[알림] 삭제된 동영상 및 이미지나 깨진 링크, 저작권에 문제가 될 소지가 있는 내용은 이곳에 알려주시면 바로 조치하도록 하겠습니다. 감사합니다. - Fortune Cookie

Betwixt Example

다운로드

This is a simple example to help those new to betwixt. It shows how a simple bean can be converted to xml and back again. A round trip, no less!

In order to run these simple examples, the classpath needs to contain Betwixt and all its dependencies . Note that any JAXP (1.1 or later) compliant parser can be used to replace xerces and xml-apis. JUnit is not required to run betwixt (but is needed if you want to run the unit tests in CVS).

This example is based around a very simple bean representing a person:

public class PersonBean {
    
    private String name;
    private int age;
    
    /** Need to allow bean to be created via reflection */
    public PersonBean() {}
    
    public PersonBean(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }	
    
    public int getAge() {
        return age;
    }
    
    public void setAge(int age) {
        this.age = age;
    }
    
    public String toString() {
        return "PersonBean[name='" + name + "',age='" + age + "']";
    }
}

The basic usage pattern for writing beans using Betwixt is to create a BeanWriter, configure it and then pass a bean into the write method. Pretty easy.

Here's a simple application which converts a person bean to xml which is then sent to System.out:

import java.io.StringWriter;

import org.apache.commons.betwixt.io.BeanWriter;

public class WriteExampleApp {

    /** 
     * Create an example bean and then convert it to xml.
     */
    public static final void main(String [] args) throws Exception {
        
        // Start by preparing the writer
        // We'll write to a string 
        StringWriter outputWriter = new StringWriter(); 
        
        // Betwixt just writes out the bean as a fragment
        // So if we want well-formed xml, we need to add the prolog
        outputWriter.write("<?xml version='1.0' ?>");
        
        // Create a BeanWriter which writes to our prepared stream
        BeanWriter beanWriter = new BeanWriter(outputWriter);
        
        // Configure betwixt
        // For more details see java docs or later in the main documentation
        beanWriter.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
        beanWriter.getBindingConfiguration().setMapIDs(false);
        beanWriter.enablePrettyPrint();

        // If the base element is not passed in, Betwixt will guess 
        // But let's write example bean as base element 'person'
        beanWriter.write("person", new PersonBean("John Smith", 21));
        
        // Write to System.out
        // (We could have used the empty constructor for BeanWriter 
        // but this way is more instructive)
        System.out.println(outputWriter.toString());
        
        // Betwixt writes fragments not documents so does not automatically close 
        // writers or streams.
        // This example will do no more writing so close the writer now.
        outputWriter.close();
    }
}

The basic usage pattern for reading beans is only a little more complex. This time, you need to create a BeanReader, configure it, register the bean classes that the xml will be mapped to and then parse should be called.

Here's a simple application that converts some xml to a person bean. The bean is then converted to string and the result sent to System.out:

import java.io.StringReader;

import org.apache.commons.betwixt.io.BeanReader;

public class ReadExampleApp {
    
    public static final void main(String args[]) throws Exception{
        
        // First construct the xml which will be read in
        // For this example, read in from a hard coded string
        StringReader xmlReader = new StringReader(
                    "<?xml version='1.0' ?><person><age>25</age><name>James Smith</name></person>");
        
        // Now convert this to a bean using betwixt
        // Create BeanReader
        BeanReader beanReader  = new BeanReader();
        
        // Configure the reader
        // If you're round-tripping, make sure that the configurations are compatible!
        beanReader.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
        beanReader.getBindingConfiguration().setMapIDs(false);
        
        // Register beans so that betwixt knows what the xml is to be converted to
        // Since the element mapped to a PersonBean isn't called the same 
        // as Betwixt would have guessed, need to register the path as well
        beanReader.registerBeanClass("person", PersonBean.class);
        
        // Now we parse the xml
        PersonBean person = (PersonBean) beanReader.parse(xmlReader);
        
        // send bean to system out
        System.out.println(person);
    }
    
}

페이지 http://commons.apache.org/betwixt/
2008/03/08 17:44 2008/03/08 17:44
관련글타래
    받은 트랙백이 없고, 댓글이 없습니다. 2203번 조회되었습니다.

    댓글을 달아 주세요

    [로그인][오픈아이디란?]

    구독안내 주 2~3회 새글이 올라옵니다. 블로그 방문없이 업데이트 되는 글을 구독하세요. RSS . E-Mail . HanRSS . WZD . Google Reader . Bloglines . Delicious Bookmark this on Delicious
    [알림] 삭제된 동영상 및 이미지나 깨진 링크, 저작권에 문제가 될 소지가 있는 내용은 이곳에 알려주시면 바로 조치하도록 하겠습니다. 감사합니다. - Fortune Cookie
    * XML-RPC의 개요 문서를 참조하세요 : XML-RPC 개요

    데이터 인터페이스를 위한 XML-RPC(Java) 테스팅(1.0)중입니다. 첨부파일은 이클립스 프로젝트 2개(Server, Client)로 구성되어 있습니다. Server플러그인을 이용해서 서버를 띄운후 Java Application으로 ClientServlet.java를 실행합니다.
    xmlrpc.zip

    XML-RPC 테스팅1.0 - Server, Client 소스


    [테스트1.1 예정]
    - 라이브러리 및 소스 정리 작업
    - hashmap hashtable XML(Betwixt)방식의 인터페이스 테스트 관련글
    - 데이터 유효성 검사 로직 Bean사용
    - DB처리 메서드 작성
    - Cron작성
    - Exception처리방식
    - Exception에 따른 로그분류생성

    [ClientServlet.java]

    import java.util.HashMap;
    import java.util.Vector;
    import org.apache.xmlrpc.XmlRpcClient;
    public class ClientServlet {
     public static void main(String args[]){
      System.out.println("=] XML-RPC Client Started. ");
      String serverURL = "http://127.0.0.1:9999/XmlRpcServlet";
      String result    = "";
      try{
       XmlRpcClient server = new XmlRpcClient(serverURL);
       // 서버메서드로 넘길 파라미터처리(Vector)
       Vector sendParams = new Vector();
       sendParams.addElement( new String("sendParams"));
       // 서버접속 & 메서드실행
       result = (String)server.execute("server.getString",sendParams);
       System.out.println("=] Success Result : " + result );
       Vector vResult = new Vector();
       vResult = (Vector)server.execute("server.getVector",sendParams);
       System.out.println("=] Success Vector Result : " + vResult.size());
       for(int i=0; i<vResult.size(); i++){
        System.out.println("\tvector: " + vResult.get(i));
       }
       HashMap hResult = new HashMap();
       hResult = (HashMap)server.execute("server.getHashMap",sendParams);
       System.out.println("\thashmap: " + hResult.get("B"));
      }catch(Exception e){
       System.out.println("=] Exception: " + e.getMessage() + " - Server URL: " + serverURL);
      }finally{
      }
     }
    }
    2008/02/26 16:38 2008/02/26 16:38
    관련글타래

      댓글을 달아 주세요

      1. 웅대리꼬봉님의 생각 2008/03/10 10:16  댓글주소  수정/삭제  댓글쓰기

        웅이 대리님~~ 멋져부러~~
        ㅡ0ㅡ /

      [로그인][오픈아이디란?]

      구독안내 주 2~3회 새글이 올라옵니다. 블로그 방문없이 업데이트 되는 글을 구독하세요. RSS . E-Mail . HanRSS . WZD . Google Reader . Bloglines . Delicious Bookmark this on Delicious