While working on an AIR client, I had a design comp that required a line divider below each item renderer in a Flex List component. The List component has a style for alternating item colors but not for adding a line divider between each item renderer. I figured it shouldn’t be that hard because I can simply add a bottom border on the container used for the item renderer.
Archive for the ‘Quick Tips’ Category
Removing Padding Between a Flex List and Its Item Renderers
Wednesday, October 1st, 2008Marking Up Forms
Monday, September 29th, 2008Here is my approach when creating forms:
Make use of the label/input value pair tags. Have the label for the attribute equal its corresponding input’s id. This allows the user to activate its control by clicking on the text. Example below:
<label for="fn">First Name</label> <input type="text" id="fn" class="text_input">
Give each input type=”text” a class.
IE6 does not recognize attribute selectors. So, if you style the input selector (ie. input { border: 1px solid #CCC; }), and the form contains radio buttons or checkboxes, IE6 will apply that particular style to all inputs.

To adjust label width, float the label, then give it a width. Differentiate floating from from non-floating labels with <p>s and <div>s.
Example:
<style type="text/css" media="screen">
#myform p label { float: left; width: 9em; }
</style>
<p>
<label for="s_addrs">Shipping Address</label>
<input type="text" name="some_form" value="s_addrs" id="s_addrs" class="text_input">
</p>
<div>
<input type="checkbox" value="" id="check_saddrs" class="text_input">
<labe for="check_saddrs">Check if shipping address is different from personal</labe>
</div>

I believe that these steps are a great starting point when creating forms. Good luck!
Java Quick Tip: Class.forName() with Java Generics
Wednesday, September 24th, 2008In most cases (Lists, Maps, etc.) the syntax for using Java Generics is pretty straight forward, but for Class.forName(…) that’s not the case (at least for me).
Here’s an example of how it’s done. The first code block is the pre-Generics way. It still works, but results in a compiler warning. The second block is the new Generics way that doesn’t generate the warning.
Extending Zend_Controller_Action More Productively
Monday, September 22nd, 2008If you’re developing web apps using the Zend Framework, you’ll notice that your application-specific controller classes will need to share similar functionality with each other. For example, you may want to see if a user is logged in before granting him access to the actions of that controller, or maybe each controller needs a few objects instantiated before it can do its business. One way to do this would be to create a file and include it in the init function. This way you only write the code once, and you can include it in every class like so:
public function init()
{
require_once ‘sharedFunctions.php’;
}
But that’s not really so elegant. It doesn’t really support any object-oriented design patterns. It’s ugly. So what is a better solution? Use inheritance! Your controller classes don’t have to directly extend Zend_Controller_Action. Instead, write a parent class for all of your controllers that extends Zend_Controller_Action.
Let’s move on with an example. Say you’re writing an application that requires all actions to authenticate. If you only had one controller, you could put this check in public function init() and it would be executed before each action is called. But this application isn’t so basic. It’s pretty complex and your architecture requires you to have multiple controller classes. So, instead, create a new class called App_Controller_Action (or namespace it however you’d like). Put it in your include path, the same way you have the Zend Framework set up: App/Controller/Action.php (this way it will autoload the same way the Zend Framework classes load).
class App_Controller_Action extends Zend_Controller_Action
{
public function isAuthenticated()
{
...
}
public function moreSharedFunctionality()
{
...
}
Now all of your controller classes should be children of this class.
class Users_Controller extends App_Controller_Action
{
public function init()
{
if($this->isAuthenticated())
{
...
}
$this->moreSharedFunctionality();
}
I’m sure you can find tons of other examples where this pattern can be useful in your applications. If you need any more help with this drop me a line at davidh@arc90.com. If you have anything to add, comment below. Have fun coding!
Configuring Restlet 1.1 with Spring
Monday, September 15th, 2008Back in May I wrote a post about using Spring with Restlet 1.0.x and promised another about doing the same with Restlet 1.1.x, which provides better Spring support. Well, the time has come, so here goes!
In Restlet 1.1, which is currently at Release Candidate 1, you can now configure an application completely within the Spring application context. This means that the only Java classes you will need to create are one for starting the application, and one for each of the resources in your class. Although the Restlet authors prefer specifying the configuration in code, I like specifying it in an external, non-compiled configuration file, and this provides a great way to do that.
Custom HTTP Response Headers with Restlet
Monday, September 15th, 2008Our Java apps use the Restlet framework, and we sometimes need to send custom headers in our HTTP responses. This is infrequent enough that we forget how to do so, and need to look it up, but frequent enough that we should really have this snippet close at hand.
Securing Java Objects for Plain Text Transport
Tuesday, August 26th, 2008Update: With the inherent insecurity of DES, we recommend only using this method as a proof of concept. If you implement this approach, please use a stronger method like AES or Blowfish.
Recently I needed a way to secure some data that was going to be placed into an XML document. By using the Java APIs SealedObject class, along with the public domain Base64 class, I was able to secure an entire object, then encode it as text for inclusion in the XML.
To accomplish this, I created a class called Encrypter which provides one method for encryption and serialization, and another for reversing the process. I’ve listed the code for that class below, as well as another that demonstrates its use.
Update: We have posted the source for Encrypter, along with a compiled .jar to the Arc90 lab.
Encrypter Class
package com.arc90.example;
import java.io.Serializable;
import javax.crypto.Cipher;
import javax.crypto.SealedObject;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
/**
* Utility for encrypting/serializing and deserializing/decrypting objects
*
* @param <T> The type of object this Encrypter will accept and return
*/
public class Encrypter<T>
{
/**
* Encrypts and serializes the given object using the given password.
*
* @param object The object to encrypt and serialize
* @param password The password to be used for encryption
* @return A Base64 representation of the encrypted object
*/
public String encryptAndSerialize(T source, String password)
{
if(!(source instanceof Serializable))
{
throw new IllegalArgumentException("Source object must implement Serializable.");
}
try
{
SecretKey key = buildSecretKey(password);
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
SealedObject sealedObject = new SealedObject((Serializable) source, cipher);
return Base64.encodeObject(sealedObject);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
/**
* Deserializes and decrypts the Java object from the given cipher text.
*
* @param cipherText Base64 representation of the encrypted object
* @param password The password that was used for encryption
* @return The unencrypted object
*/
@SuppressWarnings("unchecked")
public T deserializeAndDecrypt(String cipherText, String password)
{
try
{
SecretKey key = buildSecretKey(password);
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
SealedObject sealedObject = (SealedObject) Base64.decodeToObject(cipherText);
return (T) sealedObject.getObject(cipher);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
/**
* Builds a secret key from a text password
*
* @param password The password to be used when generating the key
* @return The generated key
* @throws Exception
*/
private SecretKey buildSecretKey(String password) throws Exception
{
byte[] passwordBytes = password.getBytes();
DESKeySpec keySpec = new DESKeySpec(passwordBytes);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
return keyFactory.generateSecret(keySpec);
}
}
Demo Class
package com.arc90.example;
import java.util.ArrayList;
import java.util.List;
/**
* Demonstrates use of the Encrypter class
*/
public class Demo
{
private static final String PASSWORD = "YOUR_PASSWORD";
@SuppressWarnings("unchecked")
public static void main(String[] args)
{
List<Integer> secrets = new ArrayList<Integer>();
secrets.add(4);
secrets.add(8);
secrets.add(15);
secrets.add(16);
secrets.add(23);
secrets.add(42);
Encrypter<List<Integer>> encrypter = new Encrypter<List<Integer>>();
/*
* Encrypt and serialize the object
*/
String cipherText = encrypter.encryptAndSerialize(secrets, PASSWORD);
System.out.println(cipherText);
/*
* Deserialize and decrypt the string
*/
List<Integer> out = encrypter.deserializeAndDecrypt(cipherText, PASSWORD);
for(Integer i : out)
{
System.out.println(i);
}
}
}
Empty Subclasses Are Good
Friday, August 15th, 2008I write lots of server-side software with XML APIs. I’m constantly taking an XML document as input, maybe transforming it to another format, sending that XML doc somewhere for processing, then returning the resulting XML back to the client. It’s all nice and flexible and loosely coupled, but if all my parameters are of type XmlDocument my code is hard to read, and I may accidentally confuse parameters and still compile just fine. By subclassing XmlDocument and adding no new code, I can get compile-time checks against parameter confusion, better readability, and all the XmlDocument functionality I know and love still works unchanged.
Let’s say my service uses adapters that implement the following interface:
public interface IMyProcessAdapter
{
XmlDocument TransformToMyProcessSubmission(XmlDocument rawInput);
XmlDocument RunMyProcess(XmlDocument myProcessSubmission);
}
I have some app code to execute against an IMyProcessAdapter-implementing class:
function XmlDocument GetProcessResults(IMyProcessAdapter someAdapter, XmlDocument rawInput)
{
XmlDocument myProcessSubmission = someAdapter.TransformToMyProcessSubmission(rawInput);
XmlDocument myProcessResults = someAdapter.RunMyProcess(myProcessSubmission);
return myProcessResults;
}
No problem. Everything compiles and runs just fine. However, the following code also compiles just fine, even though I’ve gotten all my XmlDocument parameters confused:
function XmlDocument GetProcessResults(IMyProcessAdapter someAdapter, XmlDocument rawInput)
{
XmlDocument myProcessSubmission = someAdapter.TransformToMyProcessSubmission(rawInput);
XmlDocument myProcessResults = someAdapter.RunMyProcess(rawInput); // Note how I accidentally pass in the rawInput, not myProcessSubmission
return myProcessSubmission; // And then I pass back the input, not the output!
}
But what if I subclassed XmlDocument for each parameter? I don’t actually add any functionality to these new classes, though of course I could some day. I’m just asking the compiler to ensure that every time I pass an XmlDocument parameter it’s really the one I mean to use. Here’s my new interface declaration with these new subclasses:
public class RawInput : XmlDocument {}
public class ProcessSubmission: XmlDocument {}
public class ProcessResponse: XmlDocument {}
public interface IMyProcessAdapter
{
ProcessSubmission TransformToMyProcessSubmission(RawInput rawInput);
ProcessResults RunMyProcess(ProcessSubmission myProcessSubmission);
}
My code is now easier to read, as its intent is much clearer, and any accidental substitution of a RawInput for a ProcessSubmission will result in a compilation error, not a bug late in testing or production:
function ProcessResponse GetProcessResults(IMyProcessAdapter someAdapter, RawInput rawInput)
{
ProcessSubmission myProcessSubmission = someAdapter.TransformToMyProcessSubmission(rawInput);
ProcessResponse myProcessResults = someAdapter.RunMyProcess(myProcessSubmission);
return myProcessResults;
}
And of course, since all these parameters inherit from XmlDocument, I can call myProcessResults.SelectSingleNode(“//whatever”), myProcessSubmission.LoadXml(“<hi mom/>”), etc. If there’s a downside to this approach, please let me know in the comments, because I can’t find it.
DoubleChecking your PHP
Monday, August 4th, 2008PHP allows you to define variables anywhere, at any time. They do not have to be defined prior to use. This can lead to silly bugs when you misspell a variable name. Anytime I found one of these errors in my code, I’d say to myself, “I wish I had a script that could show me alphabetized variable lists with a count” – so I built this script to save myself debugging time.
DoubleCheck (db.php) can be run against a PHP file and will output an alphabetized list of variables with their count. It will also print out methods with their count. Its still in version 0.1 and I hope to expand on it in the future.
Feel free to contact me with request or bug fixes.
Enjoy!
Mac OS X: A Keyboard Shortcut for Maximize Window
Wednesday, July 30th, 2008This is probably one of the most useful ‘custom’ tweaks I’ve added to my mac since I got it – I use it constantly.
Add a Keyboard Shortcut to Maximize the Current Window using Quicksilver
I use Command-Shift-M.