Tim Mattison

Hardcore tech

Deploying Multiple WAR Files on a Single Instance With Elastic Beanstalk’s Command-line Tools

| Comments

In June this year AWS added the ability to run multiple WAR files with Elastic Beanstalk in a single EC2 instance. This makes deploying several small applications a lot more cost effective.

In order to do this you need to create a ZIP file containing all of the WAR files you want to deploy and you must include a directory called .ebextensions even if it is empty. In my case I just added and empty file called .ebextensions/README.md to make it happy. Obviously if you use .ebextensions for any kind of customization you won’t need to do anything.

When Elastic Beanstalk sees that you’ve deployed a file like this it treats it differently than a normal bundle. It takes the WAR file called ROOT.war and deploys that as the root application. The rest of the WAR files are deployed in directories derived from their file names. For example, application1.war would be accessed through the /application1 path.

Deploying with eb deploy creates a ZIP file that includes everything in your current directory. The problem is that eb init creates a .gitignore file in your deployment directory. eb deploy picks that up that .gitignore and adds it to the archive. On the EC2 instance that runs your application it sees that your archive doesn’t contain just WAR files and the .ebextensions directory and it treats it like a normal single application deployment. If/when this happens you’ll see that you just get your WAR files placed in the /var/lib/tomcat8/webapps/ROOT directory.

There are two possible fixes for this problem.

Solution #1: You can just delete the .gitignore file. IMHO, this isn’t a great solution since you need to remember to do it for each project.

Solution #2: You can patch the Python code that creates the ZIP archive and tell it to ignore the .gitignore file. To do that you need to modify your ebcli/core/fileoperations.py file. On my system, since I’m not using pip, it was located at ~/.ebvenv/lib/python2.7/site-packages/ebcli/core/fileoperations.py. If you use pip or another package manager it will probably be in a different location.

The function you need to modify is called zip_up_folder. My original version looks like this:

1
2
3
4
5
6
7
8
9
10
11
def zip_up_folder(directory, location, ignore_list=None):
    cwd = os.getcwd()
    try:
        os.chdir(directory)
        io.log_info('Zipping up folder at location: ' + str(os.getcwd()))
        zipf = zipfile.ZipFile(location, 'w', zipfile.ZIP_DEFLATED)
        _zipdir('./', zipf, ignore_list=ignore_list)
        zipf.close()
        LOG.debug('File size: ' + str(os.path.getsize(location)))
    finally:
        os.chdir(cwd)

The code I added to set up the ignore_list is:

1
2
3
    if ignore_list is None:
        ignore_list = []
    ignore_list.append(".gitignore")

So my updated function looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def zip_up_folder(directory, location, ignore_list=None):
    cwd = os.getcwd()
    try:
        os.chdir(directory)
        io.log_info('Zipping up folder at location: ' + str(os.getcwd()))
        zipf = zipfile.ZipFile(location, 'w', zipfile.ZIP_DEFLATED)

        if ignore_list is None:
            ignore_list = []
        ignore_list.append(".gitignore")

        _zipdir('./', zipf, ignore_list=ignore_list)
        zipf.close()
        LOG.debug('File size: ' + str(os.path.getsize(location)))
    finally:
        os.chdir(cwd)

After updating that code and doing another eb deploy my set of WARs were all happily running in a single EC2 instance as I’d expect.

How Would You Implement “Cron” on AWS as Inexpensively as Possible?

| Comments

There seems to be a common problem I’ve seen in app developer threads. CloudKit provides tons of functionality to run your app without your own infrastructure but it only runs the APIs they provide. There is an Android syncing API that provides similar things but with the same limitations. Lots of app developers are really cheap because they’re testing the water to see if their app is worth spending money on or not.

The problem: You need to do some simple processing on a data set and give the processed data set to your users.

The solution: Run a scheduled job that processes the data and puts it in S3.

The constraints: You must use AWS. The cost must be under $9 / month (less than a t2.micro) and cheaper is better. You can’t run it on your laptop/Raspberry Pi. It must run at least once per day.

I think it’s a fun exercise to see how this problem can be solved. As I’m learning more and more about AWS there seem to be multiple ways to do it so I’m interested in seeing what other people come up with.

Some possible solutions I’ve seen so far:

How would you do it?

Validating Guava Event Bus Interactions With Mockito

| Comments

Are you using Guava’s event bus in your Java project? Do you need to test and validate interactions with the event bus but are having trouble? Mockito can help you out here with just a few lines of code.

Assume you have two event types. We’ll call them WantedEvent and UnwantedEvent. In your test you can use Mockito to create a mock event bus like this:

1
mockEventBus = mock(EventBus.class);

Then you can use Mockito’s doAnswer functionality to intercept all interactions with the event bus and do something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
doAnswer(new Answer<Void>() {
    @Override
    public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
        Object argument = invocationOnMock.getArguments()[0];

        if (argument instanceof WantedEvent) {
            wantedEventCount++;
        } else if (argument instanceof UnwantedEvent) {
            unwantedEventCount++;
        } else {
            throw new UnsupportedOperationException("This kind of event was not expected");
        }

        return null;
    }
}).when(mockEventBus).post(anyObject());

When you use your event bus in your tests now you’ll be counting the number of times WantedEvent and UnwantedEvent are published (you do need to make those variables accessible outside the scope of this anonymous Answer<Void> block).

You’ll also be throwing exceptions if you see any other kinds of events that you didn’t expect so you can fail immediately if there is additional unwanted behavior going on. Naturally you can leave the else part out and ignore other events completely too.

Using this simple pattern I’ve been able to debug, test, and be confident in the implementation of several projects that use the Guava event bus.

Do you have any tricks or tips related to this article? Is there a better or easier way to do what I’m doing here? Did this get you out of a bind? Post in the comments!

Mockito and ServletInputStreams

| Comments

I was working on a few applications that involve servlets recently and I came across a situation that initially seemed challenging to test with Mockito. I wanted to do something relatively simple which was read a Protobuf sent from a client, turn it into an object, and do some processing on it.

The question is how do you test a servlet that needs to get the input stream from a servlet request?

I found a Stack Overflow post that addresses how to do this with an older version of the ServletInputStream but doing it now requires that you override three additional methods (isFinished, isReady, and setReadListener).

My issue with this is that I don’t want to override those methods because I don’t really know what I want them to do. If I’m mocking something I want to make sure I know when and where it will be used or I want the mocking framework to return default values or throw exceptions so I know where to look when something breaks.

What I landed on was using the thenAnswer method like this:

Mocking a ServletInputStream
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
byte[] myBinaryData = "TEST".getBytes();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(myBinaryData);
      
mockServletInputStream = mock(ServletInputStream.class);

when(mockServletInputStream.read(Matchers.<byte[]>any(), anyInt(), anyInt())).thenAnswer(new Answer<Integer>() {
    @Override
    public Integer answer(InvocationOnMock invocationOnMock) throws Throwable {
        Object[] args = invocationOnMock.getArguments();
        byte[] output = (byte[]) args[0];
        int offset = (int) args[1];
        int length = (int) args[2];
        return byteArrayInputStream.read(output, offset, length);
    }
});

If you need to ever mock a ServletInputStream feel free to use this code to do it. So far it has worked perfectly for me.

Fixing Javac on Mac OS When Multiple JVMs Are Installed

| Comments

For some reason I decided to install the Java 8 JDK a few days ago when I upgraded to Yosemite. In IntelliJ it isn’t a problem but on the command-line it isn’t so nice. Here’s what I get when I try to use javac:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$ javac src/com/timmattison/Main.java
warning: /Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/lib/ct.sym(META-INF/sym/rt.jar/java/lang/Object.class): major version 52 is newer than 51, the highest major version supported by this compiler.
It is recommended that the compiler be upgraded.
warning: /Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/lib/ct.sym(META-INF/sym/rt.jar/java/lang/String.class): major version 52 is newer than 51, the highest major version supported by this compiler.
It is recommended that the compiler be upgraded.
/Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/lib/ct.sym(META-INF/sym/rt.jar/java/lang/Object.class): warning: Cannot find annotation method 'value()' in type 'Profile+Annotation': class file for jdk.Profile+Annotation not found
/Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/lib/ct.sym(META-INF/sym/rt.jar/java/lang/String.class): warning: Cannot find annotation method 'value()' in type 'Profile+Annotation'
warning: /Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/lib/ct.sym(META-INF/sym/rt.jar/java/lang/AutoCloseable.class): major version 52 is newer than 51, the highest major version supported by this compiler.
It is recommended that the compiler be upgraded.
/Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/lib/ct.sym(META-INF/sym/rt.jar/java/lang/AutoCloseable.class): warning: Cannot find annotation method 'value()' in type 'Profile+Annotation'
warning: /Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/lib/ct.sym(META-INF/sym/rt.jar/java/lang/System.class): major version 52 is newer than 51, the highest major version supported by this compiler.
It is recommended that the compiler be upgraded.
/Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/lib/ct.sym(META-INF/sym/rt.jar/java/lang/System.class): warning: Cannot find annotation method 'value()' in type 'Profile+Annotation'
warning: /Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/lib/ct.sym(META-INF/sym/rt.jar/java/io/PrintStream.class): major version 52 is newer than 51, the highest major version supported by this compiler.
It is recommended that the compiler be upgraded.
/Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/lib/ct.sym(META-INF/sym/rt.jar/java/io/PrintStream.class): warning: Cannot find annotation method 'value()' in type 'Profile+Annotation'
warning: /Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/lib/ct.sym(META-INF/sym/rt.jar/java/io/FilterOutputStream.class): major version 52 is newer than 51, the highest major version supported by this compiler.
It is recommended that the compiler be upgraded.
/Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/lib/ct.sym(META-INF/sym/rt.jar/java/io/FilterOutputStream.class): warning: Cannot find annotation method 'value()' in type 'Profile+Annotation'
warning: /Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/lib/ct.sym(META-INF/sym/rt.jar/java/io/OutputStream.class): major version 52 is newer than 51, the highest major version supported by this compiler.
It is recommended that the compiler be upgraded.

When I run javac -version I get mostly what I’d expect:

1
2
$ javac -version
javac 1.7.0_45

So why is it trying to use libraries from the Java 8 JDK? Simply because I forgot to set JAVA_HOME. On Mac OS you can quickly fix this by adding the following line to your .bash_profile and starting a new Terminal session:

1
export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.7.0_45.jdk/Contents/Home/"

Of course you should change _45 to reflect the specific version you’re running and validate that the path in the JAVA_HOME variable exists.

Good luck!

When Unicode Goes Wrong in Java

| Comments

NOTE: This is only guaranteed to work with the Sun JVM since this option is “an internal detail of Sun’s implementations”.

UPDATE 2014-11-12 6:22 PM: The real fix is to set the environment variable LANG to en_US.UTF-8 right before you start your JVM.

Is Unicode breaking in your application and you can’t figure out where? Maybe data from HttpClient is coming back mangled, maybe database queries via JDBC are having Unicode data replaced with question marks, maybe your protobufs are getting shredded, but somewhere something is eating your Unicode data and nothing you’ve tried fixes it. Well…

Did you know the JVM itself has a global Unicode setting specified by the -Dfile.encoding option? Most people I talked to didn’t know about it, myself included, when I ran into a Unicode issue on a project. After some great teamwork and research we found this option, set it, and everything started working again.

All we had to do was put -Dfile.encoding=UTF8 in the script that ran our JVM and everything was fixed but that was only a temporary fix. You really need to set LANG to en_US.UTF-8. If you want to play with it I created a test project on Github that is incredibly simple and shows the right and wrong settings and what they do to a simple trademark symbol. Otherwise, try this on your project and see if it fixes the issue.

Good luck!

Using Interfaces in Camel’s Java DSL With Spring

| Comments

When writing some routes with Camel’s Java DSL I came across this exception:

1
Caused by: java.lang.IllegalStateException: No method invocation could be created, no matching method could be found on: null

After a lot of tracing I figured out that it was related to me calling the .bean(...) method with a class that was actually just an interface. What was happening was that Camel wants to instantiate this class, usually using Spring, but cannot do that if it isn’t a concrete implementation.

This proved to be a real problem because I had an interface that had two implementations. One of these implementations is used for debugging and the other is used for production. I didn’t want to have to manually select which one I was using in my code because that’s Spring’s job so I came up with a way to do it.

For the complete background here’s what my interface looks like:

The interface
1
2
3
4
import org.apache.camel.Processor;

public interface ProtobufToWire extends Processor {
}

This converts a Protobuf to our “wire” format. That format could be the native protobuf binary format or JSON. I implement this empty interface in two classes called ProtobufToBinary and ProtobufToJson and I want to use the JSON one only for debugging.

To be clear doing this always fails with the exception I listed above:

A route that always fails
1
from(SOME_URI).bean(ProtobufToWire.class);

To fix this I added this to my Java-based Spring config:

Getting an instance of ProtobufToWire
1
2
3
4
@Bean
public ProtobufToWire protobufToWire() {
    return new ProtobufToBinary();
}

Now because, I believe, that Camel’s bean(...) method doesn’t look up the beans with Spring this still fails. What I needed to where I am defining my routes is this:

Finally, how to get Camel to instantiate the right type
1
2
3
4
5
6
7
    @Autowired
    private ProtobufToWire protobufToWire;

    @Override
    public void configure() {
      from(SOME_URI).bean(protobufToWire.getClass());
    }

What I’m doing here is getting Spring to autowire an instance of that interface into a private variable and then asking it for its real concrete type. Part of me says that I shouldn’t have to do this but this is what works for me.

Did this help you out? Do you have a better way to do it? Post in the comments!

Activating U2F on a Yubikey Neo on Mac OS

| Comments

I just got my Yubikey Neo with U2F support and I felt like the documentation on how to get it up and running was a bit hard to find. If you are having trouble getting started with U2F these few quick steps will help you get through it.

Step 0: Download and install the Yubikey Neo Manager application. This is NOT the Yubikey Personalization Tool! The Yubikey Personalization Tool does not support enabling U2F yet.

Step 1: Open the Yubikey Neo Manager with your Yubikey installed and click Change connection mode [OTP] Yubikey Neo Manager main screen

Step 2: On the Change connection mode check the U2F box to change the setting from OTP to U2F and click OK. Yubikey Neo Manager main screen Yubikey Neo Manager main screen

The application will now prompt you to remove your device. You can remove it and plug it back in again. Close the Yubikey Neo Manager application.

Step 3: Open Chrome and install the FIDO U2F (Universal 2nd Factor) extension from the Chrome web store.

Step 4: Register on Yubico’s U2F demo page and you’re done.

Now you can log in on the demo page and other sites that support U2F.

Building Apache Camel Applications With Guice

| Comments

UPDATE 2015-07-27: Included instructions to run the project from the command-line

Apache Camel is a great framework for implementing Enterprise Integration Patterns. However, most of the examples you’ll find out there show you how to use it with the Spring framework. I’m much more comfortable with Google Guice since I’ve used it in more production projects.

I did find an example of how to use Guice with Apache Camel but it wasn’t commented well and involved doing a lot of extra work that didn’t provide me any benefits. So below I’ve listed the things that you’ll need to do to get Guice and Camel working together. What we are doing here is setting up Guice as a JNDI provider and automatically loading a Guice CamelModule via JNDI.

Step 1: Create a jndi.properties file in your project’s resources directory. The java.naming.factory.initial line tells JNDI to use Guice, the org.guiceyfruit.modules tells the javax.naming.InitialContext class which module it should run at startup.

jndi.properties
1
2
3
4
5
# Guice JNDI provider
java.naming.factory.initial = org.apache.camel.guice.jndi.GuiceInitialContextFactory

# list of guice modules to boot up (space separated)
org.guiceyfruit.modules = com.timmattison.CamelGuiceApplicationModule

Step 2: Create a class with a static main method that will run your Camel routes. Because JNDI and Guice do most of the work there isn’t much to do here.

com.timmattison.CamelApplication
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.timmattison;

import javax.naming.InitialContext;

/**
 * Created by timmattison on 10/27/14.
 */
public class CamelApplication {
    public static void main(String[] args) throws Exception {
        // Create the Camel context with Guice
        InitialContext context = new InitialContext();

        // Loop forever
        while (true) {
            // Sleep so we don't kill the CPU
            Thread.sleep(10000);
        }
    }
}

Step 3: Create a class that extends RouteBuilder that implements a route (or multiple routes).

In my case I created a RestRoutes class that used the RESTlet framework and created a single route using the Direct component.

I moved the constants out to separate classes so they’d be easier to refer to in other places if necessary.

com.timmattison.CamelConstants
1
2
3
4
5
6
7
8
package com.timmattison;

/**
 * Created by timmattison on 10/27/14.
 */
public class CamelConstants {
    public static final String DIRECT_TEST_ROUTE_1 = "direct:testRoute1";
}
com.timmattison.HttpConstants
1
2
3
4
5
6
7
8
9
10
package com.timmattison;

/**
 * Created by timmattison on 10/27/14.
 */
public class HttpConstants {
    public static final String TEST_URL_1 = "/test1";
    public static final String TEST_URL_2 = "/test2";
    public static final String TEST_URL_3 = "/test3";
}
com.timmattison.RestRoutes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.timmattison;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.rest.RestBindingMode;

/**
 * Created by timmattison on 10/27/14.
 */
public class RestRoutes extends RouteBuilder {
    public static final String RESTLET = "restlet";
    public static final int PORT = 8000;

    @Override
    public void configure() throws Exception {
        restConfiguration().bindingMode(RestBindingMode.auto).component(RESTLET).port(PORT);

        rest(HttpConstants.TEST_URL_1)
                .get().to(CamelConstants.DIRECT_TEST_ROUTE_1);
    }
}

Step 4: Create the interfaces and the implementations that we’re going to use in our route.

Here we’re creating four things:

  1. The interface that we’re implementing that handles the route (SayHello1) that gets injected with Guice via JNDI. This interface doesn’t do anything other than give Guice a way to reference implementations of it.
  2. An implementation of that interface (BasicSayHello1). Also, BasicSayHello1 is going to have a dependency that we want injected with Guice to make the example more complete.
  3. The interface for the class that we want Guice to inject (MessageHandler)
  4. The implementation that gets injected (BasicMessageHandler)
com.timmattison.jndibeans.interfaces.SayHello1
1
2
3
4
5
6
7
8
9
package com.timmattison.jndibeans.interfaces;

import org.apache.camel.Processor;

/**
 * Created by timmattison on 10/27/14.
 */
public interface SayHello1 extends Processor {
}
com.timmattison.jndibeans.BasicSayHello1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.timmattison.jndibeans;

import com.timmattison.jndibeans.interfaces.SayHello1;
import com.timmattison.nonjndibeans.interfaces.MessageHandler;
import org.apache.camel.Exchange;

import javax.inject.Inject;

/**
 * Created by timmattison on 10/27/14.
 */
public class BasicSayHello1 implements SayHello1 {
    private final MessageHandler messageHandler;

    @Inject
    public BasicSayHello1(MessageHandler messageHandler) {
        this.messageHandler = messageHandler;
    }

    @Override
    public void process(Exchange exchange) throws Exception {
        exchange.getOut().setBody(messageHandler.getMessage(getClass().getName()));
    }
}
com.timmattison.nonjndibeans.interfaces.MessageHandler
1
2
3
4
5
6
7
8
package com.timmattison.nonjndibeans.interfaces;

/**
 * Created by timmattison on 10/28/14.
 */
public interface MessageHandler {
    public String getMessage(String input);
}
com.timmattison.nonjndibeans.BasicMessageHandler
1
2
3
4
5
6
7
8
9
10
11
12
13
package com.timmattison.nonjndibeans;

import com.timmattison.nonjndibeans.interfaces.MessageHandler;

/**
 * Created by timmattison on 10/28/14.
 */
public class BasicMessageHandler implements MessageHandler {
    @Override
    public String getMessage(String input) {
        return "Hello " + input + "!";
    }
}

Step 5: Create the direct route that handles the route from RestRoutes

com.timmattison.DirectTestRoutes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.timmattison;

import com.timmattison.jndibeans.interfaces.SayHello1;
import com.timmattison.jndibeans.interfaces.SayHello2;
import com.timmattison.jndibeans.interfaces.SayHello3;
import org.apache.camel.builder.RouteBuilder;

/**
 * Created by timmattison on 10/27/14.
 */
public class DirectTestRoutes extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        from(CamelConstants.DIRECT_TEST_ROUTE_1)
                .beanRef(SayHello1.class.getName());
    }
}

Step 6: Create a Guice module that extends CamelModuleWithMatchingRoutes. I bound my SayHello1 interface to BasicSayHello1, MessageHandler to BasicMessageHandler, and included my RestRoutes and DirectTestRoutes.

com.timmattison.CamelGuiceApplicationModule
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.timmattison;

import com.timmattison.jndibeans.BasicSayHello1;
import com.timmattison.jndibeans.interfaces.SayHello1;
import com.timmattison.nonjndibeans.BasicMessageHandler;
import com.timmattison.nonjndibeans.interfaces.MessageHandler;
import org.apache.camel.guice.CamelModuleWithMatchingRoutes;

/**
 * Created by timmattison on 10/27/14.
 */
public class CamelGuiceApplicationModule extends CamelModuleWithMatchingRoutes {
    @Override
    protected void configure() {
        super.configure();

        bind(SayHello1.class).to(BasicSayHello1.class);

        bind(MessageHandler.class).to(BasicMessageHandler.class);

        bind(RestRoutes.class);
        bind(DirectTestRoutes.class);
    }
}

Now if you don’t want Guice to handle any external JNDI bindings then you’re done. You can run this application as-is and it will serve up the RESTlet route.

To run the application from Maven do this:

com.timmattison.CamelGuiceApplicationModule
1
mvn camel:run

You can test it by using cURL like this:

1
2
$ curl http://localhost:8000/test1
Hello com.timmattison.jndibeans.BasicSayHello1!

If you want to have Guice handle JNDI bindings you can easily add those into your module. For example, if I wanted to be able to get an instance of SayHello1 by using the JNDI name sayHello1FromGuice I could add this to my module:

1
2
3
4
5
    @Provides
    @JndiBind("sayHello1FromGuice")
    SayHello1 sayHello1FromGuice(Injector injector) {
        return injector.getInstance(SayHello1.class);
    }

This tells JNDI that our Guice provider will handle any JNDI requests for this name. Luckily, we didn’t have to create any of these manually because Guice automatically creates JNDI bindings for anything that you’ve called bind on using its class name.

For example there is an automatic JNDI binding for com.timmattison.jndibeans.interfaces.SayHello1 because we called bind(SayHello1.class).to(BasicSayHello1.class). If we ever want an instance of whatever Guice has bound to this we can ask JNDI for it using SayHello1.class.getName().

You’ll notice that in our DirectTestRoutes class we routed the direct test route to beanRef with the parameter SayHello1.class.getName(). That’s all you need to do as you add more classes to your Camel routes.

Want to try this out without building everything from scratch? Head over to my apache-camel-guice repo on Github.

Good luck! Don’t forget to post in the comments!

Hacking Together a Super Simple Webserver With Netcat on a Raspberry Pi

| Comments

A few months ago I wanted to get some data out of WeatherGoose II Climate Monitor so I could convert it into JSON and consume it in another application. I hacked something together and converted their format to JSON in a few hours as a proof-of-concept and the code sat for a few months.

A co-worker recently asked me if they could hook up to my script with a browser to try to do some visualization. I didn’t want to install Apache or nginx as a front end and I didn’t want to modify the script to run its own webserver so I came up with a one-liner that uses netcat to get the output of my script into their browser.

But wait! netcat has an option for this. However, on the Raspberry Pi it is not available and I didn’t want to start downloading new versions.

Here it is:

1
SCRIPT="./weathergoose.py 192.168.1.99" && PORT="8080" && while true; do $SCRIPT | nc -l -p $PORT; done

You’ll need to set SCRIPT to the script you want to run (including any parameters it needs) and PORT to the port you want to listen on.

Be careful! This is not a real webserver. This just spits your scripts output back to the browser. Anything the browser sends to the script is ignored.

Also, the script runs first and pipes its output to netcat. This happens before netcat accepts a connection and can cause some confusion. Here’s a concrete example.

Assume I wrote a script that just returns the time. If I use the above snippet and start it at 5:00 PM but I hit it with my web browser at 5:15 PM the time that I get back will be 5:00 PM. The next time I hit it it will be 5:15 PM. The easiest way to think about it is that you get the data from when the script started or at the time of the previous request, whichever is later.

I hope to come up with a fix for this issue but I haven’t had the time yet. Do you have a fix? Does this work for you? Post in the comments below.