Programming Secure FTP in Java

Often server applications need to upload or download files using FTP.  But in this age of increasing security awareness vendors are now asking this be done using SFTP (Secure FTP).

Fortunately this is not difficult using the JSch (Java Secure Channel) library.  The downloadable JSch archive includes numerous examples.  I used the to implement SFTP for my server application.

Starting a connection to an SFTP server using JSch is somewhat simple.

JSch jsch = new JSch();

// start session
session = jsch.getSession(username, host);

// specify our own user info to accept secure connection to FTP server
UserInfo ui = new MyUserInfo(host);

// set password

// connect

// get SFTP channel
Channel channel = session.openChannel("sftp");
schannel = (ChannelSftp) channel;

The trick is getting past confirmation of the authenticity of the host. I do this my creating my own UserInfo implementation, MyUserInfo, which knows about the host I am connecting to. The only method I implement is the promptYesNo method which simply checks if the message is asking about the host I want to connect to.

protected MyUserInfo(final String pKnownHost) {
    this.mKnownHost = pKnownHost;

public boolean promptYesNo(final String pMessage) {
    // message looks like this "The authenticity of host '' can't be established..."
    final int start = pMessage.indexOf("'") + 1;
    final int end = pMessage.indexOf("'", start);
    final String host = pMessage.substring(start, end);

    // is the host a known host?
    return this.mKnownHost.equals(host);

Now uploading is trivial.

schannel.put(src, dest);

For further reading please see Java: What is the best way to SFTP a file from a server.

URLEncoder.encode is Deprecated So What Do I Use for Encoding?

The Surface on Flickr

(Photo: The Surface by Daniel*1977)

URLEncoder.encode(String url) is deprecated.  Java wants you to use URLEncoder.encode(String url, String enc).  But what do you put for the encoding parameter?  I always forget which is the whole point of this post. 🙂

URLEncoder.encode(url, "UTF-8");

Also on Windows if you want you can do:

URLEncoder.encode(url, "Cp1252");

For further reading please see default encoding of a jvm.

Using ResourceBundle and MessageFormat for Error Messages

When generating error messages, two Java utility classes, ResourceBundle and MessageFormat, are extremely practical and powerful.  From the ResourceBundle JavaDoc:

Resource bundles contain locale-specific objects. When your program needs a locale-specific resource, a String for example, your program can load it from the resource bundle that is appropriate for the current user’s locale. In this way, you can write program code that is largely independent of the user’s locale isolating most, if not all, of the locale-specific information in resource bundles.

This allows you to write programs that can:

  • be easily localized, or translated, into different languages
  • handle multiple locales at once
  • be easily modified later to support even more locales

And from the MessageFormat JavaDoc:

MessageFormat provides a means to produce concatenated messages in a language-neutral way. Use this to construct messages displayed for end users.

MessageFormat takes a set of objects, formats them, then inserts the formatted strings into the pattern at the appropriate places.

This is an example of an error message resource bundle,

userAlreadyExists=A user already exists with the name {0}.
passwordInvalid=Please enter a valid password.

This is an example of how you would use this resource bundle.

protected static final ResourceBundle resourceBundle =

public boolean handleLogin(DynamoHttpServletRequest pReq, DynamoHttpServletResponse pRes) {


  // user already exists
  String errMsg1 = resourceBundle.getString("userAlreadyExists");
  errMsg1 = MessageFormat.format(errMsg1, userName);


  // password invalid
  String errMsg2 = resourceBundle.getString("passwordInvalid");


Enums in Java

Slide-together : now with cards on Flickr
(Photo: Slide-together : now with cards by fdecomite)

Enums are highly useful data types introduced in Java SE 5.0.  Though I love using them I often forget the exact syntax so this post is to remind me later how to use it.

public enum Example {

// create one using its name
Example myExample = Example.valueOf(“bar”.toUpperCase());

// if statement
if (myExample == Example.FOO) System.out.println(“FOO!”);

// switch statement
switch (myExample) {
  case FOO: System.out.println(“FOO!”);
  case BAR: System.out.println(“BAR!”);

// output as String using name

For further reading please see Java’s Enums guide and Enum Types (The Java™ Tutorials > Learning the Java Language > Classes and Objects).

Unit Test for Threaded Logging

Brian Ploetz sent me this great unit test for threaded logging.  In it we are trying to find if a deadlock occurs.


import junit.framework.TestCase;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Appender;
import org.apache.log4j.Logger;

 * Unit test for the ThrottlingFilter in a multi-threaded environment
public class ThrottlingFilterThreadUTest extends TestCase {

  private static final Log logger = LogFactory.getLog(ThrottlingFilterThreadUTest.class);

  private static ThreadMXBean threadMXBean;

  protected void setUp() throws Exception {
    threadMXBean = ManagementFactory.getThreadMXBean();"Thread contention monitoring supported: "
        + threadMXBean.isThreadContentionMonitoringSupported());"Thread contention monitoring enabled: "
        + threadMXBean.isThreadContentionMonitoringEnabled());
    threadMXBean.setThreadContentionMonitoringEnabled(true);"Thread contention monitoring enabled: "
        + threadMXBean.isThreadContentionMonitoringEnabled());

   * Tests multiple threads using the same filter instance at the same time
  public void testThreads() {
    Logger rootLogger = Logger.getRootLogger();
    Appender fileAppender = rootLogger.getAppender("FILE");
    ThrottlingFilter throttlingFilter = (ThrottlingFilter) fileAppender.getFilter();

    ThreadGroup infoThreadGroup = new ThreadGroup("info-group");
    ThreadGroup errorThreadGroup = new ThreadGroup("error-group");
    Thread errorThread1 = new ErrorThread(errorThreadGroup, "error-thread-1");
    Thread infoThread1 = new InfoThread(infoThreadGroup, "info-thread-1");
    Thread errorThread2 = new ErrorThread(errorThreadGroup, "error-thread-2");
    Thread infoThread2 = new InfoThread(infoThreadGroup, "info-thread-2");

    while (true) {
      ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds());
      for (int i = 0; i < threadInfos.length; i++) {
        ThreadInfo threadInfo = threadInfos[i];
        if (threadInfo != null && threadInfo.getThreadState() == Thread.State.BLOCKED) {
          System.out.println("Thread '" + threadInfo.getThreadName()
              + "' is blocked on the monitor lock '" + threadInfo.getLockName()
              + "' held by thread '" + threadInfo.getLockOwnerName() + "'");

      if (!infoThread1.isAlive() && !errorThread1.isAlive() && !infoThread2.isAlive()
          && !errorThread2.isAlive())

  public static class ErrorThread extends Thread {

    private static final Log logger = LogFactory.getLog(ErrorThread.class);

    public ErrorThread(ThreadGroup tg, String name) {
      super(tg, name);

    public void run() {
      for (int i = 0; i < 10; i++) {
        try {
        } catch (Exception e) {
          long start = System.currentTimeMillis();
          logger.error("Error!", e);
          long end = System.currentTimeMillis();
          System.out.println("Took " + (end-start) + "ms to log error");

    // simulate large stack traces
    private void test(int i) {
      if (i >= 500)
        throw new RuntimeException("D'OH!");

  public static class InfoThread extends Thread {

    private static final Log logger = LogFactory.getLog(InfoThread.class);

    public InfoThread(ThreadGroup tg, String name) {
      super(tg, name);

    public void run() {
      for (int i = 0; i < 100; i++) {"Hi!");

The log4j.xml test file.








Get JSTL Vars from PageContext

JSTL sets its vars in the pageContext.  For example:

pageContext.setAttribute("foo", bar);

Therefore to get a JSTL variable use the pageContext within a tag or a JSP page.  For example:

// get item from pageContext and put in request
atg.servlet.DynamoHttpServletRequest drequest = atg.servlet.ServletUtil.getDynamoRequest(request);
drequest.setParameter("foo", pageContext.getAttribute("foo"));

Note that getAttribute assumes the variable is in the page scope.  If you want to get a variable from for example the request scope you would do this.

pageContext.getAttribute("foo", javax.servlet.PageContext.REQUEST_SCOPE);

For further reading please see PageContext.

Encode URI

To encode an URI you can simply use Java’s URLEncoder’s encode method which has been available since JDK 1.4.

String encodedUri;
  try {
    encodedUri = URLEncoder.encode(uri, "UTF-8");
  catch (UnsupportedEncodingException exc) {
    // this should never happen
    logger.warn("UTF-8 is not a supported encoding?  Not encoding for now...", exc);
    encodedUri = uri;

Dynamically generate sitemap.xml

sitemap.xml is a top level document on your website “for webmasters to inform search engines about pages on their sites that are available for crawling.”  Google not surprisingly has its own documentation on how to improve your site’s visibility using sitemap.xml.

Typically sitemap.xml is a static file that is hand generated.  But on large sites it makes more sense to generate this dynamically.  One way to do this is to generate it on demand using a servlet.  Here is my simple solution.  I did not include the implementation for outputPages() since that will be specific to each application server’s DB hierarchy or web server’s file structure.

public class SiteMap extends HttpServlet {

  protected static final String MIME_TYPE_XML = "application/xml";

  // XML tags
  protected static final String SITE_MAP_XML_INFO = "";
  protected static final String SITE_MAP_BEGIN =
  protected static final String SITE_MAP_END = "";

  protected static final String LOC_BEGIN = " ";
  protected static final String LOC_END = "";
  protected static final String PRIORITY_BEGIN = " ";
  protected static final String PRIORITY_END = "";
  protected static final String URL_BEGIN = "";
  protected static final String URL_END = "";

  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    // set content type to be XML

    // get writer
    PrintWriter out = response.getWriter();

    // output header

    // output pages
    outputPages(request, out);

    // output end

  protected void outputPage(String uri, String priority, PrintWriter out, String urlStart) {
    out.println(LOC_BEGIN + urlStart + uri + LOC_END);
    out.println(PRIORITY_BEGIN + priority + PRIORITY_END);

Then you configure web.xml to use the SiteMap servlet.