Monday, November 25, 2013

Yet another InstallCert for Java, now with STARTTLS support

Java

⇓ ... now forked at GitHub

added on 2017-10-21



Many of the Java folks, who ever dealt with SSL-enabled protocols and self-made SSL certificates, know of the InstallCert tool. This simple command-line tool, published in 2006 by Andreas Sterbenz at the official Sun blog, allows obtaining SSL certificates as they are presented by the hosts we connect to, with further optional saving them to the system trust store.

Sun's blog is not with us any more, but a copy of the original InstallCert publication and code is still available from some of the users' blogs, like this one, or archives like that one. Curiously, one of the current blogs at Oracle mentions this tool, but without reference to the original author, and with a reference (currently somewhat outdated) to the mentioned user blog instead...

Well, the original Andreas' tool served faithfully to me for quite a while, but every good thing has its limitations... In particular, the original InstallCert could not deal with hosts that operate using STARTTLS technique.

The new code


Diving into STARTTLS required quite a refactoring of the original code, though the main parts of it are still in place . In particular, modular approach was taken to deal with STARTTLS implementations for different protocols, so the code does not fit in single Java file any more, but is rather packaged as an executable .jar.

It is now possible to obtain certificates from hosts that not only speak plain SSL/TLS, but also expose their certificates via STARTTLS over IMAP, POP3, SMTP and LDAP.

For new application-level protocols with STARTTLS extension to be supported, an abstract STARTTLS handler is defined as a StarttlsHandler interface. This interface needs to be implemented by every new protocol handler, and the latter is to be registered with the Starttls wrapper class. This registration needs to be hard-coded so far. But keeping in mind the small number of STARTTLS-compatible application-level protocols yet to be implemented, this should not be a problem .

The certificates collected by the program are now stored at two locations:
  • the standard jssecacerts keystore in the lib/security folder of your JRE;
  • in an extracerts keystore in your current directory; the latter may be handy in order to save collected certificates in pure form for further redistribution.
One of the new features is also the new template for collected certificates' aliases. They are now named like "host - certificate_subject" for better human readability .

Downloads


The following downloads are available:
Please feel free to use and modify. The original license looks like 3-clause BSD one.

Usage – HOW-TO


Prerequisites

  1. Download the binary distribution archive from here or here.
  2. Unzip it to a location of your choice.

Obtaining a certificate from a plain SSL/TLS or an LDAP/STARTTLS server

Run the program like this:
java -jar installcert-usn-20140115.jar host_name
or
java -jar installcert-usn-20140115.jar host_name:port
or
java -jar installcert-usn-20140115.jar host_name:port truststore_password

The default port is 443 (for HTTPS). The default truststore password is "changeit" as per JSSE convention.

Obtaining a certificate from an IMAP / POP3 / SMTP server with STARTTLS extension

In this case you will need the JavaMail library, and make sure you have it on your classpath. Please also keep in mind that it is necessary to indicate the main class explicitly in the command line if you have more than one jar.

To make things easier, two shell scripts are provided: run-with-javamail-starttls.sh for Unix and run-with-javamail-starttls.cmd for Windows. You will have to edit at least one of them first, so to reflect the actual location of the JavaMail .jar file.

General notes and final housekeeping

If the program succeeds in obtaining a certificate (or several of them), and the certificates are not known yet, it will ask you whether you wish to save them. Upon successful run the program saves the new certificate(s) to two files, as mentioned above:
  • the standard jssecacerts keystore in the lib/security folder of your JRE;
  • an extracerts keystore in your current directory; this one may be handy in order to save collected certificates in pure form for further redistribution.
The first one will be needed by your software for normal JSSE operation. The second one is a good candidate for "clean" storage of your selected certificates.

Please keep in mind that in order to have the standard jssecacerts keystore file in the lib/security folder of your JRE successfully created/modified, you will most likely need to have administrative (superuser, root) privileges.

Enjoy!



... rebuilt for Java 1.6 and fixed

added on 2014-01-15

The download links and examples were updated to reflect the new build made to be compatible with Java 1.6 as per Eric's comment. The certificate handling logic was also improved for better discrimination of new certificates vs known ones.


... now forked at GitHub

added on 2017-10-21

This code is now forked and available at Github: https://github.com/spyhunter99/installcert . The fork was created with an intention to achieve embeddability, and looks actively developed...

Monday, June 17, 2013

Look Ma, no ResourceBundle :) Step 2: Dealing with message arguments

Java
In the previous post an approach to internationalization of Java applications was suggested that does not need a ResourceBundle to do the job. Collections of localized messages may be arranged to be referenced as static class members rather than string aliases for properties in a ResourceBundle. The main benefit is gained from getting references to messages compiler verifiable, with programmer's IDE autocompletion aids available for localized messages as a bonus .

This approach was described and implemented previously at initial level, being still more of a concept than of a tool for real life applications. The main feature missing was an ability to supply arguments to localized messages, similar to MessageFormat.

Changes


Getting message arguments into the game resulted in certain refactoring, particularly in substantial separation of code from data and coining a concept of I18nHandler. Another change in concept was due to the fact that it is not possible to get a string value of an object via its toString() method if you are to supply formatting arguments. Hence, only methods like s(TArg1 arg1, TArg2 arg2) are available in these cases. Some less important change is that I18nItem no more extends HashMap but rather has more Map instances as members . And the former p(String language, String message) method for instantiating multi-language messages was refactored to lm(String localeTag, String message) in a separate class. One more notable change is that differentiation of messages by language turned into differentiation by locale language tag. And finally, the package was renamed to usn.i18n.nobundle.

New design


Data

LocalizedMessage is the basic container for localized messages. Internally it is a tuple of a locale language tag and a corresponding localized message. In case you do not care about locale-specific formatting of dates and numbers, feel free to reduce the full language tag to just the language subtag like "en". The localized message may be a mere string or a formatting pattern as per MessageFormat convention. The standard way to construct a LocalizedMessage instance is via its static factory method lm(String localeTag, String message). Normally there is no need to construct an isolated LocalizedMessage instance unless as a component of an I18nItem.

I18nItem is the basic class to represent an internationalized message. Internally is has a collection of LocalizedMessage instances for a necessary set of locales. I18nItem is not intended for direct use by applications but rather serves as the base class for an hierarchy of more specific subclasses.

Special care was taken to reduce the risk of wrong use of arguments for messages, e.g. providing arguments of wrong type or in wrong number. With this in mind the following I18nItem subclasses are offered for use:
  • I18nItem0 – the class to use for messages without arguments;
  • I18nItem1<TArg1> – a generic class to use for messages with exactly one argument;
  • I18nItem2<TArg1,TArg2> – a generic class to use for messages with exactly two arguments;
  • I18nItem2<TArg1,TArg2,TArg3> – a generic class to use for messages with exactly three arguments;
  • I18nItemAny – a class to use for messages with arbitrary number of arguments, as the last resort for cases that did not fit into previous subclasses;
A snippet for declaring some set of internationalized messages might look like this:
...
import usn.i18n.nobundle.I18nItem;

// get 'lm()' available as shorthand method without being prefixed by
// 'LocalizedMessage'
import static usn.i18n.nobundle.LocalizedMessage.lm;

...

static I18nItem0 MESSAGE_1 = new I18nItem0
    (lm ("en", "That's cool!"),
     lm ("fr", "C'est le pied!"),
     lm ("ru", "Круто!"));
static I18nItem1<Integer> MESSAGE_2 = new I18nItem1<Integer>
    (lm ("en", "I know {0,number,integer} guys seeking something" +
               " like this..."),
     lm ("fr", "Je sais que {0,number,integer} gars à la recherche" +
               " de quelque chose comme ceci..."),
     lm ("ru", "Я знаю ещё {0,number,integer} ребятишек, которые" +
               " хотели чего-то подобного..."));

Handlers

The next important topic to take care of is an approach to obtaining user language / locale preferences during run time. In anticipation of vast variety of application architectures, this topic is resolved in the most general way with the help of the I18nHandler class. This class has absorbed almost all the code that is responsible for handling of methods like s(TArg1 arg1, TArg2 arg2), and meanwhile it allows applications to achieve necessary behavior by its subclassing and overriding getDefaultLocaleTag() and most importantly getUserLocaleTags() methods. The only thing an application needs to do is:
1) subclass I18nHandler or select from its existing subclasses as necessary;
2) create an instance of the selected I18nHandler subclass; this instance will establish itself as a singleton and take care of all the rest.

I18nHandlerForSingleUser is an almost ready to use I18nHandler subclass that is intended for use by applications like desktop ones, with single user per application instance, when it is possible to define all user preferences upon application startup. You may only still wish to override the getDefaultLocaleTag() method.

Context based internationalization

There are also cases to be taken care of specially, when user preferences are conveniently available from some execution context rather than from the application directly. A standard example is a web application, where some primitive user preferences may be retrieved from a ServletRequest instance. Or maybe even better from an associated HttpSession instance. These cases are taken care of by I18nHandlerInContext<TContext> and I18nHandlerForServletRequest subclasses, to be subclassed further as necessary.

And  I18nHandlerInContext<TContext> subclasses require a special family of I18nItem subclasses, that take a TContext instance as the first argument for all their methods:

Internationalization for logging

Finally, to bring the renovated package closer to real world application needs, two more classes are added that get this internationalization technology available for logging: I15dLogger and I15dLoggerFactory. These two bridge I18nItem with SLF4J in hope that is going to be sufficient these days .

Behind the scenes


So what happens when an I18nItem instance's s() or similar method is called?

  1. The I18nHandler singleton is located.
  2. Its getUserLocaleTags() method is called. This method is expected to be overridden by a subclass to do something meaningful . An array of user preferred locale language tags is the result.
  3. A negotiation between user preferences and locales available for given I18nItem instance takes place in the handler's findBestLocaleTag(I18nItem,String[]) method. For every user's preferred locale two attempts are made: for exact match and for approximate match via language subtag. If no luck, then the system default locale is attempted. If again no luck, then plain English is attempted. And if not successful again, the first locale available for given I18nItem instance is selected.
  4. The localized message (message pattern) is retrieved from given I18nItem instance for the locale language tag selected on the previous step.
  5. Message formatting arguments are applied if required.

Downloads


Both jar and source downloads are available. And the project is now hosted at Github. Please feel free to use and modify. The license is BSD.


Usage – HOW-TO


  1. Download the .jar file .
  2. Add it to your application's class path.
  3. Make a decision on the I18nHandler subclass you need: whether it should depend on some context for obtaining user's locale preferences or should it get these preferences from the application directly; hence select an existing I18nHandler subclass or make a subclass of your own.
  4. Create an instance of the chosen I18nHandler subclass in your application; no need to care about its further fate; feel free to mark it with @SuppressWarnings ("unused").
  5. Create as many of I18nItem sublasses' instances as you need for all the messages that require internationalization.
  6. Use your messages via corresponding s(TArg1 arg1) and similar methods.
  7. Refer to the modest example on the package summary javadocs page and to API docs in general when necessary.
  8. Enjoy .

Package name


I personally feel not very comfortable having a negative word like "nobundle" in the package name. But got no better idea so far. So positive ideas on naming are welcome!

Comments welcome


Though the library is already tested in a real life application, it is probably undercooked and may contain bugs. It may also ask for improvement here and there. So any comments are welcome too!..

Saturday, February 23, 2013

Look Ma, no ResourceBundle :) Or yet another approach to i18n in Java

Java
Everyone knows the traditional way to make a Java application international: one should give every text message a symbolic name, place all the strings in various languages in a set of special resource files, and then get message strings used via their symbolic names in the prescribed manner. This is not all of course, and one furthermore has to face different locales, plurals, genders, etc. ... And ResourceBundle has always been an important part of these internationalization facilities.

This approach is well developed, and lots of tools are available to help using it, and still there is an issue about it. Java code is linked to string resources via symbolic names that are mere strings, and it is pretty easy to get them out of sync in the course of changes. And as these links are not checked by compiler, a programmer is almost certain to feel happy until a surprise at run time...

A colleague of mine has once mentioned that it would be more robust and convenient to have text resources linked to Java code via class member names. Then these links would be checked by the compiler, and a programmer could also benefit from autocompletion facilities provided by modern IDE's.

It took some time to get the idea crystallized, and here is the result. It is all about a class named I18nItem that extends HashMap (that might be any other Map) and has an overridden toString() method. Every instance of such a class would wrap one text message in different languages, indexed by language. One more task was to implement a convenient way to construct such collections as members of some class, so to allow easy referring to them from other parts of code.

The new approach in action


Let's have a look at what a standard use case might look like.

First an application would typically have I18nItem subclassed:
...
import usn.util.i18n.I18nItem;

public class AppSpecificI18nItem extends I18nItem
  {
    private static final long serialVersionUID = 1L;

    // define a simple subclass constructor to be used
    AppSpecificI18nItem (I18nItem.LanguagePair... data)
      {
        super (data);
      }

    // let's assume the default application language is going to be
    // French, so override the appropriate method
    @Override
    protected String getDefaultLanguage ()
      {
        return "fr";
      }

    // then the application needs to define the way to obtain current
    // user's language preferences as string array, most preferred
    // ones coming first
    @Override
    protected String [] getUserLanguages ()
      {
        // normally we are expected to do something more interesting
        // here...
        return super.getUserLanguages ();
      }
  } // class AppSpecificI18nItem

Next we need to construct our international string resources without using ResourceBundle – in any Java class you may find appropriate:
...
import usn.util.i18n.I18nItem;

// get 'p()' available as shorthand method without being prefixed by
// 'I18nItem'
import static usn.util.i18n.I18nItem.p;

public class MyMessages
  {
    public static I18nItem MESSAGE_1 = new AppSpecificI18nItem
        (p ("en", "That's cool!"),
         p ("fr", "C'est le pied!"),
         p ("ru", "Круто!")); 
    public static I18nItem MESSAGE_2 = new AppSpecificI18nItem
        (p ("en", "Just what we need!"),
         p ("fr", "Exactement ce qu'il nous faut!"),
         p ("ru", "То, что нужно!"));
    // ...
  } // class MyMessages

And finally we are going to use the messages we have defined:
...

// in some cases implicit conversion to String is available, and the
// overridden 'getUserLanguages()' method combined with
// 'I18nItem#toString()' takes care of everything...
System.out.println (MyMessages.MESSAGE_1);

// ... and in other cases the 's()' shorthand method is at our
// disposal...
logger.info (MyMessages.MESSAGE_2.s ());

And in every case like these your IDE is likely to assist you with right selection of the message to use...

Downloads


Both jar-with-source and demo downloads are available. Please feel free to use and modify. The license is BSD.

Acknowledgements


Special thanks to my colleague Sergey Petrov for the idea that access to a resource via some class member might be preferable against string alias .



Continued: Step 2: Dealing with message arguments

added on 2013-06-21

Friday, September 30, 2011

XSLT, entities, Java, Xalan...

Java
The Apache XML Project / Xalan-J
As already mentioned, I have been using XSLT and Xalan-J for quite a long while. It was recently that I was dealing with an HTML-related transform that used a lot of special characters.

Previously I blindly used to assume that named character references are a part of HTML, not defined for generic XML, so not available in XSLT files too. No big problem if numeric character references are available. But that time I had a good incentive to give it a better thought . After all, the very name of XML states extensibility. So what prevents us from getting named character references being defined for XSLT files too?

In fact, nothing prevents. An absolutely legal way to get them defined is to extend the document type declaration for XSLT, like this:
<?xml version="1.0" standalone="yes" ?>
<!DOCTYPE transform [
  <!ENTITY % w3centities-f PUBLIC "-//W3C//ENTITIES Combined Set//EN//XML"
      "http://www.w3.org/2003/entities/2007/w3centities-f.ent">
  %w3centities-f;
]>
<xsl:transform version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
...

With this small modification the miracle happened, and named character references stopped complaining . Everything was fine, but, as one of the Murphy's laws states, "If everything seems to be going well, you have obviously overlooked something" .

This time the pitfall was in the reference to the entities definition,
"http://www.w3.org/2003/entities/2007/w3centities-f.ent". If we tell the XSLT engine to use some external resource, it naturally has to go for it . In case we do not take necessary care, the only place to go is the Internet. Everything is going to work, but maybe slower than we might expect, and crashing if Internet connection is not available.

The standard approach to deal with this is using a catalog-based entity/URL resolver. This time unexpectedly it did not help. Nothing was wrong with the resolver and the catalog, and still the XSLT engine persistently went fetching the entities from the Internet.

The cause of the issue was found in the Xalan-J sources. Perhaps nobody before considered seriously using external entities in an XSLT file, thus no traces of using an entity resolver for an XSLT file in the code. It may be worth mentioning that those of us who might be not familiar with Xalan-J as such and just plainly use JAXP, are likely to tread on the same issue, as Xalan-J is a part of the reference JAXP implementation that is endorsed into standard JDK/JRE implementations like Oracle J2SE and OpenJDK.

The Fix


The last Xalan-J release 2.7.1 was taken as the basis for amendments. For those who need just things working, a patched Xalan-J binary build is available as xalan-2.7.1-usn-20110928.jar. Those interested in what is under the hood are welcome to have a look at the modifications.

The fix was submitted to the Xalan-J project as an attachment to issue XALANJ-2544.

Usage – HOW-TO


In case you feel like using some named character references in your XSLT file:
  1. Add appropriate entities to your XSLT transform/stylesheet, either one by one, like this:
    <?xml version="1.0" standalone="yes" ?>
    <!DOCTYPE transform [
      <!ENTITY nbsp  "&#x000A0;">
      <!ENTITY ndash "&#x02013;">
    ]>
    <xsl:transform version="1.0"
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    ...
    
    or all at once:
    ...
    <!DOCTYPE transform [
      <!ENTITY % w3centities-f PUBLIC "-//W3C//ENTITIES Combined Set//EN//XML"
          "http://www.w3.org/2003/entities/2007/w3centities-f.ent">
      %w3centities-f;
    ]>
    ...
    
  2. If you could limit yourself to a definite set of entities, or your XSLT engine is not Xalan-based, have fun
  3. If not, go ahead and download the patched Xalan-J binary as xalan-2.7.1-usn-20110928.jar.
  4. Arrange your JVM to use the patched .jar, keeping in mind that Xalan-J is an endorsed technology. One of possible approaches is to use -Djava.endorsed.dirs=path_to_the_folder_containing_the_new_jar JVM launcher option. See more on the Oracle Java Endorsed Standards Override Mechanism page.
  5. Make sure you use some XML Entity Resolver. You may wish to have a look at Apache XML Commons Resolver as a good candidate.
  6. Get yourself a catalog for your resolver, if not yet. If starting from scratch, that may be a plain text file in OASIS TR9401 format:
    PUBLIC "-//W3C//ENTITIES Combined Set//EN//XML"
           "file:///path_to_your_local_copy/w3centities-f.ent"
    SYSTEM "http://www.w3.org/2003/entities/2007/w3centities-f.ent"
           "file:///path_to_your_local_copy/w3centities-f.ent"
    
  7. Get your catalog known to the resolver, say, via the xml.catalog.files system property supplied to the JVM launcher: -Dxml.catalog.files=your_catalog_file_name_with_path.
  8. Enjoy .

Sunday, September 4, 2011

Java, Xalan, Unicode command line arguments...

Java
I have always believed on bare word that Java is Unicode-friendly by design. And I have been using Xalan-J happily for quite a long while already.

It was just recently that I ran into Unicode-related problem with Java, and that was occasionally related to Xalan-J. Strictly speaking, Xalan-J was not to blame. But that was Xalan-J Command-Line Utility who refused to do its job when handling file names with characters missing from my local system code page.

It did not take a long search to discover that the problem is known and platform-specific, at least specific for Windows. The bug is known at least since the early days when the yet-to-come Java 6 was called Mustang ("Support for Unicode in Mustang ?" , 2005). It was discussed later on JavaRanch - Unicode: cmd parameters (main args); exec parameters; filenames and on OpenJDK 'core-libs-dev' mailing list - RFE 4519026: (process) Process should support Unicode on Win NT, request for review and Unicode support in Java JRE on Windows.

The origin of the bug looks like dating back to the days when it was necessary to have Java running on both Unicode and non-Unicode (e.g. Windows 9x) platforms, so using non-Unicode system calls in Java launcher code was somehow justified. A lot of water has flown under the bridge since then, and Windows 9x is no more supported by new JVM versions... And still my quick experiment revealed that the new Java 7 comes with the same bug in its place...

The right approach would be to get the bug fixed in the Java launcher. But unfortunately it is already long since I wrote something in C/C++... So the quick-and-dirty solution happened to be a Java wrapper.

Wrapper Implementation


The first idea was to get a wrapper just for Xalan-J. But then I remembered of the other command-line utilities written in Java and came to an idea of a general-purpose command line wrapper.

It was necessary to provide possibility of handling Unicode parameters at command shell level (e.g. file names, etc). And then supply all the command line arguments to Java, bypassing the command line . The solution was found as passing the command line arguments via a temporary file, one argument per line, to be written by command shell in some flavor of Unicode, to be further read in by the Java wrapper. And there was no rich variety of convenient Unicode flavors under Windows, as the cmd tool only allows easy output in UTF-16LE using the /u switch.

The resulting wrapper is available for download and free use under Apache 2.0 license, as both source and a compiled .jar.

Other command-line tools coming to my mind besides Xalan-J, that might benefit from using with this wrapper, include: Batik, FOP, CSSToXSLFO, ...

Usage – HOW-TO


  1. Download the .jar file and save it to a location of your choice.
  2. Prepare / modify the script you use to launch your command-line tool. Say, for Xalan-J your script might contain something like:
    @cmd /u /c echo -IN >%TMP%\xalan-args.tmp
    @cmd /u /c echo %~f1 >>%TMP%\xalan-args.tmp
    @cmd /u /c echo -XSL >>%TMP%\xalan-args.tmp
    @cmd /u /c echo %~f2 >>%TMP%\xalan-args.tmp
    @cmd /u /c echo -OUT >>%TMP%\xalan-args.tmp
    @cmd /u /c echo %~f3 >>%TMP%\xalan-args.tmp
    @if not %4. == .  cmd /u /c echo %~4 >>%TMP%\xalan-args.tmp
    @if not %5. == .  cmd /u /c echo %~5 >>%TMP%\xalan-args.tmp
    ...
    java [...] usn.unicode.UnicodeLauncher org.apache.xalan.xslt.Process %TMP%\xalan-args.tmp
    
    Ensure that usn-unicode-20110903.jar is on your class path. Note that all right angle redirection characters are doubled, except the first line... Refer to the "Using batch parameters" Microsoft page for syntax like %~f1. Note also %~4 instead of %4 to remove surrounding quotes if any.
  3. Have fun

Friday, August 19, 2011

Tomcat Redirect Valve

Java
Apache Tomcat

⇓ Probably the most important part – "All we need is already here"

added on 2011-11-27

⇓ Another important news – ... now implemented as Tomcat 8 component

added on 2013-03-17

⇓ And the final news – ... now available as standard Tomcat feature

added on 2014-11-16



Background


Every mature web resource eventually realizes that it needs URL redirection.

Leaving aside manual and client-side redirection techniques, and concentrating on server-side redirection, one can see that in the Apache HTTP Server world mod_rewrite is the canonical and powerful tool to do the job.

In the Java world there is also a recognized leader for this task. That is UrlRewriteFilter, also hosted at Google Code. BTW, the front page of that project contains a good list of reasons for one to be interested in URL rewriting (redirection).

There is nothing wrong about UrlRewriteFilter. It is feature rich, and mature, and well supported, and actively developed. Nothing wrong except it is a Filter .

On one hand, being a Filter is not bad. In any case Filter is a standard concept defined by the Servlet specification, so portability across different web application containers may be considered as guaranteed.

On the other hand, having URL rewriting as part of a web application may be not always sufficient. It is not uncommon for a servlet container to host more than one web application, and thus separation of responsibilities may become a concern. Web application belongs to the developer's responsibility domain. Meanwhile the container belongs to the administrator's responsibility domain. And an administrator may have his own ideas on the requirements for redirection. So an administrator may need a separate facility for setting up server-side redirects securely, without risk of being blamed for ruining the developer's masterpiece... And speaking seriously, an administrator may occasionally wish to establish server-wide redirection policies that would be common for all the applications being hosted.

Unfortunately there is no common standard for Java web application containers that we could base upon for this task. Every container seems to have its own specifics. Narrowing our needs to Tomcat as one of the widely used containers we may come to an idea that a Valve may be the right tool. BTW, there is an noteworthy consideration of Valves vs Filters in Nicolas Fränkel's blog.

The idea of a Redirect Valve for Tomcat has been in the air for quite a while already. Curious to note, it was even on the Tomcat 4 TODO list. And deep googling for a "RedirectValve" reveals several in-house implementations of such a Valve being mentioned across various exception logs here and there. Meanwhile it looks like nobody cared to make such a tool publicly available so far...

Implementation


The first draft implementation of a Redirect Valve was suggested in 2002 by Jens Andersen. Unfortunately the implementation was incomplete and thus was not adopted for inclusion into the Tomcat project.

Bringing the existing draft to working state was not a hard job. So the final result:
  • allows configuration of a Valve instance in terms of Java regular expressions and substitutions using capturing groups;
  • for every incoming HTTP request:
    • makes an effort to reconstruct the original request URL from sparse pieces available at the valve level;
    • saves the URL as a request attribute to be used by subsequent RedirectValve instances that may follow in the pipeline;
    • matches the URL against a pre-configured regular expression;
    • in case the match succeeds, sets the response status code as SC_MOVED_PERMANENTLY, sets the response "Location" header as prescribed by a pre-configured expression using capturing groups and gets the request out of the processing pipeline;
Well, nothing fancy at all, but looks like doing the job for standard cases...

This RedirectValve implementation was submitted to the Tomcat project again. The result was the same as for the submission of 2002, the reasons now being that in the times of UrlRewriteFilter there is no need for other tools, and those willing to have a redirection Valve are free to wrap UrlRewriteFilter into a Valve by themselves...

Admitting this may be true, I still dare to offer this Valve to the public. Please feel free to use and modify. The license is Apache 2.0. Both the source and a compiled .jar are available. Still, as the code is not likely to become a part of the Tomcat project, the package name prefix is changed from org.apache to usn.apache .

Usage – HOW-TO


  1. Download the .jar file .
  2. Copy it to the lib folder of your Tomcat installation or to any other appropriate location of your choice. You may also wish to have a look at Tomcat classloader overview at MuleSoft.
  3. Register RedirectValve as a Valve with your Tomcat by adding an appropriate section to the contents of relevant <Host> element in your conf/server.xml file. Say, a task of redirecting/mapping a Tomcat web application to a virtual directory at your front-end server on the same machine might be configured like this:
    <Valve
        className="usn.apache.catalina.valves.RedirectValve"
        from="^http://([^:]+):8080/my-web-app/(.*)$"
        to="http://{1}/my-virtual-dir-at-the-front-end-server/{2}"
        />
    
    Feel free to add as many RedirectValve elements in a series as you wish.
  4. Restart Tomcat.
  5. Enjoy .



"All we need is already here"

added on 2011-08-24

Being curious about when Google gets my blog indexed and listed , I have occasionally found somewhere in the third dozen of search result pages that a "Redirect Valve" for Tomcat already exists as RewriteValve, a component of JBoss Web Server. Looks like the code does not have any dependencies on JBoss internals, and the license is LGPLv2.1 or later. The functionality looks really rich and closely resembles mod_rewrite.

I wish I knew it before starting off with my simplistic implementation... Well, one more great tool to enjoy!



... now implemented as Tomcat 8 component

added on 2013-03-17

It recently appeared that a new rewrite valve implementation is being developed as a component of Tomcat 8. The docs say that the capabilities and configuration facilities resemble Apache HTTP Server mode_rewrite closely. This is good news for all of us IMHO...



... now available as standard Tomcat feature

added on 2014-11-16

The latest and probably the final news on this topic is that as of June 2014 Tomcat 8 has reached release status, with rewrite valve as a standard component. Nothing more left to be desired...