Skip to content

Archive

Category: Software

Recently I have been messing around with Django, a very cool Python powered web framework that makes it very easy to create websites quickly. Like similar frameworks (i.e. Ruby on Rails, CakePHP, etc.) Django excels at doing most of the heavy lifting for you. What is most jarring at first, and perhaps the most powerful design choice later on, is that Django has an almost complete separation of server side code from website design.

How does it work?

Django works in a very straightforward way.

  1. Upon receiving a new request, Django will match the request to a handler function.
  2. The handler function will gather all of the data needed to display the page as well as do any server-side changes (i.e. database updates or whatever).
  3. The handler function will pass the information to the HTML template to render and the result will be sent back to the requester.

This very straight forward, three step process is just a high level view of the power that Django offers however.

1. Match incoming requests to an appropriate handler function

This step is actually done by using Django’s urlpatterns system. Essentially a collection of regex this (very fast!) function easily re-directs your incoming requests to their destinations. For instance in the example below a request to www.example.com/ would be handled by the index_handler function, whereas a request to www.example.com/hello/ would be handled by some_other_function.

urlpatterns = patterns('',
     ('^/$', index_handler),
     ('^hello/$',  some_other_function),
)

What’s beautiful about this is that you can easily change the URL structure of your website (or just change URL mappings) without actually moving any code. So unlike something like classical PHP, where the code is embedded in the web page, Django simply looks at the incoming URL and then decides which code it should run. If I want to change my URL syntax from www.example.com/blog/ to www.example.com/awesomeblog/ I can do it (without breaking anything!) by just changing this file. And this is just the start of the cool things you can do with this file. As the official Django tutorial says:

Because the URL patterns are regular expressions, there really is no limit on what you can do with them. And there’s no need to add URL cruft such as .php — unless you have a sick sense of humor, in which case you can do something like this:

(r’^polls/latest\.php$’, ‘polls.views.index’),

But, don’t do that. It’s silly.

2. The handler function

Instead of reinventing the wheel, each handler function is simply a standard Python function that takes in a request object. In its most basic form it looks something like this:

def hello(request):
     return HttpResponse("Hello world")

Of course being standard Python these functions also inherit the ability to do anything Python can do, including using real objects. Django does an excellent job of marrying these objects with the database engine so that, if you want to, you don’t ever have to write any real SQL. Instead Django will handle the creation of highly optimized SQL calls for you automatically when you call basic object functions.

One of the coolest built in features is the Form class. This class represents a standard HTML form as well as a selection of standard rendering formats (i.e. tables, ordered lists, unordered lists, etc.) in addition to allowing you to completely customize them. Why put this HTML in a Python function and not in the HTML template? Because using it here gives us free validation. I’ll give you an example:

class ContactForm(forms.Form):
     subject = forms.CharField()
     email = forms.EmailField(required=False)
     message = forms.CharField()

Creates a form class with three fields (two of which are required). The resulting HTML (depending on how you want it displayed) is something like:

<tr><th><label for="id_subject">Subject:</label></th><td><input type="text" name="subject" id="id_subject" /></td></tr>
<tr><th><label for="id_email">Email:</label></th><td><input type="text" name="email" id="id_email" /></td></tr>
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>

OK so how is it used?

def contact(request):
     if request.method == 'POST':
          form = ContactForm(request.POST)
          if form.is_valid():
               return HttpResponse("Everything was valid!")
          else:
               form = ContactForm()
               return render_to_response('contact_form.html', {'form': form})

This function will accept the form’s submitted POST arguments, validate them (meaning that at a minimum the subject and message fields need to be filled out) and return a page saying “Everything was valid!”. If the form is not valid it simply hands off the form object to the template engine to be rendered into the html file called “contact_form.html”

3. The template engine

Sticking to its MVC roots Django makes it very easy for web designers to use the data they need without actually needing to write any real code.

For instance here is the example contact_form.html from above:

<html>
  <head>
    <title>Contact us</title>
  </head>
  <body>
    <h1>Contact us</h1>
    <form action="" method="post">
      <table>
        {{ form.as_table }}
      </table>
      <input type="submit" value="Submit">
    </form>
  </body>
</html>

The {{ }} braces tell the temple engine to place a Python object in the page at that spot. This is great but what if you need to handle multiple pieces of data (like a Python list)? The template engine allows you access to easy functionality to accomplish anything you can think of. Here is an example of some template ‘code’ that will put all of the items in item_list in an unordered HTML list for displaying.

<ul>
  {% for item in item_list %}
    <li>{{ item }}</li>
  {% endfor %}
</ul>

More to come

I know this post sounds a lot like an advertisement but the truth is that the flexibility and power of Django is really stunning. I will definitely be doing some more work in this framework going forward so expect to see more updates sometime in the future.

Useful links:

These posts were originally featured on The Linux Experiment

One week, three distributions (Day 0)

With the recent releases of Linux Mint Debian Edition, Ubuntu and Kubuntu 10.10 I am once again starting to feel that need to hop around and try something new out. …I’ve set myself up a little experiment of sorts: try each distribution for two days each and on the 7th day choose the best from among the three. Now obviously this isn’t a very fair test, 48 hours is hardly enough to definitely test which of these distributions is truly the best…

One week, three distributions (Day 2: Kubuntu 10.10)

…When I first booted into the desktop I was very pleasantly surprised. I haven’t used KDE since version 4.3 when I had given up on it because, while beautiful and functional, there were just too many rough edges. It seems to be an Internet cliché at this point but I am going to throw it out there anyway: KDE 4.5 is the KDE release you have been waiting for…

Kubuntu 10.10
One week, three distributions (Day 4: Ubuntu 10.10)

…It’s hard to place exactly what makes this theme so nice but Canonical has done a wonderful job iterating the old theme from 10.04 and making some subtle changes that have an incredible overall effect… This level of polish even extends to the new sound menu. Canonical has implemented new sound APIs which allow media players to integrated natively with the sound menu in a way that is just awesome…

Ubuntu 10.10

One week, three distributions (Day 6: Linux Mint Debian Edition)

…I have to say that my first impression of LMDE was a mixed one. On one hand it spewed text everywhere as it booted, which I assume came from its Debian heritage. On the other hand the boot was ridiculously fast… Once at my desktop I was presented with a very familiar Linux Mint set up…

Linux Mint Debian Edition

One week, three distributions (Day 7: Conclusions)

…What makes a great distribution great? This is a very interesting question that I’m sure would generate a wide array of unique and passionate responses. Some prefer ease of use, while others demand nothing less than complete control over what they can tweak. There are people who swear by using nothing but open source solutions, while others are happy to add proprietary code into the mix as well. This is the great thing about Linux, we get so many choices which means we get to decided what we want…

Java Web Start is a technology that allows easy deployment of Java based software through a web browser. The advantages of this framework are numerous but one nice thing is that it allows you far more freedom then the completely sandboxed Java applet. In this post I will detail how I converted my Hash Verifier application to run right from the browser.

Java Network Launching Protocol (JNLP)

The javax.jnlp libraries provide the functionality needed to launch the application from within a web browser. This is done through the use of a specially crafted XML file called a jnlp file. This file specifies the application information including the location of the executable jar and any class libraries associated with it. The nice thing about this is that it allows you to specify different class files spending on the platform it is being run on. This is exactly what I needed in order to get the correct SWT libraries loaded on the target platform.

As an example of what a jnlp file looks like here is the file I created for my Hash Verifier application:

<?xml version=”1.0″ encoding=”utf-8″?>
<jnlp spec=”1.0+” codebase=”http://www.tylerburton.ca/webstart” href=”hv.jnlp”>
<information>
<title>Hash Verifier</title>
<vendor>tylerburton.ca</vendor>
<homepage href=”http://tylerburton.ca” />
<description>A graphical file digest generator</description>
<description>Hash Verifier</description>
</information>

<security>
<all-permissions />
</security>

<resources>
<j2se version=”1.5+” />
<jar href=”HashVerifier.jar” />
</resources>

<resources os=”Windows” arch=”x86″>
<jar href=”http://www.tylerburton.ca/swt/3.6.1/swt-win32-windows-x86.jar” />
</resources>

<resources os=”Windows” arch=”x86_64″>
<jar href=”http://www.tylerburton.ca/swt/3.6.1/swt-win32-windows-x86_64.jar” />
</resources>

<resources os=”Windows” arch=”amd64″>
<jar href=”http://www.tylerburton.ca/swt/3.6.1/swt-win32-windows-x86_64.jar” />
</resources>

<resources os=”Linux” arch=”ppc”>
<jar href=”http://www.tylerburton.ca/swt/3.6.1/swt-gtk-linux-ppc.jar” />
</resources>

<resources os=”Linux” arch=”ppc64″>
<jar href=”http://www.tylerburton.ca/swt/3.6.1/swt-gtk-linux-ppc64.jar” />
</resources>

<resources os=”Linux” arch=”x86_64″>
<jar href=”http://www.tylerburton.ca/swt/3.6.1/swt-gtk-linux-x86_64.jar” />
</resources>

<resources os=”Linux” arch=”amd64″>
<jar href=”http://www.tylerburton.ca/swt/3.6.1/swt-gtk-linux-x86_64.jar” />
</resources>

<resources os=”Linux” arch=”x86″>
<jar href=”http://www.tylerburton.ca/swt/3.6.1/swt-gtk-linux-x86.jar” />
</resources>

<resources os=”Linux” arch=”i386″>
<jar href=”http://www.tylerburton.ca/swt/3.6.1/swt-gtk-linux-x86.jar” />
</resources>

<resources os=”Linux” arch=”i686″>
<jar href=”http://www.tylerburton.ca/swt/3.6.1/swt-gtk-linux-x86.jar” />
</resources>

<resources os=”Mac” arch=”x86_64″>
<jar href=”http://www.tylerburton.ca/swt/3.6.1/swt-cocoa-mac-x86_64.jar” />
</resources>

<resources os=”Mac” arch=”amd64″>
<jar href=”http://www.tylerburton.ca/swt/3.6.1/swt-cocoa-mac-x86_64.jar” />
</resources>

<resources os=”Mac” arch=”x86″>
<jar href=”http://www.tylerburton.ca/swt/3.6.1/swt-cocoa-mac-x86.jar” />
</resources>

<resources os=”Mac” arch=”i386″>
<jar href=”http://www.tylerburton.ca/swt/3.6.1/swt-cocoa-mac-x86.jar” />
</resources>

<resources os=”Mac” arch=”i686″>
<jar href=”http://www.tylerburton.ca/swt/3.6.1/swt-cocoa-mac-x86.jar” />
</resources>

<resources os=”Mac”>
<jar href=”http://www.tylerburton.ca/swt/3.6.1/swt-carbon-mac.jar” />
</resources>

<resources os=”SunOS” arch=”sparc”>
<jar href=”http://www.tylerburton.ca/swt/3.6.1/swt-gtk-solaris-sparc.jar” />
</resources>

<resources os=”SunOS” arch=”x86″>
<jar href=”http://www.tylerburton.ca/swt/3.6.1/swt-gtk-solaris-x86.jar” />
</resources>

<application-desc main-class=”ca.tylerburton.hashverifier.HashVerifierMain” />

</jnlp>

As you can see I have outlined all of the platform configurations that I am going to be compatible with. Java Web Start takes care of the rest for me automatically.

Digital signatures

The final step is to digitally sign the executable jar. This is required because when deploying an application that is not sandboxed, or one that requires access to low-level functions and libraries (as is the case in SWT), the end user needs to know that the code they are receiving came directly from the source. The easiest way to do this is to follow the instructions here. Unfortunately unless you are willing to pay to have your certificate signed by a trusted certificate authority the end user will need to click OK through a big security warning before they can use your program. It’s a small issue to overcome but if Minecraft can do it without too much of a headache I’m sure you can too.

Easy deployment

It’s as simple as that. I didn’t have to re-write my code, heck I didn’t even have to adjust a single line and it all just works. To see the result on your platform click here.

Note: unfortunately there is an issue with the Mac version of Java Web Start & SWT that prevents it from working correctly. Until Apple fixes this, or OpenJDK takes over and does it, SWT applications cannot be started correctly on that platform through Web Start.

Both Java and Mono (the open source implementation of C# and .NET) will be receiving pretty big updates this year. These represent two very popular virtual machine based coding platforms that offer portability and a slew of helpful standard libraries. Here are just a handful of the improvements each will see in the coming release.

Java SE 7.0

While no tentative release date has been scheduled for Java 7 yet, the team has recently completed milestone 10 of 10. Sacrificing some features (which will be delayed until Java 8.0) Java 7 still has quite a few intriguing new additions.

  1. G1 (new garbage 1st garbage collector)

    This new garbage collector improves upon the original generational one by introducing the concept of regions. You can think of regions has smart versions of the generational lists that should allow the collector to clean up large chunks of garbage with increased efficiency.

  2. Dynamic language support

    The JVM will now support some internal changes which will allow dynamic languages (like Perl and Ruby) to leverage the speed and widespread nature of JVM for languages that aren’t strongly typed like Java. This in turn will will let dynamic languages have hooks into the standard Java libraries as well.

  3. NIO (New I/O)

    A new set of libraries for dealing with I/O. This will let Java do some interesting things like create symbolic links as well as giving general I/O operations a big performance boost.

  4. Native Java video libraries

    New standard video libraries will let the JVM playback and record video sources on any platform. No more relying on external libraries to do the job.

  5. Strings in switch statements

    I for one never really understood why you weren’t allowed to do this before. Obviously switch statements are highly optimized to act on numeric values but would it really be that hard for the compiler to change the string switch statement into an if statement for me? Now I don’t have to even think about it anymore.

  6. Automatic resource management

    Rather than having to worry about closing that I/O stream, Java will now take care of it for you. The new syntax is:do(BufferedInputStream bis = …) { //do some work} //it will automatically be closed here

  7. Others

    Other improvements include compressed 64-bit pointers to save memory, new parallel processing libraries to leverage multi-core CPUs and graphics acceleration improvements.

Mono 2.28

The folks over at the Mono team just finished up a new release that contains quite a few interesting additions as well.

  1. Full C#/ASP.NET 4.0 support

    This is nice to see because it means at the very least Mono and .NET are on equal footing when it comes to language syntax.

  2. New generational garbage collector

    Moving away from the older Boehm-Demers-Weiser garbage collector to a new generation garbage collector (a la Java) should mean improved performance at the temporary expense of extra memory usage. This should let the runtime decide the best time to schedule a garbage collection action and only focus on the objects most likely to need collection.

  3. Dynamic language support

    Similar to Java, this version of Mono now also supports the System.Dynamic libraries. Again this will allow dynamic languages to leverage the portable nature of Mono as well as hooking into the various Mono runtime libraries.

  4. New parallel libraries and frameworks

    These new libraries should make it even easier to create applications that make use of parallel processing. Among the libraries is PLINQ, an optimized version of LINQ for multi-core systems.

  5. Overall performance improvements

    Mono now targets LLVM which should make it better as a server platform. In addition there have been a lot of code fixes and performance improvements throughout the project. Finally this version of Mono has also removed Glib as a dependency which should make it lighter and more portable.

This post was originally featured on The Linux Experiment

Open source software (OSS) is great. It’s powerful, community focused and, lets face it, free. There is not a single day that goes by that I don’t use OSS. Between Firefox, Linux Mint, Thunderbird, Pidgin, Pinta, Deluge, FileZilla and many, many more there is hardly ever an occasion where I find myself in a situation where there isn’t an OSS tool for the job. Unfortunately for all of the benefits that OSS brings me in my daily life I find, in reflection, that I hardly ever do anything to contribute back. What’s worse is that I know I am not alone in this. Many OSS users out there just use the software because it happens to be the best for them. And while there is absolutely nothing wrong with that, many of these individuals could be contributing back. Now obviously I don’t expect everyone, or even half for that matter, to contribute back but I honestly do think that the proportion of people who do contribute back could be much higher.

Why should I?

This is perhaps the easiest to answer. While you don’t have to contribute back, you should if you want to personally make the OSS you love even better.

How to I contribute?

Contributing to a project is incredibly easy. In fact in the vast majority of cases you don’t need to write code, debug software or even do much more than simply use the software in question. What do I mean by this? Well the fact that we here on The Linux Experiment write blog posts praising (or tearing to shreds supplying constructive criticism) to various OSS projects is one form of contributing. Did I lose you? Every time you mention an OSS project you bring attention to it. This attention in turn draws more users/developers to the project and grows it larger. Tell your family, write a blog post, digg stories about OSS or just tell your friends about “this cool new program I found”.

There are many other very easy ways to help out as well. For instance if you notice the program is doing something funky then file a bug. It’s a short process that is usually very painless and quickly brings real world results. I have found that it is also a very therapeutic way to get back at that application that just crashed and lost all of your data. Sometimes you don’t even have to be the one to file it, simply bringing it up in a discussion, such as a forum post, can be enough for others to look into it for you.

Speaking of forum posts, answering new users’ questions about OSS projects can be an excellent way to both spread use of the project and identify problems that new users are facing. The latter could in turn be corrected through subsequent bug or feature requests. Along the same lines, documentation is something that some OSS projects are sorely missing. While it is not the most glamorous job, documentation is key to providing an excellent experience to a first time user. If you know more than one language I can’t think of a single OSS project that couldn’t use your help making translations so that people all over the world can begin to use the software.

For the artists among us there are many OSS projects that could benefit from a complete artwork makeover. As a programmer myself I know all to well the horrors of developer artwork. Creating some awesome graphics, icons, etc. for a project can make a world of difference. Or if you are more interested in user experience and interface design there are many projects that could also benefit from your unique skills. Tools like Glade can even allow individuals to create whole user interfaces without writing a single line of code.

Are you a web developer? Do you like making pretty websites with fancy AJAX fluff? Offer to help the project by designing an attractive website that lures visitors to try the software. You could be the difference between this and this (no offense to the former).

If you’ve been using a particular piece of software for a while, and feel comfortable trying to help others, hop on over to the project’s IRC channel. Help new users troubleshoot their problems and offer suggestions of solutions that have work for you. Just remember: nothing turns off a new user like an angry IRC jerk.

Finally if you are a developer take a look at the software you use on a daily basis. Can you see anything in it that you could help change? Peruse their bug tracker and start picking off the low priority or trivial bugs. These are often issues that get overlooked while the ‘full time’ developers tackle the larger problems. Squashing these small bugs can help to alleviate the 100 paper cuts syndrome many users experience while using some OSS.

Where to start

Depending on how you would like to contribute your starting point could be pretty much anywhere. I would suggest however that you check out your favourite OSS project’s website. Alternatively jump over to an intermediary like OpenHatch that aggregates all of the help postings from a variety of projects. OpenHatch actually has a whole community dedicated to matching people who want to contribute with people who need their help.

I don’t expect anyone, and certainly not myself, to contribute back on a daily basis. I will however personally start by setting a recurring event in my calendar that reminds me to contribute, in some way or another, every week or month. If we all did something similar imagine the rapid improvements we could see in a short time.

Windows?? *GASP!*

Sometimes you just have to compile Windows programs from the comfort of your Linux install. This is a relatively simple process that basically requires you to only install the following (Ubuntu) packages:

To compile 32-bit programs

  • mingw32 (swap out for gcc-mingw32 if you need 64-bit support)
  • mingw32-binutils
  • mingw32-runtime

Additionally for 64-bit programs (*PLEASE SEE NOTE)

  • mingw-w64
  • gcc-mingw32

Once you have those packages you just need to swap out “gcc” in your normal compile commands with either “i586-mingw32msvc-gcc” (for 32-bit) or “amd64-mingw32msvc-gcc” (for 64-bit). So for example if we take the following hello world program in C

#include <stdio.h>
int main(int argc, char** argv)
{
printf(“Hello world!\n”);
return 0;
}

we can compile it to a 32-bit Windows program by using something similar to the following command (assuming the code is contained within a file called main.c)

i586-mingw32msvc-gcc -Wall “main.c” -o “Program.exe”

You can even compile Win32 GUI programs as well. Take the following code as an example

#include <windows.h>
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
char *msg = “The message box’s message!”;
MessageBox(NULL, msg, “MsgBox Title”, MB_OK | MB_ICONINFORMATION);

return 0;
}

this time I’ll compile it into a 64-bit Windows application using

amd64-mingw32msvc-gcc -Wall -mwindows “main.c” -o “Program.exe”

You can even test to make sure it worked properly by running the program through wine like

wine Program.exe

You might need to install some extra packages to get Wine to run 64-bit applications but in general this will work.

That’s pretty much it. You might have a couple of other issues (like linking against Windows libraries instead of the Linux ones) but overall this is a very simple drop-in replacement for your regular gcc command.

*NOTE: There is currently a problem with the Lucid packages for the 64-bit compilers. As a work around you can get the packages from this PPA instead.

I stumbled upon a really interesting website tonight run by the guys behind the Debian project. Essentially it is a series of programming language benchmark results, run under different configurations, that not only shows you how each language performed, but also lets you compare and contrast them to one another. So for instance I can compare the performance of C and C++ running on x64 Ubuntu with an Intel Q6600 quad-core. Or Java 6 server VM vs C# Mono or even all four together. If you’re at all interested at seeing how you’re favourite programming language stacks up I highly recommend giving this site a visit.

Back in this previous post I mentioned the possibility of putting up a sort of how-to guide on SWT programming. Well I’ve finally found some time to do so. I will try to make this as step-by-step as possible so that anyone reading this will completely understand what I’m doing.

What you’ll need

I’m making the following assumptions before starting:

  1. That you’ve already installed the Java Development Kit (not just the Java Runtime)
  2. That you’ve installed Eclipse. You can use an alternative but all of my examples will be based on Eclipse. I’m also going to assume that you are at least familiar enough with Eclipse to compile a Java program.
  3. That you have some understanding of Java or at least some programming experience.
  4. That you have the SWT library for your platform downloaded. You can find this on the download page here.
  5. That you’ve created a project in Eclipse (or your IDE) for this walk through.

Import SWT

The first thing you want to do is import the SWT libraries that you have downloaded as an Eclipse project. Start by creating a new project specifically for SWT. For instance I named mine org.eclipse.swt (following the Java standard namespace naming conventions). Next import the SWT files into that project. To do this simply click File > Import and then choose Archive File under the General folder.

Then browse to the zip file you downloaded and choose the project to import this to (again in my example this project is org.eclipse.swt). When all is said and done you should have a project in your workspace for SWT similar to the one I’ve got here:

SWTify your project

To finish adding the SWT libraries into your project we need to add them to your project’s class path. Right-click on your project and click properties. On the left hand side of the window you will see an item called Java Build Path. On that page there will be a number of tabs: Source, Projects, Libraries, etc. Click Projects and then click the Add button. Select the org.eclipse.swt project and click OK. You should see something like this indicating that the SWT libraries will be included in your project’s build path.

We are now ready to begin programming!

The default SWT program

import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class MySWTProject {

     public static void main(String[] args) {

          Display display = new Display();
          Shell shell = new Shell(display);

          shell.open();

          while(!shell.isDisposed()) {
               if(!display.readAndDispatch()) {
                    display.sleep();
               }
          }

          display.dispose();
     }
}

OK so what does it mean. In SWT all of the graphical things that you can do are tied to a Display object. A Display is essentially a link to the OS’ underlying graphics output. What we are talking about is not a monitor – in fact a Display can contain multiple monitors – but rather a more abstracted concept of graphics. If this sounds confusing don’t worry, for the most part that’s all you’ll really need to know about the Display object.

A Shell should be a little easier to understand. It represents a window, the base application container. In fact if you run the above program you should see something like this:

A Shell can be manipulated in all of the ways that you think it would be. For instance you can give it a title by using the setText() method.

shell.setText(“Here is my window title”);

The open() method tells the Shell to start displaying itself. You can also do some interesting things like using the pack() method to size the Shell in order to make it just large enough to hold whatever you put into it.

The little while loop part first checks to make sure that our shell still exists and then executes any input that we may want our application to respond to (via the readAndDispatch() method). Finally we dispose of all resources we have requested from the OS by calling dispose() on the Display object. This is important because unlike regular Java programming we do not get automatic garbage collection in SWT. There is a silver lining however – calling dispose() on an object like Display will automatically call dispose() on any children that are registered with it. That is why we didn’t need to call dispose() on our Shell.

OK I get it, now show me a button

Interaction is very easy to add. For instance we can add a button to our Shell above by simply adding the following code after the line where we create our Shell.

     Button button = new Button(shell, SWT.PUSH);
     button.setText("Push Me");
     button.pack();

Of course you will also need to import the Button library for this to work. In the constructor we pass in the shell (where we want to attach this button, similar to how we attached our shell to the Display object) and a flag called SWT.PUSH. SWT.PUSH tells the button to act as a push button. Next using setText() again we set the button label. Finally using the pack() method, as described above, we can resize the button to be just large enough. If you re-run the program now you will should see something like the following:

Pretty simple stuff. We can even add an action listener that will respond when the button is pressed by using code like this:

button.addSelectionListener(new SelectionListener() {
    public void widgetDefaultSelected(SelectionEvent e) {
          widgetSelected(e);
     }

     public void widgetSelected(SelectionEvent e) {
          System.out.println("The button was pressed!");
     }
});

Again very simple. I hope that this very brief introduction will help people realize that SWT programming is very similar to regular AWT/Swing GUI creation (although each has their own unique weirdness). If you would like to download the sample code file that I used to create this you can do so here. Please let me know if you have any questions about what I have said above, I’d be happy to help. On the other hand if you want a more in-depth look feel, free to hop over to my Hash Verifier post and grab a copy of the source there. The Eclipse Foundation also has an excellent code snippet section here that will show you how to use each GUI widget.

Happy programming.

After reading up on how you can use SWT to give Java a more native look and feel I was interested in giving it a shot first hand. I decided to break out old faithful (Hash Verifier) and re-write it completely in Java/SWT. The end result was an application that has essentially equivalent functionality (see below for differences) but is completely cross-platform. No matter what operating system you end up running this on (Windows, Mac OSX, Linux) it should have a native look and feel. I will explain how I accomplished this literal “write once, run anywhere” code below.

Easy deployment

The download consists of three different programs. The first, and main, named HashVerifier.jar is not actually the Hash Verifier program, but rather a simple sequential application launching system that I wrote to make cross-platform deployment even easier. When you run HashVerifier.jar, either by double-clicking on it or by running it from the terminal with java -jar HashVerifier.jar, it opens up the included rules file and begins to execute the lines one after another. If there is a special platform specific file (such as rules.mac) it will run that instead. Let’s take a look at rules:

java -jar AdaptiveSWT swt.jar
java -XX:+AggressiveOpts -XX:+UseParallelGC -jar HashVerifierApp

As you can see each line is a separate command to be run.

Getting that right look

When HashVerifier.jar starts it reads each line and runs that as a shell command. The line java -jar AdaptiveSWT swt.jar starts the second included program. AdaptiveSWT uses Java’s built in cross-platform UI toolkit, Swing, and displays a small dialog while it downloads the platform’s native SWT library. This is necessary because otherwise I would need to create separate downloads for each platform, each with their unique native SWT library. By using AdaptiveSWT I can instead let it handle all of the dirty work for me. This is really the trick that lets me release exactly one version of the program that looks correct for everyone. The AdaptiveSWT program is even smart enough to know not to re-download the library if you already have it. That being said if you ever do have an issue where you need to re-download the library either delete the swt.jar file in the program directory or change the first line to java -jar AdaptiveSWT -force swt.jar. This forces the download to happen regardless of it you already have it or not.

Hash Verifier

The next line logically starts the actual Hash Verifier application (with a couple of extra performance enhancing flags passed along as well). This version should work almost identically as the previous with a few key differences:

  • I have removed the Export to Hash File menu option as I simply just didn’t use it enough to warrant me spending the time to re-develop it.
  • I have removed the old Help menu option and replaced it with a visit website option.
  • RIPEMD-160 has been replaced with MD2, mostly because that is what the JVM supports “out-of-the-box”.

That’s about it. Please let me know if you have any issues running it on your platform of choice.

Requirements

  • OS: Windows, Mac OSX or Linux (Gtk+)
  • Internet connection
  • Java JRE (targeted at JavaSE-1.6 but might work on the previous version as well)

As before the binary only package contains just the executables, whereas the all package contains the source code as well.

Binary Only Package All Package
File name: hash_verifier_0_3_0_0_binary.zip hash_verifier_0_3_0_0_all.zip
File hashes: Download Here
GPG signature: Download Here Download Here
Screenshots:
License: (LGPL) View Here
Version: 0.3.0.0
File size: 68.6KB 107.1KB
File download: Download Here Download Here

NOTE: This software was tested on Windows Vista, Mac OS 10.6 and Linux Mint 9. While it may (and should) run on similar platforms I have not been able to test this. Please remember that this software is provided “as is” and without any sort of warranty. Use at your own risk.

After a little bit of pressure from the people responding to my previous post (My search for the best KDE Linux distribution), I have finally given in and tried out Chakra. The Chakra Project starts with Arch Linux as a base but, instead of forcing you to build your own distro piece of piece, Chakra comes more or less pre-packaged.

Installation

The installation was one of the best I’ve ever seen. For alpha software this distribution’s first point of interaction is already very polished – even warning me that it is not stable software and might therefore eat my hamster.

The install process even let me decide to install some very useful packages, like Microsoft Core TTF Fonts and Adobe Flash, right away. Even the Language & Time step was incredible, offering a rotating globe that I could drag around and manipulate.

The only issue I had was trying to create a disk partition to install the OS to. This was because I was trying this out inside of VirtualBox, and the virtual hard disk did not have any partitions on it whatsoever. There is a bug and (thankfully) work-around for this known issue with their Tribe installer, and after reading a quick walk-through I was once again ready to install.

The Desktop

The desktop is standard KDE version 4.4.2 after install. Opening up Pacman (or is it Shaman?) showed me a list of brand new software that I could install, including the newest KDE 4.5. One of Project Chakra’s great strengths will be in this rolling release of new software updates. The concept of installing once and always having the most up-to-date applications is very intriguing.

Unfortunately, as with most alpha software, Shaman is still pretty buggy and often crashed whenever I tried to apply the updates. Also unfortunate is that Shaman started a trend of applications simply crashing for no reason. I don’t want to give this distribution a bad reputation, because it is still pre-release software, but I think it goes without saying that the developers have some bug squashing to do before a stable release will be ready. Something I found rather strange is that the current default software selection that Chakra ships with includes two different browsers, Konqueror and rekonq, but no office software whatsoever.

Google Chrome much?

Final Thoughts (for now!)

The Chakra Project looks very promising, albeit very unpolished at the moment. If they can manage to fix up the rest of the distribution, getting it just as polished feeling as the installer, this will definitely be one to look out for. I look forward to trying it out again once it hits a stable release.