Monday, January 17, 2011

Injecting ExtJS components via an html template

Use Ajax to load an html page as a template for ExtJS and then plug ExtJS components into it.

Sometimes a web page layout may be too complicated or time-consuming to develop purely in ExtJS or perhaps you want to convert an existing html page to use ExtJS components. In either case there is a simple and straightforward way to inject ExtJS components into a complex html page. There are only a few simple steps needed to accomplish this:
  • create the html
  • fetch the html
  • load the html
  • plug in the ExtJS components
Here is a snippet from myPage.html. Notice the {idBase} included as part of the id. That is a template param that will be replaced when the ExtJS XTemplate is processed. The purpose of {idBase} is to help make sure that each div section has a unique ID and is not really germain to this article.
    
...
The following methods are from myScript.js. This method loads the html using an Ajax request:
     initStructure : function() {
         Ext.Ajax.request({
             url : 'myPage.html',
             disableCaching : false,
             method : 'GET',
             success : this.onStructureLoaded.createDelegate(this)
         });
     } // initStructure()
This success handler puts the html text into an ExtJS XTemplate and then loads that into the body of this component (an ExtJS panel or window):
     onStructureLoaded : function(response, options) {
         var template = new Ext.XTemplate(
             response.responseText
         });

         this.body.update(template.apply({
             idBase : this.id
         }));

         this.initMyButton();
     ...
     } // onStructureLoaded()
Once the html has been loaded into the DOM we can start plugging our ExtJS components into it:
     initMyButton : function() {
         new Ext.Button({
             applyTo : this.getCustomId('myButton'),
             text : 'My Button',
             handler : this.onMyButtonClick.createDelegate(this)
         });
     } // initMyButton()

     getCustomId : function(name) {
         return String.format('{0}_{1}', name, this.id);
     } // getCustomId()

Wednesday, January 12, 2011

Spring-loading and injecting external properties into beans

Let's say you have a Spring managed bean that contains some properties that you would like to externalize from your application, say perhaps in a JBoss 'conf' folder properties file.  Apparently you can do this via annotations in Spring 3, but it's also fairly straightforward in Spring 2.5:

From the context.xml file:

    <bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:my_app.properties"/>
        <property name="placeholderPrefix" value="$prop{"/>
    </bean>
 
    <bean id="someBeanWithProps" class="my.class.with.Props">
        <property name="myPropA" value="$prop{prop.file.entry.prop.A}"/>
        <property name="myPropB" value="$prop{prop.file.entry.prop.B}"/>
    </bean>

JBoss, JNDI and java:comp/env

On startup JBoss will process any xyz-service.xml files it finds in the deploy folder before it processes any war or ear files, etc.  One thing this could be useful for is to preload configuration values into JNDI, thus making them available to web applications when they start up.  It may sound simple but it consists of a non-obvious four step process:

1.  Create a JNDIBindingServiceMgr mbean in the xzy-service.xml file.

2.  In the WEB-INF/jboss-web.xml file map a resource-env-ref entry over to a JNDI value bound in step 1.

3.  In the WEB-INF/web.xml file create a resource-env-ref entry for each JNDI bound value.

4.  Access the JNDI value from somewhere, such as a servlet filter, using 'java:comp/env'

First, the xyz-service.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE server PUBLIC "-//JBoss//DTD MBean Service 4.0//EN"
    "http://www.jboss.org/j2ee/dtd/jboss-service_4_0.dtd">
<server>

    <mbean code="org.jboss.naming.JNDIBindingServiceMgr"
           name="netcds.cas.client:service=JNDIBindingServiceMgr">

        <attribute name="BindingsConfig" serialDataType="jbxb">

            <jndi:bindings
                xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"
                xmlns:jndi="urn:jboss:jndi-binding-service:1.0"
                xs:schemaLocation="urn:jboss:jndi-binding-service:1.0 resource:jndi-binding-service_1_0.xsd">

                <jndi:binding name="my/jndi/property">
                    <jndi:value type="java.lang.Boolean">false</jndi:value>
                </jndi:binding>

            </jndi:bindings>
        </attribute>
        <depends>jboss:service=Naming</depends>
    </mbean>

</server>

Next, the resource-env-ref entry in the jboss-web.xml file:

    <resource-env-ref>
        <resource-env-ref-name>my/jndi/property</resource-env-ref-name>
        <jndi-name>my/jndi/property</jndi-name>
    </resource-env-ref>

And the associated web.xml entry:

    <resource-env-ref>
        <resource-env-ref-name>my/jndi/property</resource-env-ref-name>
        <resource-env-ref-type>java.lang.Boolean</resource-env-ref-type>
    </resource-env-ref>

Finally, accessing the JNDI value from a servlet filter:
      
    boolean result = false;
    try {
        InitialContext context = new InitialContext();
        result = (Boolean)context.lookup("java:comp/env/my/jndi/property");
    } catch (final NamingException e) {
        // log and/or sys out
    }

Thursday, December 16, 2010

No dynamic filters in servlet spec 2.4 you say?

I had a requirement recently to be able to dynamically control CAS security filters in a web application (default CAS security to off for development and allow it to be turned on by external configuration post-deployment).  Unfortunately, servlet spec 2.4 does not allow one to programatically add new servlet filters (at least that's the prevailing theory).  This is a feature added/being added to the servlet 3.0 API.

My friend Google said there were a number of others who wanted to do the same thing but they were being pointed to servlet 3.0.  Unfortunately, servlet 3.0 and J2EE 6 were not an option for me, so it was looking like a tough nut to crack.

Then it struck me, what if I created a generic, conditional servlet filter that took the name of the class of the real filter as an init param?  And, what if I passed in the condition that was to be evaluated to determine whether or not to create and/or invoke the real filter?  Then, in the conditional filter, I could examine the condition and, as necessary, dynamically create an instance of the wrapped filter class.

Turns out it worked like a charm.  Here's how.  First the filter definition in web.xml:

    CAS Authentication Filter
    my.org.security.servlet.ConditionalFilter
    
        condition
        cas/enabled
    
    
        wrapped-class
        
            org.jasig.cas.client.authentication.AuthenticationFilter
        
    


public class ConditionalFilter implements Filter {

    // instance of the actual filter being wrapped
    private Filter _wrappedFilter;

    // are we to ignore the wrapped filter?
    private boolean _ignore = true;

    public ConditionalFilter() {
    } // constructor

    public void init(FilterConfig filterConfig) throws ServletException {
        // the 'condition' init param tells us whether or not 
        // the wrapped filter is active
        _ignore = !checkCondition(filterConfig.getInitParameter("condition"));

        try {
            if (!_ignore) {
                // the wrapped filter is active so we create an instance 
                // of it and initialize it
                _wrappedFilter = getFilterInstance(
                    filterConfig.getInitParameter("wrapped-class")
                );
                _wrappedFilter.init(filterConfig);
            }
        } catch (Exception e) {
            throw new ServletException(e);
        }
    } // init()

    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain filterChain)
        throws IOException, ServletException {
        if (!_ignore) {
            // the wrapped filter is active so we let it do its work
            _wrappedFilter.doFilter(request, response, filterChain);
        } else {
            // wrapped filter is inactive so simply move on to the next filter
            filterChain.doFilter(request, response);
        }
    }  // doFilter()

    public void destroy() {
        if (_ignore) {
            _wrappedFilter.destroy();
        }
    }  // destroy()

    private Filter getFilterInstance(String className)
        throws ClassNotFoundException, InvalidClassException,
               InvocationTargetException, IllegalAccessException,
               InstantiationException, NoSuchMethodException {
        // try to create an instance of the wrapped filter 
        // with the given class name
        Class filterClass = Class.forName(className);
        java.lang.reflect.Constructor constructor = filterClass.getConstructor();
        Object filter = constructor.newInstance();

        if (!(filter instanceof Filter)) {
            throw new InvalidClassException(
                String.format("'%s' is not an instance of Filter", className)
            );
        }
        return (Filter)filter;
    } // getFilterInstance()

    /*
     * looks up the configured 'condition' via JNDI to determine 
     * whether or not the wrapped filter is active
     */
    private boolean checkCondition(String condition) {
        boolean result = false;

        try {
            InitialContext context = new InitialContext();
            String path = String.format("java:comp/env/%s", condition);
            result =(Boolean)context.lookup(path);
        } catch (final NamingException e) {
            System.out.println(
                "unable to load condition from JNDI"
            );
        }

        return result;
    } // checkCondition()

} // class ConditionalFilter

Friday, April 2, 2010

One Thumb Up for Pair Programming

Pair programming is one of the characteristics of extreme programming and is, frankly, something I have not been a particularly strong advocate of. The idea of two developers sitting side-by-side, sharing one keyboard and working the exact same problem seems terribly inneficient to me. However, there are two reasons why, for short periods of time, that it would be beneficial to engage in pair programming.

The first one would be for test driven development. For a particular functional area under development one developer would write the unit/integration tests and one would write the code. To me, this would be the most efficient use of pair programming.

The second reason why I think it would be beneficial to perform short stints of pair programming would be to gain insight into the work practices, processes and procedures of one's teammates. For me personally, I could see how my teammates work and glean some ideas on how I could be more productive and efficient. What tools do they use? How do they use them? Do they have any shortcuts or time-savers? Likewise, it would be an opportunity for me to help my teammates improve their efficiency by offering suggestions based on the things that I do that help me.

Tuesday, March 9, 2010

jboss plugin for auto-deploying artifact during build

This is VERY handy for automatically deploying your artifact/war after a maven build is completed. Simply add the mvn goal jboss:hard-deploy to your maven command.
<plugin>
   <groupId>org.codehaus.mojo</groupId>
   <artifactId>jboss-maven-plugin</artifactId>
   <version>1.4</version>
   <configuration>
      <jbossHome>${jboss.home}</jbossHome>
      <serverName>default</serverName>
      <fileName>target/my-app.war</fileName>
   </configuration>
</plugin>

Saturday, March 6, 2010

Tunneling PUT and DELETE from ExtJS to Jersey ReST

Here is how you can invoke AJAX POSTs in ExtJS that map to PUT and/or DELETE methods in your Jersey ReST services.

The first step is to configure Jersey to allow this:
<init-param>
    <param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name>
    <param-value>com.sun.jersey.api.container.filter.PostReplaceFilter</param-value>
</init-param>
The next step is to issue the AJAX request (in this case we're going to issue a POST but tell Jersey to invoke the PUT mapped method instead):
Ext.Ajax.request({
    headers : {
        'X-HTTP-Method-Override' : 'PUT'
    },
    method: 'POST',
    url: '/my-api/some-service',
    params: {
        name : someObj.name,
        date : someObj.date,
        amount : someObj.amount
    },
    success: this.onSaveSuccess.createDelegate(this),
    failure: this.onSaveFailure.createDelegate(this)
});

Friday, March 5, 2010

CSS for flowing boxes in a DataView

Here is some CSS that can be used to flow/float boxes inside an ExtJS DataView:

.dataViewNode {
   width: 10em;
   float: left;
   height: auto;
   overflow: hidden;
   position: relative;
   margin: 4px;
   z-index: 5;
   text-align: center;
   padding: 2px 0 0 0;
   font-size: 0.8em;
}  

Thursday, January 28, 2010

InputStream from URL BufferedImage

Here is how you can make an InputStream for a BufferedImage:

    URL url = new URL("http://www.google.com/intl/en_ALL/images/logo.gif");
    BufferedImage image = ImageIO.read(url);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ImageIO.write(image, "gif", os);
    InputStream is = new ByteArrayInputStream(os.toByteArray());

Sunday, December 20, 2009

Was I defeating bean pooling in OpenEJB?

As I previously reported I had to use JNDI to obtain a reference to my stateless session bean from my Jersey Rest service.

In so doing I created a helper class that would, among other things, cache the JNDI and EJB references I needed.

That got me to wondering - since I was using the same EJB reference over and over was I somehow defeating the stateless session bean pooling that OpenEJB was surely providing me?

The only documentation I could find on this hinted that pooling worked via the bean method invocations and not the bean reference itself. But, I wanted to see it with my own eyes. I did notice that my JNDI lookup was returning a proxy object and not my bean implementaion, so this provided me some hope that I was not defeating pooling.

My first test was to invoke my EJB 10 times via the same reference and, from inside my EJB implementation identify the bean instance that was invoked. Well, the 10 invocations went to the same instance - no pooling so far.

But, my test was not very realistic so I modified it to invoke my EJB 10 times via the same reference but from 10 separate threads. This time the 10 invocations were handled by 10 different instances of my bean implementation. Whew - proof that I had not defeated pooling by caching and reusing the bean reference I was retrieving from JNDI.

Out of curiosity I increased my invocations to 100 and this time only 9 unique instances of my stateless session bean were used to handle these 100 requests.

Tomcat, OpenEJB and Jersey, oh my

I was recently investigating putting EJBs behind Restful web services.

I did get it working without too much trouble using Jersey and JBoss AS 5.1, but I had to deploy my web app in exploded directory form and not as a war. No matter what I tried I could not get Jersey to find the rest service classes when I deployed my app as a war. This was contrary to my experiences with JBoss 4 and is probably due to the new virtual file system architecture in JBoss 5.

This prompted me to take a look around and see what else is out there. I stumbled upon OpenEJB and thought I would give that a shot inside Tomcat 6.

It was pretty simple getting Tomcat going with Jersey and within a few minutes I had my web service running inside standalone tomcat (without the EJB usage, of course).

However, when I dropped the OpenEJB war file into Tomcat things fell apart and my app would no longer deploy due to an apparent class loader issue which seemed to be introduced by OpenEJB. I tried a lot of different things but couldn't get past the class loader problem. I even went as far as to download and debug into the OpenEJB source code but I quickly found myself in compiled 3rd party code.

Here is the error I kept getting: Could not fully load class: com.sun.jersey.spi.container.servlet.ServletContainer due to: javax/ws/rs/core/Application in classLoader: org.apache.openejb.core.TempClassLoader

I finally decided to simply place the Jersey jars (asm.jar, jersey-core.jar, jersey-server.jar, and jsr311-api.jar) into the Tomcat lib folder and that did the trick. I also set the Jersey dependency to 'provided' in the maven pom for my webapp.
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-server</artifactId>
        <version>1.1.4.1</version>
        <scope>provided</scope>
    </dependency>
Also, I was hoping the @EJB annotation in my rest service class would inject my stateless bean reference, but it did not - I had to use JNDI. By default, OpenEJB uses the following scheme (you can configure) for naming your beans in JNDI: implementation class name + either 'Local' or 'Remote'.

For example, say you have an EJB class named AccountBeanImpl and it implements interfaces AccountBeanLocal and AccountBeanRemote. The corresponding JNDI names for the account bean would be AccountBeanImplLocal and AccountBeanImplRemote.

Thursday, October 22, 2009

J2EE Integration and Messaging

work in progress

CharacteristicWeb ServicesJMSJCA
sync vs. asyncsyncasync
security/encryptionyes, WS-Securityyes
transactionsyesyesyes
reliability (guaranteed delivery)yesyes
batch
systems use same technologyjava-non javajava-javajava-legacy/EIS

GoF Design Patterns

work in progress

NameDescription
Creational Patterns (AbFacBuildFacProSingle)
Abstract Factoryinterface for creating family of related/dependent objects without specifying concrete classes
Builderseparates construction from representation; same construction process can create different objects
Factory Methodinterface for creating an object; lets subclasses decide which class to instantiate
Prototype
Singletoncontrols access to finite number of instances
Structural Patterns (AdBriComDecFaFlyProx)
Adapterconvert one interface to one the client expects
Bridgefunctional abstraction -> internal implementation
Compositehierarchical tree structures with elements of varying complexity but a uniform interface
Decoratoradd or remove functionality without changing external appearance
Facadeunifying interface on top of a group of interfaces/components of a subsystem
Flyweightsharing/reusing objects
Proxysurrogate controls access to real object
Behavioral Patterns (ChainComIntItMedMemObStateStratTempVis or C2I2M2-OSS-TV)
Chain of Responsibilitymessage handled where it is first received or directed on to another object for handling
Command
Interpreter
Iteratorsequentially access items in a collection that is separate from the underlying collection
Mediatorobject that manages message distribution among other objects
Mementorepresents snapshot of object's state
Observerbroadcast messages to interested listeners
Stateobject alters behavior when internal state changes
Strategygroup of classes that represent a set of possible behaviors
Template Method
Visitorthink of using the enhanced for to iterate over a list in java and perform some operation on that list
underlined patterns are ones I have personally used

J2EE Persistence Strategies

This is a summary of the J2EE persistence strategies that a Sun Certified Enterprise Architect should be familiar with (use scrollbars at bottom to view entire table):

StrategyEase of DevelopmentPerformanceScalabilityExtensibilitySecurityStrategy
CMPrelatively simple; preferred over BMPcontainer dependentEJB container dependent *avaries by implementationEJB providedCMP
BMPmore involvedvery efficient w/control over SQLEJB container dependent *avaries by implementationEJB providedBMP
JDOsimplepossibly some performance penaltydeveloper managedvaries by implementationdeveloper managedJDO
JPAthe simplestpossibly some performance penaltyEJB container dependent *avaries by implementationEJB providedJPA
ORM/DAOssimplepossibly some performance penaltydeveloper managedvaries by implementationdeveloper managedORM/DAOs
JDBCmost time-consuming and involvedtheoretical best performancedeveloper managedvaries by implementationdeveloper managedJDBC
iBatis/DAOsomewhere between ORM and JDBCexcellent performancedeveloper managedvaries by implementationdeveloper managediBatis/DAO
*a = stateless session beans more scalable than stateful

not covered by SCEA exam

Spring can help level the playing field outside EJB in some of the above developer managed areas by helping with transactioning, scalability and security.

Friday, September 18, 2009

assign IDs in ExtJS, or else...

I was recently working on the UI side of things and having difficulty getting my complex 2-column form layout to display correctly (creating components dynamically and adding them to the the parent window object and nested panel objects).  Elements were either missing or grossly misplaced.

In ExtJS, IDs are automatically generated for your UI elements if you don't specifically assign them yourself, so I didn't really give much thought to the fact that I wasn't assigning my own IDs.  I was taking stabs in the dark and then for some reason decided to assign my own IDs and when I did, viola, it started working like a charm.  Lesson learned.

Thursday, September 17, 2009

the phone call

Yesterday morning my 3-year-old son called me at work to talk about something we would do together later that day.  He knows that I get home around dinner time so, mid conversation, I hear him call out to my wife "mom, can you make dinner now?"  Simply heart warming.

reflections on opportunities past

There are a lot of things I miss about being in the service (military) and besides the people, one of the things I miss most was the knowledge that no matter how good or how bad your current assignment was you knew it was going to change.  

The military thrives on leadership and to cultivate this its members are regularly reassigned in order to broaden their experiences and afford them opportunities for increased responsibility.  And there were so many choices of places you could go and things you could do.

My first experience with this was what they call "service selection night" at the Naval Academy.  It's actually an entire day and they start very early in the morning as it takes a while to get through 1000 people.  They make announcements over the PA system and summon people in groups, according to their ranking in the graduating class, down to the selection office.  The purpose of this event is for first class midshipmen (seniors or "firsties" as we were affectionately called) to choose what they were going to do after they graduated.

So, you hear your number called and you head down to the selection office.  You walk in the room and on the walls are listings of all the possible assignments that a young ensign or 2nd lieutenant could have.  There was Naval Aviation (Navy Air), Marine Air, Navy SEALs, Marine Infantry, artillery, Navy surface, or subs (submarines) or nuclear power, or whatever.  You could even pick the exact ship you were going to be assigned to and thus your home port.  It was really very exciting.  

For me, I knew I wanted to be a Marine and flying sounded exciting too so I thought I would give it a shot and become a pilot.  So that's what I chose - Marine Air.

And that's kinda how it was during my time in the service - there were always new opportunities and always choices and there was always something new to look forward to while you were busy enjoying where you currently were and the people you were with.  

After flight school I got to choose what aircraft I would get to fly and where I would be stationed.  At the end of my first tour where I flew CH-46 helicopters out of Southern California things got a little more interesting.  As you move up you start talking to your 'monitor' (aka career counselor - someone back at Headquarters Marine Corps in Washington, DC) who is another officer temporarily assigned on his way up the ladder to work with a certain group of people and fill the openings left by others moving on to new assignments.  Again - choices, but now there was some negotiation and you had someone who had a bigger picture than you who could help guide you to the next assignment that would set you up for the one after that, and so on.  

In my dozen years of post-military life I really haven't seen that - at least not at the places where I've worked.  I think there may have been something remotely similar to that at General Motors.  I mean, they did send me to leadership development courses and they did say they "had big plans for me" when I informed them I was leaving.  But, although I enjoyed my time there, I did not stay long enough to find out.   

Wednesday, July 30, 2008

Instrumenting with proxies

Using the InvocationHandler interface one can create a simple, yet sophisticated, means of instrumenting a class to obtain statistics about its usage: 

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.InvocationTargetException;

public class MyProxy implements InvocationHandler {

    private Object _target;
    public Object getTarget() { return _target; }
    public void setTarget(Object target) { _target = target; }

    public
MyProxy(Object target) {
        _target = target;
    } // constructor

    public Object invoke(Object proxy,
                         Method method,
                         Object[] args)
            throws Throwable {

        Object result = null;

        long start = System.currentTimeMillis();

        try {
            result = method.invoke(_target, args);
        } catch (InvocationTargetException ite) {
            long stop = System.currentTimeMillis();
            // log the exception here

            throw ite.getCause();
        }

        long stop = System.currentTimeMillis();
        // log the invokation results
        // (_target, method, stop - start);

        return result;
    } // invoke()

    public static Object createProxy(Object target) {
        Object result = target;

        Class targetClass = target.getClass();
        result = Proxy.newProxyInstance(
            targetClass.getClassLoader(),
            targetClass.getInterfaces(),
            new
MyProxy(target)
        );


         return result;
    } // createProxy()

} // class MyProxy

Monday, July 28, 2008

limiting characters in an html textarea

Here is a way to limit the amount of text entered into a textarea.  Note, this works in both IE and FireFox.  Also, this only limits characters entered via keystrokes and does not work for copy/paste.

/* -------------------------------------------------------------------------
limits the amount of text that can be typed into a textarea
example usage: <textarea onkeypress="return limitText(event, this, 40);">
--------------------------------------------------------------------------*/
limitText : function(event, textArea, maxChars) {
    var result = true;

    if (textArea.value.length >= maxChars) {

        if (textArea.createTextRange) {
            var range = document.selection.createRange().duplicate();
            result = range.text.length > 0;
        } else {
            result = event.keyCode in { // always let these keys through
                37 : "left",
                39 : "right",
                38 : "up",
                40 : "down",
                33 : "pageUp",
                34 : "pageDown",
                46 : "del",
                36 : "home",
                35 : "end",
                27 : "esc",
                8 : "back"
            };
        }
    }

    return result
} // limitText()