Friday 7 November 2008

Rails 2.0 ActionMailer and SMTP email

Okay, you want to use ActionaMailer in Rails to send smtp mail. First some useful links:




1 - Create a new file in the config/initializers/action_mailer.rb (The file can be called anything)

2 - Place the following settings in it:



ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.default_charset = "utf-8"
ActionMailer::Base.raise_delivery_errors = true

ActionMailer::Base.smtp_settings = {
:address => "your.smtp.server",
:port => 25,
:domain => "your.domain",
:user_name => "username",
:password => "password"
}



You should be able to send SMTP mail. Go and read the above doc about using ActionMailer to create the email and send it.

Tuesday 19 August 2008

On the Rails Hype Cycle

I found this interesting graph on a blog entry about the Technology Hype Cycle.

The diagram is interesting and made me think about my current Rails experience. Each time I code and do something, I really enjoy myself. A side question is ... am I allowed to enjoy myself whilst coding? Past experience in most Java frameworks has been defined more by pain than "enjoyment". I digress.

Two days ago a new rails book I ordered from Amazon arrived(Simply Rails 2 - by Patrick Lenz). I was frothing with anticipation. Even though I have only read the first few chapters and I haven't really learned anything that I didn't already know, yet I am still frothing.

I think that I am still on the way to reach the peak of Inflated Expectations. I just hope that when the Trough of Disillusionment sets in that it won't be so bad. I guess live it up now.

Monday 11 August 2008

I am really enjoying Rails!

Well for a freelance project, I decided to use Ruby On Rails. I have heard the hype. Seen developers at work use it ... blah etc.

After mixing tutorials for Rails 1.2 and Rails 2.0 (There are not that many for 2.0) I actually managed to code something quite easily. I was quite surprised. I think that the scaffolding thing is just awesome. I even "rewrote" my small app a few times as I learnt to do it better. I think the telling thing was that I wrote the app in Rails 2.1.0. Once I uploaded it to my server I was having it hosted on, I realised that they only offered Rails 2.0.2. I rewrote it again. I even managed to figure out how to various rails versions on my local machine and use the version I wanted. Very cool.

Some helpful Rails 2.0 tutorials:


I did this all on my mac. I installed Mamp to get MySql and I eventually settled on textmate as editor as my machine just did not have enough grunt to use Eclipse.

The really great thing is that I am enjoying it. There are some things that have been frustrating, but this has been way easier to learn than say Spring/Hibernate combo.

Friday 9 May 2008

REST in Spring without using Spring Webservices

I quite like using Spring. Especially when using the Spring/Hibernate combo.

About a year ago I started using Spring for a whole heap of REST webservices I was writing. In the process I found it surprisingly easy. Various other colleagues experimented with RESTLET (http://www.restlet.org/) and Jersey (https://jersey.dev.java.net/). But as I wanted to use Hibernate easily and I was using Spring MVC to build the client component of the project I was working on, so I used Spring MVC to build the services. Pretty simple. (Even though I refer to Spring 2.5 in the pom file, I am not using the features of 2.5.)

Here's an example:

I have created a simple webapp using maven. The webapp is called rest-webapp. I have created a stupid service that retrieves the name of an evil programmer.

This means that the request would look like:
http://localhost:8080/rest-webapp/evil/programmers/1

and this would return:
Dr Evil

I wrote a simple class that does this and also returns a 404 error if the request for tne evil programmer does not exist.

This means that the request would look like:
http://localhost:8080/rest-webapp/evil/programmers/6

would return a 404 error with the message: HTTP Status 404 - This evil programmer does not exist!!



pom.xml

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>2.5</version>
</dependency>


web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.
com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>rest-webapp</display-name>
<description>Test Rest Service</description>
<servlet>
<servlet-name>mytest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mytest</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>1</session-timeout>
</session-config>
</web-app>


mytest-servlet.xml (Spring Application Context)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>

<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/evil/programmers/*">myController</prop>
</props>
</property>
</bean>

<bean id="myController" class="au.bandaid.programming.controller.MyTestController">
</bean>

</beans>



MyTestController.java

package au.bandaid.programming.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Hashtable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import au.bandaid.programming.exception.HttpStatusException;

public class MyTestController implements Controller {

private Hashtable list;

public MyTestController() {
list = new Hashtable();
// Set an arbitary list
list.put("1", "Dr Evil");
list.put("2", "Big Bad Billy");
list.put("3", "Big Bad Billy");
list.put("4", "Stevie Exception");
list.put("4", "Frank Void");
}

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {

// Determine the type of method
try {
if (request.getMethod().toUpperCase().equals("GET")) {
writeResponse(response, "text/xml", HttpServletResponse.SC_OK, get(request));
}
//else if (method.toUpperCase().equals("POST"))
//else if (method.toUpperCase().equals("DELETE"))
//else if (method.toUpperCase().equals("PUT"))

else {
throw new HttpStatusException(HttpServletResponse.SC_NOT_IMPLEMENTED, "Operation: " + request.getMethod() + " not supported.");
}
}
catch (HttpStatusException e) {
response.sendError(e.getStatusCode(), e.getMessage());
}
catch (Exception e) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
}

return null;
}

private String get(HttpServletRequest request) throws HttpStatusException {

// Grab some parameters
// I am not using any now
String type = request.getParameter("type");

// Look at the request
// am expecting rest-webapp/programmers/1
Pattern p = Pattern.compile("[1-9]+");
Matcher m = p.matcher(request.getPathInfo());
String index = "";
if (m.find()) {
index = m.group();
}

if (!list.containsKey(index)) {
throw new HttpStatusException(HttpServletResponse.SC_NOT_FOUND, "This evil programmer does not exist!!");
}

return "" + list.get(index) + "";
}

private void writeResponse(HttpServletResponse response, String contentType, int statusCode, String ouput) throws IOException {
response.setContentType(contentType);
response.setStatus(statusCode);
PrintWriter out = new PrintWriter(response.getOutputStream());
out.println(ouput);
out.close();
}

}

Some extra reading:
http://jira.springframework.org/browse/SPR-4419 - Comprehensive REST Support
http://springframework.org/docs/MVC-step-by-step/Spring-MVC-step-by-step.html

Tuesday 29 April 2008

Some have style, unfortunately most don't

Last year I came across this post by Kathy Sierra entitled Code Like a Girl. (It's a great little article and I even wanted to get a t-shirt made up saying - Do you code like a girl?) Since then I have been pondering the issue of writing code that not only works, but looks good and is ultimately understandable to the developer who will come after me to maintain it.

Over the past year I have done a fair bit of maintenance on a legacy app. One thing that struck me is that the app has had a number of developers over the years. Each developer has stamped his/her mark on it. In some cases the stamp is great and in other cases what they have done is rather average. I also noticed a distinct lack of consistency in variable/class names, documentation etc. My job has been to fix a few defects or add some functionality. Typically taking days to understand how the code works and then making 5-10 lines of changes. In each case I have been tempted to redo, rewrite or refactor the code into my style. (I suspect most developers are often tempted with these dark thoughts). But then I faced the risk of breaking something or stamping yet another developers fancy onto the every-growing mangled mess of code. (A side issue is that I see coding as a form of art - maybe a later blog).

Recently I saw this oldish book at work The Elements of Java Style. Nothing too earth shattering in the book but I just loved these principles:
  • Adhere to the style of the original
  • Adhere to the Principle of Least Astonishment - avoid doing things that will surprise the user of your code (If I had a dollar for every time I have been astounded by someone's "creativity" ...)
  • Document any deviations
In the first chapter it states:
"All good software performs well. But great software, written with style, is predictable, robust, maintainable, supportable, and extensible."

There are plenty of style guides out there. But in my experience developers just don't do it. Just imagine if we did. Wouldn't it be cool?

Tuesday 25 March 2008

Maven Webapps debug with Eclipse and Tomcat

I like using Maven. I also like using Step-Trace-Debugging. So here is what I do to accomplish this using Tomcat, Maven and Eclipse.

Required:
Steps:
  • Create or Import your maven project into Eclipse
  • Select File > Properties for this project
  • Select the Tomcat property
  • Check the box "Is a Tomcat Project"
  • Enter the context name. For my example, dcmdb
  • Click Apply
  • Go to /conf/Catalina/localhost and edit the context file i.e. dcmdb.xml.
    • Edit the docBase and workDir to point to the location of your maven project
    • Notice that the docbase should point to ../dcmdb/target/dcmdb-1.0 where
      • ../dcmdb = the location of my maven project
      • ../target/ = the directory that is created when using the maven package command
      • ../dcmdcb-1.0 = the directory that is my artifact name. It's the webapp
  • The final step involves changing the Java Build Path property in Eclipse by pointing the source output to /target/dcmdb-1.0/WEB-INF/classes. This means that once you make a change to your code all you need to do is restart tomcat.

Saturday 8 March 2008

Learning Ruby on Rails 2.0

I have finally made some time to start learning Ruby on Rails. Here's my story:

Downloading and installing
Well at home I am running windows on a laptop with busted keys. Because one of my offspring keeps ripping keys from the keyboard. The latest victims are the spacebar and the "n" key. Sad but true. So I am a little lazy at times I so installed instant rails: http://instantrails.rubyforge.org/wiki/wiki.pl

Finding a suitable tutorial
I then discovered that there is a difference between Rails 2.0 and 1.x. But Rails 2.0 tutorials seem hard to come by (well again if Google does not produce on the first page ... then it's hard to find :)

Ones that I did find and am working through:
Will update as I go.