Wednesday, August 17, 2011

Quick and Dirty Url Parameter Decoding / Debugging in Flash Actionscript Example

Here's a quick and dirty way to parse url parameters and debug without hooking up to a debugger in Flash

//pretend the url is
var urlString:String ='window.location.href.toString');
var parametersString = urlString.substr(urlString.indexOf('?')+1);
var urlVariables:URLVariables = new URLVariables(parametersString);'alert',;

What you should see, if this code was implanted in your flash application, is a javascript alert window pop up with name 'radguy' in it. ExternalInterface lets you take advantage of the more then likely presence of javascript in your environment. Using the already present alert functionality in javascript could save considerable time when you can't easily connect your code to a debugger. (Like when trying to debug a kiosk app you can't directly interface with)

Tuesday, May 31, 2011

Concrete HttpClient Example

Apache/Jakarta is one of the major reasons Java development has been a mainstay for as long as it has. The Organization has created some of the most useful tools and frameworks available for Java. One tool I came across 5 years ago was the HttpClient package. The project seems to have undergone many changes and added a lot stuff. I downloaded version 4.1 of the package the other day and had a difficult time reconciling my old idea of HttpClient and the current offering. The documentation is strangely lacking in concrete  examples. Here's a chunk of code to get you going with basic authentication in HttpClient 4.1

   String host = "";
   String fullUrl = "";
   String username = "username";
   String password = "password";

   HttpHost targetHost = new HttpHost(host, 80);
   DefaultHttpClient client = new DefaultHttpClient();
   AuthScope authScope = new AuthScope(targetHost.getHostName(),targetHost.getPort());
   UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
   client.getCredentialsProvider().setCredentials(authScope, creds);

   try {
      HttpGet simpleRequest = new HttpGet(fullUrl);
      ResponseHandler responseHandler = new BasicResponseHandler();
      String serverResponse = client.execute(
simpleRequest , responseHandler);
   } catch (Exception e) {
       System.out.println("Exception while retrieving data : " + e);
   } finally {

That's it, if you don't need authentication you can just not mess with the authscope and credentials stuff. The package seems to be powerful enough build a webserver out of, but sometimes you just need to scrape a website :)

Wednesday, March 16, 2011

3D actionscript objects to bitmaps example

Here's a quick post on how to convert your 3d spark component into a bitmap for use with the drag manager. I'm not going to wax poetic about this , if anyone want's further explanation please let me know and I'd be happy to go into details.

The dice object here is a 3D skinnable component. In order to keep the perspective
the same when converting it to bitmapData, you need to have your perspectiveProjection properly set.

var ds:DragSource = new DragSource();
dice.transform.perspectiveProjection = new PerspectiveProjection();
dice.transform.perspectiveProjection.projectionCenter = new Point(400,220);
dice.transform.perspectiveProjection.fieldOfView = 10
var bitmapData:BitmapData = BitmapUtil.getSnapshot(dice);
var bitmap:Bitmap = new Bitmap(bitmapData);
var snap:Image = new Image();
snap.width = 80;
snap.height = 80;

I ended up not even using the drag manager in the application this is from, but the research it took to get this far was too good to forget.

Friday, March 4, 2011

Switch states in Flash application example

Here's a quick problem I had to deal with last night. If you are making a programmatic Flex application and you need to switch the application state (the states you can tie various views to in your mxml code) you will have to first get a reference to the application object.

import mx.core.FlexGlobals;
import spark.components.Application;

public class StandardClass

private var _application:Application = mx.core.FlexGlobals.topLevelApplication as Application;


Note the imports above, there are many different application objects to choose from, but if you are making a standard Flex application you will want to use the Spark object. Also, you cannot apparently reference static things in FlexGlobals without first importing it. This is different behavior then you would see in Java.

So next we just need to simply pass the application object the name of the state we wish to invoke.

application.currentState = "State2";

And that's it! If you're interested in setting transition animations you can check out the "transistions" property of the application object to set custom animations.

Tuesday, February 15, 2011

Common memory leak causes in Java

Java may not have pointers, but memory leaks still happen. You can easily consume most of your memory on the heap if you're not taking care to free up memory you no longer need. The possibility for memory leaks seems to go up dramatically the more programmers work on a single project. This is especially true if some don't fully understand the java memory model.

In this post I'm going to cover the most common scenarios likely to cause a memory leak. In my next post I'll go over some powerful tools included in the current JDK which allow you to discover and hopefully fix memory leaks.

Common causes of memory leaks in Java

1) Static variables

Many junior programmers in java do not fully understand what static means. This misunderstanding is perhaps the most common cause of unintended memory leaks. To understand static variables, think of the scope of a variable, or, where does a variable live? If you declare a variable inside a  method, this is called a method scoped variable. It only exists while that method is running and is usually destroyed and released for garbage collection as soon as the method exits. If you declare a variable inside a class definition, then it is OBJECT scoped. It is NOT CLASS SCOPED. Remember a class is a blueprint for an object, and an instance of an object is completely different then the class from which it was built. The variable that is object scoped will be deferenced and ready for garbage collection as soon as all references to the object are destroyed. When you null out the only reference to an object, it is properly deferenced.

A STATIC VARIABLE is CLASS SCOPED. A static variable lives on the blueprint of an object, not the object itself. The classes in java are usually loaded right away at startup and are never deferenced until you shut down the JVM. If you declare a variable as static it will live for the entire lifetime of the JVM, unless it is individually nulled out. If a static variable references non static objects, it effectively makes those objects static as well. You can clear out a static collection, but depending on how the collection is cleared you may or may not be freeing up memory. Be careful. If you don't understand why something needs to be static, ask someone who does understand. Static is a surprisingly sticky subject and many career programmers still don't fully understand what it means.

2) Thread local variables

If you consume libraries from another party (apache, an internal group,wherever) be warned about these buggers. Java programmers who sometimes want to appear more clever then they are, utilize thread local variables to cache information on a thread, usually to speed up processing in a opaque way.

In the way that variables can be scoped to a method or an object or a class, thread local variables are scoped to a thread. Threads in Java are not always easy to trace and often stick around for the lifetime of the application.

If say, an xml parser, decides to put a ton of cached objects in a thread local variable, and forgets to clear it's cache after it is done, you will have that now useless cache taking up space in your heap for the lifetime of that thread. For more about discovering thread local variables please see my previous post.

3) Poorly implemented data structures

Poorly implemented data structures can be just as damaging and confusing as either of the other two common issues.  When you store data in a common array, you have to null out the indices of the array if you want the objects contained within to be deferenced. A seemingly simple thing like that can become easily obfuscated and forgotten when implementing a complicated data structure, like a specialized tree or specialized hash table.

The best thing to do in most scenarios is try to encourage the use of standard data structures (usually through sun or apache) that have been used by many people, thoroughly tested, and de-bugged.

You will sometimes run into career developers who have spent too much time implementing their own vector class or their own tree structures to ever consider using the standard tools. In fact, many of these 'blinded by undeserved ego' types will not even know of the common classes developed a decade ago. If you find yourself debugging memory leaks in your co-workers data structures to often, consider looking for a different development group to be apart of, or a different company. It's good to have a grounded understanding of how all the major data structures work, it's bad to assume that everything you do will somehow be magically better then other (almost always smarter) professionals.

Those are the most common causes of memory leaks I've seen in my career. I've caused some and fixed some. In my next post I'm going to chronicle using the new JDKs exciting version of jvisualvm. The included heap analysis tools have come along a way since jhat, and are now even comparable, in some ways, to expensive products such as jProfiler. Cool beans.

Wednesday, February 9, 2011

Inspecting thread local variables In Java example

I ran into an issue with some Thread Local Variables recently and came up with a quick way to actually see the buggers.

Using reflection you can get a good idea of the TLVs on your current thread.

package threadLocal;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class sandbox {

    public static void main(String[] args) throws Exception {

        Field field1 = Thread.class.getDeclaredField("threadLocals");
        Object o1 = field1.get(Thread.currentThread());
        Field field2 = o1.getClass().getDeclaredField("table");
        Object[] o2 = (Object[]) field2.get(o1);
        for (Object temp : o2) {
            if (temp != null) {
                Field field3 = temp.getClass().getDeclaredField("value");
                Object o3 = field3.get(temp);
This will print out all the TLVs on your current thread. You can also set them to null or whatever you want with a little more reflection. Particularly by nulling out all the buckets in the Object[] o2.  Thread Local Variables are rarely used responsibly in Java programming. I advise you don't use them unless you really have a rock solid reason to (and even when you think you do, you probably don't). They are often forgotten about and lead to many unintended memory leaks down the line.

Tuesday, January 25, 2011

Quickly Embedding HTML/RichText in the RichTextArea in Flex 4 example

In Flex Builder you can visually layout your application in the design view. This is a massive time save, especially when constructing a quick utilitarian application or proof of concept. Unfortunately there doesn't seem to be a particularly good way to enter rich text into a positioned RickTextArea. You can enter text in the design view but you can't embolden just a portion of the text or underline just one word.

A quick way  to get around shortfall is to switch over to the source view and embed some quick HTML structure into the RickText Spark component.
<s:RichText id="someText" x="53" y="23" width="449" height="153">
            He <s:span fontWeight="bold">huffed</s:span>
            and <s:span fontWeight="bold">puffed</s:span>

The spark namespace has most of the standard HTML tags defined, allowing to specify basic html structures inside of a RichText area. This is a quick way to add some Rich Text to you component. If you need to keep style elements separate, which you probably should, I think you can use the same method I used in the last post.

Tuesday, January 4, 2011

Styles in Flex 4 example

A quick note on declaring inline styles for Flex 4. If you're looking to quickly set up a text field in your mxml file but don't want to declare a separate css file (like in the case where your application only has one mxml file) you may need this.

        @namespace s "library://";
        @namespace mx "library://";

   <s:RichText id="text" x="42" y="20" text="Some text of sorts" />

Where #text is the id of your text field.