Axeorcat.com

Would you prefer to be an axe or a cat? That is the question. // I Code. I Sysadmin. I Beer.
April 15, 2010

Java Examples

Format a date or parse a string to a date

java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("dd/MM/yy");
String display = sdf.format(dat);
Date date = sdf.parse(display);

Return contents of a file as a string

public static String getFile( String fileName )
  throws FileNotFoundException, FileNotFoundException, IOException
{
  BufferedReader in = new BufferedReader(new FileReader(fileName));
  String input = null;
  StringBuffer inBuf = new StringBuffer();
  while((input = in.readLine()) != null) {
    inBuf.append(input);
    inBuf.append("\n");
  }
  return inBuf.toString();
}

Get a Throwable’s stack trace into a String instead of a
stream.

public static String getExceptionStack(Throwable thr)
    {
        String rv="";
        if (thr!=null) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            PrintStream pri = new PrintStream(out);
            thr.printStackTrace(pri);
            rv = out.toString();
        }
        return rv;
    }

Convert a java.util.ResourceBundle to a
java.util.Properties

public static Properties convertToProperties(ResourceBundle bundle)
    {
        Enumeration enum = bundle.getKeys();
        Properties props = new Properties();

        while (enum.hasMoreElements()) {
            String name = (String)enum.nextElement();
            String value = bundle.getString(name);
            props.put(name, value);
        }

        return props;
    }

Simple static methods to dump data structures to a String for
display/debug purposes.

public static String displayMap(Map data)
    {
        StringBuffer buf = new StringBuffer();
        Set keys = data.keySet();
        Iterator iter = keys.iterator();
        while (iter.hasNext()) {
            String name = (String)iter.next();
            Object value = data.get(name);
            buf.append(name);
            buf.append("=");
            buf.append(value);
            buf.append("\n");
        }

        return buf.toString();
    }
    public static String displayArray(Object[] data)
    {
        StringBuffer buf = new StringBuffer();
        for(int i=0;i<data.length;i++) {
            buf.append("\n\t");
            buf.append( data[i].toString() );
        }
        buf.append("\n");
        return buf.toString();
    }
    public static String displayList(List data)
    {
        StringBuffer buf = new StringBuffer();
        for(int i=0;i<data.size();i++) {
            buf.append("\n\t");
            buf.append( data.get(i).toString() );
        }
        buf.append("\n");
        return buf.toString();
    }
    public static String displayVector(Vector data)
    {
        StringBuffer buf = new StringBuffer();
        if( data != null ) {
            for(int i=0;i<data.size();i++) {
                buf.append("\n\t");
                buf.append( data.get(i).toString() );
            }
            buf.append("\n");
        }
        return buf.toString();
    }

Simple String splitters

public static Vector splitToVector( String s, String sep )
    {
        StringTokenizer st = new StringTokenizer( s, sep );
        Vector ret = new Vector( st.countTokens() );
        while (st.hasMoreTokens()) {
            ret.add( st.nextToken() );
        }
        return ret;
    }
    public static String[] splitToArray( String s, String sep )
    {
        String[] ret = null;
        if( s != null ) {
            StringTokenizer st = new StringTokenizer( s, sep );
            ret = new String[ st.countTokens() ];
            int i = 0;
            while (st.hasMoreTokens()) {
                ret[i++] = st.nextToken();
            }
        }
        return ret;
    }

Replace all occurrences of foo with bar in input

public static String replace(String input, String foo, String bar)
{
        StringBuffer buf = new StringBuffer(input);
        int index = input.lastIndexOf(foo);
        while (index>0) {
            buf.replace(index, index+foo.length(), bar);
            index = input.lastIndexOf(foo, index-1);
        }
        return buf.toString();
}

JNDI lookup for name

public static Object lookup( String url, String name ) throws NamingException
    {
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory" );
        env.put(Context.PROVIDER_URL, url  );
        env.put("weblogic.jndi.createIntermediateContexts", "true");
        InitialContext context = new InitialContext(env);
        return context.lookup(name);
    }

Get a JDBC connection from a datasource in JNDI

final static String CONTEXT_FACTORY = "weblogic.jndi.WLInitialContextFactory";
private static Connection getDBConnectionJNDI(String url, String datasourceName)
        throws SQLException, NamingException
    {
        InitialContext ctx = null;
        if( url != null ) {
            Hashtable env = new Hashtable();
            env.put( Context.INITIAL_CONTEXT_FACTORY, CONTEXT_FACTORY );
            env.put( Context.PROVIDER_URL, url  );
            env.put( Context.SECURITY_CREDENTIALS, "weblogic" );
            env.put( Context.SECURITY_PRINCIPAL, "system" );
            ctx = new InitialContext(env);
        }
        else {
            ctx = new InitialContext();
        }
        javax.sql.DataSource ds
            = (javax.sql.DataSource) ctx.lookup ( datasourceName );
        ctx.close();
        Connection conn = ds.getConnection();
        return conn;
    }

Get a JDBC connection directly to the database url instead of
from a datasource/pool.

public final static String DRIVER = "oracle.jdbc.driver.OracleDriver";
public static Connection getDBConnectionDirect( String url, String user, String pwd )
        throws SQLException
    {
        Class.forName( DRIVER ).newInstance();
        java.util.Properties props = new java.util.Properties();
        props.setProperty("user", user);
        props.setProperty("password", pwd);
        return DriverManager.getConnection( url, props  );
    }

Return predefined locale from a country ISO code

public static Locale getLocaleFromIsoCode(String isoCode)
    {
        if("GB".equals(isoCode)) return Locale.UK;
        if("DE".equals(isoCode)) return Locale.GERMANY;
        if("FR".equals(isoCode)) return Locale.FRANCE;
        if("IT".equals(isoCode)) return Locale.ITALY;
        return null;
    }

Get a resource or props file on the class path.

public static URL getResource(String name)
{
    return getClass().getClassLoader().getResource(name);
}
public static Properties getProperties(String name) throws java.io.IOException
{
    Properties props = null;
    URL url = getResource( name );
    if( url != null ) {
        props = new Properties();
        props.load( url.openStream() );
    }
    return props;
}

Standard XML imports

import java.io.*;
import java.util.*;
import org.xml.sax.InputSource;
import org.jdom.Element;
import org.jdom.Document;
import org.jdom.Namespace;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;

Parse an XML string or stream, returning a JDOM root
element

public static Element toJdom( String xml )
    {
        Element ret = null;
        try {
     SAXBuilder builder = new SAXBuilder( SAX_DRIVER, false );
            Document doc = builder.build( new StringReader(xml) );
            ret = doc.getRootElement();
        }
        catch (JDOMException e) {
            e.printStackTrace();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }
public static Element toJdom( InputStream xml )
    {
        Element ret = null;
        try {
            Document doc = sJdomBuilder.build( xml );
            ret = doc.getRootElement();
        }
        catch (JDOMException e) {
            e.printStackTrace();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

Serialize a JDOM tree to a String

public static String toXml(Element elem)
{
 XMLOutputter jdomOutputter = new XMLOutputter("  ", false);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            jdomOutputter.output(elem, out);
        } catch (IOException e) {
            // never happen
        }
        return out.toString();
}

Take a continuous XML string (or org.xml.sax.InputSource) and
add new lines so it’s more human readable

public static String beautify(String xml) throws JDOMException
    {
        ByteArrayInputStream inp = new ByteArrayInputStream(xml.getBytes());
        InputSource src = new InputSource(inp);
        return beautify(src);
    }
public static String beautify(InputSource src) throws JDOMException
    {
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(src);
        XMLOutputter out = new XMLOutputter("  ", true);
        return out.outputString(doc);
    }

Set JAXP drivers

public static String setJAXPClasses()
    {
        final String SYSTEM_SAX_FACTORY = "javax.xml.parsers.SAXParserFactory";
        final String SYSTEM_DOM_FACTORY = "javax.xml.parsers.DocumentBuilderFactory";
        final String SYSTEM_XSL_FACTORY = "javax.xml.transform.TransformerFactory";
        if( SET_JAXP || System.getProperty( SYSTEM_SAX_FACTORY ) == null ) {
            // .. then I want to use Xerces for SAX
             System.setProperty( SYSTEM_SAX_FACTORY, "org.apache.xerces.jaxp.SAXParserFactoryImpl" );
        }
        if( SET_JAXP || System.getProperty( SYSTEM_DOM_FACTORY ) == null ) {
            // ... then I want to use Xerces for DOM
            System.setProperty( SYSTEM_DOM_FACTORY, "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl" );
        }
        if( SET_JAXP || System.getProperty( SYSTEM_XSL_FACTORY ) == null ) {
            // ... then I want to use Xalan for XSL
            System.setProperty(SYSTEM_XSL_FACTORY, "org.apache.xalan.processor.TransformerFactoryImpl");
        }

        return "JAXP Parameters::"  + " SAX: " +  System.getProperty( SYSTEM_SAX_FACTORY )
                                   + " DOM: " +  System.getProperty( SYSTEM_DOM_FACTORY )
                                   + " XSL: " +  System.getProperty( SYSTEM_XSL_FACTORY ) ;
    }

Parse using Xerces, setting specific parser features, and
return as JDOM

import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Namespace;
import org.jdom.input.SAXBuilder;
import org.jdom.input.DOMBuilder;
import org.xml.sax.XMLReader;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.apache.xerces.parsers.SAXParser;
import org.apache.xerces.parsers.DOMParser;
public static Document parse( InputStream in, boolean validate )
        throws SAXException,java.io.IOException, Exception
    {
        DOMParser parser = new org.apache.xerces.parsers.DOMParser();

        if(validate) {

            parser.setFeature("http://xml.org/sax/features/validation", true );
            parser.setFeature("http://xml.org/sax/features/namespaces", true );
            parser.setFeature("http://apache.org/xml/features/validation/schema", true );
            parser.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true );
            parser.setFeature("http://xml.org/sax/features/external-general-entities", true);
            parser.setFeature("http://apache.org/xml/features/continue-after-fatal-error", false);

            parser.setProperty(
   "http://apache.org/xml/properties/schema/external-schemaLocation", MY_SCHEMA_LOCATIONS );
        }
        // setting this will disable validation if grammar is not specified (how??)
        // parser.setFeature("http://apache.org/xml/features/validation/dynamic", true );
        parser.setErrorHandler( new org.jdom.input.BuilderErrorHandler() );

        InputSource inputSource = new org.xml.sax.InputSource( in );
        parser.parse( inputSource );
        org.w3c.dom.Document w3Doc = parser.getDocument();
        DOMBuilder builder = new org.jdom.input.DOMBuilder();
        Document jDoc = builder.build(w3Doc);
        return jDoc;
    }

Define your namespace constants

final static String SOAP_ENV_W3_2001 =
        "http://www.w3.org/2001/12/soap-envelope";
final static String SOAP_ENV = SOAP_ENV_W3_2001;
final static String SOAP_ENV_PREFIX = "SOAP-ENV";
public static Namespace SOAPNS = Namespace.getNamespace(
        NamespaceConstants.SOAP_ENV_PREFIX, NamespaceConstants.SOAP_ENV );

A simple abstract base class for your JMS message
handlers.

import javax.ejb.MessageDrivenBean;
import javax.ejb.MessageDrivenContext;
import javax.jms.MessageListener;
import javax.jms.Message;
/**
* Just extend this and do something in the onMessage method.
*/
abstract public class BaseHandler implements MessageListener, MessageDrivenBean
{
    /*
    *
    */
    MessageDrivenContext ejbContext;
    /**
    * The main message processing method.
    */
    abstract public void onMessage( Message msg );
    /**
    * Start method just loops waiting for messages.
    */
    private void start()
    {
        synchronized(this) {
            while(true) {
                try {
                    wait();
                }
                catch(InterruptedException ie) {
                }
            }
        }
    }
    /**
    *
    */
    public void setMessageDrivenContext(MessageDrivenContext mdc)
    {
        ejbContext = mdc;
    }
    /**
    *
    */
    public void ejbRemove()
    {
    }
    /**
    *
    */
    public void ejbCreate()
    {
    }
}

An example handler

public class MyHandler extends BaseHandler
{

    /**
    * Process this xml message (main business logic).
    */
    public String process( String xml ) throws MyXmlFormatException
    {
 // do something
    }
    /**
    * JMS onMessage.
    */
    public void onMessage( Message msg )
    {
        try {
            // cast to ObjectMessage
            ObjectMessage objMsg = (ObjectMessage) msg;

            // must contain a String
            String msgText = (String) objMsg.getObject();
            // call the process method
            String response = process( msgText );
     if( response != null ) {
   // send a JMS Reply
     }

        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }

}

Simple self contained message listener just prints messages to stdout (copied from BEA)

public class DebugMsgListener
  implements MessageListener
{
  private static int listenerCounter=0;  // global count of DebugMsgListeners
  private int listenerId; // identifies a particular listener
  public DebugMsgListener()
  {
    this.listenerId = ++listenerCounter;
  }
  /** Message listener interface.
    * @param msg message
    */
  public void onMessage(Message msg)
  {
    try {
      String msgText;
      if (msg instanceof TextMessage) {
        msgText = ((TextMessage)msg).getText();
      } else {
        msgText = msg.toString();
      }
      System.out.println("DebugMsgListener["+listenerId+"] : JMS Message="+ msgText);
      // The sleep() is for demonstration purposes only; without it
      // the same DebugMsgListener tends to get used to service incoming messages,
      // making it harder to show the pool in action.
      try {
        Thread.sleep(1000);
      } catch (InterruptedException ie) {}
    } catch (JMSException jmse) {
      jmse.printStackTrace();
    }
  }
}

Set JMS message properties from a Map

static public void setMessageProperties(Message msg, Map props) throws JMSException
    {
        if (props==null) {
            return;
        }
        Set keys = props.keySet();
        Iterator iter = keys.iterator();
        while (iter.hasNext()) {
            String name = (String)iter.next();
            String value = (String)props.get(name);
            msg.setStringProperty(name, value);
        }
    }

Set up your JMS queue connections (use a separate one for
receiving and sending)

QueueConnectionFactory qconFactory = (QueueConnectionFactory) context.lookup( MY_FACTORY );
QueueConnection qcon = qconFactory.createQueueConnection();
QueueSession sendQueueSession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
QueueSession receiveQueueSession = null;
qcon.start();
QueueSender producer = sendQueueSession.createSender(queue);
QueueRequestor requestor = new QueueRequestor( sendQueueSession, q );

Get a queue or topic from JNDI

    /**
    * Lookup a Topic.
    */
    public Topic getTopic( String jndiName ) throws NamingException
    {
        return (Topic) context.lookup( jndiName );
    }

    /**
    * Lookup a Queue.
    */
    public Queue getQueue( String jndiName ) throws NamingException
    {
        return (Queue) context.lookup( jndiName );
    }

Create an initial context

public InitialContext getInitialContext( String url ) throws NamingException
    {
        Hashtable env = new Hashtable();
        env.put(Context.PROVIDER_URL, url  );
        env.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory" );
        env.put("weblogic.jndi.createIntermediateContexts", "true");
        return new InitialContext(env);
    }

How to do a JMS reply using getJMSReplyTo() and correlation
ID

Destination dest = inMsg.getJMSReplyTo();
if( dest instanceof Queue && ((Queue)dest).getQueueName() != null ) {
   queue = (Queue) dest;
} 

outMsg.setJMSCorrelationID( inMsg.getJMSMessageID() );
QueueSender sender = ... // getQueueSender( queue );
sender.send( outMsg );

A Weblogic start up class

import weblogic.common.T3StartupDef;
import weblogic.common.T3ServicesDef;
public class BlankStartup implements T3StartupDef
{
    public void setServices(T3ServicesDef services) {
    }
    public String startup (String name, Hashtable params) throws Exception {
        return "OK " + name;
    }
}

Send a mail using java mail

public void send( String toAddress, String fromAddress, String theSubject, String theText )
    {
        try {
          Properties props = new Properties();
          props.put("mail.smtp.host", this.host);
          Session s = Session.getInstance(props, null);

          MimeMessage message = new MimeMessage(s);

          InternetAddress from = new InternetAddress(fromAddress);
          message.setFrom(from);
          InternetAddress to = new InternetAddress(toAddress);
          message.addRecipient(Message.RecipientType.TO, to);

          message.setSubject( theSubject );
          message.setText( theText );

          Transport.send(message);
        }
        catch( Exception e ) {
            logger.error(e.getMessage(), e);
        }
    }


Xml processing using JSTL

You can process your own arbitrary XML documents using the power of JSTL.
This can be used as an alternative to XSLT.

Mixed mode JSTL works if the file has a ".jspx"
rather than a ".jsp" extension.


<?xml version='1.0' ?>
<someElement xmlns:c="http://java.sun.com/jstl/core_rt">
  <c:out value="wow, jstl works"/>
</someElement>

To get this to work with a ".jsp" extension,
you need a special jsp:root element


<?xml version='1.0' ?>
<jsp:root
  xmlns:c="http://java.sun.com/jstl/core_rt"
  xmlns:jsp="http://java.sun.com/JSP/Page"
  version="2.0">
<someElement>
  <c:out value="wow, jstl works"/>
</someElement></jsp:root>

Note on jsp:root If there
is a jsp:root element you must define the version and jsp namespace on it
even if you don’t use it in the document (xmlns:jsp=”http://java.sun.com/JSP/Page”)
or you will get the error "Invalid standard action".
You also get this error if the jsp:root is not the root element of the xml
document.

Note on XHTML Sadly XHTML is defined by DTD
so you can’t mix in JSTL tags since the document won’t be processed with namespace
awareness, and validating parsers will reject unknown elements like "c:out".
Even if it passed validation, in XHTML all attribute names must be in lower
case
so for example using some JSP constructs can not work by definition:

  This would break XHTML
even if you could get it to ignore jsp: namespace elements
  <jsp:directive.page contentType=”application/xhtml+xml”/>