Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Mike Wilson www.whisperingwind.co.uk

« Newer Snippets
Older Snippets »
Showing 1-7 of 7 total  RSS 

'ant' build file for HelloWorldServlet and JettyLauncher

A pretty straightforward 'ant' build file. You will need to edit the jetty.home property to indicate where you installed Jetty.

   1  
   2  <?xml version="1.0" encoding="UTF-8"?>
   3  <project basedir="." default="compile" name="hello-servlet">
   4    <property name="build.dir"	location="classes" />
   5    <property name="src.dir"	location="src/main/java" />
   6    <property name="jetty.home"	location="/home/mrw/projects/jetty-6.1.3" />
   7    <property name="jetty.lib"	location="${jetty.home}/lib" />
   8  
   9    <path id="jetty.lib.path">
  10      <pathelement path="${jetty.lib}/jetty-6.1.3.jar" />
  11      <pathelement path="${jetty.lib}/jetty-util-6.1.3.jar" />
  12      <pathelement path="${jetty.lib}/servlet-api-2.5-6.1.3.jar" />
  13    </path>
  14  
  15    <target name="compile" description="Compile the project">
  16      <mkdir dir="${build.dir}" />
  17      <javac debug="true" destdir="${build.dir}" srcdir="${src.dir}"
  18  	classpathref="jetty.lib.path">
  19        <compilerarg value="-Xlint:unchecked" />
  20        <compilerarg value="-Xlint:deprecation" />
  21      </javac>
  22    </target>
  23  
  24    <target name="all"  depends="clean,compile"
  25        description="Recompile from scratch"/>
  26  
  27    <target name="server" depends="compile" description="Launch the server">
  28      <java classname="com.babblemind.JettyLauncher" fork="true"
  29  	classpathref="jetty.lib.path">
  30        <classpath>
  31  	<pathelement path="${build.dir}" />
  32        </classpath>
  33      </java>
  34    </target>
  35  
  36    <target name="clean" description="Delete all files created by compile">
  37      <delete dir="${build.dir}" />
  38      <delete dir="docs/api" />
  39    </target>
  40  </project>

Minimal Java servlet

There is nothing particularly original here -- there are variations of this all over the place. This works nicely with my JettyLauncher class (see my other posts on DZone Snippets).

   1  
   2  
   3  package com.babblemind;
   4  
   5  import javax.servlet.ServletException;
   6  import javax.servlet.http.HttpServlet;
   7  import javax.servlet.http.HttpServletRequest;
   8  import javax.servlet.http.HttpServletResponse;
   9  import java.io.IOException;
  10  import java.io.PrintWriter;
  11  
  12  public class HelloWorldServlet extends HttpServlet{
  13      protected void doGet(HttpServletRequest httpServletRequest,
  14  	HttpServletResponse httpServletResponse)
  15  	    throws ServletException, IOException {
  16  
  17          httpServletResponse.setContentType("text/plain");
  18          PrintWriter out = httpServletResponse.getWriter();
  19          out.println("Hello World!");
  20          out.close();
  21      }
  22  }

Minimal Jetty http server with Java servlet

This will start a Jetty http server with a single Java servlet at the root. See http://www.mortbay.org/ for Jetty downloads. This needs HelloWorldServlet from one of my other posts. Make life easier by downloading my ant build.xml as well.

   1  
   2  
   3  package com.babblemind;
   4  
   5  import org.mortbay.jetty.Server;
   6  import org.mortbay.jetty.servlet.Context;
   7  import org.mortbay.jetty.servlet.ServletHolder;
   8  
   9  public class JettyLauncher {
  10      public static void main(String[] args) throws Exception {
  11  	Server server = new Server(8080);    
  12  	Context root = new Context(server, "/", Context.SESSIONS);
  13  	root.addServlet(new ServletHolder(new HelloWorldServlet()), "/*");
  14  	server.start();
  15      }
  16  }

Add a jar file to Java load path at run time

Sometimes it is necessary to amend the class load path at run time. For example, dynamically adding jar files containing user-configurable JDBC data sources. The way this is done is truly monstrous -- the URL Path format was only revealed when a colleague looked into the Java library sources.

   1  
   2  import java.net.URL;
   3  import java.io.IOException;
   4  import java.net.URLClassLoader;
   5  import java.net.MalformedURLException;
   6  
   7  public class JarFileLoader extends URLClassLoader
   8  {
   9      public JarFileLoader (URL[] urls)
  10      {
  11          super (urls);
  12      }
  13  
  14      public void addFile (String path) throws MalformedURLException
  15      {
  16          String urlPath = "jar:file://" + path + "!/";
  17          addURL (new URL (urlPath));
  18      }
  19  
  20      public static void main (String args [])
  21      {
  22          try
  23          {
  24              System.out.println ("First attempt...");
  25              Class.forName ("org.gjt.mm.mysql.Driver");
  26          }
  27          catch (Exception ex)
  28          {
  29              System.out.println ("Failed.");
  30          }
  31  
  32          try
  33          {
  34              URL urls [] = {};
  35  
  36              JarFileLoader cl = new JarFileLoader (urls);
  37              cl.addFile ("/opt/mysql-connector-java-5.0.4/mysql-connector-java-5.0.4-bin.jar");
  38              System.out.println ("Second attempt...");
  39              cl.loadClass ("org.gjt.mm.mysql.Driver");
  40              System.out.println ("Success!");
  41          }
  42          catch (Exception ex)
  43          {
  44              System.out.println ("Failed.");
  45              ex.printStackTrace ();
  46          }
  47      }
  48  }

Basic ant script with vim & jikes

Apache ant build XML. This will use jikes in place of javac. Any compiler error output is formatted so that vim can parse it.

ant is a modern alternative to make. The build script is an XML file. It works particularly well with java. Download it for free from the Apache ant site. Most people find ant a lot nicer to live with than make.

   1  
   2  <?xml version="1.0"?>
   3  
   4  <project name="Hello" default="compile" basedir=".">
   5    <property name="name" value="Hello"/>
   6    <property name="version" value="1.0"/>
   7  
   8    <!-- Project directories.
   9    -->
  10  
  11    <property name="build" value="build"/>
  12    <property name="dist" value="dist"/>
  13    <property name="src" value="src"/>
  14  
  15    <!-- Compiler directives.
  16    -->
  17  
  18    <property name="optimize" value="off"/>
  19    <property name="deprecation" value="on"/>
  20    <property name="debug" value="on"/>
  21  
  22    <property name="build.compiler" value="jikes"/>
  23    <property name="build.compiler.emacs" value="true"/>
  24  
  25    <target name="init">
  26      <tstamp/>
  27      <mkdir dir="${build}"/>
  28    </target>
  29  
  30    <!-- Compile all the .java files from the source directory into
  31         the build directory.
  32    -->
  33  
  34    <target name="compile" depends="init">
  35      <javac srcdir="${src}" destdir="${build}" includes="**/*.java"
  36        debug="${debug}" deprecation="${deprecation}" optimize="${optimize}">
  37      </javac>
  38    </target>
  39  
  40    <target name="clean" depends="init">
  41      <delete dir="${build}"/>
  42      <delete dir="${dist}"/>
  43    </target>
  44  
  45    <target name="test" depends="compile">
  46      <java classname="HelloWorld" fork="yes">
  47        <classpath>
  48          <pathelement location="${build}"/>
  49        </classpath>
  50      </java>
  51    </target>
  52  </project>

Open a JDBC connection

This opens a JDBC connection givine a driver class name, database URL, user name and password. It is possible this method is deprecated and some newer procedure is preferred. I need to look into that.

   1  
   2      /*
   3      ** driverClass is the JDBC driver class name as a String.
   4      */
   5  
   6      try
   7      {
   8  	Class.forName (driverClass);
   9  	connection = DriverManager.getConnection (url,
  10  	    userName, password);
  11  	connection.setAutoCommit (false);
  12      }
  13      catch (SQLException ex)
  14      {
  15  	/*
  16  	** "Connect error"...
  17  	*/
  18      }
  19      catch (java.lang.ClassNotFoundException ex)
  20      {
  21  	/*
  22  	** "Driver error"...
  23  	*/
  24      }

Execute arbitary SQL in JDBC & get column names etc from the meta data

This will execute an arbitary SQL string in JDBC and extract the column names. I extracted this code from a much larger module I wrote years ago, so it isn't complete and hasn't been tested. You have been warned.

   1  
   2      /*
   3      ** connection is a java.sql.Connection obtained in the usual way.
   4      */
   5  
   6      PreparedStatement statement =
   7  	connection.prepareStatement (sqlString);
   8      statement.setMaxRows (configModel.getMaxRows ());
   9  
  10      if (statement.execute ())
  11      {
  12  	ResultSet resultSet = statement.getResultSet ();
  13  	ResultSetMetaData metaData = resultSet.getMetaData ();
  14  
  15  	/*
  16  	** Get the column names.
  17  	*/
  18  
  19  	for (int i = 0 ; i < metaData.getColumnCount () ; i++)
  20  	{
  21  	    int columnType = metaData.getColumnType (i + 1);
  22  	    String columnName = metaData.getColumnLabel (i + 1);
  23  
  24  	    /*
  25  	    ** Do something with columnType & columnName.
  26  	    */
  27  
  28  	}
  29  
  30  	/*
  31  	** Fetch the rows.
  32  	*/
  33  
  34  	while (resultSet.next ())
  35  	{
  36  	    String value;
  37  
  38  	    for (int i = 0 ; i < metaData.getColumnCount () ; i++)
  39  		value = resultSet.getString (i + 1);
  40  	}
  41      }
  42      else
  43      {
  44  	/*
  45  	** Query was probably update/insert/delete.
  46  	*/
  47  
  48  	int rowCount = statement.getUpdateCount ();
  49      }
  50  
  51      statement.close ();
« Newer Snippets
Older Snippets »
Showing 1-7 of 7 total  RSS