IBM®
메인 컨텐츠로 가기
    Korea [국가변경]    이용약관
 
 
   
        제품    서비스 & 솔루션    고객지원 & 다운로드    회원 서비스    
메인 컨텐츠로 가기

한국 developerWorks  >  자바 | XML | 오픈 소스  >

JiBX 1.2, Part 2: XML 스키마를 Java 코드로 변환

XML 스키마에서 정돈된 형태의 사용자 정의 Java 코드 생성하기

developerWorks
Go to the previous page14 페이지 중 3 페이지Go to the next page

문서 옵션
PDF format - Fits A4 and Letter

PDF - Fits A4 and Letter
222 KB (36 pages)

Get Adobe® Reader®

샘플 코드


제안 및 의견
피드백

튜토리얼 평가

이 컨텐츠를 개선하기 위한 도움을 주십시오.


스키마에서 기본 바인딩 및 코드 생성

JiBX 바인딩 정의와 해당 Java 코드는 XML 스키마 정의에서 쉽게 생성할 수 있으며 이 섹션에서는 이 작업을 수행하는 방법에 대해 설명한다.

간단한 예제 스키마 소개

Part 1에서 생성한 스키마 중 하나를 간단한 예제로 사용하여 시작하자. Listing 1은 온라인 매장의 주문을 표현하기 위해 만든 이 스키마의 약식 버전을 보여 준다. 전체 스키마는 샘플 코드의 dwcode2 디렉토리에 있는 starter.xsd로 제공된다.


Listing 1. 첫 번째 예제 스키마

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:tns="http://jibx.org/starter" elementFormDefault="qualified" 
    targetNamespace="http://jibx.org/starter">
  <xs:simpleType name="shipping">
    <xs:annotation>
      <xs:documentation>Supported shipment methods. The "INTERNATIONAL" shipment
      methods can only be used for orders with shipping addresses outside the U.S., and
      one of these methods is required in this case.</xs:documentation>
    </xs:annotation>
    <xs:restriction base="xs:string">
      <xs:enumeration value="STANDARD_MAIL"/>
      <xs:enumeration value="PRIORITY_MAIL"/>
      <xs:enumeration value="INTERNATIONAL_MAIL"/>
      ...
    </xs:restriction>
  </xs:simpleType>
  <xs:complexType name="item">
    <xs:annotation>
      <xs:documentation>Order line item information.</xs:documentation>
    </xs:annotation>
    <xs:sequence/>
    <xs:attribute type="xs:string" use="required" name="id">
      <xs:annotation>
        <xs:documentation>Stock identifier. This is expected to be 12 characters in
        length, with two leading alpha characters followed by ten decimal digits.
        </xs:documentation>
      </xs:annotation>
    </xs:attribute>
    <xs:attribute type="xs:int" use="required" name="quantity">
      <xs:annotation>
        <xs:documentation>Number of units ordered.</xs:documentation>
      </xs:annotation>
    </xs:attribute>
    <xs:attribute type="xs:float" use="required" name="price">
      <xs:annotation>
        <xs:documentation>Price per unit.</xs:documentation>
      </xs:annotation>
    </xs:attribute>
  </xs:complexType>
  <xs:complexType name="address">
    <xs:annotation>
      <xs:documentation>Address information.</xs:documentation>
    </xs:annotation>
    <xs:sequence>
      <xs:element type="xs:string" name="street1">
        <xs:annotation>
          <xs:documentation>First line of street information (required).
          </xs:documentation>
        </xs:annotation>
      </xs:element>
      ...
    </xs:sequence>
    <xs:attribute type="xs:string" name="state">
      <xs:annotation>
        <xs:documentation>State abbreviation (required for the U.S. and Canada,
        optional otherwise).</xs:documentation>
      </xs:annotation>
    </xs:attribute>
    <xs:attribute type="xs:string" name="postCode">
      <xs:annotation>
        <xs:documentation>Postal code (required for the U.S. and Canada, optional
        otherwise).</xs:documentation>
      </xs:annotation>
    </xs:attribute>
  </xs:complexType>
  <xs:complexType name="customer">
    <xs:annotation>
      <xs:documentation>Customer information.</xs:documentation>
    </xs:annotation>
    <xs:sequence>
      <xs:element type="xs:long" name="customerNumber"/>
      ...
    </xs:sequence>
  </xs:complexType>
  <xs:element type="tns:order" name="order"/>
  <xs:complexType name="order">
    <xs:annotation>
      <xs:documentation>Order information.</xs:documentation>
    </xs:annotation>
    <xs:sequence>
      <xs:element type="xs:long" name="orderNumber"/>
      <xs:element type="tns:customer" name="customer"/>
      <xs:element type="tns:address" name="billTo">
        <xs:annotation>
          <xs:documentation>Billing address information.</xs:documentation>
        </xs:annotation>
      </xs:element>
      ...
      <xs:element type="tns:item" name="item" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
    <xs:attribute type="xs:date" use="required" name="orderDate">
      <xs:annotation>
        <xs:documentation>Date order was placed with server.</xs:documentation>
      </xs:annotation>
    </xs:attribute>
    ...
  </xs:complexType>
</xs:schema>




위로


기본 바인딩 및 코드 생성

XML 스키마에서 JiBX 바인딩과 Java 클래스를 생성하려면 먼저 클래스를 컴파일한 후 JiBX 배포판의 jibx-tools.jar에 있는 org.jibx.schema.codegen.CodeGen 도구를 실행해야 한다. 이 도구는 명령행에서 직접 실행하거나 Apache Ant와 같은 빌드 도구를 통해 간접적으로 실행할 수 있다.

튜토리얼 다운로드에는 생성을 실행하는 codegen 대상이 포함된 Ant build.xml 스크립트가 있다.

이를 확인하려면 설치된 다운로드의 dwcode2 디렉토리에서 콘솔을 열고 ant codegen을 입력한다. 시스템에 Ant가 설치되어 있고 지침에 따라 다운로드 코드를 설치했으면 그림 1과 같은 출력이 표시된다.


그림 1. Ant build 사용
스키마 기반 생성에 대한 Ant build 출력

CodeGen을 콘솔에서 직접 실행할 수도 있다. 이렇게 하려면 다음을 수행해야 한다.

  1. jibx-tools.jar을 Java 클래스 경로에 추가한다.
  2. org.jibx.schema.codegen.CodeGen을 실행할 클래스로 지정한다.
  3. 생성할 스키마 정의를 표시한다.

제공된 Ant codegen 대상은 추가 매개변수를 사용하여 CodeGen에게 gen/src 디렉토리를 생성된 데이터 모델 패키지 구조의 루트로 사용하고 해당 디렉토리에 있는 기존 파일을 모두 삭제한 후 생성을 실행하도록 지시한다. dwcode2 디렉토리의 콘솔에서(권장되는 설치 지침을 따른 것으로 간주함) Ant codegen 대상을 복제하는 Java 명령행은 다음과 같다.

java -cp ../lib/jibx-tools.jar org.jibx.schema.codegen.CodeGen -t gen/src -w starter.xsd

Windows의 경우, 다음 명령을 사용한다.

java -cp ..\lib\jibx-tools.jar org.jibx.schema.codegen.CodeGen -t gen\src -w starter.xsd

명령행에서 다른 여러 가지 옵션을 CodeGen에 전달할 수 있다. 이러한 옵션은 이 튜토리얼의 뒷 부분에서 설명된다. 이제 생성된 Java 코드를 살펴보자.




위로


생성된 아티팩트

생성된 코드는 Listing 1 스키마에 있는 5개의 전역 유형 정의에 해당하는 5개의 클래스로 구성되어 있다. Listing 2에서는 org.jibx.starter.Order 클래스와 전체 org.jibx.starter.Shipping 클래스에서 발췌한 생성된 코드의 일부 샘플을 보여 준다.


Listing 2. 생성된 코드

/**
 * Order information.
 *
 * Schema fragment(s) for this class:
 * <pre>
 * <xs:complexType xmlns:ns="http://jibx.org/starter" 
   xmlns:xs="http://www.w3.org/2001/XMLSchema" name="order">
 *   <xs:sequence>
 *     <xs:element type="xs:long" name="orderNumber"/>
 *     <xs:element type="ns:customer" name="customer"/>
 *     <xs:element type="ns:address" name="billTo"/>
 *     <xs:element type="ns:shipping" name="shipping"/>
 *     <xs:element type="ns:address" name="shipTo" minOccurs="0"/>
 *     <xs:element type="ns:item" name="item" minOccurs="0" maxOccurs="unbounded"/>
 *   </xs:sequence>
 *   <xs:attribute type="xs:date" use="required" name="orderDate"/>
 *   <xs:attribute type="xs:date" name="shipDate"/>
 *   <xs:attribute type="xs:float" name="total"/>
 * </xs:complexType>
 * </pre>
 */
public class Order
{
    private long orderNumber;
    private Customer customer;
    private Address billTo;
    private Shipping shipping;
    private Address shipTo;
    private List<Item> itemList = new ArrayList<Item>();
    private Date orderDate;
    private Date shipDate;
    private Float total;
    ...
    /**
     * Get the 'shipTo' element value. Shipping address information. If missing, the 
     * billing address is also used as the shipping address.
     */
    public Address getShipTo() {
        return shipTo;
    }
    /**
     * Set the 'shipTo' element value. Shipping address information. If missing, the 
     * billing address is also used as the shipping address.
     */
    public void setShipTo(Address shipTo) {
        this.shipTo = shipTo;
    }
    /**
     * Get the list of 'item' element items.
     */
    public List<Item> getItems() {
        return itemList;
    }
    /**
     * Set the list of 'item' element items.
     */
    public void setItems(List<Item> list) {
        itemList = list;
    }
    ...
}
/**
 * Supported shipment methods. The "INTERNATIONAL" shipment methods can only be used
   for orders with shipping addresses outside the U.S., and one of these methods is
   required in this case.
 *
 * Schema fragment(s) for this class:
 * <pre>
 * <xs:simpleType xmlns:xs="http://www.w3.org/2001/XMLSchema" name="shipping">
 *   <xs:restriction base="xs:string">
 *     <xs:enumeration value="STANDARD_MAIL"/>
 *     <xs:enumeration value="PRIORITY_MAIL"/>
 *     <xs:enumeration value="INTERNATIONAL_MAIL"/>
 *     <xs:enumeration value="DOMESTIC_EXPRESS"/>
 *     <xs:enumeration value="INTERNATIONAL_EXPRESS"/>
 *   </xs:restriction>
 * </xs:simpleType>
 * </pre>
 */
public enum Shipping {
    STANDARD_MAIL, PRIORITY_MAIL, INTERNATIONAL_MAIL, DOMESTIC_EXPRESS, 
    INTERNATIONAL_EXPRESS
}

Listing 2에서 볼 수 있듯이 CodeGen은 자동으로 스키마 문서를 생성된 코드의 Javadoc으로 변환한다. (이 예제에서는 각 클래스 Javadoc의 앞쪽에 있는 주석과 getShipTo()setShipTo() 메소드에 대한 주석의 일부로 표시된다). 기본적으로 CodeGen은 실제 스키마 정의를 클래스 Javadoc에 통합하고 get/set 특성 액세스 메소드의 경우 특성에 해당하는 스키마 구성 요소를 설명한다.

Listing 1의 order complexType 정의에 있는 반복 항목 요소와 같이 반복되는 값의 경우, CodeGen은 기본적으로 Java 5 유형 목록을 생성한다. Listing 1의 shipping 유형과 같은 simpleType 제한 열거형의 경우 CodeGen은 기본적으로 Java 5 열거형을 생성한다. Listing 2에서 이들 인스턴스에 대해 생성된 코드를 볼 수 있다.

생성된 JiBX 바인딩

생성된 코드 외에 CodeGen에서는 Java 클래스와 XML의 상호 변환 방법을 JiBX 바인딩 컴파일러에게 알려 주는 JiBX 바인딩 정의(여기에서는 binding.xml 파일)도 생성된다. 바인딩 정의에는 JiBX에서 수행할 모든 세부 사항이 포함되기 때문에 바인딩 정의의 구조는 매우 복잡하다. 다행히 CodeGen 바인딩 및 코드 생성을 사용하여 JiBX 작업을 수행하기 위해 바인딩 정의를 이해할 필요는 없다. 따라서 이 튜토리얼에서는 바인딩 정의에 대한 세부 사항을 다루지 않는다.




위로



Go to the previous page14 페이지 중 3 페이지Go to the next page
    IBM 소개 개인정보 보호정책 문의