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

John Munsch http://www.johnmunsch.com

« Newer Snippets
Older Snippets »
Showing 1-10 of 13 total  RSS 

Log4j 101

// Once you have included the Log4j jar into the classpath of your
// application, you can use the following code within each class to
// get a logger for that class. That is, all log messages issued from
// within that class will be tagged with the classname to make it
// easier to locate a problem. See my tutorial on Log4j,
// Log4j in 30 Minutes or Less (http://www.johnmunsch.com/projects/Presentations/)
// for a better introduction.

private static Logger log = Logger.getLogger(<class name>.class);


// When you need to specify the location (or a different name) for
// the log.properties file, you can set a specific System variable
// which Log4j will be guaranteed to read as soon as any part of
// your code tries to use it. You do that by passing the following
// to the JVM as you start your Java application.
-Dlog4j.configuration=file:<path to log.properties file>

Proper Use Of String and StringBuffer In Java

// This isn't really code at all, this is a comment that I use
// over and over again as I go through code written by people
// who obviously don't understand when to use a String and when
// to use a StringBuffer.

// I put this block of text wherever I find problems with Strings
// and StringBuffers to improve understanding of how each one works
// and when to use one or the other.
//
// Rule #1: Use a StringBuffer if you intend to build a string out of
// dynamic elements. That is, if you are going to include the results
// of function calls or variables as part of the string then you use
// a StringBuffer and do append() calls. StringBuffer's append is
// much faster than using "+" to stick together String objects.
//
// Rule #2: But, if you are just building a string out of static pieces
// of text, it's better to use Strings and "+" than creating a
// StringBuffer and making append calls. Instead just use a String
// and a bunch of "+" signs between the sections. For example:
// String test = "this " + "is " + "a " + "test " + "string";
// is _not_ expensive. Why? Because all the pieces are static text and
// the compiler can make it into this _as it compiles the code_:
// String test = "this is a test string";
//
// Rule #3: For goodness sake, do this:
// StringBuffer test = new StringBuffer();
// test.append("static string ");
// test.append(dynamicCall());
// test.append(" another static string ");
// test.append(someVariable);
// DON'T DO THIS:
// StringBuffer test = new StringBuffer();
// test.append("static string " + dynamicCall());
// test.append(" another static string " + someVariable);
// This is officially the worst of all worlds. You need to use a
// StringBuffer in this case because you've got some dynamic parts
// but there is still addition going on between dynamic parts (the
// function call and variable) and static strings. Ack!
//
// If you can't remember anything else, remember this:
// static strings = String and "+"
// dynamic strings = StringBuffer and append() 

Returning A File As An Attachment From JSP

// This is truly a snippet. It's a small piece of code you use
// within a JSP file to make sure that the file you are
// returning is not interpreted by the browser. You use this
// when you want to return a TXT file, JPG or other file that
// the browser might open on its own rather than offer a
// dialog to the user so it can be saved.
//
// Note: In this example I'm returning a text file so I set
// the MIME type of the response to text/plain, but you need
// to make sure it matches the type of data you are returning.

response.setContentType("text/plain");

response.setHeader("Content-Disposition", "attachment; filename=\"test.txt\"");

JDBC 101

// Note the use of a prepared statement. You can gain a couple of different benefits
// from using a prepared statement versus a conventional statement. One is that the
// database can compile the statement once and simply insert different values into the
// variables each time you call it. For frequently used functions this can result in
// improved performance. The second advantage is where the values to be passed in might
// be changable by hostile users (e.g. a search term taken from a webpage). In those
// cases assembled SQL strings are suseptible to attack by cleverly phrased inputs but
// prepared statements are not because they are _never_ interpreted as actual SQL, only
// as values for variables.
//
// See my other code snippets "Getting A Data Source From Tomcat" and "Data Source 101"
// for more information on how to get the data source you pass into a routine like this.

    /**
     * In this case the Record object is something we are saving to the database.
     */
    public void persistRecord(DataSource dataSource, 
        Record record) throws Exception {

        Connection conn = null;
        PreparedStatement st = null;
        
        int retVal = 0;
        
        try {
            conn = dataSource.getConnection();
            
            st = conn.prepareStatement("insert into test(a, b) values(?, ?)");

            st.setInt(1, record.getA());
            st.setString(2, record.getB());
            
            int records = st.executeUpdate();
        } catch (SQLException se) {
            log.error(se, se);
            throw se;
        } finally {
            UtilityJDBC.closeSQLClasses(conn, st, null);   
        }
    }

    /**
     * NOTE!! if you close a statement the associated ResultSet
     * is closed too so you should copy the contents to some other
     * object. The result set is invalidated also if you recycle a
     * Statement and try to execute some other query before the result
     * set has been completely examined.
     * 
     * @param conn
     * @param st
     * @param rs
     * @throws SQLException
     */
    public static void closeSQLClasses(Connection conn, Statement st,
        ResultSet rs) {

        try {
            if (rs != null) {
                rs.close();
            }

            if (st != null) {
                st.close();
            }

            if (conn != null) {
                conn.close();
            }
        } catch (SQLException se) {
            log.error(se, se);
        }
    }

A Client For the XML-RPC Servlet

// When combined with the Apache XML-RPC library this code
// will let you call the servlet in the snippet "An XML-RPC
// Servlet". Of course, since XML-RPC is pretty ubiquitous
// you can also use this code to call servers in dozens of
// other languages as well.

import java.util.Vector;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.xmlrpc.XmlRpcClient;

public class XMLRPCTestClient {
    private static final String serverAddress = 
	"http://localhost:8080/lol/remoteapi";
    private static Log log = LogFactory.getLog(XMLRPCTestClient.class);
    
    /** Creates a new instance of XMLRPCTestClient */
    public XMLRPCTestClient(String address) {
        try {
            XmlRpcClient xmlrpc = new XmlRpcClient(address);

            Vector params = new Vector();
            params.addElement("Hello World! Hello!");

            try {
                // this method returns a string
                String result = (String) xmlrpc.execute("echo.echo", params);
                System.out.println(result);
            } catch (Exception e) {
                log.error("The remote procedure call failed.", e);
            }
        } catch (java.net.MalformedURLException mue) {
            log.error(
                "The address given for the XML-RPC interface is bad: " + address);
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        XMLRPCTestClient xmlRPCTestClient = new XMLRPCTestClient(
            serverAddress);
    }
}

An XML-RPC Servlet

// This depends upon the Apache XML-RPC library.

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.xmlrpc.XmlRpcServer;

public class XmlRpcServlet extends HttpServlet {
    public class EchoHandler {
        public String echo(String input) {
            return input;
        }
    }
	
    private XmlRpcServer server = new XmlRpcServer();

    private static Log log = LogFactory.getLog(XmlRpcServlet.class);

	@Override
	public void init(ServletConfig config) throws ServletException {
        server.addHandler("echo", new EchoHandler());
	}

	@Override
	protected void doGet(HttpServletRequest request, 
			HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, 
			HttpServletResponse response) throws ServletException, IOException {
        byte[] result = server.execute(request.getInputStream());
        
        response.setContentType("text/xml");
        response.setContentLength(result.length);
        
        OutputStream output = response.getOutputStream();
        output.write(result);
        output.flush();
    }
}


// The following needs to be added to your web.xml file to
// expose the servlet so it may be called remotely.
  <servlet>
    <servlet-name>XmlRpcServlet</servlet-name>
    <servlet-class>XmlRpcServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>XmlRpcServlet</servlet-name>
    <url-pattern>/remoteapi</url-pattern>        
  </servlet-mapping>    

Ant 101

// Ah Ant. How I love thee, how much better a build tool
// than my ex build tool Make.
//
// This is my current starting build.xml Ant script for any
// Java project. It specifies my usual directories, it will
// build source code, make a Jar, build a War, clean up build
// products, create Javadoc, and even run unit tests.
//
// Notice that I use the JReleaseInfo library to automatically
// generate a Java class that contains version numbers, build
// numbers, etc. Be sure to put the Jar from that library in
// the library directory to get that feature:
// http://jreleaseinfo.sourceforge.net/

<?xml version="1.0"?>
<project name="New Project" basedir="." default="all">
    <target name="init">
        <property name="appName" value="newProject"/>
    
        <property name="buildDir" value="${basedir}/build"/>
        <property name="libDir" value="${basedir}/lib"/>
        <property name="javaSourceDir" value="${basedir}/src"/>
        <property name="testDir" value="${basedir}/test"/>
        <property name="webSourceDir" value="${basedir}/web"/>
        <property name="etcDir" value="${basedir}/etc"/>
        <property name="tempDir" value="${basedir}/tmp"/>
        <property name="classDir" value="${buildDir}/classes"/>

        <!-- This may get overridden when we are called from Anthill. -->
        <property name="version" value="Local Build"/>
        <property name="deployDir" value="${buildDir}"/>

        <property name="distDir" value="${deployDir}/dist"/>
        <property name="junitDir" value="${deployDir}/JUnit"/>
        <property name="javadocDir" value="${deployDir}/apidoc"/>

        <!-- Create the directories where we put all the build products. -->    
        <mkdir dir="${buildDir}"/>
        <mkdir dir="${classDir}"/>
        <mkdir dir="${distDir}"/>
        <mkdir dir="${junitDir}"/>
        <mkdir dir="${javadocDir}"/>

        <path id="compileClasspath">
            <fileset dir="${libDir}"/>
        </path>

        <!-- Make available build info in such a way that we can display it to the user. -->
        <taskdef name="jreleaseinfo" classname="ch.oscg.jreleaseinfo.anttask.JReleaseInfoAntTask">
            <classpath refid="compileClasspath"/>
        </taskdef>

        <jreleaseinfo className="MyReleaseInfo" packageName="com.johnmunsch.${appName}"
                targetDir="${javaSourceDir}" project="${appName}" version="${version}" 
                buildNumFile="buildnum.properties" buildNumProperty="buildnum">
            <parameter name="VersionNum" type="int" value="1" />
            <parameter name="RevisionNum" type="Integer" value="0" />
        </jreleaseinfo>
    </target>

    <target name="compile" depends="init">
        <javac srcdir="${javaSourceDir}" destdir="${classDir}" debug="true" deprecation="true">
            <classpath refid="compileClasspath"/>
        </javac>

        <!-- Copy files needed to run the software to destinations in the 
         build directory. I do this because I usually pull all binary files like
         this from inside the Jar files that make up my application rather than
         having them loose. So they need to be copied to the class dir so they
         get included in the Jar file for the application. -->
        <copy todir="${classDir}" >
            <fileset dir="${javaSourceDir}">
                <include name="**/*.gif"/>
                <include name="**/*.jpg"/>
                <include name="**/*.png"/>
                <include name="**/*.wav"/>
                <include name="**/*.dtd"/>
                <include name="**/*.properties"/>
            </fileset>
        </copy>
    </target>

    <target name="jar" depends="init,compile">
        <jar jarfile="${distDir}/${appName}.jar" compress="true" 
            basedir="${classDir}"/>
    </target>

    <target name="war" depends="jar">
        <war destfile="${distDir}/${appName}.war" webxml="${etcDir}/WEB-INF/web.xml">
            <fileset dir="web"/>
            <lib dir="${libDir}">
                <include name="jstl.jar"/>
                <include name="standard.jar"/>
            </lib>
            <lib dir="${libDir}">
                <include name="*.jar"/>
            </lib>
            <lib dir="${distDir}">
                <include name="${appName}.jar"/>
            </lib>
        </war>
    </target>

    <target name="all" depends="war" description="Build everything.">
        <echo message="Application built."/>
    </target>

    <target name="javadoc" depends="init" description="Javadoc for the code.">
        <javadoc packagenames="*" sourcepath="${javaSourceDir}" 
	        destdir="${javadocDir}"/>
    </target>

    <target name="clean" depends="init" description="Clean all build products.">
        <delete dir="${tempDir}"/>
        <delete dir="${javadocDir}"/>
        <delete dir="${junitDir}"/>
        <delete dir="${distDir}"/>
        <delete dir="${classDir}"/>
        <delete dir="${buildDir}"/>
    </target>

    <target name="junit" depends="jar" description="Performs unit tests.">
        <javac srcdir="test" destdir="${classDir}" debug="true" deprecation="true">
            <classpath refid="compileClasspath"/>
        </javac>

        <mkdir dir="${tempDir}"/>

        <junit failureproperty="junit.failed">
            <formatter type="xml"/>
            <batchtest todir="${tempDir}">
                <fileset dir="${classDir}">
                   <include name="**/*Test.class"/>
                   <include name="**/Test*.class"/>
                </fileset>
            </batchtest>
            <classpath>
                <path refid="compileClasspath"/>
                <pathelement location="${classDir}"/>
            </classpath>
        </junit>

        <mkdir dir="${buildDir}/JUnit"/>

        <junitreport tofile="TESTS-TestSuites.xml" todir="${tempDir}">
            <fileset dir="${tempDir}">
                <include name="TEST-*.xml"/>
            </fileset>
            <report todir="${junitDir}"/>
        </junitreport>
  	
        <fail message="JUnit test failure." if="junit.failed"/>  	
    </target>
</project>

Getting A Data Source From Tomcat

// You can setup a data source in tomcat using a context file
// or you can set one up using the Administration web pages
// as well. Either way you do it, here is the simple code to
// get the data source from Tomcat so you can start pulling
// out database connections.

// Obtain our environment naming context
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");

// Look up our data source by the name we gave it when we created it. 
// In this case that's "jdbc/EmployeeDB".
DataSource ds = (DataSource) envCtx.lookup("jdbc/EmployeeDB");

Data Source 101

// Way too many people hard code their JDBC connections to
// the database server(s). Use data sources to connect to
// your databases. They can be setup easily in any major
// Java application server as well as JSP/servlet engines
// like Tomcat and Spring.
//
// If you aren't running inside a container that provides
// you with easy access to a data source though, you can
// include the Jakarta Commons DBCP library and create a
// data source as shown in the code below. The result is
// a data source complete with pooling, caching, etc. that
// you can pass to other code that just expects to receive
// a data source.

BasicDataSource dataSource = new BasicDataSource();

dataSource.setDriverClassName(System.getProperty("driverClassName"));
dataSource.setUsername(System.getProperty("username"));
dataSource.setPassword(System.getProperty("password"));
dataSource.setUrl(System.getProperty("url"));

Velocity 101 Unit Tests

// Unit tests for the Velocity 101 code. Note that the second test is
// actually a test to confirm that the function returns a failure
// correctly when the Velocity template file is not found.
//
// Be sure to get the test.vm file that goes with these unit tests.

package com.johnmunsch.util;

import org.apache.velocity.VelocityContext;

import junit.framework.TestCase;

public class BoilerplateTest extends TestCase {
    private VelocityContext context = null;
    private String testTemplate = null;

    protected void setUp() throws Exception {
        context = new VelocityContext();
        testTemplate = System.getProperty("testTemplate");
    }

    /**
     * A very basic test to see if we can get a word inserted into a template
     * with the Boilerplate class.
     * @throws Exception 
     */
    public void testApply() throws Exception {
        context.put("foo", "Velocity");
        
        String output = Boilerplate.apply(context, testTemplate);
        
        assertEquals(output, "<html><body>Hello Velocity World!</body><html>");
    }
    
    /**
     * Same sort of test as above except this time we specify a bogus name for
     * the template file and we expect to get an exception. The failure occurs
     * only if we don't have an exception thrown.
     */
    public void testApply2() {
        context.put("foo", "Velocity");

        try {
            Boilerplate.apply(context, "heyheypaula.vm");
            
            fail();
        } catch (Exception e) {
            // We expect an exception. Failure is when we don't see one.
        }
    }
}


// This is a required file for the unit tests in "Velocity 101 Unit Tests".
// Put it into a file and make sure that the filename is passed into the unit
// test above as a System property.

<html><body>Hello $foo World!</body><html>
« Newer Snippets
Older Snippets »
Showing 1-10 of 13 total  RSS