Showing posts with label Tutorials. Show all posts
Showing posts with label Tutorials. Show all posts

Monday, September 19, 2011

Enabling SSL in Apache Tomcat 6 The Easy Way

NOTE: This article does not use the APR tomcat module but rather the default Tomcat 6 deployment.

To enable SSL for Apache Tomcat 6, perform the following:

1. Create an SSL certificate using the java supplied keytool:

$JAVA_HOME/bin/keytool -genkey -alias tomcat -keyalg RSA

NOTE: If you get the error:
keytool error: java.lang.Exception: Key pair not generated, alias <tomcat> already exists
Then most probably you have a key file already in your user directory. If you are root, this will be /root/.keystore

2. You will be requested for data that will show on your user browser's certificate, fill them all in.
Notice that the bold font is my input. No problem if you stick to the password "changeit" as it is the default password used by tomcat.

Enter keystore password: changeit
Re-enter new password: changeit
What is your first and last name: Jeremy Atkins
What is your organizational unit: OU
What is the name of your organization: NOYO
What is the name of your city or your locality: MyCity
What is the name of your state or province: Saudi Arabia
What is the two-letter country code for this unit:  uk
Is the entered data correct: yes

Enter key password for <tomcat>
        (RETURN if same as keystore password): PRESS RETURN KEY

It is important to have the keystore password and the key password the same. This is done by pressing the RETURN KEY in the last step. This is necessary since Tomcat doesn't support having different passwords in the keystore and key.

3. When you're done with the previous step, a keystore file gets created in the user directory named keystore. Since I'm the root user, I will find it in /root/.keystore.
Check that the file /root/.keystore got created.

4. Next, open the tomcat server.xml for editing:
vi ${tomcat_installation_dir}/conf/server.xml

And uncomment the following section by removing the <!-- and the --> surrounding them from top and bottom:

   <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS"
               />

5. Change the port number from 8443 to 443 which is the default SSL port known to all browsers.
Switch to 8443 while in development if needed.

   <Connector port="443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS"
               />


6. Now add the following line in between to tell tomcat where to locate the keystore and specify the password you specified:

<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
   maxThreads="150" scheme="https" secure="true"
   clientAuth="false" sslProtocol="TLS"
   keystoreFile="${user.home}/.keystore" keystorePass="changeit"
               />

Tomcat will automatically replace ${user.home} with the path of the home directory for the user tomcat is running under. Which in my case is "/root"

7. Restart apache tomcat using:
<tomcat_installation_dir>/bin/catalina.sh stop
<tomcat_installation_dir>/bin/catalina.sh start


Wednesday, June 13, 2007

A Useful Command Prompt Tip

netstat -an |find ":80"

The above command I use so frequently. It really helps me out figure if there is a webserver running on the machine (ie. listening on port 80).

Actually, this command is a combination of two commands. The first is netstat which displays a boring long table.

The second is find "XX" which ignores all strings that dont contain "XX".

The '|' is the pipe operator. Now the command simply pipes the output of 'netstat' into 'find', the result is the line that contains the string "80".

If you're from a linux background, you'll find this post a bit too obvious. Since we're used to using the 'grep' command (which is similar to 'find' on windows).

Monday, May 14, 2007

The 'Call Super' Antipattern

A common design problem that is usually solved using the 'Call Super' antipattern (also referred to as code-smell). Simply stated, the problem occurs when the subclass needs to share the implementation of the super classes over-ridable methods.

In such case, 'Call Super' anti-patten is usually used by calling the over-ridden methods from within the subclass's over-riding methods.

I'll show a 'Call Super' code sample, then show a much better and neater solution (proposed by Martin Fowler).

The Bad Solution (Using the 'Call Super' AntiPattern):

class Penguin {
public void intoduceYourSelf() {
System.out.println("Hi, I'm classified as a penguin.");
}
}

class EmperorPenguin Extended Penguin {
public void introduceYourSelf() {
super.introduceYourSelf();
System.out.println("My real name is Emperor Penguin");
}
}
A Better Solution
A much better solution is to have an abstract method in the super class for the extra actions the subclasses will perform. And thus, the subclass only needs to implement that abstract method:

class Penguin {
public void introduceYourSelf() {
System.out.println("Hi, I'm classified as a penguin.");
talkAboutYourselfMore();
}


abstract public talkAboutYourselfMore();
}


class EmperorPenguin extends Penguin {
public void talkAboutYourselfMore() {
System.out.println("My real name is Emperor Penguin");
}
}



Thats it. A neat alternative solution that I love to use.

Sunday, April 29, 2007

Lazy Evaluation and Caching...

... are the most widely used techniques for improving your software's implementation performance.

Then what are they and how can I use them?

Lazy Evaluation is exactly just like a Lazy Employee; he wont do the job unless some one directly requests it from him. Infact, he'll postpone it forever until the request is made official.

Caching on the other hand is simply storing frequently used data in some quick array or memory for fast retreival, although the same data is stored in a database or in a file, the programmer usually chooses to cache it in its accessible form for fast retreival. This memory could be an Array, a Berkley DB file, a tmp file or any other suitable media.

Google - a well known search engine - caches search results for most frequently used queries. FileNET (a really good CMS server) renders all content objects inside one single HTML page ready for access (instead of querying it from a database everytime). The HTTP protocol itself caches different requested pages on the internet on local internet proxies and implements the HTTP headers to do so. And even does your browser cache some html pages from time to time.

Thats why you usually need to press Ctrl+F5 to force requesting to refresh the page from the server.

As a programming example, lets say you have a small class named UserAccountManager and this class contains a single method:

public static String UserAccountsManager.getUsername(int UserId);

And a single private array which is simply a HashMap mapping a UserID to the Username which is used by getUsername(int UserId).

The method is implemented simply to execute a query on the database:

"SELECT USERNAME FROM USERS WHERE ID=" + UserId

Here is a simple way to see how caching and lazy evaluation can be applied.

The program can implement caching using a private array map that maps the user id to the username string. This array is filled only once from the database when the program first loads.

The tricky part when implementing caching is knowing when to re-generate the cache, or more accurately, how to identify that the original data store has changed or not? If changed, then the cache needs to be regenerated or else your program is using out-of-date data.
Any calls to getUsername will simply access the array instead of accessing the database. This is whats Caching all about.

Now, lazy evaluation simply changes the implementation so that the array AINT FILLED AT ALL until someone actually calls the getUsername() method.

The advantage here is that you dont waste memory or connect to the database until someone actually calls the function. (ps. It might need not be called at all).

After all this explanation, there is a very annoying advice that you have to stick to:

"Never implement optimization techniques such as caching or lazy evaluation until a bottle neck is identified in the system using benchmarking and testing procedures that shows that need. This simply means, avoid Premature Optimization as much as you can."

Sunday, April 01, 2007

Swing/AWT

Fortunately, I've found lots of books and online material that teach you Java swing/awt programming for desktop environments.

Unfortunately, very few (approximately none) discuss structuring your application code.

I've seen "Learning Java" over discuss the 'Adapter' design pattern when it comes to separating UI actions from application functionality. But still, I'm looking for patterns that will make code scale, techniques that will handle complex user interfaces using simple class relations without cross-referencing different variables, classes and elements along the code.

Till I meet such a tutorial or reference, I think I'll be treating Swing the MFC way.
Lucky me , I've done MFC ;)

Monday, March 05, 2007

Power Shell versus Bash

A good command prompt has always been a weakness point in MS Windows. Compared with bash scripting in Linux/Solaris/UNIX, the command prompt simply lacks a command prompt.

Microsoft aggressively striked back this time with Microsoft's new Power Shell. You can download it from the following link or read more about it here. Expect better automation tasks and large bash scripts to be so common on Windows.

Saturday, February 17, 2007

Writing .bat files / Part 1 / Hello World

You create a batch file by writing it in a text file then saving the file with the ".bat" extension at the end, this will tell windows that this is an executable batch file.

Here I will create a text file containing the following and save it as "test.bat":

echo "Hello World, this is my first batch file!"

The word 'echo' is a DOS command that simply tells the command shell to display the text message following it.

You can test your first batch file by opening a command line window. To open a command prompt window there are two ways:

First, you can go to Start > All Programs > Accessories > Command Prompt
Or, you can go to Start > Run then type in 'cmd' and click OK.

Once the command prompt is open, you can run your batch file by typing its name followed by enter:

c:\> test.bat

Make sure to change the directory to the location where the test.bat file was saved, in the above example it assumes it was saved in the C:\ top folder. If it was saved in a different location, e.g. F:\my_folder then you can change directories by typing:

c:\> cd /D F:\my_folder
f:\my_folder> test.bat

The output:
f:\my_folder> echo "Hello World, this is my first batch file!"
"Hello World, this is my first batch file!"

Notice that the string got displayed, but also the command 'echo' got displayed too. To hide the commands being executed you can add "@echo off" at the top of the test.bat file.

@echo off
echo "Hello World, this is my first batch file!"

Now executing test.bat would result in:

F:\my_folder>test.bat
"Hello World, this is my first batch file!"

Congratulations, your first batch file is ready. Unfortunately, till now it does nothing interesting other than print a message.

Friday, February 16, 2007

The Art of Delegation Using Batch Automation

For those people whom hate donkey work, I have good news for you... even donkey work has a creative side.

The creativity lies in automating the donkey... in software this means writing code to do the job and writing scripts to handle your book keeping tasks.

Using bash scripts on linux and unix are so common. On windows, people hardly know that a command prompt exists, and that they can make their life much easier by writing batch files.

The first rule of automation says:


"If you repeat anything more than once, then consider
automating it."
Most people fail in committing to this rule due to one of three reasons:

1. They fail to notice that they are repeating the same task.
2. They have so much energy that they dont feel automating is necessary.
3. They dont have the 'know how' of writing automation scripts.

Ironically enough, people that love automation turn out to be the laziest people i ever met. I believe this explains the common phrase "need is the mother of invention", to fulfill their idle needs they start creating tools to work for them.

In the next article, I'll teach you how to write simple batch scripts on windows, part of it is for my own reference and learning curve.

Saturday, February 10, 2007

Build space ship 'One' before space ship 'Two'

Whenever you have an idea for a library, product, class or anything else, always remember to build space ship one first, stop collecting extrabonanzic features and ideal design methodologies to reach directly to your dream space ship, start with space ship 'one' always.

This means, if its a product, this would be the minimal set of features that will make it usable.

If its a library, this means exposing the minimal set of functions that are sufficient to achieve the main objective of the library.

If its a class, then allow the smallest simplest possible code that'll make it work.

Ofcourse, before you even think of starting to work on Spache Ship 'Two', remember to launch spache ship 'One', or else, you're skipping the advice.

In a product's sense, space ship one is usually your own design, thoughts and implementation. After launching space ship one, people will start giving you feedback on certain conveniences, improvements, enhancements which you should take into account in space ship two.

The important thing to remember is: "DONT TAKE MUCH FEEDBACK FROM PEOPLE ON SPACESHIP ONE, DONT ADD FEATURES PEOPLE WANT ON SPACESHIP ONE, JUST IMPLEMENT SPACE SHIP ONE AND LAUNCH IT."

Nothing more, nothing less, if you cant launch space ship one, dont even think of building a space ship.

Thursday, February 01, 2007

Yours Sincerely

Starting and Ending emails has always been a major issue with myself.

Does 'Yours Sincerely' sound a bit too formal? Shall I use 'Regards' or 'Best Regards'? Maybe 'Best Regards' will give an impression that I'm a bit too excited or something, I'll use 'Regards' instead. What about 'Yours Faithfully'? which will I use, when? What about the name prefix... hmmmmm... "Dear X" sounds so intimate, I barely know her/him, lets use "Hi X" instead, but this sounds too casual too, ok, "Hello X" seems fair enough. What about the prefix? is she a Ms or Mrs? and will he be pissed off if I used his bare name without the Mr/Prof/Highness? I need an ice breaker too, but the only one I can think of is "Hope all is well, ...".

I discovered this article that provides tips that will easily put an end to those confusing 'thought provoking' 'mind squashing' emotions you experience when you write a new email, specially when you're writing to some corporate client trying to look professional enough.

Wednesday, January 31, 2007

Java Collections, Maps, Sets, Hashs, Lists, Arrays

One thing I really hate is having to use collection types in my java code. Whenever this takes place I have to jump back to the JDK documentation and start digging for methods.

Suddenly, I decided to put an end to this fuss (sorry 3akilmit fuss). I searched google for a simple tutorial, and guess what I found. A wonderfully illustrated simple to use up-to-date small tutorial PDF document, check it out here.

Wonderful and easily digestible by an average mind.