Category Archives: Uncategorized

Preventing Software Rot – Part 1

In my years of working with large systems and complicated architectures I have found the following to be true:

  • any system architecture will eventually become out dated
  • programmers will continue to extend a system beyond it’s architecture
  • the system will eventually end up in disarray because it is held together with rubber bands and duct tape
  • management will scrap the system because it’s too costly to maintain
  • system will be replaced by new architecture that will fix everything
  • system will eventually become out dated…

The solution here is very close to cleaning out your junk drawer.

  • know what belongs in your junk drawer and what does not
  • if the idea of what goes in your junk drawer expands, don’t get a bigger drawer, put those new things in a new drawer
  • clean your junk drawer(s) regularly
  • always have a spare drawer for things that might eventually go into one of your drawers or might become their own drawer

What does a junk drawer and software have in common?

Well software is full of features (junk) that can be classified in to solving domain specific problems. For example: I have a junk drawer divided into my camera stuff and my USB gadgets. Any computer system solves a certain set of problems similar to being either a “USB gadget”, or “camera stuff”.

But what happens when I get start accumulating office supplies? Well I could create a third compartment in the drawer, or I could put them temporarily in either the USB part of my junk drawer or the camera part of my junk drawer.

This is very similar to when you get a new classification of problem shoved into your current system. You could reuse an existing drawer, or create a new compartment within the current drawer taking space/resources from the camera or USB compartments. This process could continue with cables, spare DVDs, and so on, but where does it end?

In comes the spare drawer.

Now in the case of our clutter/entropy/drawer rot problem, everything could be solved by always keeping a spare drawer. Now eventually you might accumulate so much junk your entire desk is nothing but drawers, but at least when it comes to refactoring and keeping the drawers you want, you can eliminate, move, delete, etc all without effecting your “primary” junk drawer.

How do you create a spare drawer with software?

Drawer Architecture is a new term I’ll create today. It’s an architecture similar to service oriented architecture (SOA) and enterprise service bus (ESB), but everything is exposed as a restful web service, all database create/read/update/delete transactions, all business objects are exposed, the architecture at it’s core is a fully exposed web api and it’s exposed via a web based dynamic language like, Groovy, Python, Ruby, or PHP.

Stay tuned for my next post… Creating A Drawer Based Architecture.

Continue to Struggle with Linux WebCam

I have some measured success. I was able to get a C program to work at capturing a frame from a webcam in both Java and Ruby, the big problem is is memory.

So I went back to JFM (Java Media Framework) but I am having all kinds of inconsistent issues. Sometimes it works with Groovy, sometimes it does not. I tried it working with straight Java and it’s in-consistent. It sucks that it takes so much effort just to get images I’d really like to do more than fight with device drivers and the basics of frame grabbing, but here I am…

Updated 8/18 @9:38

I am going to stick with my original C implementation, though it has a memory leak right now, it will be easier to manage than trying to muddle through the unsupported JMF.

Updated 8/18 @11:34

I now have a copy of the JMF source. I have a feeling this will be all I need to now get everything working… Plus a C primer or two…

Word Automation with Groovy

I have been working with Ruby and PHP for a bit of automation, but I thought I would give Groovy a shot. It turns out Groovy is just as easy.

First follow the steps at CodeHaus to install Scriptom. Then create a groovy file and paste this in.

package com.scottpreston.groovy.com;

import org.codehaus.groovy.scriptom.*;

def write_word() {

	def word = new ActiveXObject("Word.Application");
	word.Visible = 1;
	word.Documents.Add();
	word.Selection.PageSetup.LeftMargin = '2"';
	word.Selection.PageSetup.RightMargin = '2"';

	//Setup the font
	word.Selection.Font.Name = 'Verdana';
	word.Selection.Font.Size = 8;

	//Write some text
	word.Selection.TypeText("This is a test document");

	//quit and release COM resources
	word.quit();
	//word.Release();
	word = null;

}

write_word();

Goodbye Window XP – For Robots

For sometime I have used Windows XP for my robots, but now that I have been able to get text-to-speech and vision via webcam handled via Linux, I think my days of using Eclipse as an IDE and WindowsXP are coming to a close.

Using WindowsXP has been fine for the most part, but the overhead and licensing of installing a new version and configuring the box was a pain and remote access via RDP took resources and bandwidth. I am confident I will be able to use Ubuntu for the next robot, but I am uncertain as to the resources required to run it.

Stay tuned to ScottsBots.Com for more information…

Finally, An Ubuntu Webcam

Once I got it working I was amazed at how easy it would have been if I had the proper instructions. Even the Ubuntu site does not work well for this but here are the steps I followed to get it working.

Updated /etc/apt/sources.list with:

deb http://blognux.free.fr/debian unstable main

sudo apt-get update

sudo apt-get install easycam2 webcam-server

I then selected yes and installed dependencies and ram the program:

sudo webcam-server -p 88

I then went to my browser and typed http://ipaddress:88, and I saw a snap shot.

 

Getting URL Parameters in JavaScript & PHP

Being a web person I was so use to getting parameters from the URL in Java via the request.getParameter() method. I have found it really cool to use the same functionality in JavaScript and PHP.

Here is a JavaScript function:

function getParameter(name){
 	var out = "";
	var href = window.location.href;
	if ( href.indexOf("?") > -1 ) {
		var qs = href.substr(href.indexOf("?")).toLowerCase();
		var aqs = qs.split("&");
		for ( var i = 0; i < aqs.length; i++ ){
			if (aqs[i].indexOf(name.toLowerCase() + "=") > -1 ){
				var parm = aqs[i].split("=");
				out = parm[1];
				break;
			}
		}
	}
	return unescape(out);
}

Here is a PHP function:

function getParameter($parm) {
	$return = "";
	if (isset ($_REQUEST[$parm])) {
		$return = $_REQUEST[$parm];
	}
	return $return;
}

Viewing A Web Camera with Java

I used this to test Video For Windows and the Java Media Framework (JMF) for my robotics code. If you install the JMF this should work fine for displaying the image from your webcam.

public class WebCamViewer extends SimpleSwing {

    private Timer timer = new Timer();
	private GetFrame getFrame;
    private ImagePanel imagePanel;
    private int fps = 15;
    public static final String DEFAULT_CAMERA = "vfw://0";
    public static final long serialVersionUID = 1;

    public WebCamViewer() throws Exception {
        init(DEFAULT_CAMERA, GetFrame.RGB_ENCODING,320,240);
    }

    public WebCamViewer(String camera) throws Exception{
        init(camera, GetFrame.RGB_ENCODING,320,240);
    }
    public WebCamViewer(String camera, String encoding, int width, int height) throws Exception{
        init(camera,encoding, width,height);
    }
    private void init(String camera, String encoding, int w, int h) throws Exception{
        setTitle("WebCamViewer");
    	// creates frame grabber
        getFrame = new GetFrame(camera,encoding,w,h);
        imagePanel =  new ImagePanel(w,h);
        // set size of the window
        setSize(w + 8, h+35);

        // add imagePanel
        getContentPane().add(imagePanel,BorderLayout.CENTER);
        // make visible
        //this.pack();
        setVisible(true);
    }

    // start the camera frame capture
    public void start() {

        timer.schedule(new TimerTask() {
            public void run() {
                getPic();
            }
        }, 200, (int)(1000 / fps));
    }

    // stop the camera frame capture
    public void stop() throws Exception{
        timer.cancel();
    }

    // get frame from GetFrame
    public void getPic() {
        try {
            // set to image panel and repaint called from ImagePanel
            imagePanel.setImage(getFrame.getBufferedImage());
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
    // get the framegrabber
    public GetFrame getGetFrame() {
        return getFrame;
    }
    // get frames per second
    public int getFps() {
        return fps;
    }
    //sets frames per second
    public void setFps(int fps) {
        this.fps = fps;
    }

    public static void main(String[] args) {
        try {

            WebCamViewer webcam = new WebCamViewer(WebCamViewer.DEFAULT_CAMERA,GetFrame.RGB_ENCODING,320,240);
            webcam.start();
            //Utils.pause(2000);
            //webcam.stop();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(0);
        }
    }
}

Also included is a simple swing class. This will just display a title text and a white background.

public class SimpleSwing extends JFrame {

	public static final long serialVersionUID = 1;
	// constructor
	public SimpleSwing()  {
		// calls JFrame with title
		super("Java Robots Are Cool!");
		// set look & feel
	    WindowUtilities.setNativeLookAndFeel();
	    // closes
	    addWindowListener(new ExitListener());
	    // sets size
	    setSize(320, 240);
	    // sets pane of content
	    Container content = getContentPane();
	    // sets color to white
	    content.setBackground(Color.white);
	    // shows frame
	    setVisible(true);
	}

	  public static void main(String[] args) throws Exception{
	  	SimpleSwing test = new SimpleSwing();

	  }
}

Controlling The Command Line with Java

I wrote this to launch some batch files from within an Java program.

public class CmdExec {

    // process invoking program will call
    private Process p;

    // empty constructor
    public CmdExec() {  }

    // execute command
    public void exe(String cmdline) {
        try {
            // string for system out
            String line;
            // create process
            p = Runtime.getRuntime().exec(cmdline);
            // capture output stream of program
            BufferedReader input = new BufferedReader(new InputStreamReader(p
                    .getInputStream()));
            // get all lines of output
            while ((line = input.readLine()) != null) {
                System.out.println(line);
            }
            // close input stream
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // ability to kill process
    public void kill() {
        p.destroy();
    }
}

Getting Text and Images from The Web with Java

I used this code to get images and text from the web. First an image:

    public static BufferedImage getImage(String urlString)throws Exception {
        // construct URL
        URL url = new URL(urlString);
        // get AWT image
        Image image = Toolkit.getDefaultToolkit().getImage(url);
        // cast to BufferedImage
        return ImageUtils.toBufferedImage(image);
    }

Now to return all text as a String:

    public static String getText(String urlString) throws Exception {
        // construct url
        URL url = new URL(urlString);
        // create input buffer for reading
        BufferedReader in = new BufferedReader(new InputStreamReader(url
                .openStream()));
        // temp string
        String str;
        // create buffer to put information in
        StringBuffer buffer = new StringBuffer();
        // read until end of file
        while ((str = in.readLine()) != null) {
            // since reading line add line feed.
            buffer.append(str+"\n");
        }
        // close buffer
        in.close();
        // return as string
        return buffer.toString();
    }

Creating a Web Spider with PHP

I used this for spidering my site.

function get_links($url) {
	$req = new httprequest();
	$html = $req->get($url);
	$regex = '/mhref/m';
	$preg = '/<a href="([^0-9].+?)"/'; // 1 or more
	$preg = '/<a href="([^0-9].*?)"/'; // 0 or more
	$urls = array ();
	preg_match_all($preg, $html, $urls);
	$count = 0;
	foreach ($urls as $url => $links) {
		if ($count == 1) {
			foreach ($links as $link) {
				echo "link-> " . $link . "\n";
			}
		}
		$count++;
	}
	echo "\n\n";
	//print_r($urls);
}