Checked vs. Runtime Exceptions in Java

January 22, 2007

Good article on Effective Java Exceptions – http://dev2dev.bea.com/pub/a/2006/11/effective-exceptions.html


Remote Unix commands from Java

January 8, 2007

This post shows a simple java class which allows you to run unix commands on a remote server. Java Secure Chanel (JSch) library is used to run the commands. JSch is used in Ant and Eclipse. The only third party library required is jsch-0.x.x.jar.

package com.demo.jsch;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;

public class ShellExample {

  public static void main(String[] args) {

    String user = "username";
    String host = "servername";

    JSch jsch = new JSch();

    try {

      Session session = jsch.getSession(user, host, 22);

      UserInfo userInfo = new MyUserInfo();
      session.setUserInfo(userInfo);
      session.connect(30000);

      Channel channel = session.openChannel("shell");
      channel.setInputStream(System.in);
      channel.setOutputStream(System.out);
      channel.connect(3 * 1000);

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

}

  public static class MyUserInfo implements UserInfo {

    public String getPassword() {
      return "password";
    }

    public String getPassphrase() {
      return "";
    }

    public boolean promptPassword(String arg0) {
      return true;
    }

    public boolean promptPassphrase(String arg0) {
      return true;
    }

    public boolean promptYesNo(String arg0) {
      return true;
    }

    public void showMessage(String arg0) {
    }

  }

}

Laszlo – Simple Web Service

September 19, 2006

This post shows a simple example of a Laszlo web service. It uses the xfire web service created in this post. The user enters a symbol and clicks Get Quote, laszlo makes a call to the webservice to retrieve a quote for the symbol. The laszlo documentation describes the use of soap in laszlo applications.

This is a screenshot of the laszlo page:

Stock Quote Screen Shot

<canvas debug="true">

<soap name="stockquote"
  wsdl="http://localhost:8080/xfire-stockquote/services/StockQuote?wsdl">

<!-- Method to make a document for SOAP message requests -->
<method name="makegetQuoteDoc" args="symbol">
	Debug.write('Entering makegetQuoteDoc function');
<![CDATA[
    var s =  '<getStockQuote xmlns="http://localhost:8080/xfire-stockquote/services/stockQuote" ><security>'+symbol+'</security></getStockQuote>';

Debug.write(s);
    return s;
]]>
</method>

<handler name="onload">
    // make buttons visible once SOAP object is loaded
		canvas.buttons.setAttribute('visible', true);
		Debug.write('StockQuote soap service loaded');
    Debug.write('StockQuote WSDL at ' + this.wsdl);
    Debug.write('proxy:');
    Debug.inspect(this.proxy);
</handler>

<handler name="onerror" args="error">
    Debug.write('error:', error);
</handler>

<handler name="ontimeout" args="error">
    Debug.write('timeout:', error);
</handler>

<remotecall funcname="getStockQuote" >
  <param value="${ canvas.stockquote.makegetQuoteDoc(symbol.text) }" />
  <method event="ondata" args="value">
		    Debug.write("Got data!");
		    result.setText(value);
  </method>
</remotecall>

</soap>

<view name="buttons" x="10" y="10" visible="false" layout="spacing: 10" >
<text><b>Stock Quote Service</b></text>
<view layout="axis: x" ><text y="3">Symbol:</text><edittext id="symbol" text="IBM"/></view>
<view layout="axis: x" ><text>Result:</text><text id="result"/></view>

<button text="Get Quote" onclick="canvas.stockquote.getStockQuote.invoke()" />

</view>

</canvas>

Web Service with Spring and XFire

September 12, 2006

In a previous post I looked at how a simple quote web service with XFire. This post will implement the same webservice using XFire and Spring.

WEB-INF/web.xml

Configure the xfire dispatcher servlet and the spring config files in the web.xml

<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>/WEB-INF/applicationContext.xml
	classpath:org/codehaus/xfire/spring/xfire.xml</param-value>
</context-param>

<listener>
	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
	<servlet-name>xfire</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>

<servlet-mapping>
	<servlet-name>xfire</servlet-name>
	<url-pattern>/*</url-pattern>
</servlet-mapping>

WEB-INF/applicationContext.xml

Configure the service class in the applicationContext.xml file:

<beans>
    <bean id="stockQuoteService" class="demo.xfire.service.StockQuoteServiceImpl"/>
</beans>

WEB-INF/xfire-servlet.xml

Configure a SimpleUrlHandlerMapping and an XFireExporter to expose the methods of our service class:

<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
	<property name="urlMap">
		<map>
			<entry key="/StockQuoteService">
				<ref bean="stockQuote"/>
			</entry>
		</map>
	</property>
</bean>

<bean id="stockQuote" class="org.codehaus.xfire.spring.remoting.XFireExporter">
	<property name="serviceFactory">
		<ref bean="xfire.serviceFactory"/>
	</property>
	<property name="xfire">
		<ref bean="xfire"/>
	</property>
	<property name="serviceBean">
		<ref bean="stockQuoteService"/>
	</property>
	<property name="serviceClass">
		<value>demo.xfire.service.StockQuoteService</value>
	</property>
</bean>

Service interface

public interface StockQuoteService {
  public Float getStockQuote(String security);
}

Service Implementation

public class StockQuoteServiceImpl {

protected final Log log = LogFactory.getLog(getClass());

public Float getStockQuote(String security)
  {
    Random rand = new Random();
    log.debug("Retrieving quote for "+ security);
    return new Float(rand.nextInt(101));
  }
}

Testing

After the demo application has been deployed the url will be similar to http://localhost:8080/xfire-spring-demo/StockQuoteService?wsdl for tomcat.

To run requests against the web service you could use soapUI.

The Code

You can download the war file with the code here xfire-spring-stockquote.war

If you are not using Tomcat you need to change the location of the log file in the log4j.properties file.


Using Properties Files in Mule Configuration

September 7, 2006

In a previous post I looked at how to use quartz to trigger events in mule – we had a cron expression which dictated when an event occurred. This post explains how to externalise this cron expression to a properties file.

We create a properties file (application.properties) with the cron expression. This properties file should be on the classpath.

cron.expression=0 24 15 * * ?

First we reference our properties file in the mule config:

<environment-properties>
  <file-properties location="application.properties"/>
</environment-properties>

We can then use the same syntax as Spring to acces the parameter in the properties file:

<endpoint name="quartz.in" address="quartz:/myService">
  <properties>
    <property name="cronExpression" value="${cron.expression}" />
  </properties>
</endpoint>

This example shows how to externalise configuration properties to a properties file.


Using environment variable to control the location of log files in Tomcat

September 6, 2006

You can control the location of log files in Tomcat using the ${catalina.home} environment variable.

Example:

log4j.rootLogger=DEBUG, file

log4j.appender.file=org.apache.log4j.RollingFileAppender

log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{dd-MMM HH:mm:ss.SSS} %p - %C.%M(%L) | %m%n
log4j.appender.file.File=${catalina.home}/logs/applicationname.log

Log4j – Reporting application errors by email

September 1, 2006

This post shows how you can setup log4j to send email when errors occur in your application. log4j.properties extract:

# Root category priority: DEBUG, Appender:mail
log4j.rootCategory=debug, mail

# Configuration for receiving e-mails when ERROR messages occur.
log4j.appender.mail=org.apache.log4j.net.SMTPAppender
log4j.appender.mail.To=admin@company.com
log4j.appender.mail.From=error@application-name.com
log4j.appender.mail.SMTPHost=smtp.company.com
log4j.appender.mail.Threshold=ERROR
log4j.appender.mail.BufferSize=1
log4j.appender.mail.Subject=Application Error Occurred
log4j.appender.mail.layout=org.apache.log4j.HTMLLayout

Using Quartz to trigger events in Mule

September 1, 2006

This posts shows how to use Quartz to trigger events in Mule.
Simple Trigger

Simple triggers allows you to execute a component repeatedly after a number of miliseconds. This component will be triggered 20 seconds after the application starts (startDelay=20000) and then every 10 seconds (repeatInterval=10000)

<global-endpoints>
  <endpoint name="quartz.in" address="quartz:/myService">
    <properties>
      <property name="repeatInterval" value="10000" />
      <property name="startDelay" value="20000" />
      <property name="payloadClassName" value="java.lang.String" />
    </properties>
  </endpoint>
</global-endpoints>

<mule-descriptor name="sampleComponent"
	inboundEndpoint="quartz.in"
	implementation="demo.mule.example7.SampleComponent"/>

Cron Trigger

Cron trigger allows us to execute a component based on a cron trigger (more information on cron triggers can be found here ). This component will be triggered every day at 8:00.

<global-endpoints>
  <endpoint name="quartz.in" address="quartz:/myService">
    <properties>
      <property name="cronExpression" value="0 00 08 * * ?" />
    </properties>
  </endpoint>
</global-endpoints>

<mule-descriptor name="sampleComponent"
	inboundEndpoint="quartz.in"
	implementation="demo.mule.SampleComponent"/>

Simple Web Service with XFire

August 31, 2006

This post describes how to implement as simple http web service using xfire (a next-generation java SOAP framework).

WEB-INF/Web.xml

Configure the XFire servlet in the web.xml:

<servlet>

<servlet-name>XFireServlet</servlet-name>
<display-name>XFire Servlet</display-name>
<servlet-class>org.codehaus.xfire.transport.http.XFireConfigurableServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>XFireServlet</servlet-name>
<url-pattern>/servlet/XFireServlet/*</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>XFireServlet</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>

WEB-INF/classes/META-INF/xfire/services.xml

Configure the services.xml file for xfire with the details of the service to expose:

<service>

<name>StockQuote</name>
<namespace>http://localhost:8080/xfire-stockquote/services/stockQuote</namespace>
<serviceClass>demo.xfire.service.StockQuoteService</serviceClass>
<implementationClass>demo.xfire.service.StockQuoteService</implementationClass>

</service>

StockQuoteService.java

The service class:

package demo.xfire.service;

import java.util.Random;

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

public class StockQuoteService {

protected final Log log = LogFactory.getLog(getClass());

public Float getStockQuote(String security)
  {
    Random rand = new Random();
    log.debug("Retrieving quote for "+ security);
    return new Float(rand.nextInt(101));
  }
}

Testing

After the demo application has been deployed the url will be similar to http://localhost:8080/xfire-stockquote/services/StockQuote?wsdl for tomcat.

To run requests against the web service you could use soapUI

The Code

You can download the war file with the code here: zip filexfire-stockquote.war.

If you are not using Tomcat you need to change the location of the log file in the log4j.properties file.


What is OpenLaszlo?

August 21, 2006

OpenLaszlo is the leading open source platform for the development and delivery of browser based Rich Internet applications”. OpenLaszlo programs are written in XML and JavaScript and transparently compiled to Flash and soon DHTML. The OpenLaszlo APIs provide animation, layout, data binding, server communication, and declarative UI. A good example of a laszlo application is LaszloMail. I have been working with laszlo on and off for about a year now, over the next while I will post about some of my experiences.


What is Mule?

August 21, 2006

Mule is an opensource Enterprise Integration Bus. An ESB can be described as “A framework that allows for interactions between services and applications using disparate transport and messaging technologies”. Mule offers many transports out of the box including:

  • HTTP
  • JMS
  • SMTP
  • TCP
  • JDBC
  • RMI
  • FTP
  • Etc…

It also has integrates with many proven open source technologies including:

  • Spring
  • Quartz
  • Apache Axis
  • XFire
  • Spring
  • Acegi
  • Etc…

Some good introductory articles for mule can be found here. I have been working with mule in an enterprise integration project for the last few months so over the next while I will post some more information on my experiences.


Welcome

August 9, 2006

I will use this blog to post on technologies I am working on – mostly J2EE but also any “bandwagon” I am on at the time.