ui:param ... and caching

I have the following thing:

<ui:param name="randomVideo" value="#{bean.randomVideo}" />
<a href="#{randomVideo.link}">#{randomVideo.text}</a>

Because <ui:param> does not cache the variable, Bean.getRandomVideo() is called twice, and the worst part is that the .text and .link are from different videos. I have already tried <c:set and <f:param. They both do not set the variable, maybe because I'm with facelets (JSF2).

Any ideas?

JSF 2 does not update the url after a form action?

I did not know that http://www.mkyong.com/jsf2/jsf-page-forward-vs-page-redirect/

I did not know that the upper link solves that http://www.mkyong.com/spring-mvc/handling-duplicate-form-submission-in-spring-mvc/ (which is a problem I have in my current project).

 

 

 

 

 

 

 

 

 

 

 

 

 

I hate getters and setters

I hate getters and setters in java. Half of my code is filled with them. They are pointless boilerplate code that says nearly nothing. 99.9% (I made that number up, but it sounds reasonable) percent of the cases they don't have any additional code in them.

And it is really hard to see whether a variable is read-only/read-write/write-only. You have to find the getters/setters to see that.

I have a notation where I put all the modifiers at the end of the class and separate them with a page of whitespace.

I don't like the C# solution - it's not really shorter, only binds the getter and setter together.

I have a proposition: use annotations:

    @Getter @Setter
    private boolean subscribedForEmailNotification;

And one wants to write extra code, one should be able to use the old notation. The compiler will check for collisions.

I don't see any reason why this cannot become the next syntactic sugar in java where one saves a bunch of useless code-writing.

IntelliJ IDEA 10.5 on Mac OS X: save subversion credentials

This is a note-to-self. So when I forget the solution I can come back here and find it.

IntelliJ IDEA is one of the best Java IDEs. More here.

I have had the problem of not being able to save the password of a test svn repository. I found the solution:

  1. vi ~/.subversion_IDEA/servers
  2. add the following lines:
    store-passwords = yes
    store-plaintext-passwords = yes
  3. Save and restart Idea.
  4. Play around with the changes tab until a popup shows up that asks for credentials.
  5. Give the credentials and click <Save the credentials> or whatever it says.
  6. That's it.

 

Distributed version control systems (Lecture)

This is a presentation I just gave on Bulgarian Java User Group (BGJUG). The topic is Distributed Version Control Systems (DVCS). The main DVCSs mentioned are Mercurial and Git.

Here it is:

Btw, consider it absolutely free. But if you mention my name I'd be grateful.


RichFaces presentation

This is a lecture I presented that is part of the JavaEE course.

The presentation was prepared by Radoslav Ivanov.

Exercises: RichFacesJSF1.2 project for eclipse
Installation: eclipse -> import -> existing project into workspace -> archive -> finish

Richfaces installation instructions for Eclipse in the presentation (ppt).


Disable session persistence in Tomcat

This a pretty common issue when running java web applications on Tomcat. One puts an object into session and after a restart one gets:

Caused by: java.io.NotSerializableException: java.lang.Object

It may not always be java.lang.Object, any class not implementing java.io.Serializable could be in this error.

This is due to Tomcat's default behavior of serializing all the sessions and after restart trying to deserialize them. (A good question is how does tomcat serialize them in the first place, but no time to research that).

The solution is pretty simple, find tomcat_dir/conf/context.xml and find a place where it says:

<!-- Uncomment this to disable session persistence across Tomcat restarts -->

This works for both Tomcat 6 and Tomcat 7. Tomcat guys did the effort to prepare everything so it's easy for us.

This solution deserves a blog post because every once in a while I get bugged by this problem and have forgotten the solution. Now I know where to search for one.

Why is java development so windows oriented?!

I'm using a macbook. Obviously I'm using Mac OS. Not so obviously actually - recently I saw a few people using Windows 7 on a macbook.

JDK. Developing java applications on a Mac OS is not so straightforward as it is on windows. When you start on Windows, the first thing you do is download the JDK - that's easy. On Mac OS you don't have a real JDK, you have Java for Mac OS X. It's not the same. It's always late. Using SoyLatte they made a darwin port called openjdk6 that is a lot more like a real JDK. With JavaSE 7 it's even worse - there are binaries for Windows, on Mac OS one has to build it manually which is not that easy.

Eclipse. Then there's Eclipse. Thank god - there's an Eclipse.dmg that is pretty easy to install. But (there's always a but), the shortcuts are a bit changed. Alt+Shift+X becomes ⌘+⌥+X. There's also the speed issue - Eclipse is not as fast on Mac OS as it seems on a Windows machine.

Browsers. One major setback is that if one does front-end, one needs Internet Explorer to test. Otherwise QAs come and kick one's ass because something doesn't work on IE6 for example. I hate Internet Explorer. Not only IE6, all of them.

Configuration. In my project I have:

File file = new File(element.replace("file:", ""));

my Windows-using colleagues have

File file = new File(element.replace("file:/", ""));

The good thing is that since Mac OS is unix-based I have the settings that are closer to the Ubuntu we deploy our production on.

I don't know - maybe I should buy a new Macbook with a fast SSD with a lot more juice into it than the one I have now (a two-year-old one that hasn't been reinstalled since). Now there's the question - should I buy the 13" or the 15"?

P.S. The things are getting a lot better. OpenJDK6 port is pretty mature (I use it), OpenJDK7 port is coming soon. Apple donated it's JavaSE port to Oracle, so soon Java's download page would feature a .dmg file, which will be awesome.

Still I think developing java apps on a macbook is a bit harder than on a Windows machine. I wouldn't go back to Windows because of the awesome hardware and because the OS is so much better for anything else.

Mac OS X finally with a real Java

A quote from a newsletter from Oracle.

Oracle and Apple Announce OpenJDK Project for OSX; Java SE 7 and 8 JSRs Approved

Good news all around! Oracle and Apple announced the OpenJDK project for Mac OS X. Apple will contribute most of the key components, tools and technology required for a Java SE 7 implementation on Mac OS X, including a 32-bit and 64-bit HotSpot-based Java virtual machine, class libraries, a networking stack and the foundation for a new graphical client. OpenJDK will make Apple's Java technology available to open source developers so you can access and contribute to the effort.

Furthermore, the JCP Executive Committe has approved the JSR "quartet" for Java SE 7 and Java SE 8. With this ratification, the Java standard will progress through the JCP while the open source reference implementation will be delivered through the OpenJDK project. See you on OpenJDK!

-The Oracle Technology Network Team (See Team Blog)

This means Java SE 7 woud be available for Mac OS X too and that Apple users will receive Java as soon as other platforms dog. Also the four JSRs for Java SE 7, Java SE 8, Project Coin and Lambda Expressions.

How to make Eclipse validate XSL (and of course XML) files

Intro on Eclipse

Eclipse has two major bundles:

  • Eclipse IDE for Java Developers
  • Eclipse IDE for Java EE Developers.

Info here: http://www.eclipse.org/downloads/

The major difference is that Eclipse for JavaEE includes the Web Tools Platform (WTP). WTP has editors, designers, JavaEE perspective, new projects and so on.

I generally prefer to use the ‘Java’ perspective as opposed to the ‘JavaEE’ perspective, because the latter is too cluttered, but the one thing from WTP without which I cannot live is the XML editor. There are variations for XSL transformations and XML Schemas.

XML Schemas (XSD)

By default Eclipse can validate XML Schemas, because it has the schema for XSDs. Did you get this one? Let’s try again. XSD is a language written in xml that defines rules for xml files who want to conform to certain rules. This allows us to validate such files versus a schema. Finally XSD is also XML, so there is a special XSD Schema that defines how to write XSD Schemas. And the dog catches its tail.

XML Schema language is also defined in DTD. DTD is the predecessor of XSD.

Anyway, if you want to learn more, go to W3C Schools - the best place to learn XML, XSD, XSLT. This is also the official site of WWW Consortium (W3C) which handles the expert groups that define these standards.

Where is XSL.xsd?

XSL is written in xml, so there is an XSD Schema that defines how to write XSL files.

The schema for XSLT 2.0 (2007 revision) is here: http://www.w3.org/2007/schema-for-xslt20.xsd (the most up-to-date)
The DTD for XSLT 1.0 (1999 revision) is here: http://www.w3.org/TR/1999/REC-xslt-19991116.xml (I couldn’t find XSD for XSL 1.0, maybe because XSL 1.0 is too old)

So the only thing I need to do is put XSL.xsd in Eclipse?

Yes. Here’s how: go to Window –> Preferences and then to XML –> XML Catalogs:

(XML Catalogs are a very interesting topic. There’s an article on them in this blog here)

Eclipse 3.5 preferences

Then "Add”:

Add XML Catalog from http

There are 3 ways to add an XML Schema to Eclipse

  1. Via an URL (as in the picture)
  2. Via a workspace location
  3. Via a file on the file system

How do we validate?

Here’s how:

Validate button in Eclipse

Via the "Validate" button on the context menu on any XML/XSL file.

The exact same thing can be performed for any XML File that has to be validated against an XML Schema (or DTD, of course)

iReport 3.0.0 on Mac OS. How to make it work?

iReport is a gui for designing jrxml (the actual reports) files for JasperReports. It is supposed to work on any platform.

We’re using 3.0 instead of 3.5 because 3.5 is based on Netbeans.

I’m trying to work with it on Mac OS (it was extremely slow in the virtual machine, something to do with java I guess).

First:

chmod u+x iReport.sh

…because it’s not executable.

But then it gave me a weird error:

comp:iReport-3.0.0 user$ ./iReport.sh
-bash: ./iReport.sh: /bin/bash^M: bad interpreter: No such file or directory

Google said it’s because of the problem with newline in different platforms. In linux it’s LF (\n)(line feed). In windows it’s CRLF (\r\n) (carriage return, line feed).

So this ^M character appearing in the error is actually the left-out CR.

How to fix it? Wikipedia says:

tr -d '\r' < inputfile > outputfile

This works. But then the next error. iReport.sh calls bin/startup.sh.

The same thing for it.

That’s it. Why was the shell script in a dos format only god can tell.

Note that iReport on a Mac should be in a place whose path does not involve spaces. Here’s a solution for that too.

How to have a Subversion Repository on a Windows Server (+ security), part 1

The article is written based on Windows Server, CollabNet Subversion 1.6.1, Apache 2.2. Windows XP or Vista would do as well.

Subversion comes with it’s own server – svnserve. By default there is no security. One can install svn+ssh, but on a windows server and windows client that is a bit stupid.

The other option is to setup an Apache server with mod_dav and mod_dav_svn. Fortunately the CollabNet Subversion binary comes with Apache pre-bundled with those modules. The binary even installs viewvc, which is rather nice.

Installation steps.

After installing the bundle, however, there are a lot of things to do. Most of them manually. I’ll try to describe most of them here.

Download Collabnet Subversion Server binary from CollabNet (no other place to download it from). Registration required.

So we decided to use Apache instead of svnserve, so while installing one doesn’t have to make it a service. Only Apache should be installed as a service. Another pro for Apache is that it can host multiple SVN repositories as opposed to only one by svnserve AFAIK.

Now is the time to suggest that one make the Apache server run with limited credentials. By default the service would be running with Local System account which has more privileges than God the users in the Administrators group. The concrete steps would be to create one user with compmgmt.msc. Remove it from the Users group (which removes all the default privileges) and give this user Modify right for the httpd directory (one will most probably find it in C:\Program files\Subversion\httpd) and all the repositories.

The configuration. When installing Apache asks where is the repositories basedir. Using a basedir means that all the repositories are subdirectories of the basedir:

Subversion/httpd/conf/httpd.conf:

<Location /svn>
  DAV svn
  SVNParentPath "D:/SVN Repositories/"    <— put the qoutes. installer does not do it
</Location>

Note: by default the installer does not put quotes around the dir, so if there are space characters, the server will not start. One should put the quotes himself/herself.

Now is the time to say that the Apache server is very verbose. Every error show up in the Event Viewer in the Applications tab. There are always pretty good descriptions of what is wrong. I definitely like this feature of Apache. Unfortutely one has to use Google to figure how to fix it.

Another place to look for errors is httpd/logs/errors.log. Pretty readable. I’m positively surprised.

I don’t like the basedir approach – repositories with me are in different dirs. I do it like this

<Location /svn/mycompany>

   DAV svn

   SVNPath "D:/My Company/Repository"                   <— put the qoutes

</Location>

Authentication. Very shortly – http basic and http digest. Http basic is very insecure (only base64). Http basic looks like this:

<Location /svn/mycompany>

   DAV svn

   SVNPath "D:/My Company/Repository"

   AuthType Basic

   AuthName "MyCompany subversion repository"

  
AuthUserFile "C:\Program Files\Subversion/httpd/conf/svn_auth_file"

   Require valid-user

</Location>

Now, how to make the user’s file (svn_auth_file). Use htpasswd (only for http basic):

C:\Program Files\Subversion\httpd\bin>htpasswd -cm ..\conf\svn_auth_file mihail

New password: ******

Re-type new password: ******

Adding password for user mihail

C:\Program Files\Subversion\httpd\bin>htpasswd -m ..\conf\svn_auth_file ivan

New password: *****

Re-type new password: *****

Updating password for user ivan

The first time –c is used to create the file. Any subsequent user is with –m only (which stands for MD5 as far as I remember).

svn_auth_file:

mihail:$apr1$AzWq5tu5$k554PODb79n9TZwBxBDh..

ivan:$apr1$hlr9s6gK$oFLP1WtwvOLczyUSiP10v/

For http digest the configuration first the module has to be uncommented in httpd.conf:

LoadModule auth_digest_module modules/mod_auth_digest.so    <—uncomment this line

the configuration for the location is the following:

<Location /svn/mycompany>

AuthType Digest

And users are made with htdigest:

C:\Program Files\Subversion\httpd\bin>htdigest.exe –c ../conf/svn_auth_file "MyCompany subversion repository" mihail

Adding user mihail in realm MyCompany subversion repository

New password: ******

Re-type new password: ******

C:\Program Files\Subversion\httpd\bin>htdigest.exe ../conf/svn_auth_file "MyCompany subversion repository" ivan

Adding user ivan in realm MyCompany subversion repository

New password: ******

Re-type new password: ******

The file svn_auth_file looks a bit different now:

mihail:MyCompany subversion repository:3d16aced3eac2fc74ce5663df86d145b

ivan:MyCompany subversion repository:3ff20546c01028d5008651445b62d2e0

Note: keep in mind that the realms in svn_auth_file and the <Location AuthName should match.

Note: do not confuse htpasswd and htdigest. They produce users for http basic and http digest respectively and are not interchangeable.

For now there is a pretty usable svn server that supports multiple repositories and digest auth. But the communication with the server is plain and unencrypted http.

The svnbook is available here (most up-to-date version 1.5): http://svnbook.red-bean.com/en/1.5/svn.serverconfig.httpd.html. The chapter for servers is Chapter 6.

The next part is how to setup a SSL on top of Apache.

How to consolidate (add, gather) multiple private keys in one JKS file with keytool

Do the following multiple times:

keytool
  -importkeystore
    -srckeystore mycompany1.root.ca.jks
    -srcalias
mycompany1.ca
    -destalias
mycompany1.ca
    -srcstorepass
mycompany1.ca

    -destkeystore container.root.ca.jks
    -deststorepass container.root.ca

The first time you do it the container.root.ca.jks would be created. The subsequent times it will just be filled up with new and new keypairs (public and private keys).

Certificates, keystores, java keytool utility and openssl

(Updated: four six typos fixed)

I)
From time to time I need a self-signed certificate. I use the java keytool utility to make one:

For a JKS (Java Key Store format):

keytool
-genkeypair
-keystore mihail.stoynov.jks
-storepass mihail.stoynov
-alias mihail.stoynov
-keypass mihail.stoynov
-keysize 2048
-keyalg RSA
-sigalg sha1withrsa
-dname "cn=Mihail Stoynov,
ou=MyCompany Bulgaria, o=MyCompany, L=Sofia, S=Sofia, c=BG"
-validity 3650
-v

For a PKCS#12 keystore:

keytool
-genkeypair
-keystore mihail.stoynov.p12

-storetype pkcs12
-storepass mihail.stoynov
-alias mihail.stoynov
-keypass mihail.stoynov
-keysize 2048
-keyalg RSA
-sigalg sha1withrsa
-dname "cn=Mihail Stoynov, ou=MyCompany Bulgaria, o=MyCompany, L=Sofia, S=Sofia, c=BG"
-validity 3650
-v

When the public certificate is needed separately, one can be exported in a file (mihail.stoynov.cer) like this:
(from a JKS)

keytool
-exportcert
-keystore mihail.stoynov.jks
-storepass mihail.stoynov
-alias mihail.stoynov
-keypass mihail.stoynov
-file mihail.stoynov.cer
-v

 

(from a PKCS#12)

keytool
-exportcert
-keystore mihail.stoynov.p12

-storetype pkcs12
-storepass mihail.stoynov
-alias mihail.stoynov
-keypass mihail.stoynov
-file mihail.stoynov.cer
-v

 

NOTE: keep storepass and keypass the same for easy importing into browsers

II)
Sometimes self-signed certificates are not enough and a CA root certificate must be made in order to sign a group of certificates.

First a Certificate signing request (CSR) must be made:
(from a JKS)

keytool
-certreq
-keystore mihail.stoynov.jks
-storepass mihail.stoynov
-alias mihail.stoynov
-keypass mihail.stoynov
-v
>> mihail.stoynov.csr

(from a PKCS#12)

keytool
-certreq
-keystore mihail.stoynov.p12

-storetype pkcs12
-storepass mihail.stoynov
-alias mihail.stoynov
-keypass mihail.stoynov
-v
>> mihail.stoynov.csr

(the output is directed to a file: mihail.stoynov.cer)

The file looks something like that:

-----BEGIN NEW CERTIFICATE REQUEST-----
MIICtTCCAZ0CAQAwcDELMAkGA1UEBhMCQkcxDjAMBgNVBAgTBVNvZmlhMQ4wDAYDVQQHEwVTb2Zp
YTEQMA4GA1UEChMHTWF0ZXJuYTEWMBQGA1UECxMNTWF0ZXJuYSBTb2ZpYTEXMBUGA1UEAxMOTWlo
YWlsIFN0b3lub3YwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDZ7XpdyHuF9ApZodSn
GS9/TiUtXqryPDD0elzlP2QreSkfYv8IaXnB1Xy1ZVmda/d+P4TZ/aHvAhDwQPcei4KaoRzJWX9I
Yz9hi4cmKksjg8ufDZzXUuMwtbVlricc5vWg1HcSsQJ8vpLCBIelliDJOxc4skDcT23LGQttiv0b
23pjMthEe2tJVp37Tnwr29SLz0AGziVwzb5cfAXU4PzpiASr8vF2A0c2DObS7zM5Wp7jXWIe71P5
BZgIMcUUGlCdfLQRoA7URWN2Yx2qH8gyiNaIaZYZB6o2ib8rH3UmDl/ErKJgWQyS7sr4bANY9WpA
m7H2nXfGs+X88xSbA0JRAgMBAAGgADANBgkqhkiG9w0BAQUFAAOCAQEAIn81dCSpVbI7IDLO2L2p
MW1gnjvuRs9xm6M9rMV6Kwy0Nw05qL0H8tTsFaq4J7bLBXJeXmiREUbrtpbHxLUfjtaqs5q5Txxn
c7Cm5kj7t9PWeRTW0rbzRssgT+sHqUlMKMydB8E+gGEIMQdgwdurhjpD7aevOOeN5fvv9kV7Rszv
6nC8dixyrsiiWjLUGJRP7I9HrEAXKfk3JluSYKS/ZNhTIw5a7fKvhXbRPlN1lDSvdkJAtcaG/9dZ
3KlXL7ozL8sOQTjFxUhN6kS6QujJ1T7TlkWHu9/ivIAkuXBu8P/czyLyjf1JD9fnwGnxCO2FPmcX
9/2IpwG33mMpaAmXpA==
-----END NEW CERTIFICATE REQUEST-----

Did we forget something? Yes, there's no Root CA certificate. Let's make one:
(JKS)

keytool
-genkeypair
-keystore mycompany.root.ca.jks
-storepass "mycompany.root.ca"
-alias "mycompany.root.ca"
-keypass "mycompany.root.ca"
-keyalg RSA
-keysize 2048
-sigalg SHA1withRSA
-dname "cn=MyCompany Bulgaria, ou=Office No 5, o=MyCompany, L=Sofia, S=Sofia, c=BG"
-validity 3650
-v


(PKCS#12)

 

keytool
-genkeypair
-keystore mycompany.root.ca.p12

-storetype pkcs12
-storepass "mycompany.root.ca"
-alias "mycompany.root.ca"
-keypass "mycompany.root.ca"
-keyalg RSA
-keysize 2048
-sigalg SHA1withRSA
-dname "cn=MyCompany Bulgaria, ou=Office No 5, o=MyCompany, L=Sofia, S=Sofia, c=BG"
-validity 3650
-v

Problem No 1
Keytool cannot sign CSRs. Period.

Now what do we do?

I went to OpenSSL.

In order to sign with OpenSSL I needed the root certificate in the PEM format.
P12 (PKCS#12) -> PEM:

openssl
pkcs12
-in mycompany.root.ca.p12
-out mycompany.root.ca.pem

Sign the CSR with OpenSSL:

openssl
x509
-req
-in mihail.stoynov.csr
-CA mycompany.root.ca.pem
-out mihail.stoynov.signed.cer
-days 3650
-CAcreateserial

(I don't know what -CAcreateserial is but it works)

So now I have mihail.stoynov.signed.cer.

The last step is to import it to mihail.stoynov.p12 (or .jks) in order to override the self-signed certificate with the one signed by the MyCompany Root CA.

A Prerequisite step to that is to import mycompany.root.ca.cer into mihail.stoynov.p12 (or .jks) because every certificate in the chain must be contained in the certificate chain of mihail.stoynov.

Problem No 2
Importing mycompany.root.ca.cer into mihail.stoynov.p12 fails but importing it into mihail.stoynov.jks works?!

JKS:

keytool
-importcert
-keystore mihail.stoynov.jks
-storepass mihail.stoynov
-alias mycompany.root.ca
-keypass
mycompany.root.ca
-file mycompany.root.ca.cer
-v

(this one works)

PKCS#12

keytool
-importcert
-keystore mihail.stoynov.p12

-storetype pkcs12
-storepass mihail.stoynov
-alias mycompany.root.ca
-keypass
mycompany.root.ca

-file mycompany.root.ca.cer
-v

this one fails with:

Owner: CN=MyCompany Bulgaria, OU=Office No 5, O=MyCompany, L=Sofia, ST=Sofia, C=BG
Issuer: CN=MyCompany Bulgaria, OU=Office No 5, O=MyCompany, L=Sofia, ST=Sofia, C=BG
Serial number: 49b8c365
Valid from: Thu Mar 12 08:12:13 GMT+00:02 2009 until: Sun Mar 10 08:12:13 GMT+00:02 2019
Certificate fingerprints:
MD5:  1C:0C:82:0D:35:C8:1E:48:74:9F:13:43:C9:AE:D0:F7
SHA1: DB:BB:D7:DB:8C:33:AA:06:6D:CF:D2:5C:EB:64:01:D5:AD:AB:94:38
Signature algorithm name: SHA1withRSA
Version: 3
Trust this certificate? [no]:  y 

keytool error: java.security.KeyStoreException: TrustedCertEntry not supported
java.security.KeyStoreException: TrustedCertEntry not supported
at com.sun.net.ssl.internal.pkcs12.PKCS12KeyStore.engineSetCertificateEntry(PKCS12KeyStore.java:620)
at java.security.KeyStore.setCertificateEntry(KeyStore.java:941)
at sun.security.tools.KeyTool.addTrustedCert(KeyTool.java:1958)
at sun.security.tools.KeyTool.doCommands(KeyTool.java:818)
at sun.security.tools.KeyTool.run(KeyTool.java:172)
at sun.security.tools.KeyTool.main(KeyTool.java:166)

Actually P12 format does not permit trusted certificates. It is inteded to contain key/pairs only. So importing mycompany.root.ca.cer into mihail.stoynov.p12 failed.

I tried several things:

1) Importing mihail.stoynov.signed.cer directly into mihail.stoynov.p12:

keytool
-importcert
-keystore mihail.stoynov.p12
-storetype pkcs12

-storepass mihail.stoynov
-alias mihail.stoynov
-keypass mihail.stoynov
-file mihail.stoynov.signed.cer
-v

and the response was:

keytool error: java.lang.Exception: Failed to establish chain from reply
java.lang.Exception: Failed to establish chain from reply
at sun.security.tools.KeyTool.establishCertChain(KeyTool.java:2662)
at sun.security.tools.KeyTool.installReply(KeyTool.java:1870)
at sun.security.tools.KeyTool.doCommands(KeyTool.java:807)
at sun.security.tools.KeyTool.run(KeyTool.java:172)
at sun.security.tools.KeyTool.main(KeyTool.java:166)

2) Importing mycompany.root.ca.cer into cacerts:

keytool -importcert -trustcacerts -file mycompany.root.ca.cer

This again didn't fix the problem.

Solution to Problem No 2:
Transform P12 to JKS, import the root certificate and the signed certificate into JKS keystore, transform the modified JKS back to P12.

1) Transform P12 to JKS

keytool
-importkeystore
-srckeystore mihail.stoynov.p12
-destkeystore mihail.stoynov.jks
-srcstoretype pkcs12
-srcstorepass mihail.stoynov
-deststorepass mihail.stoynov

2) import the root certificate into the JKS keystore

keytool
-importcert
-keystore mihail.stoynov.jks
-storepass mihail.stoynov
-alias mycompany.root.ca

-keypass
mycompany.root.ca

-file mycompany.root.ca.cer
-v

3) import signed certificate into JKS keystore

keytool
-importcert
-keystore mihail.stoynov.jks
-storepass mihail.stoynov
-alias mihail.stoynov
-keypass mihail.stoynov
-file mihail.stoynov.signed.cer
-v

4) transform the modified JKS back to P12

keytool
-importkeystore
-srckeystore mihail.stoynov.jks
-destkeystore mihail.stoynov.p12
-deststoretype pkcs12
-srcstorepass mihail.stoynov
-deststorepass mihail.stoynov

it said something like:

Entry for alias mihail.stoynov successfully imported.
Problem importing entry for alias mycompany.root.ca: java.security.KeyStoreException: TrustedCertEntry not supported.
Entry for alias mycompany.root.ca not imported.
Do you want to quit the import process? [no]:  n
Import command completed:  1 entries successfully imported, 1 entries failed or cancelled

I clicked yes, and it worked.

Now let's see what's the difference between mihail.stoynov.jks and mihail.stoynov.p12:
JKS:

$ keytool -list -keystore mihail.stoynov.jks -storetype jks -storepass mihail.stoynov -v

Keystore type: JKS
Keystore provider: SUN

Your keystore contains 2 entries

Alias name: mihail.stoynov
Creation date: Mar 12, 2009
Entry type: PrivateKeyEntry
Certificate chain length: 2
Certificate[1]:
Owner: CN=Mihail Stoynov, OU=MyCompany Sofia, O=MyCompany, L=Sofia, ST=Sofia, C=BG
Issuer: CN=MyCompany Bulgaria, OU=Office No 5, O=MyCompany, L=Sofia, ST=Sofia, C=BG
Serial number: f0e465bb77420e30
Valid from: Thu Mar 12 09:29:19 GMT+00:02 2009 until: Sun Mar 10 09:29:19 GMT+00:02 2019
Certificate fingerprints:
MD5:  40:9D:C2:DE:AE:11:1E:01:92:F9:C8:01:C5:92:69:CB
SHA1: D2:D0:03:5C:50:BC:F8:6C:EB:C0:36:B6:B0:8D:A8:3B:9E:B6:7B:B4
Signature algorithm name: SHA1withRSA
Version: 1
Certificate[2]:
Owner: CN=MyCompany Bulgaria, OU=Office No 5, O=MyCompany, L=Sofia, ST=Sofia, C=BG
Issuer: CN=MyCompany Bulgaria, OU=Office No 5, O=MyCompany, L=Sofia, ST=Sofia, C=BG
Serial number: 49b8c365
Valid from: Thu Mar 12 08:12:13 GMT+00:02 2009 until: Sun Mar 10 08:12:13 GMT+00:02 2019
Certificate fingerprints:
MD5:  1C:0C:82:0D:35:C8:1E:48:74:9F:13:43:C9:AE:D0:F7
SHA1: DB:BB:D7:DB:8C:33:AA:06:6D:CF:D2:5C:EB:64:01:D5:AD:AB:94:38
Signature algorithm name: SHA1withRSA
Version: 3

*******************************************
*******************************************

Alias name: mycompany.root.ca
Creation date: Mar 12, 2009
Entry type: trustedCertEntry

Owner: CN=MyCompany Bulgaria, OU=Office No 5, O=MyCompany, L=Sofia, ST=Sofia, C=BG
Issuer: CN=MyCompany Bulgaria, OU=Office No 5, O=MyCompany, L=Sofia, ST=Sofia, C=BG
Serial number: 49b8c365
Valid from: Thu Mar 12 08:12:13 GMT+00:02 2009 until: Sun Mar 10 08:12:13 GMT+00:02 2019
Certificate fingerprints:
MD5:  1C:0C:82:0D:35:C8:1E:48:74:9F:13:43:C9:AE:D0:F7
SHA1: DB:BB:D7:DB:8C:33:AA:06:6D:CF:D2:5C:EB:64:01:D5:AD:AB:94:38
Signature algorithm name: SHA1withRSA
Version: 3

*******************************************
*******************************************

 

P12 (PKCS#12)

$ keytool -list -keystore mihail.stoynov.p12 -storetype pkcs12 -storepass mihail.stoynov -v

Keystore type: PKCS12
Keystore provider: SunJSSE

Your keystore contains 1 entry

Alias name: mihail.stoynov
Creation date: Mar 12, 2009
Entry type: PrivateKeyEntry
Certificate chain length: 2
Certificate[1]:
Owner: CN=Mihail Stoynov, OU=MyCompany Sofia, O=MyCompany, L=Sofia, ST=Sofia, C=BG
Issuer: CN=MyCompany Bulgaria, OU=Office No 5, O=MyCompany, L=Sofia, ST=Sofia, C=BG
Serial number: f0e465bb77420e30
Valid from: Thu Mar 12 09:29:19 GMT+00:02 2009 until: Sun Mar 10 09:29:19 GMT+00:02 2019
Certificate fingerprints:
MD5:  40:9D:C2:DE:AE:11:1E:01:92:F9:C8:01:C5:92:69:CB
SHA1: D2:D0:03:5C:50:BC:F8:6C:EB:C0:36:B6:B0:8D:A8:3B:9E:B6:7B:B4
Signature algorithm name: SHA1withRSA
Version: 1
Certificate[2]:
Owner: CN=MyCompany Bulgaria, OU=Office No 5, O=MyCompany, L=Sofia, ST=Sofia, C=BG
Issuer: CN=MyCompany Bulgaria, OU=Office No 5, O=MyCompany, L=Sofia, ST=Sofia, C=BG
Serial number: 49b8c365
Valid from: Thu Mar 12 08:12:13 GMT+00:02 2009 until: Sun Mar 10 08:12:13 GMT+00:02 2019
Certificate fingerprints:
MD5:  1C:0C:82:0D:35:C8:1E:48:74:9F:13:43:C9:AE:D0:F7
SHA1: DB:BB:D7:DB:8C:33:AA:06:6D:CF:D2:5C:EB:64:01:D5:AD:AB:94:38
Signature algorithm name: SHA1withRSA
Version: 3

*******************************************
*******************************************

 

Do you see the difference?
It's in italic - JKS format keeps an extra trusted certificate of MyCompany Root CA.

Anyway both mihail.stoynov.jks and mihail.stoynov.p12 work perfectly.

P.S.
Does someone know better solutions to Problem No 1 and Problem No 2?
Does someone know how to sign certificates but without the cumbersome CSR step?

The "Introduction to Programming with Java" is out

The book "Introduction to Programming with Java" I coauthored is out.

The book is in Bulgarian and it's free.

For now it's only in electronic form, but we're planning to print it. We're not planning on making profit from the printed book, so we're looking for sponsors.

I co-wrote the Exceptions chapter and authored the Object-oriented programming (OOP) chapter and the Qualitative programming code chapter.

Sniff TCP connections

In the world of windows there is no standard tool to see what's going on the network level.

I have been working quite a while with web services and encryption and signing, so it's vital to me to see what's going on when a web service is being called.

TCP proxies
The way I was doing it until recently was to use TCP proxies. TCP proxies open a TCP port and forward to some other host:port. In the process of doing so it dumps every connection on the screen or in a file.
For example if I want to listen what's going on a local (for the machine I'm working on) port 8080 the following had to be done: the software working on 8080 (a web service) is moved for example to 18080, then the proxy is opened at 8080 which forwards everything to localhost:18080.

There is one minor drawback to the whole story -  the clients have to be supplied with a port that is not the port where the service resides. So if the proxy is missing - the service is invisible.

I've used mostly tcpmon and wsmonitor. wsmonitor sucks a lot. tcpmon works, but cannot handle moderately heavy traffic and has a lot of quirks that are very annoying. Anyway until recently it was my primary way of doing things.

Reading direcly from the TCP/IP Stack
There has always been software that can plug something in the TCP/IP stack of the windows machine and thus sniff the traffic. The bad side is that the machine has to be tampered with some third-party software. And some machines cannot (should not) be tampered like that.

A third way
There seems to be a software that can sniff the traffic without plugging nasty stuff in the TCP/IP stack. On such example is SmartSniff. It has what they call a "Raw Sockets" way of sniffing and so far it's working great.

Importing a class from the 'default package' (no package) - impossible

Did you know that classes in the 'default package' (classes that don't have a package) cannot be imported from classes that do have a package?

I did not know that.

Try it:

This is what javac says:

>javac Class1.java

>javac package2\Clazz2.java -cp .

package2\Clazz2.java:3: '.' expected
import Class1;
             ^
package2\Clazz2.java:3: ';' expected
import Class1;
              ^
2 errors

How stupid is this?
Is this why omitting package is deprecated?

Javac bug, Eclipse innocent, bug in static imports

I had an issue compiling some java classes. Javac failed, Eclipse's compiler worked. The issue is described here.
I was blaming Eclipse, I was blaming java6's endorsing. I was thinking it was due to JAXB.

It comes out they all were innocent.

Here's my code:

package f;

 

import static f.ProblematicClass.E1.E2.VALUE;

 

import javax.annotation.Resource;

 

public class ProblematicClass {

 

    @Resource

    public static enum E1 {

        F(VALUE);

 

        private E1( E2
requiredBankAccounts ) {

        }

 

        public static enum E2 {

            VALUE;

        }

    }

}

The result with javac is:

>javac f\ProblematicClass.java

f\ProblematicClass.java:9: cannot find symbol
symbol  : class Resource
location: class f.CorrectClass1
        @Resource
         ^
1 error

After some research I think I simplified the problem:
(If I continue to simplify it would still fail to compile but at some
point it would start to compile which yesterday drove me crazy.
This is the most simplistic case that consistently fails to compile)

package f;

 

import static f.ProblematicClass.E1.VALUE;

import
javax.annotation.Resource;

 

public class ProblematicClass {

 

      @Resource

      public static enum E1 {

            VALUE;

      }

}

All of these changes fix the compilation error (from javac):

...

// Reverse the order of imports

import
javax.annotation.Resource;

import static f.ProblematicClass.E1.VALUE;

...

or

...
      // Use the FQN of the annotation

      @javax.annotation.Resource

      public static enum E1 {

            VALUE;

      }

...

This all makes me think that the static import fails the next one only if the next one is an annotation (I've tried with a java.util.Collection - it compiled).
I have tried this with jdk6u3 and jdk6u10.
I don't have jdk 1.5. Can someone test it on jdk 1.5?

Update: GRRRRRRRRRRRRRR, Somebody found it before me:
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6391197
It was reported on 27th of June, 2006 :'(

Here's what they say:

Workarounds:
1) switching the order of the import statements works (although they often get changed back by our development tools).
2) Commenting out the static import statements, then compiling, then putting the import statements back and
compiling again with the old classes still there also works. This means that the compiler errors happen at the strangest
of times
, and in large programs it can be very difficult to work out how to workaround the problems.

Weird javac case - Eclipse's compiler is wrong again.

I have some code.
I have two classes. They both have inner enums.
The two inner enums have an annotation.

But one of them does not compile. The other one compiles just fine.

In eclipse there's no error, but when I build the code from ant I get a compilation error - the annotation class is not found:

[javac] ProblematicClass.java:147: cannot find symbol
[javac] symbol  : class XmlType
[javac] location: class package.ProblematicClass
[javac]     @XmlType(name="fff")
[javac]      ^
[javac] 1 error

I spent some time looking for it - I thought that the classpath is wrong, I endorsed an updated version of the API (java 6). The issue persisted.

Then I decided to use javac directly:

javac -verbose -classpath lib\X.jar;lib\X2.jar -d bin -sourcepath src -encoding UTF-8 src\package\ProblematicClass.java

Strangely enough I got the same error?! Then I did the same for the class that did compile successfully using ant - it worked.
So there was a difference between the two classes and I had to find it.

And I found it, can you find it?

-->


-->

//Does not compile

public class ProblematicClass

{

@XmlType( name = "fff1" )

public static enum InnerType {}

}

// Compiles

public class CompilableClass

{

@XmlType( name = "fff2" )

public enum InnerType {}

}

Yes, you're correct. The second enum is not static.
This only happens with inner static enums. The anomaly does not occur if it's an inner static class. I don't know why.

So I'm thinking that in the ProblematicClass the annotation is not visible because the import of XmlType is not visible.
I was correct - this one works:

-->


-->


-->

//Does not compile

public class ProblematicClass

{

@javax.xml.bind.annotation.XmlType( name = "fff1" )

public static enum InnerType {}

}

I just supplied the FQN of @XmlType.

So eclipse is working, javac is not. Now is the time to say that Eclipse is not using javac. I thought it was using jikes (made by IBM), but that's not correct. Eclipse is using its own incremental compiler part of JDT Core. JDT stands for Eclipse Java Development Tools.

http://www.eclipse.org/jdt/core/:

JDT Core is the Java infrastructure of the Java

IDE. It includes:

  • An incremental Java compiler. Implemented as an Eclipse

    builder, it is based on technology evolved from VisualAge for Java compiler.

    In particular, it allows to run and debug code which still contains unresolved

    errors.

  • ...

So either javac or Eclipse's compiler is wrong. I would bet that javac is following the spec more strictly.

This is the second time I'm catching Eclipse's compiler of misconduct. The first time was something related to a very complex case with generics - one of the compilers said it was a warning, the other - error.

Update: I was wrong. I was trying to report the problem. I was making a pretty simple case. I used a different annotation: @javax.annotation.Resource. It worked both on Eclipse and on javac.
So the problem is somehow linked with JAXB.

JAXB is an API bundled with Java 6 (an 'endorsed standard' a 'standalone technology'). The version bundled was JAXB 2.0. If one wants to use a newer version, say JAXB 2.1, an 'Endorsed Standards Override Mechanism' had to be used.

Info on JAXB here.
Info on endorsed mechanism here.

I'm currently with JDK 6 update 10. Somewhere I saw that 'endorsed standard override mechanism' was no longer necessary.

It looks like the problem is more on javac side than on Eclipse's compiler.

I will investigate further.

Update2: It comes out that 'Endorsed Standards Override Mechanism' was existing prior to java 6. Only the standalone technologies were added in Java 6.

Update3: It comes out that 'Endorsed Standards Override Mechanism' is still used.

Update4: It comes out that this bug is very hard to reproduce. My simple examples at some point just started compiling 🙁

Update5: I just created some code that consistently reproduces the bug. I'll write it in a new entry to be cleaner.

Update6: I fixed coloring and finished the new article on the bug.

JAX-WS: Always clean-up generated stuff before regenerating.

I'm using JAX-WS.
When I'm generating stuff for a web service I generate the jaxws package in a 'gen' source folder.
I don't need the compiled stuff so I generate it to a temp folder that I don't care about.

It comes out that I do have to care about that folder because yesterday I got an obscure error:

com.sun.xml.ws.model.RuntimeModelerException: The serviceName cannot be retrieved from an interface.

This error has only 1 (one) hit on Google. Don't trust me?
Try this one out:

http://www.google.com/search?q=%22com.sun.xml.ws.model.RuntimeModelerException%3A+The+serviceName+cannot+be+retrieved+from+an+interface.%22

The use case in the forum has nothing to do with my environment so I cleaned up and everything worked like a charm.

I've always been unhappy with how production unready wsgen is (here).

Apache Tomcat 6 - enlarge VM's heap space

By default enlarging Java VM's heap space happens via "-Xms128m -Xmx512m".

How do we tell Tomcat 6 about it? They say via the CATALINA_OPTS variable (which is shared by all Tomcat instances on that machine). Or even via JAVA_OPTS (all java programs would use these settings).

But what if I want to set these options only to a specific Tomcat instance?
Google couldn't answer that.

I could mess with the startup scripts, which is not a good idea.

The best solution I found is to set the variable (CATALINA_OPTS) only on the console instance that is to start the Tomcat. This variable is not visible to other instances.
This works on windows - because of the temporary variables.

Slides + workspace on the java.util.concurrent lecture

Here are the slides and an eclipse workspace (eclipse ganymede) from the lecture Krasi and I did yesterday evening:

bgjug.concurrency1.ppt (3.83 MB)    (MS Office 2003)
bgjug.concurrency.pptx (488.64 KB)    (MS Office 2007)
bgjug.concurrent.workspace.zip (313.84 KB) (demos on CyclicBarrier, CountDownLatch, Non-blocking stack, Producer-consumer implemented with two Conditions, interruptable Lock)

This is the poster with the annotation.



Hibernate, @EmbeddedId and renaming columns

Making a composite natural key looks like that: (example from Manning book for JPA/Hibernate):

public class UserId implements Serializable {
    private String username;
    private String departmentNr;
    ...
}

And using it:

class SomeClass {
    ...
    @EmbeddedId
    private UserId userId;
    ...
}

The column names in SomeClass are id_username and id_departmentNr.
So one can't do the following

@SuppressWarnings( "unchecked" )
List<SomeClass> old = (List<SomeClass>) em.createQuery(
    "from someClass sc where sc.userId.username = :username and
sc.userId.entityType = :departmentNr")
          .setParameter(...).getResultList();

Because Hibernate wouldn't recognize the column names - it would say something like "someclass0._username - cannot find it".
So one has to do column names rewriting:

class SomeClass {
    ...
    @EmbeddedId
    @AttributeOverrides( {
        @AttributeOverride( name = "
username", column = @Column( name = "username" ) ),
        @AttributeOverride( name = "
departmentNr", column = @Column( name = "departmentNr" ) ) } )
    private UserId userId;
    ...
}

Which sucks 🙁

JAX-WS, the knowledge I gathered during my research

Some notes I could later use.
A stack comparison of most (I don't see JAX-RPC) of the available Web Service stacks in Java: http://xfire.codehaus.org/Stack+Comparison
(Could be somehow biased since it's made by the guys that do one of the stacks).

https://metro.dev.java.net/ = JAX-WS+WSIT

JibX - fast XML processing tool, JAX-WS can't use it - it can only use JAXB.

SoapUI - cool tool for testing web services, as a standalone and as an eclipse plugin - www.soapui.org

WSIT - Java API for better integration with .NET WCF and the WS-I standards.

My eclipse shortcuts and tweaks

In a project where requirements change on a daily basis, refactoring is one's biggest friend.
I'm currently in such a project - not my kind of thing but reality sometimes sucks.
Anyhow, I've tried to look at it from the bright side.

I'm currently perfecting my refactoring skills in eclipse.

Here's what I can share.

Everybody knows about

Ctrl + Shift + R - find resource (file )
Ctrl + Shift + T - find type (class)

Alt+Shift+C - Change method signature

Alt+Shift+S - Context menu for source generation.


Alt+Shift+X, J
- Launch current focused code as Java Console App
Alt+Shift+D, J - Debug current focused code as Java Console App
Ctrl + L - go to line - when watching stack traces. NEW
Ctrl + O - find method in class.   NEW
Ctrl + T - Hierarchy of a class (subclasses + base classes).   NEW

But do you know these:
Alt+Shift+X, Q - Launch current focused script as an Ant Build Script (focused on a target in the 'Outline' window launches only that target, very handy)
Ctrl + >, Ctrl + < - Navigates through warnings and errors in a source file. Extremely handy.

Ctrl + 1 - launches the solution box or whatever that's called.
Ctrl + 3 - finds any window.
Middle button closes tabs as in browsers (only IE does not do that) - VERY, VERY COOL. Ganymede (Eclipse 3.4) only.
Ctrl + E - list of all the open windows (by Joke). NEW
Ctrl + J - incremental search (like Ctrl + F, F3 in browsers (real browsers, IE can't do that)), then arrow up/down to go to next previous, Enter to stop (by rado). NEW

Ctrl + Shift + / - collapse all. NEW2
Ctrl + Shift + * - expand all. These are very nice in long classes. NEW2

Debugging
Ctrl + Shift + I - inspect selected source code while debuging.
The 'Display' window is my biggest friend - inside it you can write code and evaluate it with Ctrl + Shift + D (print result in the box) and Ctrl + Shift + I ( inspect the code in a context window.

That's for now, I'll update this regularly. If someone uses something regularly that is not here, please tell.

java.lang.Throwable, the "... 3 more" case, how to read it

We have the following:
(The code is taken from here http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Throwable.html#printStackTrace())

HighLevelException: MidLevelException: LowLevelException
    at Junk.a(Junk.java:14)
    at Junk.main(Junk.java:4)
Caused by: MidLevelException: LowLevelException
    at Junk.c(Junk.java:24)
    at Junk.b(Junk.java:18)
    at Junk.a(Junk.java:12)
    ... 1 more
Caused by: LowLevelException
    at Junk.e(Junk.java:31)
    at Junk.d(Junk.java:28)
    at Junk.c(Junk.java:22)
    ... 3 more

What does ... 1 more or ... 3 more means?

This is what it means:

HighLevelException: MidLevelException: LowLevelException
    at Junk.a(Junk.java:14)
    at Junk.main(Junk.java:4)

Caused by: MidLevelException: LowLevelException
    at Junk.c(Junk.java:24)
    at Junk.b(Junk.java:18)
    at Junk.a(Junk.java:12)
    ... 1 more =
(take the last line from the upper stack)
=> at Junk.main(Junk.java:4)

Caused by: LowLevelException
    at Junk.e(Junk.java:31)
    at Junk.d(Junk.java:28)
    at Junk.c(Junk.java:22)
    ... 3 more
= (take the last 3 lines from the upper stack)
=>  at Junk.b(Junk.java:18)
    at Junk.a(Junk.java:12)
    at Junk.main(Junk.java:4) (taken from the upper upper stack)

@Override in eclipse

When one implements an interface, the template in Eclipse puts an @Override and it does not complain about it. Ant javac task also compiles without warnings.

Sometimes other Eclipse instances start to complain exactly for that @Override stating that there's no method that's overridden. Well, Eclipse, please do make up your mind.

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Override.html
"Indicates that a method declaration is intended to override a
method declaration in a superclass. If a method is annotated with
this annotation type but does not override a superclass method,
compilers are required to generate an error message."

Well, that's not very clear. As far as I remember an Interface is a pure abstract class, right? So, which one's correct.

P.S. Sometime ago I was having a similar problem with Eclipse and generics - Eclipse only gave a warning about something (can't remember what exactly), but the javac said that it was an error - Google said something like "eclipse uses jikes, you use javac". So what, aren't there specs?!

Update: apparently JDK5 (or 1.5, suit yourself) does not allow that. So in order to get all the wrong @Overrides - set the Compliance level to 5.0 (Eclipse -> Window -> Preferences -> Java -> Compiler -> Compiler compliance level ) - and..... correct them. I have 29 left.

ant junitreport task cannot set vm arguments

ant junitreport task creates a html report from junit xml report files.
If the xml files are numerous enough and/or large enough (mine were 102MB total ), the task crashes with OutOfMemoryError.

Solution? set the GLOBAL variable ANT_OPTS. This changes defautl ant conf for the whole machine this setting is on.

Not very nice 🙂