Wednesday, May 21, 2014

Raspberry Pi is really really fun...

Raspberry Pi is really really fun to use.  Really. I keep expanding my list of things to do.

1. Map the network and post results to RabbitMQ queue
2. Install NoSQL datastore (perhaps Redis or MongoDB) to store network info
3. Make an RaspBMC Server (following an XBMC DIY blog post)
4. Create a grid computing system based on nothing but Raspberry Pis, and use the computing power to take over the world!

Okay, I might be getting a little carried away, but it's crazy how many things you can do with the Raspberry Pi!

I continued with the "mapping the network" idea.

This is what I have done so far:

1. Installed RabbitMQ on the Raspberry Pi
2. Created a queue for holding nmap (network mapping program) info
3. Installed Java on the Raspberry Pi
4. Created a Java app that will parse nmap results and can send the results to the RabbitMQ nmap info queue
5. Created a cron job that will run the nmap command, and then execute the Java app
6. Created an Android app that will read from the queue and display the results

I plan to expand the Android app so that it will do something with the info.  One idea is to install OpenAP on a wireless AP hub, and then have the app block specific MAC addresses.  Or perhaps permanently assign specific IPs to certain MAC addresses.  Not sure yet.  Ideas?

Below is a screen shot of the Android app. It shows the OS type based on info that nmap was able to fetch from the machine. The grey WiFi symbol is for a machine that nmap wasn't able to determine the OS type.  Also, nmap wasn't able to recognize the Raspberry Pi, so I added code to check the vendor of the MAC address.  If the vendor name started with "edimax" (Edimax is the manufacturer of the WiFi dongle the Raspberry Pi is using), then I set the OS type to Raspberry Pi. I made a similar assumption for my Samsung phone - which is not shown below, but is displayed using an Android icon. The app is named NetHutch - which doesn't necessarily make sense except that I happen to be pulling network info from RabbitMQ.



I'll create a post with some of the Android code soon. Until then, I will update the app to list the date and times that network mappings were performed on the main screen, and the details of which hosts were found on the next screen.

Here is a wire frame view of what the update will look like (once I get the time to make the changes). I used Evolus Pencil to create the wire frame. The numbers to the right of the date on the first screen will be the number of hosts found.



Tuesday, May 13, 2014

Raspberry Pi fun...

I received a Raspberry Pi for Christmas and I hadn't found a good use for it yet - until now!  Well, sort of.  I at least found something kind of fun to do with it...as long as your definition of fun is very loose.

I've been using RabbitMQ at work, and I found someone's post about running RabbitMQ on their Raspberry Pi.  "A ha!", I thought. "I'll load interesting messages onto channels, and then I can write an Android app that will fetch the messages.  It will be so amazing!"  The problem is that I couldn't think of what type of data I would want to get.  I ended up deciding to capture all IP addresses on my home network using nmap.

I installed RabbitMQ on the Raspberry Pi by following someone's blog post (very well written!), and then added a user and virtual host. I then wrote a script and some Java code to log all of the IP addresses on my local network. We have a number of devices that connect and disconnect throughout the day, so there would be enough of a change as time goes on to make it interesting.

The script runs nmap to get the network info, and then it calls some Java code that publishes the info to a RabbitMQ channel. I decided to use Java because it was the easiest for me to write the code. I might redo the code in Python once I get some experience with Python.

The nmap command is pretty straight forward: 

sudo nmap -oX myscaninfo.xml 192.168.1.1/24

The -oX parameter tells nmap to output the results in xml format.  

The IP address with the CIDR (Classless Inter-Domain Routing) value at the end (192.168.1.1/24) specifies the IP addresses to scan.  In the example above, it would mean the following:

192.168.1.1 is the starting IP address. We would then mask the address with 24 1 bits => 255.255.255.0.  255 is what 11111111 equals (-1 due to 0 based index).  That means that we would want to view all IP address that are in the unmasked range - 192.168.1.1 to 192.168.1.255.

The Java code parses the XML and pulls out all the address info. It then pairs the IP address with a MAC address, and publishes the data to RabbitMQ.

The next step will be to create an Android app to read from the channel and display the data.

Wednesday, April 16, 2014

Windows service gotchas...

I'm working on a new Windows service, and it's been a while since I've had to create a Windows service from scratch (they are more work, but they taste the best when created from scratch - har har). Here are some of the gotchas I've run into, and have a vague recollection of dealing with these issues before:

 1. You go to install your service (installutil <path to your service executable>), and then start it (net start <your service name>) but get an "System error 5 has occurred. Access is denied." message. 

 The issue is that you need to make sure that the directory where the executable lives has the correct privileges for whatever user you are using to run the Windows service. In my case, I was trying to run the Windows service as "Local Service". That meant that I needed to set security permissions for the parent directory to include "LOCAL SERVICE" and let "LOCAL SERVICE" have full control.

You can see which user will be executing the service by right clicking on the service from withing the "Services" application, and selecting the "Properties" menu item.  Here is the view of my service properties:

Local Service has minimal privileges, and therefore is more secure to use than Network Service or Local System.  There is no password for Local Service despite what it looks like in the image to the left.



I granted access for Local Service to the bin\Debug folder for my Windows service while testing.  


















2. You go to debug your Windows service, but it errors and quits before you can get to Visual Studio and attach to your Windows service process. I ended up adding a Thread.Sleep(10000) in the Main() method right before the ServiceBase.Run() method is called. That seems to be enough time on my machine to open the Attach to Process dialog and then navigate to my Windows service.

Also, it is important that you are running your Visual Studio instance as administrator, or you won't have privileges to attach to your Windows service.

3. You uninstall your service and then attempt to re-install the service, but you get a message stating that the service has been marked for deletion. Once that happens, then you need to reboot your machine in order to install the service. I ran into that problem before, and wrote about it here, but the short version is that you should avoid having the "Services" application running while uninstalling/installing the service.

I'll add onto this post if I hit other generic issues while working on the Windows service.

Wednesday, January 22, 2014

SQL Server and XML DML

Arthur Olcot has a great blog that covers SQL Server and focuses on optimization and SQLXML. He has a post that lists examples of using XML DML that I found to be incredibly useful. Specifically, the conditional insert example is something that I was able to borrow from for a task at work.  

I needed to add some elements to XML in a bunch of rows of data, and I only wanted to add the elements if they didn't already exist. I was afraid that I might need to do a delete, and then an insert, to make sure that I would end up with duplicate values. Thankfully you can do conditional inserts, and his example made it very easy to understand how to use the conditional.

The following is an example of how to use the conditional insert.


DECLARE @xml XML

SET @xml = '
  Cat 1
  Cat 2
  Cat 3
'

SELECT 'before where Cat 3 already exists', @xml

SET @xml.modify('
 insert (
  if (//category[contains(., "Cat 3")]) then () 
  else element category{"Cat 3"} 
 ) as last into (categories[1])
')

SELECT 'after', @xml


SET @xml = '
  Cat 1
  Cat 2
'

SELECT 'before where Cat 3 does not exist', @xml

SET @xml.modify('
 insert (
  if (//category[contains(., "Cat 3")]) then ()
  else element category{"Cat 3"} 
 ) as last into (categories[1])
')

SELECT 'after', @xml

Thanks, Arthur!

Wednesday, November 27, 2013

AWS S3 - Example of searching files in S3 using regex and the ResponseStream

There have been times when I've needed to inspect contents of text files that were created as map reduce output and stored in S3. I had been downloading the files, but there were hundreds of files and they were all very big (around 360 MB each). It was a hassle since it would take a long time to download every file, and it wasted a lot of diskspace. I wanted a way to search for certain data, and then cancel my search so I could stop downloading so much data.  
The solution I chose to use was to use a Regex against the ResponseStream available when you do a GetObject call. That way I'm downloading data, but it isn't being stored on my computer.

Here is the main bit of code for searching the objects contents:


private void SearchObjectForString(AmazonS3 amazonS3, string bucketName, string key, string searchString)
{
    Cursor.Current = Cursors.WaitCursor;

    // Issue call
    var request = new GetObjectRequest();
    request.BucketName = bucketName;
    request.Key = key;

    using (var response = amazonS3.GetObject(request))
    {
        using (var reader = new StreamReader(response.ResponseStream))
        {
            string line;
            var rgx = new Regex(searchString, RegexOptions.IgnoreCase);

            while ((line = reader.ReadLine()) != null)
            {
                Application.DoEvents();
                if (cancelled)
                {
                    Cursor.Current = Cursors.Default;
                    return;
                }

                var matches = rgx.Matches(line);
                if (matches.Count > 0)
                {
                    lstResults.Items.Add(string.Format("{0}/{1}:{2}", request.BucketName, request.Key, line));
                }
            }
        }
    }
    Cursor.Current = Cursors.Default;
}

Wednesday, November 20, 2013

Index POJOs into Solr using SolrJ and SolrServer.addBeans()

SolrJ makes indexing and querying data from solr instances very easy.  One way that SolrJ helps makes indexing data easier is that you can create a POJO (Plain Old Java Object) with annotations that will map the fields to your schema.

Note: I used Solr 4.4 (and SolrJ 4.4) when creating this example.


I created a POJO named SampleDoc that maps a number of fields to the example solr schema:

package org.codecognition;

import org.apache.solr.client.solrj.beans.Field;

public class SampleDoc {
    @Field("id")
    private String id;

    @Field("sku")
    private String sku;

    @Field("name")
    private String name;

    @Field("title")
    private String title;

    @Field("price")
    private float price;

    @Field("inStock")
    private boolean inStock;

    public String getId() { return id; }

    public void setId(String id) { this.id = id; }

    public String getSku() { return sku; }

    public void setSku(String sku) { this.sku = sku; }

    public String getName() { return name; }

    public void setName(String name) { this.name = name; }

    public String getTitle() { return title; }

    public void setTitle(String title) { this.title = title; }

    public float getPrice() { return price; }

    public void setPrice(float price) { this.price = price; }

    public boolean isInStock() { return inStock; }

    public void setInStock(boolean inStock) { this.inStock = inStock; }
}


The POJO can then be indexed using the HttpSolrServer.addBeans() method:

package org.codecognition;

import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

public class SolrJWithAddBeansExample {

    public static void main(String[] args) {
        try {
            HttpSolrServer server = new HttpSolrServer("http://localhost:8983/solr");

            server.addBeans(makeTestRecords(100));

            server.commit();
        } catch (SolrServerException | IOException e) {
            e.printStackTrace();
        }
    }

    private static List<SampleDoc> makeTestRecords(int numRecords) {

        List<SampleDoc> sampleDocs = new ArrayList<SampleDoc>(numRecords);
        Random random = new Random();

        for (int i = 0; i < numRecords; i++) {
            SampleDoc sampleDoc = new SampleDoc();

            sampleDoc.setId((UUID.randomUUID().toString()));
            sampleDoc.setInStock(true);
            sampleDoc.setName(String.format("test%s", random.nextInt(10000)));
            sampleDoc.setPrice(random.nextFloat());
            sampleDoc.setSku("somesku");
            sampleDoc.setTitle(String.format("test title %s", random.nextInt(10000)));
            sampleDocs.add(sampleDoc);
        }

        return sampleDocs;
    }
}

You can find the code here.

Friday, August 23, 2013

Using custom matchers for POJOs with Mockito...

I was trying to do the "right" thing by using TDD while working on a project, and I hit what looks to be a common problem of figuring out how to tell mock objects what to return based on whatever the argument value was that was passed in to the mock's method. It is really easy to specify which values to look for if you are dealing with a simple data type, but it isn't as straight forward if the argument is a complex object. The solution I used is the one I found on StackOverflow.

Here is the code I used:
// member of test class
private MyWorker mockMyWorker = mock(MyWorker.class);
private List<String> listOfOutputValues;
private final String theValueIWant = "some test value";

The class I am testing will use a helper class named MyWorker in this example. The class being tested will call the method MyWorker.listOutputValues(SomeObject) to get a list of output values. The SomeObject has an attribute named someValue. I only want the MyWorker class to return the output listing if the someValue matches a specific value.

I added a "when" statement in the @Before section of the test class. The "when" statement uses the custom matcher to check the value of SomeObject.getSomeValue().

@Before
private void Setup() {
 listOfOutputValues = createTestOutputValues();

 when(mockMyWorker.
                listOutputValues(argThat(hasValidAttributeValue()))).
                   thenReturn(listOfOutputValues);
}

When the mockMyWorker.listOutputValues(SomeObject) method is called in the test code, then it will return the list of Strings if SomeObject.getSomeValue() equals theValueIWant. Here is how the custom matcher is defined in the test class:
// private method in test class
private Matcher<SomeObject> hasValidAttributeValue() {
 return new BaseMatcher<SomeObject>() {
  @Override
  public boolean matches(Object o) {
   return ((SomeObject)o).getSomeValue().equals(theValueIWant);
  }

  @Override
  public void describeTo(Description description) {

  }
 };
}