Subscribe:

Main Menu

Jumat, Juni 20, 2008

JAXB

JAXB... :) JAXB ini kayak Castor tadi. Jadi JAXB itu untuk XML Parser. Metodenya agak beda :). mungkin juga lebih mudah kali ya.. :D. Caranya gini nech.. misalnya kita mau buat XML kayak gini :).


<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<todolist>
<item>
<name>Clean room.</name>
<priority>4</priority>
<task>
<description>Pick up clothes.</description>
<timeEstimate>10</timeEstimate>
</task>
<task>
<description>Straighten magazines</description>
<timeEstimate>20</timeEstimate>
</task>
</item>
<item>
<name>Get kids.</name>
<priority>10</priority>
<task>
<description>Pick up kids at school at 1525.</description>
<timeEstimate>30</timeEstimate>
</task>
</item>
<item>
<name>Bastomi</name>
<priority>1</priority>
<task>
<description>Tidur</description>
<timeEstimate>300</timeEstimate>
</task>
</item>
</todolist>



Sebelumnya perlu di ketahui dulu bentuk xsdnya.. bentuk xsd dari xml itu adalah sbb :

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="todolist">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" minOccurs="0" name="item" type="entry"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="entry">
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="priority" type="rank"/>
<xs:element minOccurs="1" maxOccurs="unbounded" name="task" type="subentry"/>
</xs:sequence>
<xs:attribute default="0" name="totalItemTime" type="xs:int"/>
</xs:complexType>
<xs:complexType name="subentry">
<xs:sequence>
<xs:element name="description" type="xs:string"/>
<xs:element default="0" name="timeEstimate" type="xs:int"/>
</xs:sequence>
</xs:complexType>
<xs:simpleType name="rank">
<xs:restriction base="xs:int">
<xs:minInclusive value="1"/>
<xs:maxInclusive value="10"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>


Setelah itu Generate file xsd di atas, kita kasih nama filenya item.xsd misalnya. kita generate dengan cara sbb :


java -jar jaxb-xjc.jar item.xsd


eh iya seblumnya kalian harus punya dulu jaxb-xjc.jar dan jaxb-impl.jar :).

OK lanjut :)..

Setelah di generate. akan ada direktori generate. nah kita pake source ini untuk project kita :)
kita buat project baru dan jangan lupa untuk menambahkan generate tadi ke project kita :).

Buat class dengan Nama TodoList dengan isi sbb :


package jaxb2;

import generated.ObjectFactory;
import generated.Todolist;
import generated.Entry;
import generated.Subentry;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.Marshaller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.xml.sax.SAXException;

/**
*
* @author bastomi
*/

public class TodolistUtil {
private JAXBContext jaxbContext;
private ObjectFactory objectFactory;
private Todolist todolist;
private static String packageName = "generated";
private String xmlFileName = "todolist2.xml";
TodolistUtil() {
createContextAndObjectFactory();
createTodolist();
}
private void createContextAndObjectFactory() {
try {
jaxbContext = JAXBContext.newInstance(packageName);
objectFactory = new ObjectFactory();
} catch (JAXBException e) {
System.out.println("There was this problem creating a context " + e);
}
}
public Todolist getTodolist(){
return todolist;
}
private void createTodolist() {
try {
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

File f=new File(xmlFileName);
if(!f.exists()){
todolist =objectFactory.createTodolist();
}else{
todolist = (Todolist) unmarshaller.unmarshal(f);
}

} catch (JAXBException e) {
System.out.println("There is this problem with unmarshalling: " + e);
}
}
private void persistTodolist() {
try {

Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
new Boolean(true));
marshaller.marshal(todolist, new FileOutputStream(xmlFileName));

} catch (JAXBException e) {
System.out.println("There was this problem persisting the item: "
+ e);
} catch (FileNotFoundException e) {
System.out.println("There was this problem creating a destination file "
+ e);
}
}
public Entry makeNewItem(String name, int priority) {
Entry newItem = null;
// try {
newItem = objectFactory.createEntry();
newItem.setName(name);
newItem.setPriority(priority);
// } catch (JAXBException e) {
// System.out.println("There was this problem creating a new item: "
// + e);
// }
return newItem;
}
public Subentry makeNewTask(String description, int time) {
Subentry newTask = null;
// try {
newTask = objectFactory.createSubentry();
newTask.setDescription(description);
newTask.setTimeEstimate(time);
// } catch (JAXBException e) {
// System.out.println("There was this problem creating a new task: "
// + e);
// }
return newTask;
}
public void addItem(Entry item) {
todolist.getItem().add(item);
persistTodolist();
}
}


Terus buat main class nya untuk test nya :). kasih aja namanya AddNewItem, isinya kayak gini :)

package jaxb2;

import generated.Entry;
import generated.Subentry;
import java.util.List;
/**
*
* @author bastomi
*/

public class AddNewItem {

public AddNewItem(String[] args) {
TodolistUtil util = new TodolistUtil();
List<Entry> list=util.getTodolist().getItem();
for(int i=0;i<list.size();i++){
System.out.println(list.get(i).getName());
System.out.println(list.get(i).getPriority());
List<Subentry> sublist=list.get(i).getTask();
for(int j=0;j<sublist.size();j++){
System.out.println(sublist.get(j).getDescription());
System.out.println(sublist.get(j).getTimeEstimate());
}
}
if (args.length > 3) {
Entry newItem = util.makeNewItem(args[0], Integer.parseInt(args[1]));
for (int j = 2; j < args.length; j = j + 2) {
Subentry newTask = util.makeNewTask(args[j],Integer.parseInt(args[j + 1]));
newItem.getTask().add(newTask);
}
util.addItem(newItem);
}
}

public static void main(String[] args) {
String[] baru={"Bastomi","1","Tidur","300"};
new AddNewItem(baru);
}
}

Nah Setelah itu jalankan pRogramnya :). insyaallah sukses :D.

0 komentar: