Sunday, January 13, 2019

Gather all hammers inside toolbox - revisited

It's been a long time since I wrote something here. When I started this blog, one of the first thing I wrote about was how to set up development environment. It was ten years ago - see here. A lot of things changed in Java world in this time. Let's try to set up everything again using modern and most popular tools now.

What are we going to install? For today it will be:
  • Java JDK - we still have Java like in the past, however significant changes were done by Oracle last time.
  • IntelliJ Idea  - an IDE, as replacement for Eclipse
  • Apache Maven - dependency management
  • Git - version control system
As before, all things will be installed in C:\Development

Installing Java JDK

We all get used to that Java is free to use either for personal or commercial purpose. It was true for Java 8 and older versions until 1st January 2019. Starting from 1st Jan 2019 Oracle announced end of public updates of Java SE 8. It simply means If You use Java in commercial purpose and You want get updates for Your Java SE 8, from 1st January 2019 You have to pay for this.

Why Java 8, what about other versions like 9,10,11...? From Java 8, every three years Oracle will relese Java version known as Long Time Support (LTS). First LTS is Java 8, second is Java 11 - it means that Java 9 and 10 is no longer supported now. Changing licensing model for commercial use means that You have to pay for the updates/support for each LTS version starting from 8 (from 1st Jan 2019). See more here.

So what are options? We can:
1. Stay with latest available Java 8 from Oracle (JDK 8u192) without possibility to update anything - we don't have security updates, but we are free of charge.
2. Become Java Commerical User and pay for latest JDK (11 at the time of writing)
3. Use OpenJDK from Oracle - this is free Java for commercial use, but each new version is publicly available in 6-month interval, with 6-month support/updates available. So every half a year You have to update used OpenJDK on Your own.
4. Use a Java based on OpenJDK but with long-term support - for example Amazon Corretto 11 available here.

Let's use JDK 8 from Oracle from point 1. If You want to use latest free Java with LTS You can use Amazon Corretto from point 4 - just download .zip file and extract it for exmple into C:\Development\Java\AmazonJDK\Java11_64bit

Step 1: Download 64 bit version of JDK 8u192 or Windows from here.
Step 2: Create directory C:\Development\Java\OracleJDK\Java8_64bit and start the installer:

Remove installing public JRE and choose previously created directory:

Step 3: After succesfull install create system variable named JAVA_HOME with value C:\Development\Java\OracleJDK\Java8_64bit then modify Path system variable by adding %JAVA_HOME%\bin at the end.

Step 4: Verify Java installation by opening command line and type java -version and javac -version. You should see informationa about Java installed:

Java is installed.

Installing IDE - IntelliJ Idea

Step 1:
Create directory C:\Development\Jetbrains\Idea
Step 2: Download and install an application JetBrains Toolbox from here. This is an application to maintain all products from Jetbrains (IntelliJ Idea manufacturer). It allows to automatically update installed tools.

Step 3: Configure toolbox.

Choose created directory in step 1. Do not forget to  click apply after choosing it. If You have any license from Jetbrains, log in into your account now - You will not have to provide license when installing tools:

Now You can choose a tool to install:

After click on a tool, it will be installed into the previously selected directory:

Just click on tool to launch it. You can also change settings of the tool being installed, like update plan, memory consumption and so on:

IntelliJ Idea is installed. Start it, then go thru some creator in order to perform basic settings (You may leave all the options default).

Hello World in Java - using IntelliJ Idea and installed JDK

Step 1: Create directory C:\Development\Projects

Step 2: Run Idea. You will see initial screen for creating/opening/downloading a project. Choose create new project:

Step 2: Choose Java project type:

Idea is shipped with its own JDK. We would like to use our own JDK. Press button New ans select the JDK directory C:\Development\Java\OracleJDK\Java8_64bit (or another directory like C:\Development\Java\AmazonJDK\Java11_64bit if You use Amazon Corretto)Then press Next.

Step 3: Choose project type from template: 

 Step 4: Choose project name and location (use projects directory created in step 1): 

Step 5: Sample application is ready. You can start is using green "play" button:

Step 6 (optional): Leave only our installed JDK for future projects. 

As mentioned above, Idea comes with built in JDK. We can disable showing this JDK as a option to select for future projects and leave only those we installed in C:\Development\Java\OracleJDK\Java8_64bit. In order to do it open project properties and find Platform SDK. Then choose JDK provided by Idea and delete it:

Then select our installed Java and change its name:

From now this is only one and thus default Java to use in Java projects. Of course You can add other JDK version like OpenJDK.

That's all. Idea is configured and ready for Java development.

Installing Maven

Maven will be used for dependency managment, building and running future apps. Idea comes with bundled Maven, so we do not have install our version. But similar to installing Java, we will install our own version of Maven.

Step 1: Create directory C:\Development\Maven. Then download Maven (binary zip archive) from here and unpack it to the created directory.

Step 2: Create directory C:\Development\Maven\repository for artifacts downloaded by Maven:

Step 3: Tell Maven to use created above directory as a repository. 

Locate Maven settings file named settings.xml and add a line inside:

Step 4: Add Maven's bin folder to the system PATH variable in order to use maven commands from console.

Step 5: Verify if Maven is installed correctly. 

Open command line and execute command: mvn -version. You should see similar information:

Note 1: Maven displays information about Java used. That's why You have to install Java before and set JAVA_HOME variable.

Note 2: There is no need to set up MAVEN_HOME or M2_HOME system variable like it was done for previous versins of Maven.

Step 6: Tell Idea to use installed Maven. Open settings, type Maven in search field. Idea will show settings for Maven. Choose Maven installation directory. You may notice that Idea will display recognized version of selected Maven installation and local respoitory path will change to the value set in step 3:

That's all. Maven is installed and configured in IntelliJ Idea.

Installing Git

Git will be used to track changes we make in our projects files. 

Step 1: Download Git for Windows from here
Step 2: Create directory C:\Development\Git. Run the downloaded git installer and choose created directory as the installation target: 

Install Git using all defaults, but choose Your favourite text editor and PATH modification:

This option will modify PATH system variable, allowing to execute git command from command line. 

Step 3: Verify installation and basic configuration. 

Open command prompt and execute command git -version to see if git responds. After that configure user and email: 

Step 4: Make IntelliJ aware of installed Git.

Open settings and type Git in search box. Go to Git settings and set path to git.exe:

That's all. Git is installed and configured in IntelliJ Idea.

Make Java Hello World in control of Git

Using git is beyond of the scope of this blog :) There are many great tutorials explaining the nature of git - for example this one. I will show how to add a git support to the existing project (Hello World created earlier).

Step 1: Convert existing projest into git respository. 

Open project location (C:\Development\Projects\Test) and using context menu (right mouse click) select option Git Bash Here. Git will open its terminal with path set to the project. Now enter command git init:

This will create empty repository:

The project is now maintained by Git.

Step 2: Verify git integration under IntelliJ Idea. 

Open Test project in Idea to see that it is recognized as a git project now:

Step 3 (optional): Use git command directly from IntelliJ Idea.

Idea has great integration with Git, however it is possible to use git commands entered by hand directly in Idea - just like we use them in Git Bash. We can use Idea's terminal and set it to open Git Bash under the hood. Go to the settings and find options for Termimal. Set shell path to point to the Git Bash executable script with some additional options:

Now we can execute git command in Idea's terminal:

That's all. Development environment is set up and ready for work :)

Thursday, December 08, 2011

JSF 1.2 (myFaces) + RichFaces 3.3.x + IE 9 = troubles

Note: below description uses Eclipse Indigo, Tomcat 7.0.28, MyFaces 1.2.12, RichFaces 3.3.3 (Final).

  • working JSF 1.2 sample application from here
  • RichFaces 3.3.x added to the project
You will learn:
  • how to fix problems with RichFaces 3.3.x for IE 9
Let's assume that You develop JSF 1.2 web application. It does not matter if Your application uses .jsp pages or Facelets with .xhtml pages. I assume that .jsp pages are in use. Then You decided to add some Ajax capabilities, new components and so on. So You simply take RichFaces and add them to the project. This is simple thing:
a) download latest RichFaces 3.3.3 (final), take those jars: richfaces-api-3.3.3.Final.jar, richfaces-impl-3.3.3.Final.jar, richfaces-ui-3.3.3.Final.jar and place them in WEB-INF\lib folder of Your web application. 
b) modify your web.xml file by adding there:
  <display-name>RichFaces Filter</display-name>

  <servlet-name>Faces Servlet</servlet-name>
c) add proper taglib directives to each Your jsp page (note that for .xhtml pages syntax is different):
<%@ taglib uri="" prefix="a4j"%>
<%@ taglib uri="" prefix="rich"%>
Now You can use RichFaces components. Let's try to modify our sample JSF 1.2 application by creating new web project named "JSFRichFaces". Then let's add ajax button (<a4j:commanButton>) and expandable toggle panel (<rich:simpleTogglePanel>). All modifications are shown below:

Everything works OK under Firefox, Chrome, IE 7, IE 8 - unless You use Internet Explorer 9. You can observe two problems: with RichFaces ajax components and RichFaces components layout.

RichFaces 3.3.x does not fully support IE 9. RichFaces developers encourage everyone to migrate into RichFaces 4.x which are IE 9 compatible. The main problem is that RichFaces 4.x works only with JSF 2.x application, and this is not so easy to migrate If You have many clients where You already delivered Your application...

Problem 1: ajax components do not work (some JavaScript errors).

When You try to press ajax button named "Go (RichFaces) " under IE 9, You can observe following error (open IE Developer's Toolbar Java Script console before):

Solution: You have to force IE 9 to act as IE 8, where RichFaces 3.3.x works OK. In order to do it You have to define X-UA-Compatible header for each page. You can do it in two ways:
a) add a special <meta> element for each page or
b) write a special filter which adds this header to the HTTP response

In our simple case it is sufficient to add a <meta> into the page <head> section:

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />
Remember that this <meta> must be placed as first element in <head> section!

Problem 2: RichFaces components have broken layout (problems with CSS).

When You open our sample application under IE 9, toggle panel has no CSS styles set at all. Under Chrome or Firefox everything looks OK. Checking HTTP request/response headers shows that for IE 9 proper CSS for RichFaces component (CSS located in the .jar file) is not loaded and server returns error:

Console under Eclipse shows that exception is thrown:

Under Firefox everything looks OK:

Why it happens? Accroding to that article, there was a change in IE 9 for MIME type handling. IE 9 ignores CSS styles if they are not delivered with a text/css MIME type.

Why it works for previous IE 7 and IE 8? Because also HTTP Request Accept header sent by IE 9 is different than sent from IE 7 or 8. IE 7/8 sent text/css, */* as Accept, where IE 9 sends only text/css as Accept.
Knowing that it is time to look inside myFaces source, to find the code which produces mentioned exception. Everything is located in (located in myfaces-impl-1.2.11.jar) in the selectContentType() method. It works for IE 7/8 because */* sent in Accept by IE 7/8 is on supported content type list, where text/css is not recognized at all.

Solution: add text/css support, then recompile and replace it in myfaces-impl-1.2.11.jar (or build complete myfaces-impl-1.2.11.jar). In order to avoid this mumbo-jumbo with Maven to build whole .jar, just create simple Java Project, create a in certain package, change it and compile, then replace compiled class in myfaces-impl-1.2.11.jar ;-)

Or download recompiled myfaces-impl-1.2.11.jar from here.

That's all. IE 9 works again without need to add Your web page to its compatibility view list or something. And You have time to migrate to JSF 2.x and RichFaces 4.x before IE 10 comes to market...

Wednesday, September 21, 2011

Tomcat - using Realm to protect access to JSF application (part 2 of 2)

Note: below description uses Eclipse Indigo, Tomcat 7.0.28, MyFaces 2.1.7
  • understanding basics of Tomcat's Realm
You will learn:
  • how to define users and roles in own web applications (JSF 2.0 as example)
  • how to use encrypted passwords for realm users instead od plain text
In the previous post I described how to configure access to Tomcat's server administration application using Tomcat's Realm elements. The whole thing boiled down to write a few lines of text in server.xml file. But how does it look like when we have to do it from scratch in our application?

Step 1. Let's create very simple JSF application which has only 3 pages:
  • /index.html - main page with two buttons navigating into two pages:
  • /unrestrictedPage.xhtml - page always accessible and visible to anyone
  • /restricted/restrictedPage.xhtml - page and directory available only for valid users
The complete application structure will look like:

Step 2: we have to add a privilleged user named admin with password adminpass who belongs to role privillegedUsers (You can choose any user login, password and role name). Just simply add this line:
<user username="admin" password="adminpass" roles="privillegedUsers" />
into [tomcat directory]\conf\tomcat-users.xml file.

Step 3: configuring application. We have to modify web.xml of our sample application by adding following text:
              All persons belong to that role have access to restricted application area.


        <realm-name>Restricted access</realm-name>
First we defined a role named privillegedUsers - the same we put in tomcat-users.xml file above. Second we have to defined prottected parts of our application, by providing proper URL pattern. Please note that we have two entries here: /restricted/* - everything in this directory is protected in case someone typed this part manually in browser's address bar,  /faces/restricted/* - JSF adds "faces" prefix when navigating between pages, so the URL is a little bit different and we have to watch for this also. After that we have to define a role which is allowed to access to the protected parts. This is privillegedUsers role defined earlier. At the end we have to define the way how the authentication is done - the simplest way is BASIC, which displays predefined form with credentials.

Now we are ready to deploy our application on Tomcat and run it. It should look like this:

when we try to access to restricted area. In order to do this we have to put credentials for user defined in step 2 (admin, adminpass).

Note: there is a little trick here, for the button "Restricted area" - see index.xhtml page source code:
<h:commandButton value="Resricted area" action="/restricted/restrictedPage.xhtml?faces-redirect=true" />
<h:commandButton value="Unrestricted area" action="/unrestrictedPage.xhtml" />
Because JSF internally by default makes forward to other page, browser is unaware what has happened and display URL from one step back. In such case our URL security patterns will not match anything, and restrictedPage.xhtml will be displayed without asking for login and password! In order to make protection work we have to perform full redirection for that action in order to force browser to fetch target URL and display it. For JSF applications it is better to use filters or Spring Security in order to avoid such dirty tricks.

Encrypted passwords.

As You probably have seen, passwords vor valid users are stored inside tomcat-users.xml file as a plain text. There is a possibility to store them in encrypted form, using MD5. Here is what needs to be done:

Step 1: using Eclipse modify Tomcat server.xml and its <Realm> atrribute into:
<Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase" digest="MD5"/>
Step 2: in web.xml change <auth-method> from BASIC to DIGEST

Step 3: for user admin and his previous password adminpass we have to generate its md5 equivalent using Tomcat's digest.bat file (located in [tomcat directory]\bin folder) :

digest.bat -a md5 admin:"Restricted access":adminpass

"Restricted access" is a realm name taken from <auth-method> tag from web.xml. Those names must match, if name contains spaces, it must be surrounded with "".

Step 4: using Eclipse modify Tomcat's tomcat-users.xml file:
<user username="admin" password="db7bc05adcf611fc779f32a4e680cc01" roles="privillegedUsers" /> 
where password was taken as a result of executing command from step 3.

Download source files:

Note: make sure that Java, Eclipse and Tomcat are properly installed and configured for running the project (additional configuration may be required if different directories are used).

Eclipse complete sample project is here (with all required libraries).

Tuesday, September 13, 2011

Tomcat - change default application, protecting access to web applications using Realm (part 1 of 2)

Note: below description uses Eclipse Indigo, Tomcat 7.0.28,

  • installed Java (description here)
  • installed and configured Eclipse (description here)
  • installed and confiured Tomcat for the Eclipse (description here)
You will learn:
  • how to change default Tomcat application
  • how to allow users access to Tomcat's server administration application using Tomcat's Realm

Let's assume that You have Tomcat which is configured to work in Eclipse. When You start Tomcat (using Eclipse or standard scripts from Tomcat's distribution) and type in the browser URL http://localhost:8080, You will see Tomcat's default application:

This application is located in the [tomcat directory]\webapps\ROOT folder. If You want to change this page, just edit content of file index.jsp and index.html. If You want to completely remove this application, just remove complete ROOT folder.
Removing is not the best choice, because Tomcat is shipped with a special applications for server administration. You can access those applications using links in red square. Try to click on any link - You should see screen with login and password prompt:

Those parts are protected using Tomcat Realm. What is Realm? Realm is a set of valid users (defined by user name and password) and roles where those users belong. The idea is to configure access to web application only for valid users from certain roles. But where are those users and roles stored? It depends on a implementation of a realm - they can be stored in database, in LDAP, or in xml file. Tomcat's server administration application uses xml file to define users' access. Let's try to set up some users able to start that application.

Step 1: using Eclipse open server.xml from the Servers, and make sure that entry <Realm classname="org.apache.catalina.realm.UserDatabaseRealm" resourcename="UserDatabase"></Realm> exsits between <Engine> tags, outside <Host&gt tags - it means that this realm will be used for all hosts and all applications on that  hosts:

Step 2: using Eclipse open tomcat-users.xml from the Servers and add an entry for the user who will be able to access Tomcat's server administration application:

By default UserDatabaseRealm uses [tomcat directory]\conf\tomcat-users.xml file to load users and their roles into memory on server startup. In order to allow defined users to access administration application, they need to belong to roles named manager-status, manager-gui and admin-gui. After changes made, restart Tomcat server and try to access Tomcat's administration application giving username and password from tomcat-users.xml file. If everything was set up OK, You should see mentioned applications.

You may wonder why we used here roles named manager-status or manager-gui or admin-gui. Those role names come from Tomcat's server administration application specific settings, stored in the web.xml file. In the next post I will show how to protect own application (JSF2 application will be used as an example) and how to define own roles.

Thursday, August 04, 2011

Sending emails using Java Mail and Google Mail account

  • installed Java (description here)
  • installed and configured Eclipse (description here)
  • valid Google Mail account
You will learn:
  • how to send e-mails from Java application using Java Mail and Google Mail account.

Sometimes You need to send an email from Your Java application. In order to do this You have to use valid e-mail account, and You have to know the address of SMTP server for this account. And of course You have to write some code which will connect to the SMTP server (using Your account credentials) and then create and send email. A Google Mail account will be used as an example.

Step 1: create clean Java Eclipse Project

Step 2: download  JavaMail API 1.4.4 ( from here.

After downloading JavaMail, extract it and go into its /lib folder. Copy all .jar files from that directory into Your project and add them to the build path.

Step 3: write a simple code for sending email using Google Mail. You can use TLS or SSL connection to Google SMTP server.

a) using TLS connection to SMTP server:
// ...
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
// ...
Properties propsTLS = new Properties();
propsTLS.put("mail.transport.protocol", "smtp");
propsTLS.put("", "");
propsTLS.put("mail.smtp.auth", "true");
propsTLS.put("mail.smtp.starttls.enable", "true"); // GMail requires STARTTLS

Session sessionTLS = Session.getInstance(propsTLS);

Message messageTLS = new MimeMessage(sessionTLS);
messageTLS.setFrom(new InternetAddress("", "John Smith"));
messageTLS.setRecipients(Message.RecipientType.TO, InternetAddress.parse("")); // real recipient
messageTLS.setSubject("Test mail using TLS");
messageTLS.setText("This is test email sent to Your account using TLS.");

Transport transportTLS = sessionTLS.getTransport();
transportTLS.connect("", 587, "", "sender_account_pass"); // account used
transportTLS.sendMessage(messageTLS, messageTLS.getAllRecipients());

b) using SSL connection to SMTP server:
// ...
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
// ...
Properties propsSSL = new Properties();
propsSSL.put("mail.transport.protocol", "smtps");
propsSSL.put("", "");
propsSSL.put("mail.smtps.auth", "true");

Session sessionSSL = Session.getInstance(propsSSL);

Message messageSSL = new MimeMessage(sessionSSL);
messageSSL.setFrom(new InternetAddress("", "John Smith"));
messageSSL.setRecipients(Message.RecipientType.TO, InternetAddress.parse("")); // real recipient
messageSSL.setSubject("Test mail using SSL");
messageSSL.setText("This is test email sent to Your account using SSL.");

Transport transportSSL = sessionSSL.getTransport();
transportSSL.connect("", 465, "", "sender_account_pass"); // account used
transportSSL.sendMessage(messageSSL, messageSSL.getAllRecipients());

Note: in both cases You for the connect() method, You have to pass a real login and password of the Google Mail account used. The main differences between those two methods are: different protocol (smtp for TLS and smtps for SSL), different ports (587 for TLS and 465 for SSL). In addition TLS requires STARTTLS.

Download source files:

Note: make sure that Java and Eclipse are properly installed and configured for running the project (additional configuration may be required if different directories are used).

Eclipse complete sample project is here (with all required libraries).

Wednesday, August 03, 2011

SSL in Tomcat under Eclipse (part 2 - certificate from CA)

  • You should be able to generate self signed SSL certificate and integrate it into Tomcat, as described in previous post.
You will learn:
  • how to obtain and install a real SSL certificate from well known Certificate Authority (CA)
In the previous post I described the complete procedure of generating self signed SSL certificate and integrating it into Tomcat. In this post I would like to focus on the example with real certificate obtained from CA - I will use Thawte as example.

Note: let's assume that You created an application which is going to be visible under the following URL:

Step 1: generating self signed certificate for domain

This is exactly the same step to step 1 in previous post. You have to execute the following command:

keytool -genkey -alias myappcert -keyalg RSA -keystore myapp.keystore

Step 2: Generate Certificate Signing Request (CSR).

You have to generate a special request, which will be send to the CA. You have to execute command:

keytool -certreq -keyalg RSA -alias myappcert -file certreq.csr -keystore myapp.keystore

Generated request is saved as a certreq.csr file, which will be send to CA. CA will use this file to generate certificate signed by them.

Important: You have to use exactly the same alias (in this example: myappcert) for step 1 and step 2.

Step 3: Getting certificate from CA.

Usually certificate are delivered in PKCS#7 or X.509 format. For the first one, the file with certificate will have .p7b extension, for the second one - .cer. Sometimes You can get such certificate also by email as a pure text - for the X.509 format, certificate will be placed between tags -----BEGIN CERTIFICATE----- and -----END CERTIFICATE-----, for PKCS#7 certificate will be placed between tags -----BEGIN PKCS7----- and -----END PKCS7-----. Then You have to copy the certificate content (including those begin/end tags!) and save this as a .cer or .p7b file (You can use Notepad for that). Now You are ready to import Your signed certificate.

Step 4: importing signed certificate.

a) as a .p7b (PKCS#7) format:
Acording to the Thawte, when You obtained Your certificate as a .p7b file, You need only one command to import and install this certificate in Your keystore:

keytool -import -alias myappcert -trustcacerts -file signed_cert.p7b  -keystore myapp.keystore

where signed_cert.p7b is a signed certificate obtained from CA.

b) as a .cer (X.509) format:
According to the Thawte, when You obtained Your certificate as .cer file,  You need to download Primary and Secondary Intermediate CAs and import them. They are delivered as .p7b format (i.e. intermediate.p7b). I should import them first, using command:

keytool -import -trustcacerts -alias intermediatecerts  -file intermediate.p7b -keystore myapp.keystore

and then import my certificate (it is in .cer file signed_cert.cer) using this command:

keytool -import -trustcacerts -alias myappcert -file signed_cert.cer -keystore myapp.keystore

where signed_cert.cer is a signed certificate obtained from CA.

Problem and workaround:
Both above ways seems to be simple, but... when I was buying some time ago a web SSL certificate from Thawte, I receive certificate as a pure text in e-mail. Certificate was in X.509 format (I had tags ----BEGIN/END CERTIFICATE-----). I created a signed_cert.cer file from that e-mail content. Then I tried to install intermediate certificates like it was described in Thawte documentation. Unfortunately it didn't work. The first command for importing intermediate certificates failed with error:

keytool error: java.lang.Exception: Input not an X.509 certificate

It seems that keytool does not work with .p7b format (I used JDK 1.6.0_16), so I expect that even if I get my certificate as .p7b file (complete, without need to import intermediate certificates as in a) subpoint) it will also not work. I took a .p7b file with intermediate certificates, opened it under Windows, and for each certificate found inside i exported it as a X.509 DER certificate, giving each file .cer extension. So I had three .cer (X.509) files: signed_cert.cer, thawte_primary.cer, thawte_secondary.cer. Now I had to import intermediate certificates and after that import my signed certificate with those commands:

keytool -import -trustcacerts -alias primary -file thawte_primary.cer -keystore myapp.keystore
keytool -import -trustcacerts -alias secondary -file thawte_secondary.cer.cer -keystore myapp.keystore
keytool -import -trustcacerts -alias myappcert -file signed_cert.cer -keystore myapp.keystore

Now import was OK. So the general workaround rule (if there are any troubles) is: get all needed certificates in X.509 form, import intermediate certificates (if any required) and import Your signed certificate at the end.

Important: You have to use exactly the same alias (in this example: myappcert) like You used in step 1 and step 2, except for importing intermediate certificates - You can use whatever alias You like.

Step 5: copy Your myapp.keystore file into Tomcat's /conf directory

Step 6: modify Tomcat configuration to use SSL certificate

It is exactly the same as step 3 in previous post.

That's all.

Monday, August 01, 2011

SSL in Tomcat under Eclipse (part 1 - self signed certificate)

  • installed Java (description here)
  • installed and configured Eclipse (description here)
  • installed and configured Tomcat for the Eclipse (description here)
You will learn:
  • how to set up Tomcat for SSL connection using self signed certificate under Eclipse
When You want to secure Your application SSL is the most natural choice. In order to make Your application be recognized as trusted by browser, You can by a buy a certificate from well known certificate authority (CA), which will be generated for the domain Your application uses. If You do not care about being recognized as trusted service, but instead You just want to encrypt the data exchanged between server and client's browser, You can use Your own self signed SSL certificate. In this post I will show how to generate such SSL certificate and how to set up Tomcat (from the Eclipse level) to use generated certificate.

Note: let's assume that You created an application which is going to be visible under the following URL:

Step 1: generating self signed certificate for domain

Go into Your Java bin directory (i.e C:\Development\Java\bin). Then open Windows console (under Windows Vista/7 open the console with Administrator right) and type in command:

keytool -genkey -alias myappcert -keyalg RSA -keystore myapp.keystore

where myappcert is the name of the certificate being generated and myapp.keystore is a file where certificate will be stored. You will be asked about the password for created the myapp.keystore file. Type in "mypass", press Enter and type it again and press Enter again. Then You will be asked for some details about You:

Please note that for the first question about first and last name I gave answer This is very important - this name (known as CN - Common Name) will be used for the checking if certificate on the page we visit was generated for the same URL which we typed in in the browser.
At the end You will be asked for the password for the newly created certificate. The password must be the same as one used for myapp.keystore file ("mypass"). Do not type antyhing, just press Enter to use the same password. Your myapp.keystore file containing myappcert certificate is ready.

Step 2: copy Your myapp.keystore file into Tomcat's /conf directory

Step 3:  modify Tomcat configuration to use SSL certificate.

Make sure that Your Tomcat is configured with Eclipse and works OK without SSL (start Tomcat from Eclipse and type in http://localhost:8080 in the browser). Stop Tomcat if it is running. Then open server.xml file form the "Servers" view:

and locate default element for standard HTTP connections (marked red). Then add additional element for the SSL connection (next to existing one):

Please note that next to some specific SSL settings, we set the location of the keystore file, the password for that file and certificate name to be use. SSL connection uses port 8081, where normal HTTP connection
uses port 8080.

Note 1: all modification of server.xml file were done from Eclipse level, using "Servers" view. If You want to use Eclipse WTP for starting Tomcat (like I do so far) You can't edit this file from elsewhere. Eclipse WTP overrides original Tomcat configuration files by files visible under "Servers" - changes done outside Eclipse will not be visible for WTP.

Note 2: I added element specific for SSL next to existing element for standard non encrypted HTTPS connections. This is second issue directly connected with Eclipse WTP - when You remove standard connector for HTTP, Eclipse will close Tomcat after a time set in "Timeouts" section in the Tomcat settings:

Some people try to extend the timeout time into long period, but still after this period Eclipse kills Tomcat process, as if Tomcat was not properly started in the required time. Unfortunately there is no way to set timeout into ifinite time - the only way to fix this under WTP is to leave standard HTTP element in Tomcat's server.xml file.

Step 4: that's all. Tomcat is configured to work with SSL. 

Try to enter the URL: https://localhost:8081. If You see Tomcat's page, everything works OK (You can see certificate warning - You Need to add security exception for that certificate). Of course You can still open the same Tomcat page by standard HTTP (You have two elements), just enter http://localhost:8080 URL.