Showing posts with label Tips. Show all posts
Showing posts with label Tips. 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


Disabling WebDAV DELETE, PUT, OPTIONS in Apache Tomcat 6

It really took me more than two hours searching over the internet just to understand how to do this simple configuration of disabled the WebDAV methods in apache tomcat 6 for all applications.

Here is how to do it:

In your apache tomcat 6 installation, simply open the file <installation_directory>/conf/web.xml for editing. Note that this web.xml file acts as a global file for all web applications and is processed before the web.xml's web application file.

At the end of the global web.xml file and just before the closing tag place the following text:

<security-constraint>
<web-resource-collection>
<web-resource-name>restricted methods</web-resource-name>
<url-pattern>/*</url-pattern>
<http-method>PUT</http-method>
<http-method>DELETE</http-method>
<http-method>OPTIONS</http-method>
<http-method>TRACE</http-method>
</web-resource-collection>
<auth-constraint />
</security-constraint>

The above security-constraint simply denies the above WebDAV methods to be processed by tomcat and returns a forbidden message.

The <auth-constraint /> simply means: "For any user, deny access to PUT, DELETE, OPTIONS, and TRACE methods".

After that, restart apache tomcat 6 using:

<installation_directory>/bin/catalina.sh stop
<installation_directory>/bin/catalina.sh start

To be able to verify that these methods are now forbidden, I used some javascript jquery code:
1. Open firefox with the firebug plugin installed
2. Open a webapplication that has jquery javascript file included within it.
3. Open firebug and select the "Console" tab from firebug
4. Write the following javascript code:

$.ajax({
  type: 'DELETE',
  url: "http://212.138.70.94",
  data: {},
  error: function() {alert('ERROR');},
  success: function() {alert('SUCCESS');},
});

5. Click the Run button.
6. You should see an alert dialog with the message ERROR and a response in firebug with the following message:
"NetworkError: 403 Forbidden - http://212.138.70.94/"

7. Repeat the above for the OPTIONS, TRACE and PUT methods.

I'm sure there's a simpler way to verify it other than javascript. But I don't know how.

Tuesday, May 03, 2011

Setting a default program to open files with unknown extensions or no extension on Windows 7

I always get frustrated having to select a program to open a file when most of the time this program is notepad.

I searched the internet for a way to define a default program to open files for all other files that have extensions not defined on windows. Luckily, I found this article:
http://www.fortypoundhead.com/showcontent.asp?artid=2738

To modify the registry you have to run regedit.exe and modify or add the following:

[HKEY_CLASSES_ROOT\*\shell]

[HKEY_CLASSES_ROOT\*\shell\open]
@="Open With Notepad"

[HKEY_CLASSES_ROOT\*\shell\open\command]
@="notepad.exe %1"

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.]
"Application"="Notepad"

Note the following, if the key does not exist, you have to create it.
Example, create the key "open" and created under it the key "command"
Also @= means the default value for the key
Application=Notepad means you have to create a string value containing Application and value Notepad
Also, the last key make sure to notice the ".", its not "FileExts" but rather "FileExts\.", a subkey inside FileExts labeled dot.

Or simply, the above could be saved into a *.reg file and executed.

After that you will get in the context menu the option to open with Notepad for any unknown file.

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.

Saturday, May 05, 2007

Swapping Two Integer Variables Without Using a Temp Variable

The first time I heard this question, I thought it was a joke of some kind. I never thought such was possible.

Turned out to be possible and even faster than the normal technique, here you go:

Let X be an integer variable.
Let Y be another integer variable.
X = X xor Y
Y = X xor Y
X = X xor Y

Wont buy it? Then try it out for yourself.

One more technique, you can use the - (minus) operator instead, but be careful not to step over the integer max and min limits. Here you go:

(eg. X = 12, Y = 7)
X = X - Y ( X is now 5)
Y = X + Y ( Y is now 12)
X = Y - X ( X is now 7)
(result: X = 7, Y = 12, Voila! Swapped)

Hmmmm. Coming to think of a practical use. The only way such would be useful is to swap two large memory binary buffers.

This swapping enhancement breaks the common myth of 'its either memory or speed, but not both'. The swapping algorithm you just saw proves better in both memory consumption and performance gain.

Friday, April 27, 2007

SQL Statement Shortcuts

What always bothered me when writing SQL SELECT Statements is handling long table names, and having to reference a field by its table's name to avoid ambiguous errors.

Take this for example, three tables: infobase, infobase_labels, and infobase_users. And let's imagine that those three tables each have a field named 'ID'.

So a simple select statement will go like that:

SELECT infobase.ID, infobase.NAME AS INFO_NAME, infobase_labels.NAME AS LABEL_NAME, PHONE FROM infobase_labels, infobase_users, infobase WHERE infobase_labels.ID=infobase.LABEL_ID and infobase_users.ID=infobase.USER_ID AND infobase.ID=5;

Okay, 238 characters of unreadable sql code.

Whats next? Okay, till here you have two options:
1. Live with it.
2. Find a simpler way.

I have been using option 1 for the last 7 years. Until, option two showed up ...

... the usage of name aliasing for table names to make a query simpler, now this I love, simple alias each table with a 2 letter name, and use it instead of the table name:

SELECT _IB.ID, _IB.NAME AS INFO_NAME, _IBL.NAME AS LABEL_NAME, PHONE FROM infobase_labels AS _IBL, infobase_users AS _IBU, infobase AS _IB WHERE _IBL.ID=_IB.LABEL_ID and _IBU.ID=_IB.USER_ID AND _IB.ID=5;

Okay, this makes them 205 characters long.

For me the latter is much more readable, shorted and easier to write.

Tidying the SQL statement a bit:
SELECT
_IB.ID,
_IB.NAME AS INFO_NAME,
_IBL.NAME AS LABEL_NAME,
PHONE
FROM
infobase_labels AS _IBL,
infobase_users AS _IBU,
infobase AS _IB
WHERE
_IBL.ID=_IB.LABEL_ID
AND _IBU.ID=_IB.USER_ID
AND _IB.ID=5;

Okay thats it for today. Quite a long post, but I like it ; )

Tuesday, April 17, 2007

Toggle The Toggler

We all use them, different places in our code, toggling variables.
And there are many ways to achieve the same results.


My first toggle looked like that. This toggles between 1 and -1.
a *= -1;

It then evolved to:
a = a XOR 1; // or a = a ^ 1 in Java

I also started using the modulus operator:
a = (a + 1) % 2;

Then I liked the modulus operator so much, that I started using it to toggle between three, four or N values:
a = (a + 1) % 4;

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 ;)

Saturday, March 24, 2007

Advanced For Loops

There are some skills in our career that we have reached proficient enough to an extent that we think there's nothing extra to learn.

One good example is the for loop, I mean, I dont think there is anything left I need to learn about a for loop.

Well, I was wrong, daaaaaaaaaaaaaaaamn wrong, here's one extra piece of information that'll leave you scratching your head the rest of the day.

for (int i = 0; i < arrCustomers.length(); i++)
{
println(arrCustomers[i]);
}

Becomes:

for (int i = 0, len = arrCustomers.length(); i < len; i++)
{
println(arrCustomers[i]);
}

Now the code above saves your interpreter/compiler from calling the method length() each and every iteration.

Meaning, a wonderful optimization with approximately zero extra code.

Whether you like it or not:
"You ain't a for loop expert as much you thought you were!"

Saturday, March 10, 2007

Reverse Engineering Tools That Are Not.

I've been researching for the last week for a good reverse engineering tool that would simply get handed in a large C++ codebase and would automatically walk through all the classes, functions, variables and interfaces for the purpose of generating a visualization of the live flow of code.

At the end of my research I was able to find a good reverse engineering tool called Understand for C++ and Understand for Java. This was one of the best I found. I decided to use it, was impressive, but not too impressive, it still lacked lots of stuff I needed.

Looking around, I felt a bit hopeless, until I got introduced to automated document generators.

A code documentation generator would prove as the best reverse engineering tool ever. For reverse engineering purposes, I dont think I need to go any further.