Connecting Apache and Tomcat using mod_jk

Aim of the Task: Connect Apache Http Server 2.0.63 with Tomcat 5.5

My Apache is running at 80 and Tomcat running at 8080. I have an application running in tomcat at url http://localhost:8080/examples and after this configuration I should be able to access the application through Apache.

1) Download mod_jk

Download the mod_jk module from the following location.

Copy this file to Apache modules directory.

2) Create worker.properties

Create worker.properties in the Apache conf directory and paste the following default content in it.

# Define 1 real worker using ajp13
worker.list=worker1

# Set properties for worker1 (ajp13)
worker.worker1.type=ajp13
worker.worker1.host=localhost
worker.worker1.port=8009

3) Generate mod_jk.conf

This file is auto generated by the Tomcat. Add the following line in the server.xml of Tomcat under the <Server> root tag.

<Listener className="org.apache.jk.config.ApacheConfig" modJk="APACHE_INSTALL_DIR/modules/mod_jk-1.2.27-httpd-2.0.63.so" workersConfig="APACHE_INSTALL_DIR/conf/workers.properties" />

Note: Replace APACHE_INSTALL_DIR with the complete location of the Apache Installation Directory.

Start the tomcat server and if everything is ok then Tomcat will generate the mod_jk.conf under the directory Tomcat5.5/conf/auto.

4) Modify httpd.conf

Now open the httpd.conf file and load this conf. 

Include tomcat-5.5/conf/auto/mod_jk.conf

5) Configure Tomcat applications for Apache

Add the following lines to configure how Apache uses JK module.

# Send everything for context /examples to worker named worker1 (ajp13)
JkMount  /examples/* worker1

DONE. 
Now start Apache and access the examples url without port. Ex: http://localhost/examples

Tech Jargon - 16 Dec 2008


  • Content Delivery Network - A network of Servers delivering cached content (generally images, flash and scripts) to improve performance of a site.

  • Akamai - A leading CDN company providing services to comapnies like SONY, Yahoo and Microsoft.

  • Embryonic Connection - A TCP connection which is not completely established.

  • Terracotta - is an open source JVM-level clustering software for Java. It delivers clustering as a runtime infrastructure service, which simplifies the task of clustering a Java application immensely, by effectively clustering the JVM underneath the application, instead of clustering the application itself.

ArrayList ClassCastException

When trying to typecast Object array to the Actual array type, a runtime ClassCastException is thrown.

ArrayList lst = new ArrayList();
lst.add("String 1");
lst.add("String 2");
lst.add("String 3");

String[] strArr = (String[])lst.toArray();


Solution for this is to use the toArray method with argument.

String[] strArr = new String[0];
strArr = (String[]) lst.toArray(strArr);

Customizing Blogger Menu

I wanted my Blog Archives Menu to display the Post Title instead of Months or Years. And after some R&D I came up with the following code that prints the Post titles without any Year or Month information.


<div id="r_sidebar">
  <b:section class="rsidebar" id="rsidebar" preferred="yes" showaddelement="yes">
      <b:widget id="BlogArchive1"locked="false" title="Archive" type="BlogArchive">
        <b:includable id="interval" var="intervalData">
            <b:loop values="data:intervalData" var="i">
              <b:if cond="data:i.data"><b:include data="i.data" name="interval"/></b:if>
              <b:if cond="data:i.posts"><b:include data="i.posts" name="posts"/></b:if>
            </b:loop>
        </b:includable>
        <b:includable id="menu" var="data">
            <select expr:id="data:widget.instanceId + &quot;_ArchiveMenu&quot;">
              <option value="">
                  <data:title></data:title>
              </option>
              <b:loop values="data:data" var="i">
                  <option expr:value="data:i.url"><data:i.name></data:i.name> (<data:i.post-count></data:i.post-count>)</option>
              </b:loop>
            </select>
        </b:includable>
        <b:includable id="flat" var="data">
            <ul>
              <b:loop values="data:data" var="i">
                  <li class="archivedate"><a expr:href="data:i.url"><data:i.name></data:i.name></a> (<data:i.post-count></data:i.post-count>)
                  </li>
              </b:loop>
            </ul>
        </b:includable>
        <b:includable id="posts" var="posts">
            <ul class="posts">
              <b:loop values="data:posts" var="i">
                  <li>
                    <a expr:href="data:i.url">
                        <data:i.title></data:i.title>
                    </a>
                  </li>
              </b:loop>
            </ul>
        </b:includable>
        <b:includable id="main">
            <b:if cond="data:title">
              <h2>
                  <data:title></data:title>
              </h2>
            </b:if>
            <div class="archivos">
              <div id="ArchiveList">
                  <div expr:id="data:widget.instanceId + &quot;_ArchiveList&quot;">
                    <b:if cond="data:style == &quot;HIERARCHY&quot;">
                        <b:include data="data" name="interval"></b:include>
                    </b:if>
                    <b:if cond="data:style == &quot;FLAT&quot;">
                        <b:include data="data" name="flat"></b:include>
                    </b:if>
                    <b:if cond="data:style == &quot;MENU&quot;">
                        <b:include data="data" name="menu"></b:include>
                    </b:if>
                  </div>
              </div>
              <b:include name="quickedit"></b:include>
            </div>
        </b:includable>
      </b:widget>
  </b:section>

IE Security Warning for Mixed content

Internet Explorer gives a Security warning when a page with mixed content is loaded. This happens when a Secure page (HTTPS) contains resources(images/ javascript/ css/ iframes) that are not secure... meaning if the URL for a resource in a page is HTTP then IE gives the below warning.


"This page contains both secure and nonsecure items. Do you want to display the non-secure items?"


This warning message is very annoying if it appears for every page. The solution for this is to check the pages for non-secure urls and convert them to secure. The best is to always use relative URLs where possible.

What we also observed is that 'about:blank' url loaded in an IFrame of a secured page also gives the same warning. Solution for this is to create a blank.html in the server with a blank page and load this as the default url in the iframe.

SOA Tools or Integration Tools

I agree with David Linthicum opinion on the recent SOA Tools. Click on the link to read the complete article...

SOA Vendors Focus Too Much on Integration . . .
— We've all experienced the hype: "We're a SOA tool, and we're here to help!" However, most SOA vendors out there don’t understand the value of SOA, or even how to approach SOA. They focus on the tactical and not the strategic. Why? A tactical approach is easier for them to sell, and easier for them to understand. However, this approach means they are selling their customers short.

Time Zones in Java

Here is a complete list of Java TimeZone codes and their details.

Java Timezones Complete List

To get java.util.TimeZone instance for EST, following code can be used.


TimeZone estZone = TimeZone.getTimeZone("America/New_York");


To create a Calendar object with EST Timezone, following code can be used.


Calendar cal = GregorianCalendar.getInstance(TimeZone.getTimeZone("America/New_York"));

Image Resize

Following is sample Java code for reading an Image dimensions and to Resize image while preserving aspect ratio.


import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import javax.imageio.ImageIO;

public class ImageTest {
public static void main(String[] args) {
try {
System.out.println("Before reading...");
BufferedImage bi = readImage("D:\\temp\\itsecurity.jpg");
System.out.println("After reading...");

printImageProperties(bi);

BufferedImage scaledBufImg = scaleImageToWidth(bi, 200);

System.out.println("Writing new img...");
File modImg = new File("D:\\temp\\itsecurity_mod.jpg");
ImageIO.write(scaledBufImg, "jpeg", modImg);

} catch (Exception e) {
e.printStackTrace();
}
}

public static BufferedImage scaleImageToWidth(BufferedImage bi, int newWidth) throws Exception {
int iw = bi.getWidth();
int ih = bi.getHeight();
// Getting aspect ratio
double ratio = (double) iw / (double) ih;
// Calculate new height
int newheight = (int) (newWidth / ratio);
System.out.println("Scaling... " + newWidth + " X " + newheight);

// Get Scaled image
Image scaledImg = bi.getScaledInstance(newWidth, newheight, Image.SCALE_SMOOTH);

// Create new writable Image
BufferedImage scaledBufImg = new BufferedImage(newWidth, newheight, BufferedImage.TYPE_INT_RGB);
scaledBufImg.getGraphics().drawImage(scaledImg, 0, 0, null);
return scaledBufImg;
}

public static void printImageProperties(BufferedImage bi) throws Exception {
System.out.println("Dimensions(WxH):" + bi.getWidth() + " X " + bi.getHeight());
System.out.println("MinX:" + bi.getMinX() + ", MinY:" + bi.getMinY());
}

public static BufferedImage readImage(String path) throws Exception {
File imageFile = new File(path);
InputStream is = new FileInputStream(imageFile);
BufferedImage bi = ImageIO.read(is);
return bi;
}

public static BufferedImage readImage(byte[] bytes) throws Exception {
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
BufferedImage bi = ImageIO.read(bis);
return bi;
}
}

MITM

I 've learnt today about MITM. MITM stands for Man-in-the-Middle. This is a kind of Attack done by Hackers.

In lay mans terms... In this attack the Man in the middle of two communicating parties impersonates each to the other without them knowing. The two communicating parties think that they are talking directly to each other.

You can read more about MITM from the below links.

Excel - Calculate Working Days

I needed to calculate Number of Working dates between to dates. If I subtract two dates I get total number of days.. but I had no clue on how to remove regular weekend holidays from that.

I searched on the net and found a solution, however they do not explain me where to start with and how to implement it. I being a Java guy.. I dont know how to work with Functions and VBScripting. I had to search multiple sites to get the complete information and finally arrived at the solution.

For all those ppl out there who are like me.. and need this useful script.. Simply follow the below steps to calculate number of working days between 2 dates.

  1. Open the Excel Document where you want this Formula created.
  2. On the Tools menu, point to Macro, and then click Visual Basic Editor.
  3. On the Insert menu in the Microsoft Visual Basic window, click Module.
  4. In the Module window, type the following code for the Date function...
    Public Function CountWorkingDays(ByVal varStartDate As Variant, ByVal varEndDate As Variant)
    Dim intCounter As Integer, intTotal As Integer
    Dim dtmCurrent As Date
    intTotal = 0

    If IsEmpty(varEndDate) Or IsEmpty(varStartDate) Then
    'Do Nothing
    Else

    For intCounter = 0 To (varEndDate - varStartDate)

    dtmCurrent = (varStartDate + intCounter)

    If (Weekday(dtmCurrent) = 1) Or (Weekday(dtmCurrent) = 7) Then
    'Do Nothing

    Else

    'Add the count
    intTotal = intTotal + 1

    End If

    Next intCounter

    End If

    CountWorkingDays = intTotal

    End Function

  5. Save the Module and Close the Microsoft Visual Basic window.
  6. Now in your Worksheet if you have 2 dates in 2 Cells, say D1 and F1 then your formula would be "=CountWorkingDays(D1, F1)"

Excel - Age Formula

Formula to calculate Age using a Date.

=INT((TODAY()-Date of Birth)/365.25)

DOS Date Formatting

One of my collegue was writing a DOS script that creates directories with date and archives files. The problem she faced is with the DATE command in DOS. DATE command gives date in mm/dd/yyyy format. If we use the same string for creating directory MKDIR command creates 3 directories with mm, dd and yyyy as nested directories.

C:\>echo %DATE%
Wed 03/26/2008

After some search we finally used the Substring methods in DOS to arrive with DATE format mm-dd-yyyy.

C:\>echo %date:~4,2%-%date:~7,2%-%date:~10,4%
03-26-2008

Explanation (%date:~4,2%)
% is used to enclose the expression
:~ is used to start the substring operation
4 is start index
2 is no of characters to extract