Top posts

Posts in Webdevelopment


Controlling Tomcat using Ant scripting

Posted by Jongerius under Internet, Webdevelopment
1 Star2 Stars3 Stars4 Stars5 Stars6 Stars (No Ratings Yet)
Loading ... Loading ...

As a Java webdeveloper you are faced with a lot of different aspects of development. One is testing and debugging code, to do this you need an application server like Tomcat. One of the issues I recently encountered was the need to control various Tomcat instances with a single Ant build script. Below are some of the solutions I’ve used to manipulate Tomcat.

Note: some parts of this script rely on the ant-contrib library. Download this library and include it in the tomcat.xml with the following code:

<taskdef resource="net/sf/antcontrib/antcontrib.properties">
 <classpath>
  <pathelement location="./ant-contrib-1.0b3.jar"/>
 </classpath>
</taskdef>

Starting tomcat

Though starting tomcat may seem easy. You could just use the development IDE (like Netbeans) to start and stop Tomcat, but what this lacks is the ability to control several instances with easy shortcuts. So I defined the following Ant macrodef in a file called tomcat.xml:

<macrodef name="tomcat-start">
 <sequential>
   <trycatch>
    <try>
      <if>
       <not><http url="http://localhost"/></not>
       <then>
         <java classname="org.apache.catalina.startup.Bootstrap"
             fork="yes"
             dir="${tomcat.dir}"
             spawn="true"
             jvm="${tomcat.java.home}/bin/java">
          <jvmarg value="-Dcatalina.home=${tomcat.dir}"/>
          <jvmarg value="-Dcatalina.base=${tomcat.dir}"/>
          <jvmarg value="-Djava.io.tmpdir=${tomcat.dir}/temp"/>
          <jvmarg value="-Djava.endorsed.dirs=${tomcat.dir}/common/endorsed"/>
          <jvmarg value="-Xdebug"/>
          <jvmarg value="-Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"/>
          <classpath>
           <pathelement location="${tomcat.java.home}/lib/tools.jar"/>
           <pathelement location="${tomcat.dir}/bin/bootstrap.jar"/>
          </classpath>

          <arg line="start" />
         </java>

         <waitfor maxwait="10" maxwaitunit="second" checkevery="5000">
          <http url="http://localhost"/>
         </waitfor>
         <echo message="Tomcat started"/>
       </then>
       <else>
        <echo message="Tomcat already started..." />
       </else>
     </if>
    </try>
    <catch>
     <echo message="Unable to start tomcat"/>
    </catch>
  </trycatch>
 </sequential>
</macrodef>

This macro is really easy. First it starts of by checking if tomcat is not already running (well actually it just checks to see if there is something running on port 80). If nothing is running then tomcat is started using the java defined by the ant property tomcat.java.home. This macro also depends on some other properties that are set by a different macro, which will be a bit further on in the post. Tomcat is started by using the Bootloader class provided by the server, to make sure it loads correctly the classpath is set.

The last step in the macro is to wait for tomcat to start, this has to be done since we start tomcat in a seperate java instance (the spawn option).

Stopping Tomat

Off course you also want to be able to stop tomcat to load some new data, or an entire web-app. I use the following macro to stop Tomcat:

<macrodef name="tomcat-stop">
 <sequential>
  <trycatch>
   <try>
    <java classname="org.apache.catalina.startup.Bootstrap"
         fork="yes"
         dir="${tomcat.dir}"
         spawn="true"
         jvm="${java.home}/bin/java">
     <jvmarg value="-Dcatalina.home=${tomcat.dir}"/>
     <jvmarg value="-Dcatalina.base=${tomcat.dir}"/>
     <jvmarg value="-Djava.io.tmpdir=${tomcat.dir}/temp"/>
     <classpath>
      <pathelement location="${tomcat.java.home}/lib/tools.jar"/>
      <pathelement location="${tomcat.dir}/bin/bootstrap.jar"/>
     </classpath>

     <arg line="stop" />
    </java>

    <kill-java name="Bootstrap" />
    <echo message="Tomcat stopped" />
   </try>
   <catch>
    <echo message="Unable to stop tomcat forcing shutdown....."/>
    <kill-java name="Bootstrap" />
   </catch>
  </trycatch>
 </sequential>
</macrodef>

Just like with the starting of Tomcat I use the provided Bootloader class to instruct tomcat to stop. Again I use the java that is set in tomcat.java.home as well as some other properties loaded by another macro. Since Tomcat sometimes fails to stop gracefully (due to poorly designed webapps) you also have to kill the Java process of Tomcat. This is done with the call to kill-java.

Killing any java process

As you saw in the tomcat-stop macro I used a macro called kill-java to make sure that Tomcat is really killed and no longer running in the background. The macro is as follows:

<macrodef name="kill-java"
          description="Forcefully stop tomcat....">
 <attribute name="name"/>
 <sequential>
  <!-- Execute the jps and check for any Java process with the provided @{name} attribute -->
  <exec executable="${tomcat.java.home}/bin/jps" output="pid.out.file" />
  <!-- Load in the name / pid file and strip all information except the PID -->
  <loadfile srcfile="pid.out.file" property="pid.out">
   <filterchain>
     <linecontains>
      <contains value="@{name}"/>
     </linecontains>
    <tokenfilter>
    <deletecharacters chars="@{name}"/>
    <trim/>
    <ignoreblank/>
    </tokenfilter>
    <striplinebreaks/>
   </filterchain>
  </loadfile>
  <echo message="Killing java process with pid ${pid.out}"/>
  <!-- Kill the process, warning this only Works on Windows -->
  <exec spawn="true" executable="taskkill">
   <arg line="/PID ${pid.out}" />
   <arg line="/F" />
  </exec>
  <delete file="pid.out.file" />
 </sequential>
</macrodef>

This macro is really simple and relies on the jps application provided by Java. This application returns a list of all running processes with name and process id (PID). All we need to do is get the line containing the process name provided and strip everything except the PID.

Please note: the task killing the proces is designed for Windows, you could change this with kill in Linux.

Rounding it up

Though you now have all you need to manipulate tomcat there is one last macro that we are tegenkant upon. That is the initializer of the various Tomcat properties. I use the following macro:

<macrodef name="tomcat-init">
 <attribute name="from"/>
 <sequential>
  <property name="tomcat.dir" value="${tomcat.@{from}.dir}"/>
  <property name="tomcat.server" value="${tomcat.@{from}.server}"/>
  <property name="tomcat.port" value="${tomcat.@{from}.port}" />
  <property name="j2ee.server.type" value="${tomcat.server}" />
  <taskdef name="webapp-stop"
          classname="org.apache.catalina.ant.StopTask"
          classpath="${tomcat.dir}/server/lib/catalina-ant.jar"/>
  <taskdef name="webapp-start"
           classname="org.apache.catalina.ant.StartTask"
           classpath="${tomcat.dir}/server/lib/catalina-ant.jar"/>
 </sequential>
</macrodef>

This little macro will initialize tomcat for a specific environment (for exemple DEV). Of course none of this works without the loading of some preset properties in a property file tomcat.properties. Which contains the following data:

tomcat.java.home=C:/jdk1.5.0_22_32b

tomcat.DEV.dir=d:/jakarta/tomcat5.0
tomcat.DEV.server=tomcat55-DEV
tomcat.DEV.port=8000

tomcat.MAIN.dir=d:/jakarta/tomcat5.0-MAIN
tomcat.MAIN.server=tomcat55-MAIN
tomcat.MAIN.port=8000

To load the property file just include the following instruction in the build script:

<property file="./tomcat.properties" />

Apache 2 and SSL trouble

Posted by Jongerius under Development, Webdevelopment
1 Star2 Stars3 Stars4 Stars5 Stars6 Stars (No Ratings Yet)
Loading ... Loading ...

I’ve been playing around with a couple of corporate website’s lately. One of the things I’ve been trying to work out is creating more security for the management and webmail systems for my websites. This is also were I ran into some difficulty.

I have my own root certificate for all of my websites, so that I can sign my own certificates and use them all over the place. I only have to ask my clients to accept the root certificate and all is fine. This seems to work fine except when I tried to load them into Apache. Here’s what my problem is and was. I have multiple domains hosted on the same virtual server. Which basically means a lot of websites running under one IP-address.

In this setup I have several domains I want to add a SSL variant of. For example webmail.domain.com as well as admin.domain.com. And this is where it became problematic.

I configured this without any problems in apache. Setup a virtual host listening to port 443 and setup the listener instruction in apache. But for some reason all of my secure domains ended up using the same certificate. Which off course causes a lot of security warnings for the browsers :( . And a lot of people are having the same issue, just read the thread on howtoforge.com.

As it turns out Apache is only able to host one secure virtual host per IP-address and port combination. Which is kinda obvious since Apache cannot read the domain name until it has decrypted the SSL information, something which it cannot do until the SSL handshake with the client has been done. Hence that only one set of certificates is allowed per IP and port.

Long story short I ended up setting the websites up with different ports since I don’t have multiple IP-addresses to host the websites on.


Some unexpected down-time

Posted by Jongerius under General Rant, Webdevelopment
1 Star2 Stars3 Stars4 Stars5 Stars6 Stars (No Ratings Yet)
Loading ... Loading ...

As you may have been able to notice over the past week or so my websites and those I am hosting for clients had some down-time last week. As such I’ve not been doing much other then trying to figure out what is going on, and haven’t had to much time to write something new.

Unfortunattely for me and my clients the problem seems to be with the provider I have to rent my servers. After some digging I found out even their own servers where unreachable. (Could not even setup a SSH connection to my servers).

It seems to be fixed at the moment, so keep praying that it stays that way ;) .


PHP catching all function calls

Posted by Jongerius under Development, Webdevelopment
1 Star2 Stars3 Stars4 Stars5 Stars6 Stars (No Ratings Yet)
Loading ... Loading ...

Recently I came accross something really fancy that was introduced in PHP 5. It is appearantly possible for any class to catch all functions that are called on a class. So one function would catch $obj->callOne() as well as $obj->callTwo().

So why is this a nice feature to have, well because I am a very lazy progammer and this feature allows me to magically generate getters and setters. To do this I have the following setting for each class:

  1. The constructor method __construct initializes an array containing the names of all variables that we want to store. We also create a second array to save the values in for the variables.
  2. We implement the __call function to catch all functions being called on the object, which is currently still undocumented by PHP.net

So a basic class would look something similar to this:

class MyObject {
   private $my_vars = array();
   private $allowed_vars;

   function __construct() {
      $this->allowed_vars = array('var1', 'var2', 'var3');
   }

   function  __calls($function_name, $arguments) {
      $_variablename = substr($function_name, 3);
      if (array_search($_variablename, $this->allowed_vars) !== FALSE) {
         if (stripos($function_name, 'get') == 0 && stripos($function_name, 'get') !== FALSE) {
            return $this->my_vars[$_variablename];
         } else if (stripos($function_name, 'set') == 0 && stripos($function_name, 'set') !== FALSE) {
            $this->my_vars[$_variablename] = $arguments[0];
         }
      }
      else throw new Exception('Unkown function called on '. __CLASS__);
  }
}

Which does exactly that which I described above. Mind you it’s just a very basic example but it shows the power of a catch all function.


Using Ajax in your website

Posted by Jongerius under Development, Internet, Webdevelopment
1 Star2 Stars3 Stars4 Stars5 Stars6 Stars (No Ratings Yet)
Loading ... Loading ...

I noticed something when I went through the posts I created on this blog. I have been raving for and against Ajax in several posts. Ranging from whether or not you should include Ajax for usability, how to work with Ajax in combination with forms and my personal favorite if you should use Ajax at all. Please keep in mind that this last post is really old already and probably a bit outdated.

Looking through all of these posts I noticed that even though I talked quite some bit about Ajax I never actually gave any examples of how to implement it. So today I will correct this mistake ;)

A simplified explanation of what Ajax is

It’s probably best to first give a very brief explanation of what Ajax is and how you could use it to create more dynamic and user interactive web pages. So what is Ajax actually. Well in a nutshell it’s a JavaScript implementation of communicating between the browser and the web server without having to reload an Internet page.

You can create a good impression of how it works by thinking about this as follows. In an traditional website each action a user takes will cause the browser to call a page on the web server. The web server then generates the full HTML for that page and returns it to the browser. This is visible to the user as the page they are looking at will ‘refresh’. Ajax is a technique to call the web server without reloading a page or redirecting to a new page. Hence fetching new content to an already displayed page in the browser. See the image below for a graphical overview of the communication between the browser and the web server during a typical Ajax call.

Ajax Interaction diagram

This gives you the change to greatly enhance your existing website with new features. Loading in content area’s on the fly. Submitting forms to the server without having to redirect the user, you name it and you can do it with Ajax. There are some limitations, but most of those are covered in my initial articles on this blog.

Multiple browsers, multiple problems

One of the first things I should probably try and explain is that every browser seems to have a different way of implementing the Ajax object. On its own this is not a big issue, but you need to keep track of this fact when you build some form of Ajax functionality in your website.

So creating the Ajax object needed to perform these calls to the web site has to be done with some try and catch work. Below is an example of how to create the Ajax object, supported by most of the popular browsers. In the example we first try and create the Ajax object for the Internet Explorer, which uses ActiveX objects.

try
{
// try to allocate the ActiveX object used by Internet Explorer
this.xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
this.xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
this.xmlHttp = false;
}
}

if (!this.xmlHttp &amp;&amp; typeof XMLHttpRequest!='undefined')
{
// fallback for Firefox and other Mozilla based clients
this.xmlHttp = new XMLHttpRequest();
}

After executing this code (keep in mind it is JavaScript so put it in a script block in the HTML) you should have the Ajax object available in this.xmlHttp. It may be useful to know a little more about the object functions before continuing the example. The Ajax object has the following functions:

  • .status,
    returns the current status of the page. This is after the result is returned from the web server. (Status 200 is good)
  • .responseText,
    contains the result that was sent by the webserver after the url was called
  • .open(protocol, url, asynchronized),
    will open the connection to the web server and start the call
  • .onreadystatechange,
    the event that gets triggered by the Ajax object during the call to the webserver. This will be called multiple times, especially in Internet Explorer. (Possible status: 2 = busy, 4 = done)
  • .send,
    send the request to the server and wait for the result (or not if asynchronized call was selected)

A basic call to the webserver

After initializing the Ajax object you can perform any call to the webserver you’d like. The example below will show you how to open an web page and display the result into a message box. What the content is that is returned is not relevant for the functioning of the example.

this.xmlHttp.open('GET', 'http://www.example.com/page.html', false);
this.xmlHttp.onreadystatechange = function()
{
if (self.xmlHttp.readyState == 4)
{
alert(self.xmlHttp.responseText);
}
}
this.xmlHttp.send(null);

As you can see this is a very basic example, but it does show exactly how to use the Ajax technology. You can apply this logic for loading in new content on the fly, or just preloading some stuff.

Next Page »