Tuesday, April 12, 2011

Linux Mint 10 & Intel Centrino Wireless Card

Today, I got a new laptop and chose to install Linux Mint 10. While the wired connection worked after the install, I had a little trouble with the wireless card, a Intel Centrino Advanced-N 6200.

For my Google searches, I verified the type of card using:

  $ lspci -v
...
01:00.0 Network controller: Intel Corporation Device 008a (rev 34)
Subsystem: Intel Corporation Device 5325
Flags: bus master, fast devsel, latency 0, IRQ 48
Memory at d1600000 (64-bit, non-prefetchable) [size=8K]
Capabilities: <access denied>

In short, to fix the problem I had to upgrade to kernel version 2.6.38 from 2.6.35 and install a driver.

To upgrade my kernel, I followed the helpful instructions here: Upgrade Instructions.

After a reboot, the splash screen and dmesg presented the following complaint:

  [   15.131819] iwlagn 0000:01:00.0: request for firmware file 'iwlwifi-6000g2b-5.ucode' failed.
[ 15.131870] iwlagn 0000:01:00.0: no suitable firmware found!

To resolve this issue, I download the driver, iwlwifi-6000g2b-ucode-17.168.5.2 from Intel Wireless WiFi Link drivers for Linux.

After unpacking the tar, I copied the driver to /lib/firmware:

  iwlwifi-6000g2b-ucode-17.168.5.2 $ sudo cp iwlwifi-6000g2b-5.ucode /lib/firmware

After another reboot, I was able to use my wireless card. Hopefully, this post will help anyone else in a similar situation.

Wednesday, April 6, 2011

Groovy 1.8: Playing with the new @Canonical Transformation

Groovy 1.8 introduces some new transformations through the use of annotations. One I came across that I wanted to investigate was @Canonical which gives you an implementation of equals(), hashCode(), and toString(), along with tuple constructors.

These transformations can also be applied individually through the @EqualsHashCode, @ToString(), and @TupleConstructors respectively.

As I have no experience with tuple constructors, I hope to take a look at that one later. On the other hand, I have written a fair share of equals() and toString() methods (some better than others) so I'm always looking for a good shortcut for both.

To start, I took a look at @EqualsAndHashCode. I wrote the simplest of classes that has one property and tried to see if comparing two instances with the same value would work. Since the class does not override equals(), this failed as one would expected:

  class Person {
int age
}

def p1 = new Person(age:30)
def p2 = new Person(age:30)

assert p1 == p2

The failure presented by running the script:

  Assertion failed: 

assert p1 == p2
| | |
| | Person@3040c5
| false
Person@1ec459b

Adding a simple equals() method does the trick for now as the assertion passes:

  class Person {
int age

boolean equals(o) {
age == o.age
}
}

We can use the @EqualsAndHashCode annotation and remove our override of equals(). Here the assertion will stll pass:

  import groovy.transform.EqualsAndHashCode

@EqualsAndHashCode
class Person {
int age
}

The next question I had was whether or not there was a way to exclude some properties from taking part in the comparsion. Turns out we set the annotation to ignore certain properties using excludes.

Let's add a second property, ssn, and give both our Person instances different values:

  @EqualsAndHashCode(excludes='ssn')
class Person {
int age
String ssn
}

def p1 = new Person(age:30, ssn:'1')
def p2 = new Person(age:30, ssn:'2')

assert p1 == p2

No failures here. Turns out the same can be accomplished by declaring the ssn as private:

  @EqualsAndHashCode
class Person {
int age
private String ssn
}

Now let's add @ToString into the mix:

  import groovy.transform.EqualsAndHashCode
import groovy.transform.ToString

@EqualsAndHashCode
@ToString
class Person {
int age
String ssn
}

def p1 = new Person(age:30, ssn:'1')
def p2 = new Person(age:30, ssn:'1')

assert p1 == p2
println p1

The above script prints out:

  Person(30, 1)

This is definitely more helpful than the default we get if we don't override toString():

  Person@1e092

But it could be improved perhaps if we tell the annotation to include the name of the properties in the created String:

  @ToString(includeNames=true)

We now get the more helpful:

  Person(age:30, ssn:1)

Now let's see what happens if we replace both annotations with @Canoncial:

  @Canonical
class Person {
int age
String ssn
}

def p1 = new Person(age:30, ssn:'1')
def p2 = new Person(age:30, ssn:'1')

assert p1 == p2
println p1

The assertion passes, but we now are reverted to the String representation that didn't include the field names. An attempt to add the includeNames setting failed with an exception:

  'includeNames'is not part of the annotation groovy.transform.Canonical

I found that if added the @ToString annotation back, we get the display we want.

  @Canonical
@ToString(includeNames=true)
class Person {
int age
String ssn
}

So it appears that @Canonical applies both the @EqualsAndHashCode and @ToString annotations, but applies the defaults for each. To be more selective in the behavior of the individual annotations, we need include them individually.

There look's like there are more options for each of the transformations we've used so far. I found the Javadoc for version 1.8-rc-3 in the source release to be very helpful. A link should be made availabe on the Groovy downloads page when 1.8.0 is released.

Installing Groovy 1.8: NoClassDefFoundError: GroovyStarter

Today, I tried installing Groovy 1.8-rc-3 so I could play with some of the new features of the language. On my Ubuntu machine, the current version I had installed from the repositories was 1.7.6, which in itself is pretty recent:

  $ groovy --version
Groovy Version: 1.7.6 JVM: 1.6.0_13

Since I installed Groovy through the Ubunutu repositories using apt-get, the groovy executable was already on my path:

  $ which groovy
/usr/bin/groovy

As I did not want to mess with the default install, to get 1.8 into the picture, I would have to install things manually. After unzipping the install, I expected to be able to run it easily, but I ran into an exception:

  $ /opt/groovy-1.8.0-rc-3/bin/groovy --version
Exception in thread "main" java.lang.NoClassDefFoundError: org/codehaus/groovy/tools/GroovyStarter
Caused by: java.lang.ClassNotFoundException: org.codehaus.groovy.tools.GroovyStarter
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
...
Could not find the main class: org.codehaus.groovy.tools.GroovyStarter. Program will exit.

Of course by instinct, I went to Google, but before I went to far, it hit me to check GROOVY_HOME:

  $ echo $GROOVY_HOME
/usr/share/groovy

After changing the value to my new install, I was able to verify the install:

  $ export $GROOVY_HOME='/opt/groovy-1.8.0-rc-3'
$ /opt/groovy-1.8.0-rc-3/bin/groovy --version
Groovy Version: 1.8.0-rc-3 JVM: 1.6.0_13

Nothing groundbreaking here, but hopefully I won't forget about this the next time and jump to a search page.

Saturday, February 26, 2011

Spring JMS & Groovy: Sending and Receiving Messages

I recently wrote some code using Spring JMS to send a JMS text message to a queue and to receive a response. The examples in the Spring documentation use Java of course to send and receive the messages. Here I wanted to demonstrate how the code can be simplified using Groovy .

In order to send and receive the messages, a JmsTemplate object is required. In a typical case, the template would be configured thru Spring and injected. Here, I'm going to omit the creation process here for brevity's sake, especially given any example would be specific to a particular JMS provider, but the documentation does a great job explaining how to accomplish the creation of a template using Spring.

When sending a text message, we'll need a list of parameters:

  1. The text the message should contain.
  2. The name of the queue to place the request on.
  3. The name of the queue to have the response sent to.
  4. A correlation ID so that we can receive the response created for the message being sent.

Since its simple to get out of the way here, a correlation ID can be created by creating a unique String using:

  def createCorrelationId() { UUID.randomUUID().toString() }

We'll also need a method to create a MessageCreator to give to the JmsTemplate when sending the mesage. A Java example of doing so my look like this using an inner class:

    void sendMessage(JmsTemplate jmsTemplate, String text, String requestQueue, String responseQueue, String correlationId) throws JMSException { 
jmsTemplate.send(requestQueue, new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
TextMessage message = session.createTextMessage(text);
return message;
}
});
}

This example can be made easier on the eyes by using as in Groovy since MessageCreator is an interface (we also get the benefit of not needing the throws declarations):

    def sendMessage(jmsTemplate, text, requestQueue, responseQueue, correlationId) { 
jmsTemplate.send(requestQueue, { session ->
session.createTextMessage(text)
} as MessageCreator)
}

Or we can store the MessageCreator in a variable:

    def sendMessage(jmsTemplate, text, requestQueue, responseQueue, correlationId) { 
def messageCreator = { session ->
session.createTextMessage(text)
} as MessageCreator

jmsTemplate.send(requestQueue, messageCreator)
}

In order to set the response queue and correlationID though, we'll need access to the text message created by the Session provided by the JmsTemplate:

    def correlationId = createCorrelationId() 

def sendMessage(jmsTemplate, text, requestQueue, responseQueue, correlationId) {
def messageCreator = { session ->
session.createTextMessage(text)
message.with {
setText request
setJMSCorrelationID correlationId
setJMSReplyTo session.createQueue(responseQueue)
}

} as MessageCreator

jmsTemplate.send(requestQueue, messageCreator)
}

Since the MessageCreator is defined by a closure, we can extract a method out that the closure will have access to when its executed to create the text message:

    def correlationId = createCorrelationId() 

def createMessage(session, text, responseQueue, correlationId) {
def message = session.createTextMessage(text)
message.with {
setText text
setJMSCorrelationID correlationId
setJMSReplyTo session.createQueue(responseQueue)
}
message
}

def sendMessage(jmsTemplate, text, requestQueue, responseQueue, correlationId) {
def messageCreator = { session ->
createMessage(session, request, responseQueue, correlationId)
} as MessageCreator

jmsTemplate.send(requestQueue, messageCreator)
}

Now that we have a method for sending the request message, we need a way to grab the response. A Java example:

    void receiveResponse(JmsTemplate jmsTemplate, String responseQueue, String correlationId) throws JMSException {
String selector = "JMSCorrelationID='" + correlationId + "'";
Message message = (TextMessage) jmsTemplate.receiveSelected(parameters.getRetrieveFromQueue(), selector);
String response;
if (message != null) {
response = message.getText();
}
return response;
}

A Groovier way:

  def receiveResponse(jmsTemplate, responseQueue, correlationId) { 
def selector = "JMSCorrelationID='$correlationId'"
def message = (TextMessage)jmsTemplate.receiveSelected(responseQueue, selector)
message?.getText()
}

In both reception examples, the fact we may not get a response or text in the response. This is something the caller can deal with or we can modify the examples to throw an exception:

   def receiveResponse(jmsTemplate, responseQueue, correlationId) {
def selector = "JMSCorrelationID='$correlationId'"
def message = jmsTemplate.receiveSelected(responseQueue, selector) as TextMessage
def response = message?.getText()

if (!response) {
throw new Exception("Got nothing!") // in practice would likely throw a more apt or custom exception
}

response
}

To put it all together, the code examples above can be aggregated to a class:

class JmsMessageSender {

def createCorrelationId() { UUID.randomUUID().toString() }

def createMessage(session, text, responseQueue, correlationId) {
def message = session.createTextMessage(text)
message.with {
setText text
setJMSCorrelationID correlationId
setJMSReplyTo session.createQueue(responseQueue)
}
message
}

def sendMessage(jmsTemplate, text, requestQueue, responseQueue, correlationId) {
def messageCreator = { session ->
createMessage(session, request, responseQueue, correlationId)
} as MessageCreator

jmsTemplate.send(requestQueue, messageCreator)
}

def createSelectorFrom(correlationId) {
"JMSCorrelationID='$correlationId'"
}

void receiveResponse(jmsTemplate, responseQueue, correlationId) {
def selector = createSelectorFrom(correlationId)
def message = jmsTemplate.receiveSelected(responseQueue, selector) as TextMessage
def response = message?.getText()

if (!response) throw new Exception("Got nothing!")

response
}
}

A client code example using the above class through three calls:

    JmsTemplate jmsTemplate // injected
def correlationId = messageSender.createCorrelationId()
messageSender.sendMessage(jmsTemplate, text, requestQueue, responseQueue, correlationId)
def response = messageSender.receiveResponse(jmsTemplate, responseQueue, correlationId)

Thanks for reading!

Friday, January 28, 2011

Perl: Retrieve URLs with LWP and LWP::Simple

With Perl there are many ways to make requests over the web. One method is to use the LWP module. Below is an example of using it grab the contents of a web page:

use Carp;
use LWP;

my $url = 'http://prystash.blogspot.com';
my $contents = get_contents_from($url);

print $contents;

sub get_contents_from {
my ($url) = @_;

my $agent = LWP::UserAgent->new;
my $request = HTTP::Request->new(GET => $url);
my $response = $agent->request($request);

if (!$response->is_success) {
croak "Could not get URL '$url'";
}

return $response->content
}
Another simpler method is to use the LWP::Simple module:
use Carp;
use LWP::Simple;

my $url = 'http://prystash.blogspot.com';
my $contents = get_contents_from($url);

sub get_contents_from {
my ($url) = @_;
my $contents = get($url) or croak "Could not get URL '$url'";
return $contents;
}

Thursday, January 27, 2011

Removing Files Older than a Certain Number of Days

Using the find command, we can remove files that have not been modified in a certain number of days old using the mtime option:
  -mtime n
File's data was last modified n*24 hours ago. See the comments for -atime
to understand how rounding affects the inter‐pretation of file modification times.
To delete files that are older than 6 months, we can use:
  $ find . -type f -mtime +180 | xargs rm
Or alternatively:
  $ find . -type f -mtime +180 -exec rm {} \;

Tuesday, January 25, 2011

GMaven: A Couple Early Problems Building a Plugin

My first attempt to build a Maven plugin using GMaven got off to a rough start. I don't want to use this space to complain by any means, but I would to share what I learned in case anyone else runs into something similar.

My first problem had to deal with my use of a newer version of GMaven:

      <plugin>
<groupId>org.codehaus.gmaven</groupId>
<artifactId>gmaven-plugin</artifactId>
<version>1.3</version>
<configuration>
<providerSelection>1.7</providerSelection>
</configuration>
<extensions>true</extensions>
<inherited>true</inherited>
<executions>
<execution>
<goals>
<goal>generateStubs</goal>
<goal>compile</goal>
<goal>generateTestStubs</goal>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
</plugin>

During the build of the plugin, I was given a deprecation warning stating that no mojo descriptors were found in the project:

[WARNING] Deprecation Alert:
[WARNING] No mojo descriptors were found in this project which has a packaging type of maven-plugin.

I found that reason for the warning was that the stub generation was not retaining the Javadoc annotations used to mark a Mojo. By downgrading to version 1.2 of GMaven and changing the providerSelection to 1.6, the warning went away.

Next when trying to use the plugin in another build, I was present with something ilke:

This realm = plexus.core
urls[0] = file:/opt/apache-maven-2.2.1/lib/maven-2.2.1-uber.jar
Number of imports: 10
import: org.codehaus.classworlds.Entry@a6c57a42
import: org.codehaus.classworlds.Entry@12f43f3b
import: org.codehaus.classworlds.Entry@20025374
import: org.codehaus.classworlds.Entry@f8e44ca4
import: org.codehaus.classworlds.Entry@92758522
import: org.codehaus.classworlds.Entry@ebf2705b
import: org.codehaus.classworlds.Entry@bb25e54
import: org.codehaus.classworlds.Entry@bece5185
import: org.codehaus.classworlds.Entry@3fee8e37
import: org.codehaus.classworlds.Entry@3fee19d8
-----------------------------------------------------
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Internal error in the plugin manager executing goal 'org.prystasj.plugins:jms-testing:1.0-SNAPSHOT:hello': Unable to find the mojo 'hello' (or one of its required components) in the plugin 'org.prystasj.plugins:jms-testing'
org.codehaus.groovy.runtime.GroovyCategorySupport.getCategoryNameUsage(Ljava/lang/String;)Ljava/util/concurrent/atomic/AtomicInteger;

I found the solution to this problem was to exclude the groovy-all-minimal jar, version 1.5.7 with:

   <dependency>
<groupId>org.codehaus.groovy.maven</groupId>
<artifactId>gmaven-mojo</artifactId>
<version>1.0</version>
<exclusions>
<exclusion>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all-minimal</artifactId>
</exclusion>
</exclusions>
</dependency>

I also had another that was similar error related to class CallSiteArray that was alleviated by ensuring I was using Groovy 1.6 everywhere.