Enabling SSL on a Tomcat “devl” machine (Windows)

These are the steps involved to enable SSL on Tomcat on developer machine for test purposes.

1. Create a certificate key store

Run this command in the command prompt –

[sourcecode language=”bash”]

%JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSA

[/sourcecode]

An interactive console based program is launched –

  1. When asked for a password, provide one and confirm the same.
  2. The program then prompts for your first name and last name; here, enter the name of the host machine. eg. testserver1. (Do NO T enter the IP of the host here.)
  3. Provide proper values for further prompts like Company Name, State etc.
  4. Press enter when prompted for a tomcat password.

This will create a key repository file .keystore in the home folder of the (windows) user.

2. Edit the Server.xml (in [catalina-home]/conf)

1. Uncomment the node <Connector port=”8443″……/>.

2. Edit/Add the following attributes (colored) to the above node –

protocol=”org.apache.coyote.http11.Http11Protocol” SSLEnabled=”true” keystoreFile=”${user.home}/.keystore” keystorePass=”[the-password-you-provided]” maxThreads=”150″ scheme=”https” secure=”true” clientAuth=”false” sslProtocol=”TLS” />

3. Start tomcat. Run an application using  URL “http: //[ hostname]:8443/[appname]”.

4. The browser probably shows an “Untrusted Certificate” warning – Ignore and proceed.

Following are additional steps required to enable java based HTTP-clients  talk to this newly created secured server .

3. Install the Host Certificate as Trusted

  1. Download and unzip this file to desktop.
  2. In the folder InstallCert run this in command prompt – [sourcecode language=”bash”] java -cp . InstallCert [above-host-name]:8443 [/sourcecode]
  3. When done, the program creates a file “jssecacerts” in the same folder. Copy this file to folder (java-home)/jre/lib/security.

Done !

You should now  be able to run services requiring sercured connection on this host like CAS server and clients.

Installing PHP5.3.3 on Apache 2.2x (Windows)

List of steps involved in getting PHP5 to work with a pre-installed Apache server on Windows.

  1. Download the file “php-5.3.3-Win32-VC6-x86.zip” from “http://windows.php.net/download/”
  2. Extract contents of this file to C:/PHP/
  3. Copy C:/PHP/php.ini.development to a new file  php.ini in the same folder
  4. In the httpd.conf file of Apache, add the following lines after the LoadModule block.
    [sourcecode language=”bash”]
    LoadModule php5_module "C:/PHP/php5apache2_2.dll"
    AddHandler application/x-httpd-php .php<
    # configure the path to php.ini
    PHPIniDir "C:/PHP"
    [/sourcecode]
  5. Restart Apache.

Thats it ! PHP pages should now be processed and displayed by apache. To test, create a file PHPTest.php in folder “[Apache-root]/htdocs/” with following content.


[sourcecode language=”php”]
<?php
phpinfo();
?>;
[/sourcecode]

In the browser open the URL “http://localhost/PHPTest.php”. This should now display the PHP engine details.

Now, as required the document root, extensions folder, available extension etc for PHP can be configured in the file C:/PHP/php.ini.

Apache mod_rewrite: How to use a Java RewriteMap?

This example shows how to use a Java program as a RewriteMap in Apache Httpd server.

Prerequisites on the server box:

  1. Apache HTTPD 2.2x.
  2. JDK/JRE.

What does the program do ?

Allows all URLs of form “*/secure/” to go ahead, and reject others.

Java Program

Java program for the above is pretty simple – like the one displayed below.

[sourcecode language=”java”]

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class SimpleApacheMap
{
static String SECURED_URL = "/secured/";
static String SECUREDASSETS_FOLDER = "/assets/";
static String REJECT = "/rejected/";
BufferedReader inputReader;
OutputStreamWriter outputWriter;
boolean processed;

private void startMapper() throws IOException
{
String inputToken;
inputReader = new BufferedReader( new InputStreamReader(System.in));
outputWriter = new OutputStreamWriter(System.out);
while(true)
{
inputToken = inputReader.readLine();
if(inputToken!=null && inputToken.indexOf(SECURED_URL)>0)
{
outputWriter.write(inputToken.replace(SECURED_URL, SECUREDASSETS_FOLDER));
}else
{
outputWriter.write(REJECT);
}
outputWriter.flush();
}
}

public static void main(String s[]) throws Exception
{
new SimpleApacheMap().startMapper();
}
}

[/sourcecode]

Jar file

Compile this program, create a jar file (java-apache-map.jar) from the compiled classes. (creating a jar simplifies the call to this program, especially so when complex mapping involving more dependency classes are done.) Add a manifest file pointing to the main class to make this jar runnable.

Paste this jar file in the “bin” folder in Apache root folder.

Create a file “map.sub.lock” in the bin folder. We will provide this file to Apache for using as a synchronization lock on our map program.

Edits in Httpd.conf

In the file httpd.conf, add the following lines –

[sourcecode language=”bash”]

#Define rewriteMap program and set a synchronization lock
RewriteMap forwardURL "prg:\"C:/Program Files/Java/jdk1.6.0_01/bin/java.exe\" -jar \"C:/Program Files/Apache Software Foundation/Apache2.2/bin/java-apache-map.jar\""
RewriteLock bin/map.sub.lock

[/sourcecode]

Note that we have to give the complete path to java.exe as well as the jar file having the map program. “forwardURL” is the name of our map so created.

Now append these line httpd.conf:

[sourcecode language=”bash”]

# Rewrite according to map output.
RewriteRule (.*) ${forwardURL:%1} [C]
RewriteRule (.*)/rejected/(.*) – [F]

[/sourcecode]

The first line tells apache to replace all URLs with the value returned from the map. (the whole URL is passed to the map). The [C] flag makes sure that the next rewrite rule is executed too.
The second rewrite rule checks if the map had returned a URL having the text “/rejected/” in between- in which case a “Forbidden” message is sent back to the browser.

Restart Apache – The rewrites should be working fine now.

Additional tips on using a java map program –

  1. Any debug message can be printed to System.err stream. These messages would appear in [Apache-root]/logs/errors.log.
  2. The program is started as a daemon on server startup, and executes till shutdown/any critical error.
  3. As the program has life time of the server, instance variables defined in the map program has application life time too.
  4. Complex rewrite rules involving multiple requests can be easily implemented by giving a different prefix (to the key passed to the map) for each type of requests.

Eg. A login request could pass a key like login_<sessionId>, a logout request would similarly pass logout_<seesionId>, and the mapper program can update a database (using JDBC) the time taken by each session, or count active sessions, or act as an application-context etc etc.

Apache RewriteRule : Set a session cookie on localhost

Here are the 2  (often left out) requirements to set a cookie using httpd’s rewrite rule (mod_rewrite), while working on localhost:

  1. Use the IP 127.0.0.1 instead of localhost/machine-name as the domain; e.g. [CO=someCookie:someValue:127.0.0.1:2:/], which says create a cookie “someCookie” with value “someValue” for the domain “127.0.0.1” having a life time of 2 mins, for any path in the domain (path=/). (Obviously you will have to run the application with this value in the URL)
  2. To make a session cookie, limit the flag statement to just three attributes: name, value and domain. e.g [CO=someCookie:someValue:127.0.0.1] – Any further settings, apache writes an” expires” attribute for the set-cookie header, which makes the cookie a persistent one (not really persistent, as the expires value set is the current server time – so you don’t even get to see your cookie!)

Gyroscopic Precession – the intuitive explanation

If you have done a course in rotational dynamics you would remember the *procedure* involved in solving problems on gyroscopic precession. Don’t remember ? Ok. I’ll give you a refresher.

We use law of gyro-dynamics to solve problems like this – If a vertically upward force is applied to the nose of this propelled-airplane, which direction would it actually move ?

rotations1

 

For solving this we were supposed to consider three aspects of rotational motion – the direction of angular momentum of propeller, the direction of external torque and, the direction of precessional torque. (Mind you, all these vector directions are perpendicular to their respective planes ).  Ok done. Now raise the right hand, fit these three vectors into your thumb, middle finger and pointer finger. The order to fit in these is… Hey Stop ! there has to be a much simpler and more intuitive way to solve this !

And there is. I had a different way to attack this problem which could solve it almost as fast as I read the question.

The secret is to think in terms of forces involved before plunging into rotational dynamics.

Lets see how.

Figure below shows the forces acting at the center of rotation when the airplane move in a straight line[1]. (When looked from the pilot’s seat )

rot1

Let v1 and v2 be the relative velocities of the mutually opposite masses of the propeller. When the center of rotation is stable, v1 = v2. There for the centrifugal forces they exert at centers F1 and F2 are also equal[2]. That is, the centrifugal forces of opposite ends of the propeller mass cancels off each other, exerting no resultant force at the center.

Now think of the force acting vertically upward at the center of rotation (which can be assumed to be at the nose of the airplane). This would cause the center to move upward. Lets see what happens when such a movement is initiated.

rot2

The relative velocity of mass at left w.r.t center has now reduced by v0. Also the relative velocity of mass at right has increased by the same magnitude.

Now v2 is clearly greater than v1. Consequently, F2 is greater than F1.

So what happens ? The resultant force moves the nose to the right.

Yes the airplane yaws to the right !

This approach can instantly solve questions on  direction of motion of gyroscopes !

[1] – The thrust forward is not considered, for clarity. It doesn’t interfere anyway.

[2] – Its assumed that propeller has uniform mass distribution for points equidistant from the center, which is ideally correct.

Article also available at my previous blog – “http://mindarticulated.wordpress.com/2009/08/01/gyroscopic-precession-the-simple-explanation/”

Speed of Light, Parallel Universes and the “Try-Catch-Block”

The possibility of parallel universes hinted by modern physics is always fascinating to think about.

Needless to say, it is difficult to imagine a “parallel” universe ( If our universe has no limits, then how can there be another space-time in parallel ! )

We need an approach to put all these together in such a way that our analytical mind can make a meaning of such possibilities.

Now what if we keep aside the concept of space-time framework for some time, and bring in our very famous exception-handling methodology of java, we see that in concept, different universes can exist in parallel.
Let us have a look at the code snippet below.

if(entity.level == 3)
{
  try
  {
    //(this is universe at 3rd higher level )
    // space-time based on C, the limiting speed for events in this universe
    //(like : E = m C^2)

    // — other rules
    if(entity.level == 2)
    {
      try
      {
        //(universe at 2nd higher level)
        // space-time based on Z,the limiting speed for events in this universe
        //like : (E = m Z^2)
        //– other rules
        if(entity.level == 1)
        {
          try
          {
            //(Universe at our level)
            // space-time rules based on c, speed of light.
            // like E = mc^2)
            // ... other rules of physics.
          }catch(SpeedOfLocalEventAchievedException) {
            throw new ExceptionalEntityDetected(e);
          } catch(InsideSingularityException) {
            throw new EntityAtTransit(e);
          }
	    }

/*—- code for higher universes — */

Also such an approach can explain what happens to an object when it achieves speed faster than the speed of light (which is the limiting speed of our universe). Such a case is clearly an exception (as it doest not go well with physical laws at our level) the handling for which may exist at a higher level universe. So if one imagines that a traveler who moves at a speed higher than speed of light reaches another universe, well, may be he is very much correct ! :)

Einstien writing this java code (humour)
Einstien himself explaining this java code 😉

Interestingly, Hindu mythology also speaks of different universes with different time-spans for the entities in each of them (like
Manushya Loka, Pitru Loka, Deva Loka, Brahma Loka and the Timeless Vishnu Loka) .  Well, may be the ancient sages knew how to move between the “divine code blocks”…

What if each of us are inside one of these try blocks, following these rules in a separate thread called our life ? what if at some point of time, we will move over to the next universe ?

Discovering the Physics code…

We all hope that one day physics would have an explanation for all that we see around us, all that exists, and all that would ever exist. But is the current scope of physics large enough to provide a unified law which can define everything ? Should something very important and very prevalent, but not currently included in observations, be actually be considered as an integral part of physics ?

Newton’s laws, Laws of electricity and electromagnetism, laws of relativity, uncertainty principle – all of them were established as true after precise measurements of the observed phenomena matched closely with the predictions of a corresponding law. But is physics as a science all about externally observed phenomena ? Should we agree that the only purpose of physics as a science is to make a closely matching mathematical model of the universe ? Isn’t physics, at its best, supposed to give us answer to everything that exists ?

Let’s start our “thought journey” on this with the following story.

The Story of Puttu

Puttu is an extra terrestrial being sent from his planet Puttalu to earth. The scientists of Puttalu, which is the only planet that supports life in Puttu’s universe, have sent him here to experience and find out the physical laws that act on our universe.

Puttu had arrived here on a winter night at Yakutsk, Russia. It was a cold night and nobody got out of their cars in the highways. Puttu sat on top of one of the tallest buildings in the city. He curiously watched the movement of cars, trains (and one bird too) for hours and wrote the following physical rules –

  1. Moving bodies keep themselves along the right side of the path of movement (In Russia its Left-hand drive)
  2. Moving bodies stop when a particular source of electromagnetic waves emits red light.
  3. A body at halt moves when encountered with a green light from the same source.
  4. Moving body of type A(cars) moves in perpendicular to Moving body of type B (train). There should be a perpendicular force field E, generated when Type A bodies move, which attracts and moves a Type B body.
  5. Body C (bird) should have absolutely no charge and no mass, and can move around without being effected by E produced by the light source.

Puttu suddenly derived some formula’s to find out the speed and position of a body based on these laws. Obviously he also included a law of uncertainty – which says it is impossible to precisely predict the speed and position of these bodies.

Puttu was happy that he found 5 basic rules of material physics on this newly discovered universe. He went back to his world to pass on these laws and initiate further research.

No Intelligence – No Laws !

The above story, which is far from reality has been given as a resembling example of how we are limiting the study of modern physics to only what can be measured. Our hero Puttu may be right in whatever laws he deduced on the movement of cars in a city – what he did not notice is the mutual understanding or agreement between conscious and intelligent human beings which kept this system running.

Now we may ask these questions

  1. Puttu should anyway know that bodies don’t simply move according to rules. Somebody who is intelligent has to control them !”
  2. It’s obvious that intelligence/conscience is required to understand a rule, agree to abide by it and then to follow it.

Yes that’s the point – Any rule/law is the result of an intelligent thought/decision. Lets move ahead and see different forms of intelligence.

Recorded Intelligence

What is recorded intelligence ? Take the case of a computer – it understands many complex rules involved in solving a real world problem. We know that a computer is not intelligent by itself. So when a computer is not aware of itself, how can it run understand and execute highly complicated set of rules ?

We know that a computer simply records and replays the thoughts of an intelligent source – the programmer. Hence the rules are made and understood by an “originally intelligent” being; these rules are then converted into digital form so that each time a computer goes through these digital words, the original intelligence of the programmer is applied repeatedly. The process is as simple as a farmer directing water through channels to the dry areas in his crop field. Though water reaches to dry areas by itself, the idea and intelligence of taking water to the desired location is still from an intelligent source. Even a mouse trap is an example of recorded intelligence – an example of mechanical programming.

Recorded Intelligence and the Recording Medium

In all the examples of recorded intelligence, we also see that there exists a corresponding recording medium too. Digital circuits form the recording medium of computer programs. Earth form the recording medium for irrigation canals. Spring, door, hinges and links form the recording medium of a mouse-trap. Also different levels of recorded intelligence are stored “one based on the other” on corresponding levels of recording media. The best example for this is a computer itself

  1. Electricity and semiconductors are the recording medium in processors and related circuits – which records intelligence in the form of digital logic.
  2. RAM of the computer holds the intelligence of information-flow and operations within a computer. This intelligence is built over the intelligence of digital logic.
  3. Permanent Storage of a computer stores intelligence of human written programming language. This intelligence is built over the intelligence of information flow and operations of the computer.

Recorded Intelligence v/s Original Intelligence and The self consciousness

We have now seen that rules are inseparable from intelligence – Any instance/scenario where a particular rule is being followed should definitely hint some intelligence which created it. Also we see that rules can be implemented either by the original source of intelligence (like a human being) or from a recorded replay of an intelligent process (as in mechanical/electronic/digital programming). But how to differentiate between recorded intelligence and an original source of intelligence ? To make out the difference is not simple at all ! Here is where the self consciousness comes in ! Its seems that an original source of intelligence will be conscious of its existence ! Therefore we conclude that consciousness is the primary source of intelligence – Or intelligence is the property of consciousness. (For ease expression, we will refer self consciousness as – “The Self”[0].)

Self consciousness v/s Life

The presence of self consciousness – is related to something that is very important – but not currently included in any physics book – the Life ! Wait but most of the properties we assign to “living things” are actually recorded intelligence only – as growth, reproduction and movement are almost completely biological[1] programming. Some “living things” like latent viruses may be considered as purely biological programs.  Even different behaviours of human beings are results of biological/hormone programming as encoded in the DNA. This hints at existence of consciousness ( or “The Self”) as an unrelated entity with uniform characteristic in all conscious beings – the feeling of “I exist[2].

Laws of Physics and Consciousness

As with any law, the laws of physics should definitely have an associated intelligence with it. The uniformity and regularity of physical laws hints that they are forms of recorded intelligence. This recorded intelligence should have definitely flowed from the original source of intelligence – The Self. Everything that has an order or follows a set of rules should be set – to begin with – by the Self itself. As we know that there are multiple levels of recorded intelligence – there should be a fundamental recording medium too where the self recorded the primary physical laws.
More study on the existence and reach of “The Self” as an entity, and the properties/information of the fundamental recording medium are probably the two questions that research on “complete physics” would ultimately reach to.

———————————————————

[0] If context like memory, body etc are systematically negated, the observer/executor seems to be one and the same in all conscious beings.

[1] Its not wrong to say that when physics get complicated, we call it chemistry – and Biology is in a way highly complicated chemistry.
[2] Even during sleep, when the time sense is lost – “I” still exits.