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

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

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

Java 데이터 모델 및 XML 문서 간 사용자 정의 변환을 통한 스키마 퀄리티 향상

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

문서 옵션
PDF format - Fits A4 and Letter

PDF - Fits A4 and Letter
188 KB (29 pages)

Get Adobe® Reader®

샘플 코드


제안 및 의견
피드백

튜토리얼 평가

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


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

Java 5 이하 버전 사용

이 튜토리얼의 예제 코드에서는 Java 5 형식의 콜렉션 및 열거형 기능을 사용하지만 JiBX 자체는 기존 Java 버전과 완벽하게 호환된다. 표준 JiBX 런타임은 1.3 이상의 JVM에서 작동하며 J2ME 호환성도 갖추고 있다. BindGen을 비롯한 대부분의 다른 JiBX 구성 요소는 1.4.1 이상의 JVM에서 실행할 수 있다. JiBX 다운로드에 있는 BindGen 문서에는 사용자 정의를 통해 Java 5 이전 버전의 코드를 사용할 때와 동등한 형식의 콜렉션을 BindGen에 제공하는 방법을 보여 주는 예제가 있다.

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

Java 예제 코드 소개

이제 bean 양식(private 필드, public get 및 set 액세스 메소드) 클래스 세트를 사용하여 온라인 매장의 주문을 표현하는 Java 코드 예제를 살펴보자. Listing 1에서는 대부분의 get/set 메소드를 빼고 간략하게 요약한 예제 코드를 보여 준다. 전체 샘플 코드는 샘플 코드의 src 디렉토리에 있다.


Listing 1. 기본 Java 코드
 
package org.jibx.starter;

/**
 * Order information.
 */
public class Order
{
    private long orderNumber;
    private Customer customer;

    /** Billing address information. */
    private Address billTo;
    private Shipping shipping;

    /** Shipping address information. If missing, the billing address is also used as the
     shipping address. */
    private Address shipTo;
    private List<Item> items;

    /** Date order was placed with server. */
    private Date orderDate;

    /** Date order was shipped. This will be <code>null</code> if the order has not
     yet shipped. */
    private Date shipDate;
    private Float total;

    public long getOrderNumber() {
        return orderNumber;
    }
    ...
}
/**
 * Customer information.
 */
public class Customer
{
    private long customerNumber;

    /** Personal name. */
    private String firstName;

    /** Family name. */
    private String lastName;

    /** Middle name(s), if any. */
    private List<String> middleNames;
    ...
}
/**
 * Address information.
 */
public class Address
{
    /** First line of street information (required). */
    private String street1;

    /** Second line of street information (optional). */
    private String street2;
    private String city;

    /** State abbreviation (required for the U.S. and Canada, optional otherwise). */
    private String state;

    /** Postal code (required for the U.S. and Canada, optional otherwise). */
    private String postCode;

    /** Country name (optional, U.S. assumed if not supplied). */
    private String country;
    ...
}
/**
 * Order line item information.
 */
public class Item
{
    /** Stock identifier. This is expected to be 12 characters in length, with two
     leading alpha characters followed by ten decimal digits. */
    private String id;

    /** Text description of item. */
    private String description;

    /** Number of units ordered. */
    private int quantity;

    /** Price per unit. */
    private float price;
    ...
}
/**
 * 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.
 */
public enum Shipping
{
    STANDARD_MAIL, PRIORITY_MAIL, INTERNATIONAL_MAIL, DOMESTIC_EXPRESS,
    INTERNATIONAL_EXPRESS
}




위로


기본 바인딩 및 스키마 생성

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

튜토리얼 다운로드에는 예제 코드를 컴파일하는 compile 대상과 컴파일된 코드에 대해 BindGen 프로그램을 실행하는 bindgen 대상이 포함된 Ant build.xml 스크립트가 있다.

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


그림 1. Ant build 사용
코드 기반 생성에 대한 Ant build 출력

BindGen을 콘솔에서 직접 실행할 수도 있다. 직접 실행하려면 생성에 대한 입력으로 사용할 컴파일된 클래스 파일의 경로와 함께 jibx-tools.jar을 Java 클래스 경로에 포함시켜야 한다. 제공된 Ant bindgen 대상의 효과를 복제하려면 명령행에서 클래스의 소스 파일에 대한 루트 디렉토리를 전달해야 한다. 마지막으로 생성에 사용할 루트 클래스를 표시해야 한다. UNIX® 및 Linux® 시스템의 경우, dwcode1 디렉토리의 콘솔에서(권장되는 설치 지침을 따른 것으로 간주함) Ant bindgen 대상을 복제하는 Java 명령행은 다음과 같다. (여기에서는 줄바꿈된 것으로 표시되지만 실제로는 한 행으로 입력해야 한다.)

java -cp ../lib/jibx-tools.jar:bin org.jibx.binding.generator.BindGen 
   -s src org.jibx.starter.Order

Windows의 경우 한 행으로 다음 명령을 입력한다.

java -cp ..\lib\jibx-tools.jar;bin org.jibx.binding.generator.BindGen -s src org.jibx.starter.Order
|-------10--------20--------30--------40--------50--------60--------70--------80--------9|
|-------- XML error:  The previous line is longer than the max of 90 characters ---------|

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




위로


생성된 아티팩트

Listing 2에서는 BindGen에서 생성된 스키마 출력(starter.xsd)을 보여 준다. 여기에서는 페이지 너비에 맞추기 위해 서식을 약간 변경했으며 일부 세부 사항을 제거했다. 구조를 잘 파악할 수 있도록 각 Java 클래스에 해당하는 스키마 정의의 시작 태그를 굵게 표시했다.


Listing 2. 생성된 스키마
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:tns="http://jibx.org/starter" elementFormDefault="qualified"
  targetNamespace="http://jibx.org/starter">
 <xs:complexType name="address">
  <xs:annotation>
   <xs:documentation>Address information.</xs:documentation>
  </xs:annotation>
  <xs:sequence>
   <xs:element type="xs:string" name="street1" minOccurs="0">
    <xs:annotation>
     <xs:documentation>First line of street information (required).</xs:documentation>
    </xs:annotation>
   </xs:element>
   ...
  </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 name="customer" minOccurs="0">
    <xs:complexType>
     ...
    </xs:complexType>
   </xs:element>
   <xs:element type="tns:address" name="billTo" minOccurs="0">
    <xs:annotation>
     <xs:documentation>Billing address information.</xs:documentation>
    </xs:annotation>
   </xs:element>
   <xs:element name="shipping" minOccurs="0">
    <xs:simpleType>
     <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:restriction>
    </xs:simpleType>
   </xs:element>
   <xs:element type="tns:address" name="shipTo" minOccurs="0">
    <xs:annotation>
     <xs:documentation>Shipping address information. If missing, the billing address is
       also used as the shipping address.</xs:documentation>
    </xs:annotation>
   </xs:element>
   <xs:element name="item" minOccurs="0" maxOccurs="unbounded">
    <xs:complexType>
     <xs:sequence>
      <xs:element type="xs:string" name="id" minOccurs="0">
       <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:element>
      <xs:element type="xs:string" name="description" minOccurs="0">
       <xs:annotation>
        <xs:documentation>Text description of item.</xs:documentation>
       </xs:annotation>
      </xs:element>
     </xs:sequence>
     <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:element>
  </xs:sequence>
  <xs:attribute type="xs:long" use="required" name="orderNumber"/>
  <xs:attribute type="xs:date" name="orderDate">
   <xs:annotation>
    <xs:documentation>Date order was placed with server.</xs:documentation>
   </xs:annotation>
  </xs:attribute>
  <xs:attribute type="xs:date" name="shipDate">
   <xs:annotation>
    <xs:documentation>
     <![CDATA[Date order was shipped. This will be <code>null</code> if the order
       has not yet shipped.]]></xs:documentation>
   </xs:annotation>
  </xs:attribute>
 </xs:complexType>
</xs:schema>

기본적으로 BindGen에서 스키마를 생성할 때, 한 번만 사용되는 유형에는 중첩된 complexTypesimpleType 정의를 사용하고 여러 번 사용되는 유형에는 별도의 정의를 사용한다. 이 경우에는 중첩된 형식을 사용하여 세 개의 전역 정의 즉, addressorder 복합 유형과 order 요소가 있는 스키마가 생성된다. Address 클래스는 Order 클래스에서 청구 및 배송 주소를 위해 두 번 사용되기 때문에 스키마에서 별도의 전역 정의로 표현된다. (스키마에서는 전역 정의만 다시 사용할 수 있다.) Java 데이터 구조의 다른 클래스(Customer, ItemShipping)는 Order 클래스에서 한 번씩만 참조되므로 해당 유형 정의가 order 스키마 유형 정의 안에 직접 포함된다.

BindGen의 장점 중 하나는 입력 클래스의 Javadoc에서 스키마 문서를 생성할 수 있다는 것이다. Listing 1에서 Javadoc이 있는 각 필드와 Javadoc이 있는 클래스에 해당하는 각 전역 유형에 대한 스키마 문서를 Listing 2에서 볼 수 있다. 일부 Javadoc은 BindGen에서 기본적으로 처리되어 생성되는 스키마 구성 요소와 일치하지 않을 수 있으며 "get" 액세스 메소드에 대한 Javadoc과 같은 일부 Javadoc은 스키마 문서로 변환했을 때 낯설게 보일 수도 있지만 생성된 스키마 문서는 XML 표현이 올바르게 사용되었는지 확인할 때 매우 유용하게 사용할 수 있다. "get" 메소드 Javadoc에서 "Get the ..."로 시작하는 문장을 제거하는 경우와 같이 변환 프로세스 중에 텍스트를 변경하려는 경우 스키마 문서로 사용되는 Javadoc에 대한 사용자 고유의 포맷터 클래스를 정의할 수도 있다.

클래스에 대한 소스 코드를 사용할 수 있고 루트 디렉토리 경로를 알려 주는 인수를 BindGen에 제공한 경우에만 이 Javadoc 변환 기능이 작동한다. 앞에서 설명한 명령행 샘플에서(기본 바인딩 및 스키마 생성 참조) 소스 경로는 -s src로 제공된다.

생성된 JiBX 바인딩

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




위로



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