如果找到了对您有用的资料,烦请点击右手边的Google广告支持我继续共享知识,谢谢! http://dengpeng.spaces.live.com/

2008年12月24日星期三

PASSED! Sun Certificated Specialist for NetBeans IDE

Dear Peng (Certification ID#: SUN484247)

Congratulations on completing all the requirements for the
Sun Certified Specialist for NetBeans IDE certification. You were certified on 10/31/2008.

......
......

Congratulations!

SCNBI_Page1_Covered

Certification Department

Credential Verification Report

 

Actually, this is my first IT skill certificate Big Grin

Sun NetBeans Ccertificate

Simple EHCACHE Application

Ehcache is a widely used java distributed cache for general purpose caching, Java EE and light-weight containers.
It features memory and disk stores, replicate by copy and invalidate, listeners, cache loaders, cache extensions, cache exception handlers, a gzip caching servlet filter and much more ...
Ehcache is available under an Apache open source license and is actively developed, maintained and supported.

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package helloehcache;

import java.util.Random;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

/**
*
* @author Administrator
*/

public class Main {

/**
* @param args the command line arguments
*/

public static void main(String[] args) {
//Create a CacheManager instance using defaults.
CacheManager manager = new CacheManager();
//Create a Cache and add it to the CacheManager, then use it.
/*
* @param name the name of the cache. Note that "default" is a reserved name for the defaultCache.
* @param maxElementsInMemory the maximum number of elements in memory, before they are evicted
* @param overflowToDisk whether to use the disk store
* @param eternal whether the elements in the cache are eternal, i.e. never expire
* @param timeToLiveSeconds the default amount of time to live for an element from its creation date
* @param timeToIdleSeconds the default amount of time to live for an element from its last accessed or modified date
*/

Cache memoryOnlyCache = new Cache("CacheName", 5000, true, false, 7, 2);
manager.addCache(memoryOnlyCache);
Cache testCache = manager.getCache("CacheName");

for (int i = 0; i < 10; i++) {
//Queries are coming
Random random = new Random();
String key = "Key" + String.valueOf((int) (random.nextFloat() * 10f));
String value = "Value" + String.valueOf(random.nextFloat() * 10f);
System.out.println(i + ". Quering " + key);
if (testCache.get(key) == null) {
System.out.print("Cache is not hit! ");
testCache.put(new Element(key, value));
System.out.print(key + " " + value + " has been put into cache.");
} else {
System.out.print("Cache is hit! ");
Element cachedResult = testCache.get(key);
System.out.print("The value is " + cachedResult.getObjectValue());
}
System.out.println();
System.out.println();
}
System.out.println(testCache.getStatistics().getCacheMisses() + "/10 missing");
manager.shutdown();
}
}


For more code samples, please visit: http://ehcache.sourceforge.net/documentation/samples.html

2008年11月14日星期五

ISSNIP Summer School 2008

I gave a talk in Intelligent Sensors, Sensor Networks and Information Processing (ISSNIP) yesterday. My talk covers 2 topics, one is Sensor Network Analyzer from company I am working for and Sun SPOT.

Issnip Presentation
View SlideShare presentation or Upload your own.

Daintree's Sensor Network Analyzer (SNA) provides the industry's most comprehensive solution for ZigBee and 802.15.4 testing, analysis and commissioning. For more information, please check: http://www.daintree.net/

For more information about ISSNIP, please check:http://www.ee.unimelb.edu.au/ISSNIP/events/summerschool08.html

2008年10月25日星期六

XMLBeans and SensorML conflict

Digested from: http://forums.sun.com/thread.jspa?threadID=5332907

Hi all,
i have run out of all ideas and i am in a desperate need of help here, our project is stuck in the middle because of this.
I am using xmlbeans to bind xml to java objects. We are using OM, SWE and GML (opengis.net) schema specifications for our xmls. Xmlbeans has no problem creating schema if i am not importing any of the above schemas but when i try to i get the following error

addNewLocation() in net.opengis.sensorML.x101.AbstractDerivableComponentType clashes with addNewLocation() in net.opengis.gml.AbstractFeatureType; attempting to use incompatible return type
found: net.opengis.sensorML.x101.LocationDocument.Location
required: net.opengis.gml.LocationPropertyType

I've researched this for a while and found out that the problem is within SensorML schema and here is a apparent fix for this: [ https://52north.org/twiki/bin/view/Sensornet/SensorML| https://52north.org/twiki/bin/view/Sensornet/SensorML]
Now I am assuming that I am to download (using xmlbeans' sdownload tool) the system.xsd from SensorML folder (schemas.opengis.net) and make that change and since sdownload will create a catalog file, i use that catalog file when compiling the schema and xmlbean will look at the system.xsd on my local machine and go to the net for everything else.
The above is obviously not working since I don't think it ever looks at the system.xsd on my local machine but go to the net for it and obviously stumbles upon the problem.
Does anybody have any idea what i am talking about and how i can fix this?
I will greatly appreciate any insights into this problem. Our project is stuck at this and we can't move forward until this is resolved. thanks

so fixed my own problem :D, oh what a relief.
here is what i did in case some other poor soul encounters this issue.
- I downloaded SCHEMAS_OPENGIS_NET.zip from http://schemas.opengis.net/
- made the changes to the system.xsd file that were suggested here: https://52north.org/twiki/bin/view/Sensornet/SensorML
- my xsd file imported name space like the following

here is what i did in case some other poor soul encounters this issue.
- I downloaded SCHEMAS_OPENGIS_NET.zip from http://schemas.opengis.net/
- made the changes to the system.xsd file that were suggested here: https://52north.org/twiki/bin/view/Sensornet/SensorML
- my xsd file imported name space like the following

<import namespace="http://www.opengis.net/gml" schemaLocation="http://schemas.opengis.net/gml/3.1.1/base/gml.xsd"/>
<import namespace="http://www.opengis.net/swe/1.0.1" schemaLocation="http://schemas.opengis.net/sweCommon/1.0.1/swe.xsd"/>
<include schemaLocation="http://schemas.opengis.net/om/1.0.0/om.xsd"/>


I replaced the url to the name of the above folder. in my case it was SCHEMAS_OPENGIS_NET so now i've



<import namespace="http://www.opengis.net/gml" schemaLocation="SCHEMAS_OPENGIS_NET/gml/3.1.1/base/gml.xsd"/>
<import namespace="http://www.opengis.net/swe/1.0.1" schemaLocation="SCHEMAS_OPENGIS_NET/sweCommon/1.0.1/swe.xsd"/>
<include schemaLocation="SCHEMAS_OPENGIS_NET/om/1.0.0/om.xsd"/>


and that it, compile away :)

reply to this thread if u need help with this issue, i'll try to help if i can :)






Here below is text from https://52north.org/twiki/bin/view/Sensornet/SensorML



Sensor Model Language (SensorML)


SensorML defines concepts and XML encodings for descriptions of sensors, processes and systems. SensorML is used in several OGC SWE web services (e.g. SOS, SPS, SAS).

Compiling SensorML with XmlBeans


If you want to compile the sensorML.xsd schema into Java classes with XmlBeans, you have to do a small change in the schema. Open the system.xsd file and navigate to the definition of sml:AbstractDerivableComponentType. This type is an extension of sml:AbstractProcessType, which is an extension of gml:Feature. That is, why every sml:AbstractDerivableComponent has a location element with type gml:location. The sml:AbstractDerivableComponentType also contains a second location element, which is of type sml:location Having two location elements defined in the sml:AbstractDerivableComponentType leads to compiler errors when compiling the XmlBeans created Java classes.

Solution: The sml:location restricts gml:location to gml:Point and gml:_CurveType. The easiest way to get around with that, is to change the type of the location defined in the sml:AbstractDerivableComponentType at line 24 from sml:location to "gml:location". Although this keeps back the restriction to gml:Point and gml:_CurveType, you can use these types and the schema could be compiled with XmlBeans.



Please write, if you know a better solution!



Validating SensorML with Altova XmlSpy



For those developers, who are using XmlSpy 2005: If you comment out the xs:element name="parameter" type="swe:DataComponentPropertyType" maxOccurs="unbounded" element in line 298, the validation of schema system.xsd should work! -- ChristophStasch - 19 Jun 2007



To validate all SensorML schema with XmlBeans? 2005 rel 3, you also have to outcomment the parameters element in the TransducerType. This is quick and dirty and I will try to see, whether there are better workarounds for this issue. Nevertheless the whole schema do validate for now... -- ChristophStasch - 23 Jun 2007






My comment:



I can successfully compile SensorML using XMLBeans by following the solution from https://52north.org/twiki/bin/view/Sensornet/SensorML. I am not sure why I need to modify the schema location according to http://forums.sun.com/thread.jspa?threadID=5332907. If you have any idea, please let me know. Thanks!

2008年10月21日星期二

SunSPOT Application Template Updated

It seems some API has been changed, but the template file has not reflect these changes yet. Here is the latest template file:

/*
* StartApplication.java
*
* Created on Oct 21, 2008 9:42:46 PM;
*/


package org.sunspotworld;

import com.sun.spot.peripheral.Spot;
import com.sun.spot.sensorboard.EDemoBoard;
import com.sun.spot.sensorboard.peripheral.ISwitch;
import com.sun.spot.sensorboard.peripheral.ITriColorLED;
import com.sun.spot.util.*;

import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

/**
* The startApp method of this class is called by the VM to start the
* application.
*
* The manifest specifies this class as MIDlet-1, which means it will
* be selected for execution.
*/

public class StartApplication extends MIDlet {

private ITriColorLED [] leds = EDemoBoard.getInstance().getLEDs();

protected void startApp() throws MIDletStateChangeException {
System.out.println("Hello, world");
new BootloaderListener().start(); // monitor the USB (if connected) and recognize commands from host

// long ourAddr = RadioFactory.getRadioPolicyManager().getIEEEAddress();
long ourAddr = Spot.getInstance().getRadioPolicyManager().getIEEEAddress();

System.out.println("Our radio address = " + IEEEAddress.toDottedHex(ourAddr));

ISwitch sw1 = EDemoBoard.getInstance().getSwitches()[EDemoBoard.SW1];
leds[0].setRGB(100,0,0); // set color to moderate red
while (sw1.isOpen()) { // done when switch is pressed
leds[0].setOn(); // Blink LED
Utils.sleep(250); // wait 1/4 seconds
leds[0].setOff();
Utils.sleep(1000); // wait 1 second
}
notifyDestroyed(); // cause the MIDlet to exit
}

protected void pauseApp() {
// This is not currently called by the Squawk VM
}

/**
* Called if the MIDlet is terminated by the system.
* I.e. if startApp throws any exception other than MIDletStateChangeException,
* if the isolate running the MIDlet is killed with Isolate.exit(), or
* if VM.stopVM() is called.
*
* It is not called if MIDlet.notifyDestroyed() was called.
*
* @param unconditional If true when this method is called, the MIDlet must
* cleanup and release all resources. If false the MIDlet may throw
* MIDletStateChangeException to indicate it does not want to be destroyed
* at this time.
*/

protected void destroyApp(boolean unconditional) throws MIDletStateChangeException {
for (int i = 0; i < 8; i++) {
leds[i].setOff();
}
}
}


Please note the 2 lines in bold. This bug only happens when you are using SunSPOTApplicationTemplate 1.8 with Purple SDK, in new Blue SDK, it is not a problem. This problem is because the API change.

2008年9月21日星期日

The future of mobile 一起畅想一下手机的未来

The Internet has had an enormous impact on people's lives around the world in the ten years since Google's founding. It has changed politics, entertainment, culture, business, health care, the environment and just about every other topic you can think of. Which got us to thinking, what's going to happen in the next ten years? How will this phenomenal technology evolve, how will we adapt, and (more importantly) how will it adapt to us? We asked ten of our top experts this very question, and during September (our 10th anniversary month) we are presenting their responses. As computer scientist Alan Kay has famously observed, the best way to predict the future is to invent it, so we will be doing our best to make good on our experts' words every day. - Karen Wickre and Alan Eagle, series editors
There are currently about 3.2 billion mobile subscribers in the world, and that number is expected to grow by at least a billion in the next few years. Today, mobile phones are more prevalent than cars (about 800 million registered vehicles in the world) and credit cards (only 1.4 billion of those). While it took 100 years for landline phones to spread to more than 80% of the countries in the world, their wireless descendants did it in 16. And fewer teens are wearing watches now because they use their phones to tell time instead (somewhere Chester Gould is wondering how he got it backwards). So it's safe to say that the mobile phone may be the most prolific consumer product ever invented.
However, have you ever considered just exactly how powerful these ubiquitous devices are? The phone that you have in your pocket, pack, or handbag is probably ten times more powerful than the PC you had on your desk only 8 or 9 years ago (assuming you even had a PC; most mobile users never have). It has a range of sensors that would do a martian lander proud: a clock, power sensor (how low is that battery?), thermometer (because batteries charge poorly at low temperatures), and light meter (to determine screen backlighting) on the more basic phones; a location sensor, accelerometer (detects vector and velocity of motion), and maybe even a compass on more advanced ones. And most importantly, it is by its very nature always connected.
Project out these trends another ten years. You will be carrying with you, 24x7 (a recent study of Chinese mobile customers showed that the majority of them sleep within a meter of their phones), a very powerful, always connected, sensor-rich device. And the cool thing is, so will everyone else. So what are you going to do with it that you aren't doing now? Here are some possibilities:
Smart alerts: Your phone will be smart about your situation and alert you when something needs your attention. This is already happening today -- eBay can text you when you've been outbid, and alert services (such as Google News) can deliver news, sports, or stock updates to you. In the future these applications will get smarter, patiently monitoring your personalized preferences (which will be stored in the network cloud) and delivering only the information you desire. One very useful scenario: your phone knows that you are heading downtown for dinner, and alerts you of transit conditions or the best places to park.
Augmented reality: Your phone uses its arsenal of sensors to understand your situation and provide you information that might be useful. For example, do you really want to know how much is that doggy in the window? Your phone, with its GPS and compass, knows what you are looking at, so it can tell you before you even ask. Plus, what breed it is and the best way to train him.
Crowd sourcing goes mainstream: Your phone is your omnipresent microphone to the world, a way to publish pictures, emails, texts, Twitters, and blog entries. When everyone else is doing the same, you have a world where people from every corner of the planet are covering their experiences in real-time. That massive amount of content gets archived, sorted, and re-deployed to other people in new and interesting ways. Ask the web for the most interesting sites in your vicinity, and your phone shows you reviews and pictures that people have uploaded of nearby attractions. Like what you see? It will send you directions on how to get there.
Sensors everywhere: Your phone knows a lot about the world around you. If you take that intelligence and combine it in the cloud with that of every other phone, we have an incredible snapshot of what is going on in the world right now. Weather updates can be based on not hundreds of sensors, but hundreds of millions. Traffic reports can be based not on helicopters and road sensors, but on the density, speed, and direction of the phones (and people) stuck in the traffic jams.
Tool for development: Your phone may be more than just a convenience, it may be your livelihood. Already, this is true for people in many parts of the world: in southern India, fishermen use text messaging to find the best markets for their daily catch, in South Africa, sugar farmers can receive text messages advising them on how much to irrigate their crops, and throughout sub-Saharan Africa entrepreneurs with mobile phones become phone operators, bringing communications to their villages. These innovations will only increase in the future, as mobile phones become the linchpin for greater economic development.
The future-proof device: Your phone will open up, as the Internet already has, so it will be easy for developers to create or improve applications and content. The ones that you care about get automatically installed on your phone. Let's say you have a piece of software on your phone to improve power management (and therefore battery life). Let's say a developer makes an improvement to the software. The update gets automatically installed on your phone, without you lifting a finger. Your phone actually gets better over time.

Safer software through trust and verification: Your phone will provide tools and information to empower you to decide what to download, what to see, and what to share. Trust is the most important currency in the always connected world, and your phone will help you stay in control of your information. You may choose to share nothing at all (the default mode), or just share certain things with certain people -- your circle of trusted friends and family. You'll make these decisions based on information you get from the service and software providers, and the collective ratings of the community as well. Your phone is like your trusted valet: it knows a lot about you, and won't disclose an iota of it without your OK.

Now, if we can just train it to do your laundry ...
Posted by Andy Rubin, Engineering Director

http://googleblog.blogspot.com/2008/09/future-of-mobile.html


设计师常会讨论到“设计能不能改变世界”这个问题,“改变世界”通常是我们作为个体追求的一种最高理想,我们可以退而求其次,“科技改变世界”是一条公认的真理,在中国也是,当然还有一条是我们不太“想”谈的,但我们可以光明正大来谈“科技”是如何改变人们的生活,如何改变这个社会。什么科技在改变着我们,如果我们把范围定在这几年,第一答案一定会是“互联网”,接下来的也许就是我们这篇文章的主题——“手机”,到2008年上半年中国手机用户已达 6亿,没有什么比它更普及更接近每一个个人,调查显示大部分的中国人睡觉时离手机的距离在1米之内。

这个“1米之内”的数据引用之 Google 官方 Blog 的一篇文章“The future of mobile”,这篇文章谈论了移动和手机的未来。文中说到现在全球已有32亿的手机用户,它的普及率超过了汽车、信用卡和固定电话,手机的16年就完成了固定电话百年的扩展,年轻人更少戴手表因为手机会显示时间,手机无疑是最普及的消费产品。现在手机的功能已经超过8,9年前的PC,而且它有一系列的传感探测器诸如时钟、电能、光感、温度、地理以及动力速度等。文章从几方面出发谈论了手机未来的各种可能性。

1,智能提醒。根据你的所处情况为主动你提供各种信息,诸如建议,各种即使信息等。结合你的个人信息(储存在云网络中)为你提供恰巧需要的信息。

2,AR,虚拟扩增。我们在对 Android 的期待中谈到过一些,手机的传感器可以将物理世界和虚拟信息更主动相连,比如你想知道那窗户内的小狗什么价格出卖时,在你问之前,你的手机会告诉你,甚至更多的信息,如何喂养如何训练。

3,走向主流的群体信息源。你的手机是你面向世界的麦克风,世界每一个角落每一个人都在用手机发布他们的照片、邮件、短信、 Twiiters,Blog等他们的实时体验,这些信息被索引,储存,并通过不同方式重新分发。当你在一地想知道有什么好玩的东西,你手机会告诉你别人的体验。

4,无处不在的传感探测器。手机作为机器可以了解更多周遭的世界,比如基于手机的交通情况。

5,生产工具。印度南方的渔夫使用短信可以找到最好的市场,南非的糖农可以接受到建议短信关于灌溉作物的量度等。

6,自我完善的设备。就和我们电脑上的软件自动更新一样,你的手机也将会一次次的完善成长。

7,经过信用认证的安全。控制分享的信息,基于社区评价的决定等等。

虽然在现在从一个手机来说,它并没有和其他一些数字消费品相差多少,但是由于它被使用的环境,它发挥的作用有些是我们始料未及的,如我们开头说的改变着生活改变着社会改变着世界,那么你来畅想一下手机的未来,它会是怎样,或者说你希望它怎样呢?欢迎发表你的意见。

http://www.hi-id.com/?p=1963

2008年9月20日星期六

The 3rd Shenzhou manned spacecraft PERFECTLY landed

Shenzhou 7 took off at the end of September. One of three astronauts left spacecraft and released a tiny satellite during mission.

http://en.wikipedia.org/wiki/Shenzhou_spacecraft

http://en.wikipedia.org/wiki/Shenzhou_7

 

Taking off real time video from Shenzhou 7:

The first Chinese spacewalk:

Landing……

Three HEROS

 

We will build our own short term space station and lunch it in 2012.

2008年9月12日星期五

Energy Harvesting on Mote

Read this document on Scribd: Sentilla Energy Harvesting

http://www.sentilla.com/pdf/Sentilla_Energy_Harvesting.pdf

2008年8月26日星期二

Digest:Sun SPOT Slides@Open House Sun Labs 2008

 

Read this document on Scribd: OpenHouse08 SPOTS
 
 

Add 3rd Party JAR Library to Sun SPOT Application

According to https://www.sunspotworld.com/forums/viewtopic.php?p=7666#7666

For a host app all you need to do is specify the third party jar files in your project's build.properties file:
Code:
user.classpath=/whatever/directory/<TheNameOfYourJAR>.jar

For a SPOT app to have the third party jar deployed to the SPOT you need to use the following:
Code:
utility.jars=/whatever/directory/<TheNameOfYourJAR>.jar

For a SPOT app, if you are using NetBeans, you also need to add the third party jar file to the compile classpath (i.e. <classpath mode="compile">) in the nbproject/project.xml file. If you have modified your project.xml file to use SPOT defined properties then you can add it by putting
Code:
user.classpath=${utility.jars}

in your build.properties file.

NOTE: issue about preverify JAR is discussed here as well...

2008年7月29日星期二

2008年7月20日星期日

The Procedure of Sending and Receiving Pack On Sun SPOT

The timestamp is the system time when the packet was read in from the radio chip on receives and when the packet was sent on transmits. If you consider all the steps involved in transmitting & receiving a packet things will (hopefully) become clear:

on sending spot:

1. user app packs data to send into a radiogram packet.
2. user app initiates send of packet
3. radio stack checks for route to destination, etc.
4. finally ready to send so write data to radio chip
5. data written, wait for transmission to start
6. record time packet was actually sent
7. user app can now query when transmission occurred

on receiving spot:

1. user app blocks waiting to receive a radiogram
2. radio stack receive thread blocks waiting for interrupt
3. radio receives incoming packet and stores it in fifo buffer
4. Squawk VM responds to radio interrupt and restarts receive thread
5. receive thread reads in radiogram packet from radio's fifo buffer
6. record the current time to mark when packet was received
7. radio stack processes packet and passes it to user app
8. user app does whatever it needs to with packet

As you can see from the many steps a fair amount of time can pass between when a packet is physically received & when the user program finally gets handed the packet (& ditto when sending). The timestamp on the packet is a way to minimize some of this latency.

For most applications the latency doesn't matter, but it's essential for anyone who wants to do a time synchronization protocol in order to have the clocks on several spots all be within a few milliseconds of each other.

--rgoldman

--https://www.sunspotworld.com/forums/viewtopic.php?t=1484

2008年7月19日星期六

Beijing2008, 20 days to GO

Welcom to Beijing music video

As a oversea Chinese, I am so proud! Good luck Beijing!

北京欢迎你!

迎接另一个晨曦,带来全新空气。陈天佳
Let' s embrace another morning and enjoy its ever new air.
Ying jie ling yi ge chen xi, dai lai quan xin kong qi.
气息改变情味不变,茶香飘满情谊。刘欢
With the fragrance of tea, it smells different. But it feels great, full of friendship.
Qi xi gai bian qing wei bu bian, cha xiang tiao man qing yi.
我家大门常打开,开放怀抱等你。那英
Our door is always open. We are waiting for you open-armed.
Wo jia da men chang da kai, kai fang huai bao deng ni.
拥抱过就有了默契,你就会爱上这里。孙燕姿-Stefanie Sun
After a big hug, you'll feel close with us. And surely you will love this place.
Yong bao guo jiu you le mo qi, ni jiu hui ai shang zhe li.
不管远近都是客人,请不用客气。孙悦
Our guests, no matter where you come from, please feel at home.
Bu guan yuan jin dou shi ke ren, qing bu yong ke qi.
相约好了在一起,我们欢迎你。王力宏-Wang Lee Hom
We promised to get together here. So welcome!
Xiang yue hao le zai yi qi, wo men huan ying ni.
我家种着万年青,开放每段传奇。韩红
We cultivate Chinese Evergreen in the garden. All the time, it is producing a new legend.
Wo jia zhong zhe wan nian qing, kai fang mei duan chuan qi.
为传统的土壤播种,为你留下回忆。周华健-Emil Chou
In the soil rich in traditions, we plant. Hope everything we plant here leaves you a great experience.
Wei chuan tong de tu rang bo zhong, wei ni liu xia hui yi.
陌生熟悉都是客人,请不用拘礼。梁咏琪
Our guests, no matter we've met before or not, please feel at ease.
Mo sheng shu xi dou shi ke ren, qing bu yong ju li.
第几次来没关系,有太多话题。羽泉
Even if you have been here for many times, you won't feel bored 'cause we have vast new things for you.
Di ji ci lai mei guan xi, you tai duo hua ti.
北京欢迎你,为你开天辟地。成龙-Jackie Chan
Welcome to Beijing; we've done a lot for your visit.
Bei jing huan ying ni, wei ni kai tian bi di.
流动中的魅力,充满着朝气。任贤齐-Richie Ren
Its charm in ever changing is full of life.
Liu dong zhong de mei li, chong man zhe chao qi.
北京欢迎你,在太阳下分享呼吸。蔡依林-Jolin Tsai
Welcome to Beijing; let's breathe together in the sunshine.
Bei jing huan ying ni, zai tai yang xia fen xiang hu xi.
在黄土地刷新成绩!孙楠
Let's establish new records here in China.
Zai huang tu di shua xin cheng ji.
我家大门常打开,开怀容纳天地。周笔畅
Our door is always open. We are open armed, ready to embrace the world.
Wo jia da men chang da kai, kai huai rong na tian di.
岁月绽放青春笑容,迎接这个日期。韦唯
5000-year-old China is flashing a youthful smile, waiting for the day.
Sui yue zhan fang qing chun xiao rong, huan jie zhe ge re qi.
天大地大都是朋友,请不用客气。黄晓明-Huang Xiao Ming
Our guests, no matter where you come from, please feel at home.
Tian da di da dou shi peng you, qing bu yong ke qi.
画意诗意带笑意,只为等待你。韩庚-Hangeng from Super Junior
We paint pictures and write poems to express the joy for your coming.
Hua yi shi yi dai xiao yi, zhi wei deng dai ni.
北京欢迎你,像音乐感动你。汪峰
Welcome to Beijing; like moving music, our hospitality will warm your heart.
Bei jing huan ying ni, xiang ying yue gan dong ni.
让我们都加油去超越自己。莫文蔚-Karen Mok
Let's try to challenge ourselves.
Rang wo men dou jia you qu chao yue zi ji.
北京欢迎你,有梦想谁都了不起。谭晶
Welcome to Beijing; people who have dreams are all bravo.
Bei jing huan ying ni, you meng xiang shei dou liao bu qi.
有勇气就会有奇迹。陈奕迅
If only you keep the courage, miracles will happen.
You yong qi jiu hui you qi ji.
北京欢迎你,为你开天辟地。阎维文
Welcome to Beijing; we've done a lot for your visit.
Bei jing huan ying ni, wei ni kai tian bi di.
流动中的魅力,充满着朝气。戴玉强
Its charm in ever changing is full of life.
Liu dong zhong de mei li, chong man zhe chao qi.
北京欢迎你,在太阳下分享呼吸。王霞, 李双松
Welcome to Beijing; let's breathe together in the sunshine.
Bei jing huan ying ni, zai tai yang xia fen xiang hu xi.
在黄土地刷新成绩!廖昌永
Let's establish new records here in China.
Zai huang tu di shua xin cheng ji.
北京欢迎你,像音乐感动你。林依轮
Welcome to Beijing; like moving music, our hospitality will warm your heart.
Bei jing huan ying ni, xiang ying yue gan dong ni.
让我们都加油去超越自己。张娜拉
Let's try to challenge ourselves.
Rang wo men dou jia you qu chao yue zi ji.
北京欢迎你,有梦想谁都了不起。林俊杰-JJ Lin
Welcome to Beijing; people who have dreams are all bravo.
Bei jing huan ying ni, you meng xiang shei dou liao bu qi.
有勇气就会有奇迹。阿杜-Ah Du
If only you keep the courage, miracles will happen.
You yong qi jiu hui you qi ji.
我家大门常打开,开放怀抱等你。容祖儿-Joey Yung
Our door is always open. We are waiting for you open-armed.
Wo jia da men chang da kai, kai fang huai bao deng ni.
拥抱过就有了默契,你就会爱上这里。李宇春-Chris Li
After a big hug, you'll feel close with us. And surely you will love this place.
Yong bao guo jiu you le mo qi, ni jiu hui ai shang zhe li.
不管远近都是客人,请不用客气。黄大炜-Huang Da Wei
Our guests, no matter where you come from, please feel at home.
Bu guan yuan jin dou shi ke ren, qing bu yong ke qi.
相约好了在一起,我们欢迎你。陈坤-Chen Kun
We promised to get together here. So welcome!
Xiang yue hao le zai yi qi, wo men huan ying ni.
北京欢迎你,为你开天辟地。谢霆锋-Nicholas Tse
Welcome to Beijing; we've done a lot for your visit.
Bei jing huan ying ni, wei ni kai tian bi di.
流动中的魅力,充满着朝气。韩磊
Its charm in ever changing is full of life.
Liu dong zhong de mei li, chong man zhe chao qi.
北京欢迎你,在太阳下分享呼吸。徐若瑄-Vivian Hsu
Welcome to Beijing; let's breathe together in the sunshine.
Bei jing huan ying ni, zai tai yang xia fen xiang hu xi.
在黄土地刷新成绩!费翔
Let's establish new records here in China.
Zai huang tu di shua xin cheng ji.
我家大门常打开,开怀容纳天地。汤灿
Our door is always open. We are open armed, ready to embrace the world.
Wo jia da men chang da kai, kai huai yi rong na tian di.
岁月绽放青春笑容,迎接这个日期。林志玲-Lin Ci Ling, 张梓琳
5000-year-old China is flashing a youthful smile, waiting for the day.
Sui yue zhan fang qing chun xiao rong, huan jie zhe ge re qi.
天大地大都是朋友,请不用客气。张靓颖
Our guests, no matter where you come from, please feel at home.
Tian da di da dou shi peng you, qing bu yong ke qi.
画意诗意带笑意,只为等待你。许茹芸, 伍思凯
We paint pictures and write poems to express the joy for your coming.
Hua yi shi yi dai xiao yi, zhi wei deng dai ni.
北京欢迎你,像音乐感动你。杨坤, 范玮琪-Fan Wei Qi
Welcome to Beijing; like moving music, our hospitality will warm your heart.
Bei jing huan ying ni, xiang ying yue gan dong ni.
让我们都加油去超越自己。游鸿明, 周晓欧
Let's try to challenge ourselves.
Rang wo men dou jia you qu chao yue zi ji.
北京欢迎你,有梦想谁都了不起。沙宝亮, 满文军
Welcome to Beijing; people who have dreams are all bravo.
Bei jing huan ying ni, you meng xiang shei dou liao bu qi.
有勇气就会有奇迹。金海心, 何润东
If only you keep the courage, miracles will happen.
You yong qi jiu hui you qi ji.
北京欢迎你,为你开天辟地。飞儿-FIR, 庞龙
Welcome to Beijing; we've done a lot for your visit.
Bei jing huan ying ni, wei ni kai tian bi di.
流动中的魅力,充满着朝气。吴克群-Kenji Wu, 齐峰
Its charm in ever changing is full of life.
Liu dong zhong de mei li, chong man zhe chao qi.
北京欢迎你,在太阳下分享呼吸。5566, 胡彦斌-Anson Hu
Welcome to Beijing; let's breathe together in the sunshine.
Bei jing huan ying ni, zai tai yang xia fen xiang hu xi.
在黄土地刷新成绩!郑希怡, 刀郎
Let's establish new records here in China.
Zai huang tu di shua xin cheng ji.
北京欢迎你,像音乐感动你。纪敏加, 屠洪刚, 吴彤
Welcome to Beijing; like moving music, our hospitality will warm your heart.
Bei jing huan ying ni, xiang ying yue gan dong ni.
让我们都加油去超越自己。郭容, 刘耕宏, 腾格尔
Let's try to challenge ourselves.
Rang wo men dou jia you qu chao yue zi ji.
北京欢迎你,有梦想谁都了不起。金莎, 苏醒, 韦嘉
Welcome to Beijing; people who have dreams are all bravo.
Bei jing huan ying ni, you meng xiang shei dou liao bu qi.
有勇气就会有奇迹。付丽珊, 黄征, 房祖明
If only you keep the courage, miracles will happen.
You yong qi jiu hui you qi ji.
北京欢迎你,有梦想谁都了不起。
Welcome to Beijing; people who have dreams are all bravo.
Bei jing huan ying ni, you meng xiang shei dou liao bu qi.
有勇气就会有奇迹。
If only you keep the courage, miracles will happen.
You yong qi jiu hui you qi ji.
北京欢迎你,有梦想谁都了不起。
Welcome to Beijing; people who have dreams are all bravo.
Bei jing huan ying ni, you meng xiang shei dou liao bu qi.
有勇气就会有奇迹!
If only you keep the courage, miracles will happen.
You yong qi jiu hui you qi ji.

2008年7月18日星期五

Simple JAXP Application

The Java API for XML Processing, or JAXP (pronounced jaks-p), is one of the Java XML programming APIs. It provides the capability of validating and parsing XML documents. The three basic parsing interfaces are:

    * the Document Object Model parsing interface or DOM interface
    * the Simple API for XML parsing interface or SAX interface
    * the Streaming API for XML or StAX interface (added in JDK 6; separate jar available for JDK 5)

--http://en.wikipedia.org/wiki/Java_API_for_XML_Processing

This tutorial is based on http://www.vogella.de/articles/JavaXML/article.html

We have two XML files to read in this example. They are:

config.xml

<?xml version="1.0" encoding="UTF-8"?>
<config>
<mode>1</mode>
<unit>900</unit>
<current>1</current>
<interactive>1</interactive>
</config>





person.xml



<?xml version="1.0" encoding="UTF-8"?>
<people>
<person>
<firstname>Lars</firstname>
<lastname>Vogel</lastname>
<city>Heidelberg</city>
</person>

<person>
<firstname>Jim</firstname>
<lastname>Knopf</lastname>
<city>Heidelberg</city>
</person>

<person>
<firstname>Lars</firstname>
<lastname>Strangelastname</lastname>
<city>London</city>
</person>

<person>
<firstname>Landerman</firstname>
<lastname>Petrelli</lastname>
<city>Somewhere</city>
</person>

<person>
<firstname>Lars</firstname>
<lastname>Tim</lastname>
<city>SomewhereElse</city>
</person>

</people>


Now, Here below is a simple Java application to read and write and query XML:



/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package hellojaxp;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartDocument;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class Main {

public static void main(String args[]) {
Main object = new Main();
object.readXML("config.xml");
object.writeXML("config2.xml");
object.query("person.xml", null);
}

public void readXML(String path) {

try {
// First create a new XMLInputFactory
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
// Setup a new eventReader
InputStream in = new FileInputStream(path);
XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
// Read the XML document
while (eventReader.hasNext()) {
XMLEvent event = eventReader.nextEvent();

if (event.isStartElement()) {
if (event.asStartElement().getName().getLocalPart().equals("mode")) {
event = eventReader.nextEvent();
System.out.println(event.asCharacters().getData());
continue;
}
if (event.asStartElement().getName().getLocalPart().equals("unit")) {
event = eventReader.nextEvent();
System.out.println(event.asCharacters().getData());
continue;
}
if (event.asStartElement().getName().getLocalPart().equals("current")) {
event = eventReader.nextEvent();
System.out.println(event.asCharacters().getData());
continue;
}
if (event.asStartElement().getName().getLocalPart().equals("interactive")) {
event = eventReader.nextEvent();
System.out.println(event.asCharacters().getData());
continue;
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (XMLStreamException e) {
e.printStackTrace();
}
}

private void createNode(XMLEventWriter eventWriter, String name, String value) {
try {
XMLEventFactory eventFactory = XMLEventFactory.newInstance();
XMLEvent end = eventFactory.createDTD("\n");
XMLEvent tab = eventFactory.createDTD("\t");
// Create Start node
StartElement sElement = eventFactory.createStartElement("", "", name);
eventWriter.add(tab);
eventWriter.add(sElement);
// Create Content
Characters characters = eventFactory.createCharacters(value);
eventWriter.add(characters);
// Create End node
EndElement eElement = eventFactory.createEndElement("", "", name);
eventWriter.add(eElement);
eventWriter.add(end);
} catch (XMLStreamException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}

private void writeXML(String path) {
try {
// Create a XMLOutputFactory
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
// Create XMLEventWriter
XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(new FileOutputStream(path));
// Create a EventFactory
XMLEventFactory eventFactory = XMLEventFactory.newInstance();
XMLEvent end = eventFactory.createDTD("\n");
// Create and write Start Tag
StartDocument startDocument = eventFactory.createStartDocument();
eventWriter.add(startDocument);

// Create config open tag
StartElement configStartElement = eventFactory.createStartElement("", "", "config");
eventWriter.add(configStartElement);
eventWriter.add(end);
// Write the different nodes
createNode(eventWriter, "mode", "1");
createNode(eventWriter, "unit", "901");
createNode(eventWriter, "current", "0");
createNode(eventWriter, "interactive", "0");

eventWriter.add(eventFactory.createEndElement("", "", "config"));
eventWriter.add(end);
eventWriter.add(eventFactory.createEndDocument());
eventWriter.close();
} catch (Exception ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}

private void query(String path, String keyword) {
try {
// Standard of reading a XML file
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder;
Document doc = null;
XPathExpression expr = null;
builder = factory.newDocumentBuilder();
doc = builder.parse(path);

// Create a XPathFactory
XPathFactory xFactory = XPathFactory.newInstance();

// Create a XPath object
XPath xpath = xFactory.newXPath();

// Compile the XPath expression
expr = xpath.compile("//person[firstname='Lars']/lastname/text()");
// Run the query and get a nodeset
Object result = expr.evaluate(doc, XPathConstants.NODESET);

// Cast the result to a DOM NodeList
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}

// New XPath expression to get the number of people with name lars
expr = xpath.compile("count(//person[firstname='Lars'])");
// Run the query and get the number of nodes
Double number = (Double) expr.evaluate(doc, XPathConstants.NUMBER);
System.out.println("Number of objects " + number);

// Do we have more then 2 people with name lars?
expr = xpath.compile("count(//person[firstname='Lars']) >2");
// Run the query and get the number of nodes
Boolean check = (Boolean) expr.evaluate(doc, XPathConstants.BOOLEAN);
System.out.println(check);
} catch (Exception ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}


You can download this Netbeans project from


http://www.mediafire.com/?mk445c5msi2

2008年7月17日星期四

Simple JAXB Application

Java Architecture for XML Binding (JAXB) allows Java developers to map Java classes to XML representations. JAXB provides two main features: the ability to marshal Java objects into XML and the inverse, i.e. to unmarshal XML back into Java objects. In other words, JAXB allows storing and retrieving data in memory in any XML format, without the need to implement a specific set of XML loading and saving routines for the program's class structure.

JAXB is particularly useful when the specification is complex and changing. In such a case, regularly changing the XML Schema definitions to keep them synchronised with the Java definitions can be time consuming and error prone.

The tool "xjc" can be used to convert XML Schema and other schema file types (as of Java 1.6, RELAX NG and XML DTDs are supported experimentally) to class representations. Classes are marked up using annotations from javax.xml.bind.annotation.* namespace, for example, @XmlRootElement and @XmlElement. XML list sequences are represented by attributes of type java.util.List. Marshallers and Unmarshallers are created through an instance of JAXBContext.

In addition, JAXB includes a "schemagen" tool which can essentially perform the inverse of "xjc", creating an XML Schema from a set of annotated classes.

--http://en.wikipedia.org/wiki/JAXB

country.xsd

<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="country" type="Country"/>
<xs:complexType name="Country">
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="population" type="xs:decimal"/>
</xs:sequence>
</xs:complexType>
</xs:schema>





country.xml


<country
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="country.xsd">
<name>France</name>
<population>60144000</population>
</country>





1. Download JAXB from https://jaxb.dev.java.net/


2. Convert XML schema to Java class source file. The command is xjc.bat -package.name sourceXMLSchema.xsd. For example, execute xjc.bat –countries country.xsd, we should get these files:



  • Country.java


  • ObjectFactory.java



3. Create a project in Netbeans, and copy the generated source files to the folder of project source. And do not forget to add the JAXB 2.1 library in project properties.


4. Here below is the source code of main java which shows both read and write XML functions:


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package simplejaxb;

import countries.Country;
import countries.ObjectFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
*
* @author pdeng
*/

public class Main {

/**
* @param args the command line arguments
*/

public static void main(String[] args) {
// Read and convert a XML file from disk to a Java object in memory
readAndConvert("country.xml");

// Write a Java object in memory to a XML file on disk
writeXML("country2.xml");
}

private static void readAndConvert(String path) {
try {
// Read XML to Java object
JAXBContext jc = JAXBContext.newInstance("countries");
Unmarshaller um = jc.createUnmarshaller();
JAXBElement<Country> countryElement = (JAXBElement<Country>) um.unmarshal(new File(path));
Country c = countryElement.getValue();

//Print out values from Java object
System.out.println(c.getName());
System.out.println(c.getPopulation());
} catch (JAXBException ex) {
ex.printStackTrace();
}
}

private static void writeXML(String path) {
try {
// Create java object and assign values to this object
JAXBContext jaxbContext = JAXBContext.newInstance("countries");
ObjectFactory objFactory = new ObjectFactory();
Country c = objFactory.createCountry();
c.setName("China");
c.setPopulation(BigDecimal.valueOf(130000000));
JAXBElement<Country> countryElement = objFactory.createCountry(c);

// Create instance of marshaller and write object to XML file
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true));
marshaller.marshal(countryElement, new FileOutputStream(path));
} catch (Exception ex) {
ex.printStackTrace();
}

}
}


5. if you still confuse about how the app works, you can douload the project archieve from http://www.mediafire.com/?zpt74jm5gs2








This is another example which is a bit complex than the one above. We have XML Schema file and a XML file.



books.xsd



<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" jaxb:version="1.0">


<xs:element name="Collection">
<xs:complexType>
<xs:sequence>
<xs:element name ="books">
<xs:complexType>
<xs:sequence>
<xs:element name="book" type="bookType" minOccurs="1" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>

<xs:complexType name="bookType">
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="ISBN" type="xs:long"/>
<xs:element name="price" type="xs:string"/>
<xs:element name="authors" >
<xs:complexType>
<xs:sequence>
<xs:element name="authorName" type="xs:string" minOccurs="1"
maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="description" type="xs:string" minOccurs="0"/>
<xs:element name="promotion">
<xs:complexType>
<xs:choice>
<xs:element name="Discount" type="xs:string" />
<xs:element name="None" type="xs:string"/>
</xs:choice>
</xs:complexType>
</xs:element>
<xs:element name="publicationDate" type="xs:date"/>
<xs:element name="bookCategory">
<xs:simpleType>
<xs:restriction base="xs:NCName">
<xs:enumeration value="magazine" />
<xs:enumeration value="novel" />
<xs:enumeration value="fiction" />
<xs:enumeration value="other" />
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:sequence>
<xs:attribute name="itemId" type="xs:string" />
</xs:complexType>



<xs:simpleType name="bookCategoryType" >
<xs:restriction base="xs:string">
<xs:enumeration value="magazine" />
<xs:enumeration value="novel" />
<xs:enumeration value="fiction" />
<xs:enumeration value="other" />
</xs:restriction>
</xs:simpleType>


</xs:schema>





books.xml



<?xml version="1.0"?>
<Collection>
<books>
<book itemId="999">
<name>
Learning JAXB
</name>
<ISBN>
123445
</ISBN>
<price>
34 $
</price>
<authors>
<authorName> Jane Doe
</authorName>
</authors>
<description>
This books contains step by step instructions for beginners so that they can start using Java API for XML Binding.
</description>
<promotion>
<Discount> 10% on this book if purchased by March 2003
</Discount>
</promotion>
<publicationDate>
2003-01-01
</publicationDate>
<bookCategory>other
</bookCategory>
</book>

<book itemId="129">
<name>
Java Webservices today and Beyond
</name>
<ISBN>
522965
</ISBN>
<price>
29 $
</price>
<authors>
<authorName> John Brown
</authorName>
<authorName> Peter T.
</authorName>
</authors>
<description>
This books contains information for users so that they can start using Java Web Services Developer Pack.
</description>
<promotion>
<Discount> Buy one get Learning webservices Part 1 free
</Discount>
</promotion>
<publicationDate>
2002-11-01
</publicationDate>
<bookCategory>magazine
</bookCategory>
</book>
</books>
</Collection>




Follow the same first three steps of previous example. Here below is the source of main.java to read and output a XML file:



/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package hellojaxb;

import books.BookType;
import books.Collection;
import books.Collection.Books;
import books.ObjectFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
*
* @author pdeng
*/

public class Main {

/**
* @param args the command line arguments
*/

public static void main(String[] args) {
// Read and convert a XML file from disk to a Java object in memory
readAndConvert("books.xml");

// Write a Java object in memory to a XML file on disk
writeXML("jaxbOutput2.xml");
}

private static void readAndConvert(String path) {
try {
// Read XML to Java object
JAXBContext jc = JAXBContext.newInstance("books");
Unmarshaller um = jc.createUnmarshaller();
Collection col = (Collection) um.unmarshal(new File(path));
Books bt = col.getBooks();
List bl = bt.getBook();

//Print out values from Java object
BookType book = (BookType) bl.get(0);
System.out.println(book.getName());
} catch (JAXBException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}

private static void writeXML(String path) {
try {
// Create java object and assign values to this object
JAXBContext jaxbContext = JAXBContext.newInstance("books");
ObjectFactory objFactory = new ObjectFactory();
Collection collection = (Collection) objFactory.createCollection();
Books booksType = objFactory.createCollectionBooks();
List bookList = booksType.getBook();

// Create one instance of book
BookType book = objFactory.createBookType();
book.setItemId("307");
book.setName("JAXB today and beyond");
book.setDescription("This is an intermediate book on JAXB");
book.setISBN(987665L);
book.setPrice("45$");
//book.setPublicationDate();
book.setBookCategory("other");
BookType.Promotion promotionType = objFactory.createBookTypePromotion();
promotionType.setDiscount("5% off regular price");
book.setPromotion(promotionType);
BookType.Authors authorsType = objFactory.createBookTypeAuthors();
List authorList = authorsType.getAuthorName();
authorList.add("Richard K");
book.setAuthors(authorsType);

bookList.add(book);
collection.setBooks(booksType);

// Create instance of marshaller and write object to XML file
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true));
marshaller.marshal(collection, new FileOutputStream(path));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}


5. if you still confuse about how the app works, you can douload the project archieve from http://www.mediafire.com/?vm5gy2xrcjd