I've created this blog to catalog software ideas, code examples and everything in between. I've been in the industry for over 3 years and have worked on a variety of projects from Identity and Access Management, to Web Application Security, to Java/Ruby application development.

Read More

Building a Jabber Bot

The Idea

After a great suggestion from a colleague I was inspired to create what I think is an under-used utility.  That utility is an Instant Messaging Bot.  I know they seem dated, and harken back to the days of AIM bots, but in this world of rapid publishing and communications I think they’re an under utilized tool.  This post is meant to highlight the use of two technologies: Java, and Openfire.

The Technology

Openfire is an open-source Jabber(XMPP) server.  The installation is quite simple, the only thing that is required is a JRE, and if you would like, a MySQL database.  In my installation I have installed Openfire on Ubuntu JeOS that has the sun-java6-jdk and mysqld-server packages installed.  Openfire is distributed as a debian package, so installation is a breeze.  You can read more here on how to install, this post will assume you have a working server and a Java development environment…with maven.

The Application

We want our application to login to the Jabber server, and listen for messages bound for the bot user.  Once a message is received it should be checked for a command, and a proper response should be sent back to the user.  In order to accomplish this we need three classes.  One class will handle logging into the Jabber server and beginning to listen for chat messages.  The other class will be invoked when a chat is initiated, and the other will handle messages sent in that chat session.

Smack is the client library that we will use for this project.  Spark can be download from the same site that you downloaded Openfire from.  Smack includes the two interfaces we will use for the class that listens for chat requests, and handles chat messages.  These interfaces are ChatManagerListener, and MessageListener.

The Code

We’ll start by adding our dependency for the Smack client library:

<dependency>
  <groupId>jivesoftware</groupId>
  <artifactId>smack</artifactId>
  <version>3.0.4</version>
</dependency>

Now that we have the necessary dependency we can focus on our three classes. We will start with our App class. This class as stated before is responsible for connecting to the Openfire server. Here is the App.java class.

public class App {
  public static void main(String[] args) {
    // Assumes you have the SRV records setup in DNS
    XMPPConnection conn = new XMPPConnection("yourdomain.com");
    try {
      conn.connect();
      conn.login("IM_BOT", "Your Bot Password");
      ChatManager chatManager = conn.getChatManager();
      chatManager.addChatListener(new BotChatListener());

      System.out.println("Connected");
      while (conn.isConnected()) {
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
      conn.disconnect();
    } catch (XMPPException e) {
      e.printStackTrace();
    }
  }
}

Our next class is the class responsible for listening and handling incoming chat requests and adding a message listener to the new chat. Here is the BotChatListener.java class.

public class BotChatListener implements ChatManagerListener {

  public void chatCreated(Chat chat, boolean local) {
	  chat.addMessageListener(new BotMessageListener());
  }
}

The MessageListener referred to in the BotChatListener is responsible for handling commands passed to the bot and responding to them appropriately. Here is the BotMessageListener.java class.

public class BotMessageListener implements MessageListener {

  public void processMessage(Chat chat, Message message) {
    System.out.println(chat.getParticipant() + " said -> "
        + message.getBody());
    Message botMessage = null;

    try {
      botMessage = new Message();
      if (message.getBody().equals("nothing")) {
        botMessage.setBody("Fine...");
      } else if (message.getBody().equals("make me toast")) {
        botMessage.setBody("Sure thing");
      } else {
        botMessage.setBody("What do you need?");
      }
      chat.sendMessage(botMessage);
    } catch (XMPPException e) {
      e.printStackTrace();
    }
  }
}

And that’s it…the next step is to extend the BotMessageListener class to do whatever it is you want to accomplish with your bot. If you wish, you can make a Ferris Bueller type bot, and use it to log into Google Talk with your Gmail account and respond to your co-workers messages while you’re out doing whatever it is that you do for fun.

Filed under:Java

Time Machine

Ever since Time Machine was unveiled in the latest OS X release, I’ve been very impressed with its feature set.  To be honest I’ve only had to use it to restore 2 files on my machine…both of which were critical.  The most important time that I”ve had to fire up the Time Machine was to restore my id_dsa ssh key after accidentally deleting it from Terminal.  I did not want to have to gen a new key pair and go around and change my authorized_keys files on many remote machines…so Time Machine did the trick.

Last week my wife’s MacBook took a turn for the worse.  The hard drive was making the “click of death” sound, so off the NewEgg for a new 120GB HDD.  Four days later the drive arrived at my door, and I was itching to see just how easy it was to restore from Time Machine.  The process was pretty easy…the only thing that I would have to add was that the process of getting your new HDD to show up in the list of drives to restore to wasn’t the most straight forward.  I had to first partition the new drive and then reboot the laptop for it to recognize the new HFS+ partition.  Once that was done, the rest was easy.  I hit the restore button, and when I emerged from my basement an hour or so later it was ready for a reboot.  Once it was rebooted, it was like nothing had ever happened…except for the 2 weeks of lost data because my wife isn’t the most diligent about plugging in her external Time Machine backup drive.  With that in mind I envy those of you with Time Capsules…but I don’t envy the price tag.

Tags:

Filed under:OS X

Update a BIOS lately?

So, I’ve spent the past 2 hours attempting to update the BIOS on my Dell SC420 server in hopes of running ESXi. This *should* be an easy task, but if you find yourself without a floppy drive and a Windows system you are in for a 2 hour adventure. 

My first thought was to boot the server from a pen/flash/usb drive. At first glance I thought I could simply use the linux biosdisk utility from Dell available here.  The options are to create a disk image, write directly to a floppy drive, or create an RPM. I attempted using the first two options and made significant use of dd and fdisk without any luck. 

I’m wondering why it is so difficult to do this.  After Google’ing for hours, I found no good solution.  If anyone has a good idea on how to do this, I am all ears.  I am currently downloading a Fedora Core 7 Virtual Appliance so I can use revisor as mentioned here.

The question I have is how in the world do people update their BIOS’s if they do not run Windows on their server, and do not have access to a Windows machine or a floppy drive??

Tags:

Filed under:Uncategorized

Ruby Connection Notifier

Lately I’ve been spending a lot of time at coffee shops in the morning, and because of that have spent a lot of time on wireless networks that are not exactly trustworthy. I always thought it would be nice to get a little notification on incoming established tcp/udp connections. Just to know. So I created this simple ruby script that uses Growl to notify you when an inbound connection is established. Instead of using ruby/pcap to do the job, this script simply relies on the output of the Unix netstat command. The code is below, it requires the Growl Ruby binding which is available here and RubyCocoa which is available here.

#!/usr/bin/ruby
#
#  connection_notifier.rb
#  ConnectionNotifier
#
#  Copyright 2009 Paul Codding
#  All rights reserved.
#
#  Released under the BSD license.
require 'rubygems'
require File.dirname(__FILE__) + '/Growl'

class Connection
  include Comparable
  attr_accessor :protocol, :local_ip, :remote_ip, :local_port, :remote_port, :id

  def initialize(connection_entry)
    pieces = connection_entry.split(" ")
    @protocol = pieces[0]
    @local_ip = pieces[3].split(".")[0..3].join(".")
    @remote_ip = pieces[4].split(".")[0..3].join(".")
    @local_port = pieces[3].split(".").last.to_i
    @remote_port = pieces[4].split(".").last.to_i
    @id = pieces[4].split(".").join()
  end

  def (other_connection)
    @id  other_connection.id
  end

  def to_s
    "#{@protocol} connection established from #{@remote_ip} to port #{@local_port}"
  end
end

class ConnectionNotifier
  GROWL_APP_NAME="Connection Notifier"

  def initialize
    @ports = Array.new(1024)
    @ports.fill { |port| port += 1}
    @connections = Array.new
    @growl = GrowlNotifier.new(GROWL_APP_NAME,['Ruby Connection Notifier'],nil,
              OSX::NSWorkspace.sharedWorkspace().iconForFileType_('rb'))
    @growl.register()

    # Pre-populate connections array so we're not automatically notified about
    # existing established connections
    check_for_new_connections(false)
    build_list_of_listening_ports()
  end

  # Poll for changes in netstat output
  def poll
    while true do
      sleep(2)
      check_for_new_connections(true)
    end
  end

  # Check for a new connection in the output of netstat
  def check_for_new_connections(notify)
    netstat_output = `netstat -na`
    for connection_entry in netstat_output do
      if connection_entry.include?("ESTABLISHED")
        connection = Connection.new(connection_entry)

        if connection.local_port != nil && @ports.include?(connection.local_port.to_i) \
          && !@connections.include?(connection)
          @connections << connection
          if (notify)
            @growl.notify('Ruby Connection Notifier', 'Connection Established',
              connection.to_s)
          end
        end
      end
    end
  end

  def build_list_of_listening_ports
    netstat_output = `netstat -na`
    for connection_entry in netstat_output do
      if connection_entry.include?("LISTEN")
        connection = Connection.new(connection_entry)
        if !@ports.include?(connection.local_port)
          @ports << connection.local_port
        end
      end
    end
  end
end

conn = ConnectionNotifier.new
conn.poll

I’ve created a launch agent configuration for the script as well so it can start when you login. The configuration and source code is located in the ConnectionNotifier.zip file.

To run the script, either execute the script directly, or place the com.paulcodding.connection_notifier.agent.plist file in your ~/Library/LaunchAgents directory and log in again. Just note that you need to update the path to the script within the agent file before it will work. Once the script is running and you attempt a connection from an external machine, or the localhost you should see a growl notification like the image below.

Growl Notification

Growl Notification

Tags: ,

Filed under:Software

Upgrading a large RoR Project from 1.2.6 to 2.0.2

This evening while upgrading a large Ruby on Rails application that I’ve been working on for the past year and a half, I ran into some issues upgrading to 2.0.2.  As you may know actionwebservice has been ousted from rails in favor of REST.  For those of us that depend on using SOAP for interoperability with other applications, we need it to work.  After spending a great deal of time googling to remove the following error:

`report_activate_error':
RubyGem version error: actionpack(2.0.2 not = 1.13.6) (Gem::LoadError)

I found this very helpful article about getting actionwebservices to run under Rails 2.0.2. I’ve yet to see the issues that some other users have seen when using actionwebservices with Rails 2.0.2, but we shall see in the coming days of using it. One thing I had to do that I didn’t really like was to freeze the rails gems into the project. I would rather not have them in my subversion repository.Another issue encountered was with installing gems that needed compilation on my OS X Leopard machine.  Luckily I found a great article detailing the use of the ARCHFLAGS environmental variable. So to install my postgres gem all I had to do was this:

$ sudo -s# export ARCHFLAGS="-arch i386"# gem install postgres

After that, the gem was installed and I no longer received any compile time errors. This stems from the universal binary support mechanism in OS X.

Filed under:OS X, RoR

Using the OpenSessionInViewInterceptor for Spring + Hibernate3

If you’re like me and have written Spring web applications using Hibernate for persistence, you’ve probably seen this error when using FetchType.LAZY in your @OneToMany annotation.

 failed to lazily initialize a collection of role:
        your.Class.assocation no session or session was closed

If you are using lazy loading rather than eager loading for obvious reasons, and you’re trying to access associated objects in your view code, this error can be a bit difficult to resolve. Luckily there is the OpenSessionInViewInterceptor, or the OpenSessionInViewFilter. These solutions will keep the hibernate session open long enough for the view to render what is needed before it is closed, thus allowing you to access your lazy loaded associations without raising an exception. The detail of what this functionality provides can be found on the Hibernate website here.

Now, how does one get this to work in their application? Well, I’ve chosen to illustrate the basic steps necessary to implement the OpenSessionInViewInterceptor. You will need to modify 2 files. These being your applicationContext.xml, and YourApplication-servlet.xml files. We’ll start with the applicationContext.xml file. You will need to place the following snippet after you’ve defined your sessionFactory bean.

<bean id="openSessionInViewInterceptor"
    class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
    <property name="sessionFactory">
        <ref local="sessionFactory"/>
    </property>
    <property> name="flushModeName">
        <value>FLUSH_AUTO</value>
    </property>
</bean>

What does the FLUSH_AUTO do? Here is a quote from the javadoc for the interceptor:

“This interceptor will by default not flush the Hibernate Session, with the flush mode being set to FlushMode.NEVER. It assumes that it will be used in combination with service layer transactions that handle the flushing: the active transaction manager will temporarily change the flush mode to FlushMode.AUTO during a read-write transaction, with the flush mode reset to FlushMode.NEVER at the end of each transaction.”

We use the FLUSH_AUTO to automatically flush the session in this case because I am not using transactions.
Now comes the edit to your YourApplication-servlet.xml file, or whatever file you’ve used to define your URL Mappings. Add the following snippet to your URL mapping bean.

<property name="interceptors">
  <list>
    <ref bean="openSessionInViewInterceptor" />
  </list>
</property>

And that’s that, redeploy and you will no longer see that dreaded exception.

Tags: ,

Filed under:Java, Software

Spring, Hibernate, and Sitemesh

This week at work I’ve had the luxury of getting to sit down and write a sample application using a few of my favorite tools: Spring, and Hibernate-Annotations. New to this equation has been Sitemesh. I’ve been using Tiles for quite a while and have felt very comfortable with it, but at the same time a little annoyed with the amount of work and time it takes to use it. As I sat down to pour out as many best practices as possible into this sample application I figured I should use the opportunity to take the time necessary to explore a new tool. At first I had a hard time finding out just what it takes to use Sitemesh with Spring. I found some helpful hints here and there, but because this blog is meant to try to aggregate my searches into something useful for you (the reader), I will outline just what it takes to integrate Sitemesh into an application.

Sitemesh Integration

What do you have to do to integrate Sitemesh with your newly created Spring application? Well, here is the list of prerequisites:

  • Download Sitemesh from OpenSymphony.
  • Build the sitemesh-2.x.jar using ant.
  • Copy the sitemesh-2.x.jar to the WEB-INF/lib directory of your web application

Now we can move on to integrating Sitemesh into your web application. To use sitemesh with your application only 1 file needs to be edited amazingly enough. Open up your web.xml file and add this snippet:

<!-- Sitemesh -->
<filter>
	<filter-name>sitemesh</filter-name>
	<filter-class>
		com.opensymphony.module.sitemesh.filter.PageFilter
	</filter-class>
</filter>

<filter-mapping>
	<filter-name>sitemesh</filter-name>
	<url-pattern>/*</url-pattern>
</filter-mapping>

So, now what? The next step is to setup the directory structure and files necessary to make things work. Refer to this page on the OpenSymphony site detailing the creation of your first decorator, and creating the WEB-INF/decorators.xml file. I’ve included a copy of my main.jsp file for reference:

<%@ taglib uri="http://www.opensymphony.com/sitemesh/decorator"
	prefix="decorator"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
	<head>
		<title><spring:message code="application.title" /></title>
		<decorator:head />
		<%@ include file="/WEB-INF/view/includes/style.jsp"%>
		<%@ include file="/WEB-INF/view/includes/js.jsp"%>
	</head>
	<body>
		<div id="container">
			<%@ include file="/WEB-INF/view/includes/header.jsp"%>
			<div id="internalWrapper">
				<%@ include file="/WEB-INF/view/includes/links.jsp"%>
				<div id="content">
					<decorator:body />
				</div>
			</div>
			<%@ include file="/WEB-INF/view/includes/footer.jsp"%>
		</div>
	</body>
</html>

So, how do you get your Controllers to spit out decorated pages? Easy, just create a jsp that will be used as the content of the <decorator:body /> tag in the main.jsp file. When you’re returning your ModelAndView just refer to that jsp like the example below:

public ModelAndView list(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
	List<DomainObject> userList = userService.findAll();
	request.setAttribute("userList", userList);
	return new ModelAndView("list.jsp", null);
}

Here is an example snippet of my url mapping for reference as to where the jsp is located:

<prop key="/users/*.html">userController</prop>

In this case my list.jsp is located in the users folder under my web root.

So, isn’t this easier than Tiles?

Tags: , ,

Filed under:Java, Software

Project in the works

Well, I was able to spend some time this weekend to get my OpenBSD firewall back in action after a major HDD catastrophe. After getting my internal network back in order, I’ve decided to begin work on a few projects I’ve been thinking about.

The first project involves the use of Growl, the notification system written for OS X, and snort. Snort is a great little IDS that I’ve been working with for quite some time. Ever since I checked out growl, I’ve been really excited to get something going that utilizes it. Luckily the project with snort is perfect for it. In short the project will use ruby to monitor the snort IDS alert logs for alerts and use Growl to send a notification to the user. Growl does have ruby bindings…hence the choice of ruby. I could use Objective-C, the only problem with that is that I don’t know the language :) . So, ruby it is. I will keep everyone posted on the progress/caveats.

Filed under:OS X, Software

Utilizing Ruby on Rails Web Services with Java

As part of a project I’m currently working on, I’ve had to integrate a RoR application with another developer’s Java code. At first glance, things looked to be fairly simple as I envisioned a simple Web Service communication between Java and Ruby would be a breeze…not so fast. Getting the two to play nice with each other took some time as I was unaware that RoR only supports the RPC/encoded style/use and not Document/literal. After getting a prototyped client written read using Spring-ws (does not support RPC/encoded) I quickly found out that it was going to go nowhere fast. I ended up choosing to use Apache Axis as I’ve used it for a previous project, and I knew for sure it supported RPC/encoded.

Part of the reason for this blog is to share information from developer to developer issues that I’ve encountered that have either been unable or too busy to find solutions to. In this case my solution is to let the reader know that the best bet client to use when consuming RoR web services in Java is Apache Axis. If anyone would enjoy a code example or two I’d be glad to oblige…although the artifacts generated by Axis 1.4 are fairly involved, the process is fairly easy especially when using the SoapUI tool to generate the artifacts based on the RoR WSDL e.g. http://localhost:3000/web_service_name/service.wsdl .

Filed under:Java, RoR

First Tracks

Hey everyone, here’s the first post…hopefully there will be much more to come when time allows.

Filed under:Announcement