Friday, August 31, 2007

A Good PHP-based Wiki?

What is the best (or simply a pretty good) PHP-based wiki-tool?

It should:
  • Have highly customizable layout
  • Have wiki-only focus (tikiwiki for instance, is not)
  • Be secure, as in easy to make safe against spammers
  • Low on requirements to hosting environment (running in safe mode, ...)
  • Use a mysql backend
Is MediaWiki the best of breed or are there other and better alternatives?

10 Steps to Secure and Lock Down a Linux Production Server

After following a simple installation like SuSE or RedHat, there are some steps, that needs to be followed to have peace in mind. After this, you are more ready to move the server onto a production network.

Actually, not all the steps are about security only. Some of them are just nice to have checked, before going on into production.

Let us dive in:
  1. Check dmesg output: Make sure it recognizes all hardware correctly and does not show any nasty errors.
  2. Check filesystem sizes and free space: Any alarming small sizes with respect to the system you are going to be running?
  3. Setup clock synchronization
  4. Turn off not used services: Like cupsd, nfs, alsasound, ...
  5. Uninstall unused software: Starting with the software behind the above turned off services, but don't stop there.
  6. Firewall it: Consider installing a firewall on the host itself.
  7. Restrict access: Make sure access protocols are limited to ssh/sftp. Also, consider locking down sshd to only some IPs, etc.
  8. Cut down on running processes: Check running processes and consider if any of them are unimportant to your system. If so turn them off.
  9. Cut down on open ports: Use netstat and possibly a port scanner to check open ports. Have you closed all but the neccessary ones?
  10. Security updates: Create procedure (manual or automatic) to apply security updates onto the system at regular intervals.
Any other ones that you find important, that I am missing?

Thursday, August 30, 2007

Java Initializers - Add elements to a collection type at construction time

I have always had envy on languages that allows you to do this kind of declarations:
var mapLikeType = { "key1" => "value1", "key2" => "value2" }
A variable is declared, initialized to a new Map type instance, and initial values are loaded into the type. Ruby and Perl can do this, hey, even C# can do this in its v3 instance.

Well, Java can too. Sort of.
Map mapLikeType = new HashMap() {{ put("key1", "value1"); put("key2", "value2"); }};
So what is going on here?
  • A variable mapLikeType is declared of type Map
  • An anonymous class, inheriting HashMap, is created
  • The static initializer inside is executed, which puts values into the instance
  • The variable is initialized to the instance of the class
Formatting the code a little different makes it more obvious.
Map mapLikeType = new HashMap() {
{
put("key1", "value1");
put("key2", "value2");
}
};
I am not sure I would use it in production code. It seems like a serious vaste of resources to generate a new anonymous class at each instantiation.

But, I do use it in test code. Often, when writing unit tests, I need to setup part of the domain model with some initial values. The same trick can be utilized there. Assume we have a domain model of Book and Author classes. Here is how to setup a collection type with some data in it:
    Set books = new HashSet() {{
add(new Book() {{
setTitle("The Art of Computer Programming");
addAuthor(new Author() {{ setName("Donald E. Knuth."); }});
}});
add(new Book() {{
setTitle("A Method of Programming");
addAuthor(new Author() {{ setName("Edsger Dijkstra"); }});
}});
}};
This only works on non-final classes.

Wednesday, August 29, 2007

NetBeans Ruby IDE is Great

And this comes from an all time IDEA user...

I have been an active user of the IDEA Ruby plugin when developing with Rails. For some time now, the plugin has annoyed me greatly, as it seemed to leak quite a lot of memory and it was sloooow.

Looking at Headius' post on NetBeans Ruby IDE being the so-called "Bomb" and all the other fuss about the "oh so great NetBeans", combined with my current (bad) experience with the IDEA Ruby plugin, I decided to try out NetBeans Ruby IDE.

I do NOT want the all complete 152MB NetBeans download with UML modelling, SOA development and a lot of other crap. I just want Ruby and Rails support. Luckily, there is just such a download. The NetBeans folks release a nightly NetBeans Ruby IDE only download, which is only 19MB. Nice! And yes, you will want the nightly build to get interesting features.

Installation went smooth. Setting up a project went even smoother. Just pointed at the existing rails dir and NetBeans suggested the correct Ruby IDE. In addition, it has a nice feature, where you can choose to use JRuby, as the Ruby platform. That is very nice. Something IDEA does not have (yet, I think they are planning for it).

Starting up, it begins to index my Ruby installation ruby sources in addition to the project. After this, completion and type lookup begins to work.

My experience so far is that it works great. Compared to IDEA Ruby plugin, NetBeans Ruby IDE is very fast. Feature-wise, they seem to be on a par. Both seem to undergo heavy development in these times.

Of course, I miss knowing all the shortcut keys :-( For those IDEA users of you out there, that want to try this out, here is a small cheat-sheet to get you going (format: IDEA = NetBeans):
  • Goto class: Ctrl-N = Ctrl-O
  • Goto file: Ctrl-Shift-N = Shift-Alt-O
  • Goto declaration: Ctrl-B = Ctrl-B
  • Goto back/forward: Ctrl-Alt-Left/Right = Alt-Left/Right
  • Select in project view: Alt-F1 = Ctrl-Shift-1
I still miss Ctrl-E (view open files popup) and Ctrl-W (expanding, syntax-intelligent marking). Anyone know how to do that in NetBeans?

This all happened on Windows. I sold the idea about trying out NetBeans Ruby IDE to one of my colleagues, which happen to run on Ubuntu. The experience was not quite the same here. It actually crashed a couple of times, with the result of some lost changes. Not nice! Oh well, these are nightly builds :-)

Maven Profiles Activation by Property and the Maven Help Plugin

In maven, you can have profiles both in settings.xml and in the pom.xml (and other places, which I won't mention here). Profiles in settings.xml can be used to define properties that are local to your development environment on your local box. Profiles in the pom.xml of the project can define properties, that are specific to certain target environments, like staging or production.

Example: Filtering resources with properties from a profile
In this example, I have a spring applicationContext.xml, that needs to be copied from src/main/resources to target/classes, and in the process have a variable ${webServiceUrl} replaced (filtered) with the value of a property that fits the environment. What comes into the placeholder depends upon which deployment environment your build is targeting: Your local box, staging or production.

Here is the small extract of the applicationContext.xml, that will have something replaced:

<bean id="fooService" class="com.acme.foo.service.FooServiceImpl">
<property name="webserviceEndpointUrl" value="${webserviceEndpointUrl}"/>
</bean>

And in the pom.xml, we define this, to enable filtering:

<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>

Then, in settings.xml, I define this:

<profiles>
<profile>
<id>foo-development</id>
<activation>
<property>
<name>!environment</name>
</property>
</activation>
<properties>
<webserviceEndpointUrl>http://localhost:8080/services/myservice</webserviceEndpointUrl>
</properties>
</profile>
</profiles>

It defines the property and sets it to a URL, that is correct in my local development environment. Note the use of the activation element, that uses a little trick with the !-sign. It activates the profile, if the property called environment is not set.

Okay, and lastly, I list how the production and staging profiles are setup in pom.xml:

<profiles>
<profile>
<id>production</id>
<activation>
<property>
<name>environment</name>
<value>production</value>
</property>
</activation>
<properties>
<webserviceEndpointUrl>http://www.acme.com/services/myservice</webserviceEndpointUrl>
</properties>
</profile>
<profile>
<id>staging</id>
<activation>
<property>
<name>environment</name>
<value>staging</value>
</property>
</activation>
<properties>
<webserviceEndpointUrl>http://www.acme-test.com/services/myservice</webserviceEndpointUrl>
</properties>
</profile>
</profiles>

These profiles activate if the environment property is set. Which profile is determined by the value of the property. So, how to build with this? Easy!
  • If you simply type "mvn", the environment property is not set, and the profile with the localhost url from settings.xml will be activated.
  • If you type "mvn -Denvironment=production", the profile in settings.xml will not activate (as the environment property is set), but the production profile in pom.xml will.
You can read more about profiles in mavens official introduction to profiles or in the great online maven book by Sonatype in chapter 8 on profiles.

Maven Help Plugin
In my process of setting this up, I stumpled upon a cool maven plugin. The maven help plugin.
Among other things, it can list the actual, active profiles for a build with "mvn help:active-profiles". Even more cool is typing "mvn help:effective-pom" in the project, and get a dump of a pom, which is the actual pom, that maven uses when building (all mixed up with profiles, properties and settings taken from config around in the build setup).

Tuesday, August 28, 2007

JAX-WS Dynamic Dispatch with CXF

Calling a web service is most often done by using some ws implementation stack like Axis2 or CXF/XFire to generate stubs for your language. The stub code is then linked against, to do the actual calls to the web service, marshall and unmarshall data etc.

This posts shows you how to do this completely at runtime, by using the CXF API directly.

If you are willing to bind yourself directly to the CXF API (as opposed to using the standard JAX-WS apis), you can do some nice things. It can do the steps of generating stubs, but completely at runtime. Look at this code:

DynamicClientFactory dcf = DynamicClientFactory.newInstance();
Client client = dcf.createClient("http://host/invoicing.wsdl", DynamicClient.class.getClassLoader());

Object customerParam = Thread.currentThread().getContextClassLoader().loadClass("com.acme.invoicing.Customer").newInstance();

Method setCustIdMethod = customerParam.getClass().getMethod("setCustomerId", String.class);
setCustIdMethod.invoke(customerParam, "CUST-42");

Object[] result = client.invoke("doInvoicingOnCustomer", customerParam);

Here is a bit of explanation of what happens here:
  • Calling createClient on a DynamicClientFactory instance makes CXF load the WSDL, generate stubs and compile them to class files. They are now available on the current threads context classloader.
  • In this example, the invoicing.wsdl service is supposed to have a method doInvoicingOnCustomer(Customer). The wsdl will have Customer defined, which will make CXF generate a Customer class.
  • You can then call loadClass method to load the Customer class and do a newInstance
  • To call customer.setCustomerId(String), we reflect the method out and invoke the setter with the value "CUST-42".
  • And lastly, we call the doInvoicingOnCustomer remote webservice method, giving the Customer instance as parameter
And of course. The Object[] output is typed in generated classes too. Ready to be reflected upon.

The above code binds directly to the CXF API. There is also the possibility of using the standard JAX-WS API for this. There are good examples on using the standard JAX-WS API to do dynamic calls:
But I do not like it. The code in the above two links use the rather low-level API of javax.xml.soap package to construct the call to the server. It seems like you have to now a lot about the needed SOAP message format, QNames to use, etc.

Monday, August 27, 2007

java.net.HttpRetryException: cannot retry due to server authentication, in streaming mode

My battles with CXF continues :-) I was calling a web service, which was protected by basic authentication, and even though I did set username and password, I got this exception:
java.net.HttpRetryException: cannot retry due to server authentication, in streaming mode

Hmm. A google on that exact string turned up nothing. After some searching around, I got to a solution. It has to do with "chunked transfer encoding", which can be set on HttpURLConnection. In my case, I turned this off in code, by doing this against the CXF API:
FooService service = new FooService();
Foo port = service.getFoo();
Client client = ClientProxy.getClient(port);
HTTPConduit httpConduit = (HTTPConduit) client.getConduit();

HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setAllowChunking(false);
httpConduit.setClient(httpClientPolicy);
It is the last three lines, that did the trick. It turns off the use of chunking inside HTTPConduit.

The IDEA Commander Poll - The Results

For some days I have been running a poll here, asking what your usage of the IDEA commander panel is. Well, the poll is closed and here are the results:
  • What is it?: 27% gave this answer. Well, I forgot to add the "I do not use IDEA" option, so this might be non-idea users.
  • I know about it, but never use it: This is where I am placed myself, and a full 68% of the answers landed here too.
  • I use it occasionally: 0%
  • I love it, and use it regularly: 4%
I feel I have to mention that the number of given answer was less than 30.

Wednesday, August 22, 2007

Using SSL with XFire/CXF - Battling "Illegal Protocol https for HTTP URLConnection Factory"

Today I had trouble getting CXF (the new xfire) to access a WSDL file located on a SSL-based URL. In addition, it was behind basic authentication. Let us jump right in. I got this error:
org.apache.cxf.interceptor.Fault: Could not send Message.
at org.apache.cxf.interceptor.MessageSenderInterceptor.handleMessage(MessageSenderInterceptor.java:48)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:206)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:253)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:204)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:179)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:199)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:185)
at com.blogspot.techpolesen.ws.DynamicClient.atSystemHentBilagsnavneForSag(DynamicClient.java:66)
at com.blogspot.techpolesen.ws.DynamicClient.main(DynamicClient.java:25)
Caused by: java.io.IOException: Illegal Protocol https for HTTP URLConnection Factory.
at org.apache.cxf.transport.http.HttpURLConnectionFactoryImpl.createConnection(HttpURLConnectionFactoryImpl.java:44)
at org.apache.cxf.transport.http.HTTPConduit.prepare(HTTPConduit.java:468)
at org.apache.cxf.interceptor.MessageSenderInterceptor.handleMessage(MessageSenderInterceptor.java:46)
... 8 more
Exception in thread "main" org.apache.cxf.interceptor.Fault: Could not send Message.
at org.apache.cxf.interceptor.MessageSenderInterceptor.handleMessage(MessageSenderInterceptor.java:48)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:206)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:253)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:204)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:179)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:199)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:185)
at com.blogspot.techpolesen.ws.DynamicClient.atSystemHentBilagsnavneForSag(DynamicClient.java:66)
at com.blogspot.techpolesen.ws.DynamicClient.main(DynamicClient.java:25)
Caused by: java.io.IOException: Illegal Protocol https for HTTP URLConnection Factory.
at org.apache.cxf.transport.http.HttpURLConnectionFactoryImpl.createConnection(HttpURLConnectionFactoryImpl.java:44)
at org.apache.cxf.transport.http.HTTPConduit.prepare(HTTPConduit.java:468)
at org.apache.cxf.interceptor.MessageSenderInterceptor.handleMessage(MessageSenderInterceptor.java:46)
... 8 more
And googling it eventually led me to the page on configuring SSL support but it does not tell the complete story. What solved my problem was to add a cxf.xml to the root of my classpath, with this content:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:sec="http://cxf.apache.org/configuration/security"
xmlns:http="http://cxf.apache.org/transports/http/configuration"
xsi:schemaLocation="
http://cxf.apache.org/configuration/security
http://cxf.apache.org/schemas/configuration/security.xsd
http://cxf.apache.org/transports/http/configuration
http://cxf.apache.org/schemas/configuration/http-conf.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<http:conduit name="{https://myhost.com/this/is/namespace}MyPortName.http-conduit">
<http:authorization>
<sec:UserName>usernamehere</sec:UserName>
<sec:Password>passwordhere</sec:Password>
</http:authorization>
<http:tlsClientParameters secureSocketProtocol="SSL">

</http:tlsClientParameters>
</http:conduit>
</beans>
It was the secureSocketProtocol="SSL" attribute that solved the problem. Of course, you need to change "{https://myhost.com/this/is/namespace}MyPortName" into a namespace and port name that matches your WSDL. Also note, that I have added static basic authentication credentials to get access to my wsdl.

Tuesday, August 21, 2007

Keep Deployments Thin and Lightweight

In these times, were we preach keeping the architecture stack lightweight, by using tools like spring and hibernate instead of J2EE, I would like to extend the concept a bit. You should also consider keeping your deployments lightweight. Here are some steps you can follow:
  • Deploy as a war file (as opposed to ear files)
  • Avoid dependencies on container setup (such as datasources, JMS queues, authentication, ...)
I will try and explain what I mean.

Deploy as a war file
A war file is relatively simple and easy to understand. In addition to this, it is faster to build as opposed to assembling ear files.

Keeping with war files for deployment will force you out of some technologies, like ejbs for instance, and most of the time, this is a "good thing". Most of time, there are good alternatives. This is where the lightweight stack technologies like spring and hibernate comes in.

Having a war file as the end product also opens up for a much larger container choice in deployment. Tomcat, Jetty, Resin, Weblogic, ..., whereas an earfile requires a complete J2EE container.

Avoid dependencies on container setup
This is all about avoiding "stuff that needs to be setup beforehand" in the deployment phase. Ideally, the war file should be able to be dropped right into any freshly installed container, and just work.

An example is the use of in web.xml to define a datasource dependency by name, and then look it up in the code using JNDI, to get access to connections. For this to work, you rely on the datasource to be defined and setup correctly beforehand, or else your application will fail deployment. What is the alternative? Use some of the pooling implementations out there! For instance c3p0 plugs right into hibernate.

Another example is authentication. In the web.xml file, you could use the to require basic authentication to access your applications URLs. In addition to this, you might require some specific role, to get access to the application. For this to work, you rely on configuration of some JAAS implementation in the container and correct setup of it. This is not neccesarily a simple task, and containers do it differently. What is the alternative? Use acegi and extract the authentication response from the container! Jacob shows how to do basic authentication with an acegi filter.

What is the catch then?
Of course there is a catch. Having the datasource defined external to the application deployment makes it easy to switch what database you are pointing at, without redeploying. Having the container do the authentication makes the container know your principal and roles internally, enabling things like HttpServletRequest.getUserPrincipal() to answer sane values.

But, much of the deployment descriptor requirement of mapping some "made up" name to real resources, comes from J2EEs concept of a developer role, an assembler role and a deployer role. More often than not, you, the developer, has all the roles.

Try keeping it simple for yourself!

Usable stuff from commons-lang

As Java evolves, some parts of commons-lang are not that usable anymore. For instance its enum support. Others have never really appeared that helpful to me. But there are also other parts, that are always written again and again in each project, when we could just use commons-lang.

Here is what I find useful in commons-lang:
Hey, that is not a lot :-)

What a shame that we cannot add methods on existing classes in Java. Even though StringUtils has lots of methods, it seems to always lack some. In Ruby, I could just open the class definition and add new methods. I am not sure I would like that in Java (and it will never be able to, I know).

But C# in .Net 3.0 has something more controlled and type-safe. They have extension methods.

Friday, August 17, 2007

Agile Planning done right with Mingle

As a practitioner of agile methods in my daily work, I have tried several agile planning tools. In the open source space XPlanner seems to have a star, but I have never really liked it. It is much too fine grained in its estimation and followup on tasks. In the last week or so, I have had the opportunity to take a peek at what ThoughtWorks Studios have done in their new Mingle agile planning product. And I must say I am impressed. And this comes from a guy (me), who actually have been pretty involved in the development of a competing product.

To me, Mingle is agile planning tool done right. Here is some of what I like:
  • It does not target one specific method. It has a concept of project templates, where you can choose from three default ones: a default Agile one, a Scrum targeted one and an XP targeted one.
  • If you choose to use, say a Scrum-focused template, you get views and naming, that matches scrum (sprints, backlog, ...)
  • There is no mention of timeframes. Yes, you can plan cards in sprints or iterations, but there is no control of start or stop on specific dates.
  • Cards are taggable, making it possible to group arbitrarily
  • Cards have attributes (sprint number, business value, ...), which are easily edited and you can add both completely new attributes, but also new values for a given attribute.
  • There is a brilliant planning/editing screen, which can switch between list or grid view.
  • In grid view, you can drag and drop between the attribute you have chosen to group on. For instance between sprint numbers to do release planning, or between priority, if doing prioritization.
  • In list view, you can select and edit attributes of multiple cards easily.
And then there is also wiki features, export/import, the dashboard like project home, ...

If this is not enough for you, you can always check out the cool stack it is running on. It is written in Ruby on the Rails framework, but is executed on the Java VM through the marvelous JRuby and served through Jetty. Of course, this has no real meaning to the end user. But I find it cool, and boy they must have had fun mingling.

Trust me, Mingle is worth looking at.

Firefox - It is all Text

It has been said before, but that shall not stop me from shedding some extra light on it. The It's all Text firefox plugin is *great*.

Have you ever tried to author a large chunk of text in a web page and then either the browser crashes, the session is timed out at submit time or you simply accidentally hit the key combination that says "Back". All actions with the effect of loosing all you've typed.

If you have, please do try out the It's all Text firefox plugin.

Thursday, August 16, 2007

We have Closeable but still lacks the using statement

.Net has IDisposable and the using statement.

Java5 has Closeable but still lacks the using statement.

I previously blogged about how Closeable can be used, but what would be really nice in Java, was to have a using statement. If we had that, we could write something in the lines of:
using (InputStream is = ...) {
// use is here
}
Simply as syntactic sugar, as the compiler should just generate this underneath:
InputStream is = null;
try {
is = ...;
// use is here
} catch (IOException e) {
// call close on Closeable here
}
Maybe .Net has an advantage here, as they have no checked exceptions, so it can better utilize IDisposable everywhere, whereas Java5 Closeable can only be used where IOExceptions are thrown.

Are well, the JCP will be too conservative to just add such sugar...

If we do get closures, me might get to add that statement ourselves. Try and take a look at this page on closure proposals and search for closeAtEnd.

Wednesday, August 15, 2007

Java5 added Closeable and I did not even notice!

I stumpled upon some code written by a wise colleague of mine. The code use the new (well, actually not so knew anymore) java.io.Closeable interface, to add a static helper method which can be used in finally blocks to close resources. Here is the code:
import java.io.Closeable;
import java.io.IOException;
public class ResourceUtil {
public static void closeResource(Closeable resource) {
if (resource != null) {
try {
resource.close();
} catch (IOException e) {
//no operation
}
}
}
}

Now, this kind of ResourceUtil class is not at all new to me. I am used to writing such one up too. What has changed is the use of Closeable. Before that interface, I wrote one such method for InputStream, one for OutputStream, files, sockets, ...

Now we only need commons-lang to implement the class shown above :-)

Tuesday, August 14, 2007

The JetBrains IDEA Commander Plugin - Take the Poll

I am a long time IDEA user and I like it. But there is one "feature" I am still to discover the wonders of. The Commander, which can be activated by pressing Alt-2 in an open project.

Can someone please explain to me, what this "feature" can help me with in my development work?

It looks like some kind of file commander, but it is not. Well, naturally, I googled it, and this documentation from JetBrains on IDEA Commander came up. From this, it seems that it is for mass copy, move, ... operations. Okay, cannot say I have missed it. Actually, I always start by assigning the Alt-2 keybinding to something else like Ant Build.

Are you using The Commander? Take the poll at right.

Tip: Starting KDE Konsole with all your favourite tabs open

When developing software, I often have multiple tabs open in Konsole, all of which I have changed directory into some place like: One for trunk, one for starting my server, one for the debugger, one for executing tests... When I boot and startup Konsole again, I go through opening all the tabs and changing directory to the places I need in each of them. How tiring that is.

Well, there is a better way.
  • Open Konsole
  • Open and setup all the tabs you need
  • Goto Settings->Save Session Profile and enter a name that fits, say "foo"
Now, the next time you start Konsole, you can do it with "konsole --profile foo" and it will open up as when saved. Nice. Also, you can do "konsole --profiles" to list all saved profiles.

Oh how I wish I had something like konsole on windows.

Monday, August 13, 2007

Generating XML from Java using ECS is Simple and Easy

A tip on using the simple Jakarta Element Construction Set to output xml with.

Today, I had the need to produce some simple xml, from a simple object structure in Java. I was not in the mood to get one of the big guns into position (XStream, Xerces, DOM, JAXB, ...), but simply wanted to output some tag content easily, without importing the world in dependencies.

And then I found ECS, Jakarta Element Construction Set, which was just what I needed. It is simple to work with, and have a bare minimum of dependencies (as in none, nada, zip, nil, ingen, just the ecs jar).

The API of ECS is built like a fluent interface, so you can do code like this:
XMLDocument root = new XMLDocument(1.0, true, "UTF-8").addElement(new XML("books"))
.addElement(
new XML("book", true)
.addXMLAttribute("title", "Pragmatic Programmers")
.addXMLAttribute("rating", "Good").addElement(new XML("review", true).addElement("Blah blah")))
.addElement(
new XML("book", true)
.addXMLAttribute("title", "Programming in Foo")
.addXMLAttribute("rating", "Bad").addElement(new XML("review", true).addElement("Blah blah")));

String xmlString = root.toString("UTF-8");

Which produces this xml:
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book title="Pragmatic Programmer" rating="Good">
<review>Blah blah</review>
</book>
<book title="Programming in Foo" rating="Bad">
<review>Blah blah</review>
</book>
</books>

The ECS project seems dead in that the mailing lists are inactive and that it is not actively maintained. Also, the documentation is lacking, even the Javadoc. Anyhow, it is a very simple API, and it did what I needed and worked well.

Friday, August 10, 2007

Custom PopUps and Modal Dialogs in Flex

Steps on learning to develop Flash, with a Java developer focus...

In this post, I will show how to create modal dialogs in flex. In Flex, everything is so "damn" asynchronous. Well, I think that is a good thing, but it also poses interesting questions, for instance on how to make your user wait for something to complete. You can use modal dialogs built as custom PopUps for that.

Custom PopUps
You use the mx.managers.PopUpManager class to create and remove popup windows. With this, you can create both modal and nonmodal dialogs, simply by putting true or false in third parameter to createPopUp.

In this example, I will start with defining the dialog window to popup. This is defined in the file MyDialog.mxml:
<?xml version="1.0" encoding="utf-8"?>
<mx:TitleWindow xmlns:mx="http://www.adobe.com/2006/mxml" title="My Dialog" showCloseButton="true" close="closeDialog(event)">
<mx:Script>
<![CDATA[
import mx.managers.PopUpManager;
import mx.events.CloseEvent;

private function closeDialog(event : CloseEvent) : void {
PopUpManager.removePopUp(this); // close this dialog
}
]]>
</mx:Script>
<mx:VBox>
<mx:TextInput id="input" />
<mx:Button label="OK" click="closeDialog(null)"/>
</mx:VBox>
</mx:TitleWindow>

As you can see, the dialog is a TitleWindow, and it contains a close-cross in the top corner and a button. Both will call the closeDialog method if clicked, which will make the dialog remove itself using PopUpManager.

And here comes the Main.mxml file, which opens the dialog when a button is clicked.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.managers.PopUpManager;

private function showDialog() : void {
PopUpManager.createPopUp(this, MyDialog, true); // popup modal dialog
}
]]>
</mx:Script>
<mx:Button label="Open Modal Dialog" click="showDialog()"/>
</mx:Application>
When the example is run, you will see that everything else but the dialog is greyed out and not focus enabled.

Downloading the source
As usual, I have zipped up the sources for you. It can be downloaded from here. Ready to be build with maven.

Other Small Flex Tutorials
This was lesson 6 in my series of posts on what I learn about developing filthy rich flash apps using flex2. If you want to read more, the previous lessons can be found here:

Thursday, August 09, 2007

Tip: Finding Artifacts in the Maven Repository

Just a small tip.

If you constantly find yourself clicking around in the structure of www.ibiblio.org/maven2, trying to remember if something is to be found under org/apache/commons/logging or simply under commons-logging/commons-logging?

If so, give www.mavenrepository.com a try. Is lets you search the maven repository, telling you which artifacts contains which classes, their location etc.

Good tool if using maven!

Wednesday, August 08, 2007

Found Israfil mojo on google code, nice!

Just a quick note. Previously, I blogged about how to easily build flash output using the flex SDK with maven and the Israfil maven plugin. Today, I saw that the Israfil plugin has entered google code hosting. A nice move on the Israfil folks, I think. Previously, I tried getting the sources, but even though the Israfil site mentioned it to be accessible at them, it was not on the published url.

Well, I guess it is now. And thank you for that!

By the way: It has also been release in a v1.0. Was that in silence, or is it just me, that missed it?

Monday, August 06, 2007

Speedlinking about Google PageRank

Today I noticed that my Google (toolbar) Page Rank has mysteriously gone from 2/10 to 0/10. What? Not good. As a consequence of this, I googled a bit about page rank and how it works, to try and figure out what happened. Here are some links for you...

Of course, google should be the source on the google page rank algoritm, but their explanation is very simple. I then found the original article by Sergey and Brin on the PageRank algorithm, which of course is a bit academic. I then read Ian Rogers' "Page Rank Explained", which was quite informative but still gave me no answer on what went wrong. The former two links were a bit technical (which can be good), whereas the article Google PageRank: What Do We Know About It by Smahing Magazine provides some good overall conclusions. Of course, also wikipedia has an explanation on PageRank.

Unfortunately, I am still left with an open question on want happened. I know I have not changed anything or tried to do any SEO. What I suspect might have happended is something in the lines of:
  • my (relatively small) pagerank of 2, might have been based on a small number of high ranked incoming links
  • some of these sites have changed their pages linking to me in ways, that gives less ranking to me from them (for instance, by having a lot more links on the page than the one to me)
  • google has been running one of its updates of all the page ranks, which is suggested to happen periodically
Anyways, I got to feel how google can make it or break it for you, with their pageranking...

Coding Against a Walking Skeleton

This is a tip on how to startup a large and complex development task.

When I am to begin development on a new project or larger, complex task, which is mainly uncharted territory, I like to employ various techniques. One of which is called "Walking Skeleton".

A Walking Skeleton for me, is: "The smallest and simplest path, from front-end user interface input, through the system services and finally to simple, but usable output".

An example could be the development of a web application which employs a lot of input and complex data validation through a new RIA technology, a complex translation of the input on server-side into some output format and the transport of this to some other part.

Starting up on this, I would define user stories for a simple path all the way through the technology stacks of architecture. But it must be kept simple:
  • The user interface can be simple in layout, and does not need to have all required fields
  • Not all complex validations in client should be implemented, though a few simple ones could
  • On the server-side, the client input should be accepted and validated a bit
  • Some part of the server functionality can be implemented, but you can make shortcuts all over, hard-coding stuff etc.
  • Some final output shall be produced
From this, you should be able to produce a final walking skeleton in 1, 2 or 3 iterations.

From here on, when the walking skeleton is done, the story writing and planning can be thought of as putting meat on the skeleton:
  • Assess the main risks in the development (the parts you are most uncertain with)
  • Which functionality delivers the most wanted business value to the customer
Make stories out of this, and start putting meat on the skeleton...

I do not know where the term stems from (do you?), but I did a quick google on it, and found that the book on the Crystal Method (which I have yet to read) mentions it. In addition, a colleague of mine, which is currently reading the great Pragmatic Programmer book, informs me, that it is called "tracing bullets" (or something like that) in that book, which I have completely forgotten about (maybe I should read it again).

Have you got any experience with this too or maybe you have other good advice on coping with such situations?

Thursday, August 02, 2007

"Programming Flex 2": A Great Flex 2 Book!

In the proces of learning to program flex, I tell you about it here. I have just finished the great Programming Flex 2 book from O'Reilly, and thought I would tell you all about that too. It answers a lot of the questions I have learned the hard way, by browsing the web. I wish I had read this book as the very first thing!

It is an O'Reilly book

And why is this important? Well, because I think O'Reilly books are often good. They tend to be concise and to the point, this one too. Not one of those heavy-weight, 1500-pages ones, which actually does not tell you much more, than a shorter, well-written one will.

General Review

The authors do a good job of introducing flex2 in the history of flash development. You gain a solid understanding on how the platform works and how to leverage it. If you now nothing about flash/flex development, this book will get you up to speed quickly.

One really nice thing about it is, that it is tool-agnostic. It tells you about FlexBuilder yes, but it also explains how to use the command-line compilers. All of the books examples are free from IDE-ties.

Detailed Review

After an initial introduction to the platform, the book continues with the following overall subjects:

MXML / ActionScript
A quick and informative explanation of what MXML and ActionScript is, and how they relate to each other. If you know programming in languages like Java or C#, you will quickly grasp how to program ActionScript and what the ActionScript language provides.

User Interface Chapters
It then explain how to build rich, interactive flash user interfaces with flex2. It comes all the way around, telling about all the UI components, containers and layout management, view state management, media management, effects and transitions and more advances stuff like modal dialogs, drag-n-drop, cursors, customized appearence etc.

Business Logic Chapters
I call this part of the book "Business Logic Chapters", because they handle the stuff you need to know to put logic behind the UI. This includes data models for the UI components, validation and formatting and various ways to talk to servers.

The Other Chapters
In the end, there are some extra chapters on debugging and on how to build components for reuse yourself.

Conclusion

If starting up on learning flex or if you want to quickly grasp what flex/flash can do for you in rich internet application development, this book is for you! If you already program in flex2, you most likely will get informative stuff out of the book too, but you will also be skipping something.

All in all I enjoyed reading the book. Well written and informative! Recommendable.

Want more?

If you like, you can read my previous blogs on lessons I've learned while starting up on flex development:

Wednesday, August 01, 2007

Top 5 Best IDEA Plugins

Here are my top 5 plugins I always install in IDEA:

  1. SQL Query Plugin: You nearly always work with databases and this plugin is cool with that
  2. IdeaJad: More often than not, I need to quickly decompile something to see why it fails (or how it works)
  3. CopyFQNPlugin: Ctrl-Shift-Q puts fully qualified class name of class under curser into paste buffer
  4. Copyright: Ensures consistent copyright notice in all class files
  5. Dilbert Daily Strip: When I need a laugh. Presents the daily dilbert strip inside IDEA.
What is your favourite plugin and why?