"; */ ?>

java


28
May 08

Generate XSD from XML

There are several tools out there to create (or to infer) an XSD schema from XML document. I liked trang command line tool the most. Found it first when reading about Spring web services in Spring in Action book (very good book btw).

Here are four simple steps how to create XSD from XML* using trang:

Step 1. Get trang

Download trang.zip from here (at the moment of writing “trang-20030619.zip”)

Step 2. Extract it

Use “unzip trang-version.zip”, or just winzip/winrar/7z etc.. if on windows

Step 3. Make an alias

This step is optional, but makes it extremely easy to run the tool with a single command. Make an alias to the “trang.jar” by (in my case Ubuntu/Linux) editing “~/.bashrc” and adding the following:

# execute trang.jar (create XSD from XMLs)
alias xml2xsd='java -jar ~/soft/utils/trang/trang-20030619/trang.jar'

above “~/soft/utils/trang” is the directory where “trang” was unzipped to.

Step 4. Create XSD from XML

Let’s look at the XML file we need an XSD for:

$ ls -l
total 4
-rw-r--r-- 1 user group 357 2008-05-28 15:38 holiday-request.xml
 
$ cat holiday-request.xml
<?xml version="1.0" encoding="UTF-8"?>
<holidayRequest xmlns="http://mycompany.com/hr/schemas">
    <holiday>
        <startDate>2006-07-03</startDate>
        <endDate>2006-07-07</endDate>
    </holiday>
    <employee>
        <number>42</number>
        <firstName>Ultimate</firstName>
        <lastName>Answer</lastName>
    </employee>
</holidayRequest>

now run the tool against it:

$ xml2xsd holiday-request.xml hr.xsd
$ cat hr.xsd
<?xml version=”1.0″ encoding=”UTF-8″?>
<xs:schema xmlns:xs=”http://www.w3.org/2001/XMLSchema” elementFormDefault=”qualified” targetNamespace=”http://mycompany.com/hr/schemas” xmlns:schemas=”http://mycompany.com/hr/schemas”>
  <xs:element name=”HolidayRequest”>
    <xs:complexType>
      <xs:sequence>
        <xs:element ref=”schemas:Holiday”/>
        <xs:element ref=”schemas:Employee”/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name=”Holiday”>
    <xs:complexType>
      <xs:sequence>
        <xs:element ref=”schemas:StartDate”/>
        <xs:element ref=”schemas:EndDate”/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name=”StartDate” type=”xs:NMTOKEN”/>
  <xs:element name=”EndDate” type=”xs:NMTOKEN”/>
  <xs:element name=”Employee”>
    <xs:complexType>
      <xs:sequence>
        <xs:element ref=”schemas:Number”/>
        <xs:element ref=”schemas:FirstName”/>
        <xs:element ref=”schemas:LastName”/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name=”Number” type=”xs:integer”/>
  <xs:element name=”FirstName” type=”xs:NCName”/>
  <xs:element name=”LastName” type=”xs:NCName”/>
</xs:schema>

done!

$

* – NOTE: “trang” can create an XSD from multiple XML documents, not just one.

List of other tools to use as an alternative to trang:

XSD away, Good Luck!


22
Apr 08

Creating Public and Private Certificates/Keys

Public and Private Key PairHave you ever tried to communicate with somebody/something through any kind of technology? Most of the time “those” people/systems like privacy, in a way that they like their communication with everybody including you to be private. Hence once you want to communicate with them they give you something called a “public key” ( or “public-key certificate” ) and ask you to give them yours. Usually when you talk to different sources, nobody would guide you through on how to create that “public key” of yours, “they” would just want it, but you would be left alone to figure out how you should generate it.

Hence this little guide will show you one of many ways on how to generate a pair of X.509 public/private keys, and how to access this magic pair to get that “public key”, so it can be given to anyone who needs it.

First, let us throw a couple of sentences on how these keys are used. It is actually very simple – there is “YOU” and “THEY”:

  • YOU: generate a pair of public/private keys (where whatever is encrypted with your public key can only be decrypted with your private key)
  • YOU: hide your private key from everybody
  • YOU: give your public key to anybody who wants to communicate with you
  • THEY: generate a pair of public/private keys
  • THEY: hide their private key from everybody including YOU
  • THEY: give their public key to anybody who wants to communicate with them

Now when YOU and THEY have each others public keys and their own private keys communication may begin:

  • YOU: write your secret message, encrypt it with THEIR public key and send to them
  • THEY: receive your top secret message and using THEIR private key decrypt it
  • THEY: write you an answer, encrypt it with YOUR public key, and send to you
  • YOU: receive their top secret response and using YOUR private key decrypt it

Told you it is very simple!

Now let’s see how to do the magic – how to generate a pair of YOUR public and private keys.

There are number of ways – tools/libraries/code snippets/etc.. I would show you one of the simplest ways how this can be archived using a tool called… any guess? Yes – a “keytool” – make sense, right?

“keytool” is a java tool that has a great manual, and since its java – it’ll work on any OS that has JVM. In order to get/download a keytool, you just have to install Java (JRE) on your system (95% that you already have it installed, hence you can go ahead and use “keytool” without needing to install/download anything else).

Examples here are run on Linux (Ubuntu), but as long as you have Java installed, it does not really matter what OS you have to get the job done.

So, fire up the terminal (Windows’ “cmd”) and let’s generate a pair of public/private keys now:

$ keytool -genkey -alias otherguy -keypass p@ssw0rd -keystore our.keystore
Enter key store password: ksp@ssw0rd
 
You are about to enter information that will be incorporated into
your certificate request.  This information is what is called a
Distinguished Name or DN.  There are quite a few fields but you
can use supplied default values, displayed between brackets, by just
hitting &lt;Enter&gt;, or blank the field by entering the &lt;.&gt; character
before hitting &lt;Enter&gt;.
 
Common Name (hostname, IP, or your name): myname
Organization Name (company) [The Sample Company]: my company
Organizational Unit Name (department, division): department of departments
Locality Name (city, district) [Sydney]: gorodok
State or Province Name (full name) [NSW]: state of new noisy
Country Name (2 letter code) [AU]: zz

As you might figured already, a keystore is a small database, that we just created, that would hold all the keys (private/public) for many systems – right now we only have one pair, but later we can add more keys to the keystore. So let’s look at this keystore that we just generated:

$ ls -l
total 4
-rw-r--r-- 1 user group 1641 2008-04-22 20:46 our.keystore

But now you need to be able to access this “database” to get a public key, so you can share it with others. It is done by exporting this public key – again, very simple:

$ keytool -export -rfc -alias otherguy -file us-to-otherguy.cer -keystore our.keystore
Enter key store password: ksp@ssw0rd

let’s see what files we have now:

$ ls -l
 
total 8
-rw-r--r-- 1 user group 1641 2008-04-22 20:46 our.keystore
-rw-r--r-- 1 user group 1189 2008-04-22 20:48 us-to-otherguy.cer

And here it is (!) your public key certificate – “us-to-otherguy.cer”. Let’s see what’s inside:

$ cat us-to-otherguy.cer
-----BEGIN CERTIFICATE-----
MIIDQjCCAwGgAwIBAAIBATAJBgcqhkjOOAQDMIGGMQ8wDQYDVQQDDAZteW5hbWUxEzARBgNVBAoM
Cm15IGNvbXBhbnkxIjAgBgNVBAsMGWRlcGFydG1lbnQgb2YgZGVwYXJ0bWVudHMxEDAOBgNVBAcM
B2dvcm9kb2sxGzAZBgNVBAgMEnN0YXRlIG9mIG5ldyBub2lzeTELMAkGA1UEBgwCenowHhcNMDgw
NDIzMDA0NjM4WhcNMDgwNzIyMDA0NjM4WjCBhjEPMA0GA1UEAwwGbXluYW1lMRMwEQYDVQQKDApt
eSBjb21wYW55MSIwIAYDVQQLDBlkZXBhcnRtZW50IG9mIGRlcGFydG1lbnRzMRAwDgYDVQQHDAdn
b3JvZG9rMRswGQYDVQQIDBJzdGF0ZSBvZiBuZXcgbm9pc3kxCzAJBgNVBAYMAnp6MIIBuDCCASwG
ByqGSM44BAEwggEfAoGBAP1/U4EddRIpUt9KnC7s5Of2EbdSPO9EAMMeP4C2USZpRV1AIlH7WT2N
WPq/xfW6MPbLm1Vs14E7gB00b/JmYLdrmVClpJ+f6AR7ECLCT7up1/63xhv4O1fnxqimFQ8E+4P2
08UewwI1VBNaFpEy9nXzrith1yrv8iIDGZ3RSAHHAhUAl2BQjxUjC8yykrmCouuEC/BYHPUCgYEA
9+GghdabPd7LvKtcNrhXuXmUr7v6OuqC+VdMCz0HgmdRWVeOutRZT+ZxBxCBgLRJFnEj6EwoFhO3
zwkyjMim4TwWeotUfI0o4KOuHiuzpnWRbqN/C/ohNWLx+2J6ASQ7zKTxvqhRkImog9/hWuWfBpKL
Zl6Ae1UlZAFMO/7PSSoDgYUAAoGBAPDA5E5GVGzMBw3IWldpyGBs8Dwr7ArYdNRIPH7veELcENhO
7jNdBinJ/JUCcY0XoIhNVXVNkyABpGsBISfGPwgv1meyLcs0DK6ndEDBYGH0Cwoahhtb7EBhcqWQ
kqojyVtPRdNTPd8cyPDjbOOapv65+8Xe0FQoCtJXWiwF8Z17MAkGByqGSM44BAMDMAAwLQIVAJHL
9Syzc8LIEp6uNjVI+f/ox4dhAhQOug96d7B5V/rGytlAJiml9f8Qqg==
-----END CERTIFICATE-----

that is exactly what you send to everybody else to encrypt their secret messages!

The last thing that I want to show you is how to see what’s inside the keytore database:

$ keytool -list -v -keystore our.keystore
Enter key store password: ksp@ssw0rd
Key store type: gkr
Key store provider: GNU-CRYPTO
 
Key store contains 1 entry(ies)
 
Alias name: otherguy
Creation timestamp: Tuesday April 22, 2008 AD - 8:46:38;616 o`clock PM EDT
Entry type: key-entry
Certificate chain length: 1
Certificate[1]:
Owner: CN=myname,O=my company,OU=department of departments,L=gorodok,ST=state of new noisy,C=zz
Issuer: CN=myname,O=my company,OU=department of departments,L=gorodok,ST=state of new noisy,C=zz
Serial number: 1
Valid from: Wednesday April 23, 2008 AD - 1:46:59;989 o`clock AM EDT
until: Tuesday July 22, 2008 AD - 1:46:59;990 o`clock AM EDT
Certificate fingerprints
MD5: BB:35:C0:6B:D0:B2:67:26:BF:AB:AD:5A:87:51:AA:32
SHA-160: 19:67:F9:8B:DF:52:24:4A:61:4D:76:1C:79:2E:4B:5B:8E:A8:AA:E1
 
*******************************************

Here you can see that a public certificate that we exported is ” Valid from: Wednesday April 23, 2008 until: Tuesday July 22, 2008″, hence 90 days. That means it will need to be changed in 90 days, which would also, of course mean you would have to issue a new certificate to all your contacts in 90 days. In order to change this time frame, when generating a keystore, just add a “-validity <number of days>”when generating keys:

$ keytool -genkey -alias otherguy -keypass p@ssw0rd -keystore our.keystore -validity 3600

that would create a pair valid for 3600 days from the current date.

What if somebody wants to share secret with you? Well, now you are ready! :)


24
Feb 08

Install Maven Plugin for Eclipse

Installing a Maven Plugin for Eclipse can be a bit tricky if you want to get the whole spectrum of features. By default you would go to “Eclipse -> Help -> Software Updates -> Find and Install”, then “Search for new features to install”, then click on “New Remote Site”, and enter the Maven Projects name (e.g. Maven2Plugin) and its home URL there “http://m2eclipse.codehaus.org/“.

Once you install it at first everything would seem quite right. However, if you try “Import” a Maven Project, you will not see such an option in under the “General” menu, since it would be missing.

The reason for that is that “http://m2eclipse.codehaus.org/” brings in an old version of the plugin. (At the moment of writing) It brings in “Maven 2 Plugin 0.0.9”, whereas what you need is 0.0.12.

Hence you read the “Maven Integration for Eclipse” installation guide and point your “New Remote Site” to “http://m2eclipse.codehaus.org/update/” instead of “http://m2eclipse.codehaus.org/“. The one thing to be cautious about is an “update” link will try to also bring “subclipse” and “mylin” projects, hence you will need to “uncheck” them if you do not want to bring them:

Choosing only Maven dependency while installing Maven Plugin for Eclipse

Happy Maving everybody! :)


13
Jun 07

Haptic Clock Beats The Time Into You

Haptic Java Mobile ClockHave a mobile phone that you do not want to look at? Is it that bad, or maybe it is awesome, but you are just annoyed to look at it to find out something as simple as current time? Then here is a very interesting Java Mobile application that is written by Che-Wei Wang and makes your phone to literally beat the time into you.

The Haptic Clock is a small clock program for Java powered mobile phones.  The clock conveys time through  a sequence of vibrations so you never have to pull the phone out of your pocket to tell time.

 

Haptic Java Mobile Clock

Long vibrations are the number of hours of the current time on a 12 hour clock, so 6pm and 6am are both 6 vibrations.  The shorter vibrations are the number of minutes divided by 5. So 4 vibrations is 20 minutes and 7 vibrations is 35 minutes.  Example: (3) long vibrations and (6) short vibrations means it’s 3:30.  Just in case you do want to see the time, the screen displays the time with tick marks for hours, minutes and seconds.

Instructions: Press ‘5′ to vibrate the current time. Press ‘0′ to exit program. UP and DOWN to control the speed of vibrations. Time alerts (vibrations) will occur automatically every 15 minutes on the hour.

Version:         0.06
Released:      5.24.2007
Creator:         Che-Wei Wang
License:         GNU Public License (source coming soon)

Download BetaHaptic-Clock.zip  (includes JAR and JAD)
                                    Beta means it may not work on your phone or worse, may break your phone. Install and use at your own risk.

Tested on:            Nokia E70
Issues:                  J2ME drains the batteries. Looking for ways around it, or a more efficient platform.


9
Jun 07

Convert Date to String in Java


Just an example on how “java.text.SimpleDateFormat” can be used to convert a java date object (java.util.Date) to a string (String, StringBuffer, StringBuilder, etc..).
The whole magic is done by SimpleDateFormat, the child of “java.text.DateFormat”, which, as its name suggests, formats the date by a provided template.

This template is very flexible and provided to the formatter as a string. Here are the values which are used by SimpleDateFormat’s template:

Letter

Date or Time Component

Presentation

Examples

G

Era designator

Text

AD

y

Year

Year

1996; 96

M

Month in year

Month

July; Jul; 07

w

Week in year

Number

27

W

Week in month

Number

2

D

Day in year

Number

189

d

Day in month

Number

10

F

Day of week in month

Number

2

E

Day in week

Text

Tuesday; Tue

a

Am/pm marker

Text

PM

H

Hour in day (0-23)

Number

0

k

Hour in day (1-24)

Number

24

K

Hour in am/pm (0-11)

Number

0

h

Hour in am/pm (1-12)

Number

12

m

Minute in hour

Number

30

s

Second in minute

Number

55

S

Millisecond

Number

978

z

Time zone

General time zone

Pacific Standard Time; PST; GMT-08:00

Z

Time zone

RFC 822 time zone

-0800

Below, I wrote an example on how to implement the conversion. Here I used two different templates: “yyyyMMdd” and “MMddyyyy” to show that several letters from the table above can be used in different sequence for the desired format:

import java.util.Date;
import java.text.SimpleDateFormat;
... ... ... ...
 
    public void testConvertDateToString()    {
 
        //   Allocates a Date object and initializes it so that it represents the time
        // at which it was allocated, measured to the nearest millisecond.
        Date dateNow = new Date ();
 
        SimpleDateFormat dateformatYYYYMMDD = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat dateformatMMDDYYYY = new SimpleDateFormat("MMddyyyy");
 
        StringBuilder nowYYYYMMDD = new StringBuilder( dateformatYYYYMMDD.format( dateNow ) );
        StringBuilder nowMMDDYYYY = new StringBuilder( dateformatMMDDYYYY.format( dateNow ) );
 
        System.out.println( "DEBUG: Today in YYYYMMDD: '" + nowYYYYMMDD + "'");
        System.out.println( "DEBUG: Today in MMDDYYYY: '" + nowMMDDYYYY + "'");
 
    }

Results:

DEBUG: Today in YYYYMMDD: ‘20070609’
DEBUG: Today in MMDDYYYY: ‘06092007’

You may also notice that in the example I used StringBuilder, and not String or StringBuffer. The reason is simple – “best practice – use the right tool for the right task”.

“String” is immutable, meaning it cannot be changed, every time you try to change it, new String object is created and the old one is released for garbage collection, therefore String can be perfect for something like constants e.g. { private static final String FORTY_TWO = “42”; }.

StringBuilder and StringBuffer can be changed (modified), and, in fact, they have exactly the same functionality with one distinct difference – StringBuffer is synchronized and StringBuilder is not. Therefore if the segment of code we are working on is not designed to be multi threaded (used by different threads in a same time), it is better to use StringBuilder, since it will work faster.

StringBuilder is available in Java 1.5.0 (Java 2 SE 5.0) and up.

KISS – Keep It Simple Stupid ;)