How To Select a Child Element Using jQuery

Let’s assume you have an HTML string containing a parent element with a number of children and their sub children elements. If you’d like to extract HTML of one of the children (by class name or id), you can use this jQuery line:

var html = $(htmlString).find('div.target').html();

It can be useful when you get an AJAX response from the server, and only a particular section needs to extracted.

How To Populate a Timestamp Field With Current Timestamp

Raw:

SELECT SYSTIMESTAMP AS TSTAMP FROM DUAL;

Formatted:

SELECT TO_CHAR(SYSTIMESTAMP, 'DD/MM/YYYY HH24:MI:SS.FF6') AS TSTAMP FROM DUAL;

Populating a timestamp database field using a current timestamp:

INSERT INTO TABLE_NAME(TSTAMP) VALUES ((SELECT SYSTIMESTAMP FROM DUAL));

Or another way is simply to use TO_TIMESTAMP() if the timestamp time is known:

INSERT INTO TABLE_NAME(TSTAMP) VALUES (
   TO_TIMESTAMP('3/08/2010 4:38:52.000000 PM','fmDDfm/MM/YYYY fmHH12fm:MI:SS.FF AM')
);

How To Tell XStream To Not Unmarshall XML Fields

My colleague found this when he was looking for a way not to unmarshall XML fields that did not exist in his POJO using XStream. The code makes use of a MapperWrapper class:

    XStream xstream = new XStream() {
    @Override
    protected MapperWrapper wrapMapper(MapperWrapper next) {
        return new MapperWrapper(next) {

        @Override
        public boolean shouldSerializeMember(Class definedIn, String fieldName) {
            if (definedIn == Object.class) { return false; }
               return super .shouldSerializeMember(definedIn, fieldName);
            }
         };
      }
  };

What Is The Best Workplace For a Fresh Graduate?

Recently I was invited to do a presentation in-front of soon-to-be graduates at my university where I have obtained my qualification in Computer Science.  Myself and a few other of my fellow ex-classmates were suppose to give students a talk on what to expect after graduation, and what it is like working in the industry.

After my presentation, one of the soon-to-be graduates asked me a question: “What type of companies should the fresh graduate look for, and what jobs should be avoided?

Although it may sound simple, this question was not an easy one to answer. Sure, as an ex-grad my self, I remember our lecturers telling us to take any professional job, to grab any opportunity and just to get a foot in the door. Not a bad advise after all, and many including myself have followed this  path, and I am sure many still are. At the time, I was  told not to worry too much, as at the first job I will be taught everything I need to start my career path.

But only after a few years, I understood how important the first job really is. The first job can shape a graduate into a good or an average IT professional. The first job either can teach the grad the logical approach and how to be meticulous about little details or how to look for shortcuts. Also, the first job will dictate what technologies and tools the grad may use in the future, whether he or a she will become proprietary or an open source IT professional.

Off course, when applying for jobs and attending job interviews, as a  fresh graduate you are not in a position to bargain and demand the best (whatever “the best” means). Simply because the grad does not have the experience and skills to support the demands. Therefore, around the first two years, a graduate has be satisfied with the first job he got, in a hope that the experience gained will help in the professional future endeavors. The graduate hopes that the first company he got into, is a good one and considers him self very lucky to be there. But really, is the first company a good one?

One of the types of companies that I would advise for a fresh graduate to avoid is consultancy firms. Having said that, I want to say that there is nothing wrong in working for a consultancy firm (I am working for one now), it is just as a fresh grad it is not the best place in my opinion to get shaped as a strong IT professional. I will try to elaborate on this.

As a consultant, you are assigned to a different projects, usually on the clients’ site. For a fresh grad, this experience can be similar to a jump into the ocean from a plane high in the sky. One may say there is nothing wrong with that, this experience will force you to learn.

I am not sure that I fully agree here. Sure, this experience will force you to learn, learn something, definitely. Will force you to learn to do what the client needs, to follow the clients’ way. Which is often can be not entirely the right way. A consultant usually costs a client a lot of money, which is why clients want to see results delivered and delivered fast. Therefore this type of environment, is not very good for learning the skills and building a strong foundation nor the client is interested in spending the big bucks for teaching fresh grads.

Another type of companies that I don’t favor as the first job, are the big corporations (for example lets say banks). Working for a corporation at the beginning of your career, your freedom and creativity as IT professional are often restricted. You are forced to use tools that are in place and most probably cannot use other tools to get the job done, even if the other tools are better. In corporation, the fresh grad can start feeling very small, a little screw in a huge apparatus, without a clear understanding why he does what he does.

When I was hunting for jobs after Uni, I was quite skeptical about graduate programs run by some big banks or insurance companies. Usually they teach their own way to do things, which is not necessary the right way. They teach you what they need you to know for them. Corporation can be a big place, and often people don’t have time to teach you, they are there to do their job, get paid and go home. The corporations are lacking human touch, and often not having around a supervisor or a mentor who can be available when you need them, can be a real minus.

Having a mentor. I cannot stress enough when I say, how important is to have a good mentor who is there to give you a “slap” on the head and a “kick” in the right direction. Someone who really cares and have a  passion for what he does. One may say: yeah, having mentor is a good thing, but I don’t really need a “baby sitter”, I am capable learning by my self, Google is full of tutorials.

Sure, we all should (and must) be able to know how to improve ourselves through self learning. I am not saying that a lack of mentoring can be the crucial factor in failing to become a good IT professional. No, not at all. Mentor is just a person that simply has more hands on experience than you, and can explain you things in person, face to face which is sometimes much better than just reading a tutorial on the web.

How many of us, IT professionals are lucky to say that “yes, I have had a good mentor that helped when I began my career path”? I personally can say, that I was lucky. I have had two mentors. Each and every one of them have contributed in their own way to my development as an IT professional I am today. I am still drawing on those experiences and trying to improve my self on a daily basis.

So what is the right place to start working, in my opinion? I think starting in a small company (6-10 employees) is the best option for a fresh grad to get hands on experience and build a solid foundation. Usually small companies are more versatile in their choice of technologies and tools used, and there is a lot of space for creativity and for learning some basic concepts. Small companies have a lot of human interaction between the senior and junior developers, something that can only positively contribute towards professional development.

I admit, that now it is easy for me to sit and contemplate what is good and what is not so good. Many fresh grads, don’t really think that far, they just want to get out there after 3-4 years of University and start making some money.

In summary, I want to say, that the decisions one makes at the beginning of his/her career can really decide his/her professional future. The highest paying job is not necessary the best job, when starting a career. Gaining valuable skills is much more important. Therefore, the first few years of boot camp, are very important in the process of becoming a good, passionate IT professional , instead of someone who takes it as just another nine-to-five job. The latter lacks of creativity and unfortunately modern workplaces are full of them.

Making Instance Variables Thread Safe

One of the ways to achieve thread safety when creating instance variables is to make a use of ThreadLocal class.  When instance variable is wrapped in ThreadLocal, each thread accessing the variable has its own independent copy of the variable.

An even better approach is to wrap the instance variable in SoftReference, which can eliminate the risk if getting OutOfMemoryError if there is a need to keep a an object in memory for a long period of time, for example when implementing caching mechanism. The garbage collector will only collect softly referenced objects when it decides that memory is low enough to warrant it

Consider the following snippet:

public class ThreadSafeExample {

 private static final ThreadLocal<SoftReference<List<SomeObject>>> trhLocal =
                                new ThreadLocal<SoftReference<List<SomeObject>>>();
 .
 .
    public static List<SomeObject> getSafeList() {

      // Get the value of the current thread's copy of this thread-local variable
      SoftReference<List<SomeObject>> reference = trhLocal.get();

      if (reference != null)  {
         // Get this reference object's referent
         List<SomeObject> safeList = reference.get();

            if (safeList != null)  {
                 return safeList;
            }
       }

       // Ok, so we did not have previously anything,
       // lets create thread-local variable
       List<SomeObject> safeList = new LinkedList<SomeObject>();
       reference = new SoftReference<List<SomeObject>>(safeList);
       trhLocal.set(reference);

     return safeList;
   }
}

What happens in the above example is, when getSafeList() is called, the thread’s list is assigned the first time it invokes getSafeList(), which causes invocation of  trhLocal.get().  If get() does not return anything, a new copy of the instance variable is created and set to the ThreadLocal instance. Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible. This approach does not require  synchronization, which can create thread contention, and provides much faster access to the variable than via synchronization.

Off course one should consider whether ThreadLocal is really needed. Normally, a good candidates for object re-use via thread local are objects that are frequently accessed by a given thread and are non-trivial to construct. Another scenario for making use of ThreadLocal, would be when it is not really practical to extend Thread class (for example creating servlets) and thread safety is needed.

Convert XML into POJO using HierarchicalStreamReader

In this example I would like to show how unmarshall XML into a POJO using HierarchicalStreamReader. I will introduce how to use  XStream and a custom XML-to-POJO converter, describe a case study and develop an application to show the solution.

Purchase History Example
Consider the following XML. It represents represents a purchase history of a customer, that has purchased different items during a week:

<PURCHASE>
	<ITEM>
		<SUBITEM>
			<CODE>PDCT-001</CODE>
			<NAME>Product-1</NAME>
			<DAY5>1.75</DAY5>
			<TOTAL>1.75</TOTAL>
		</SUBITEM>
		<SUBITEM>
			<CODE>PDCT-002</CODE>
			<NAME>Product-2</NAME>
			<DAY7>1.00</DAY7>
			<DAY6>1.75</DAY6>
			<TOTAL>2.75</TOTAL>
		</SUBITEM>
		<SUBITEM>
			<CODE>PDCT-003</CODE>
			<NAME>Product-3</NAME>
			<DAY7>4.50</DAY7>
			<DAY6>2.00</DAY6>
			<DAY5>3.00</DAY5>
			<DAY4>2.25</DAY4>
			<TOTAL>11.75</TOTAL>
		</SUBITEM>
		<SUBITEM>
			<CODE>PDCT-004</CODE>
			<NAME>Product-4</NAME>
			<DAY7>3.50</DAY7>
			<DAY6>3.75</DAY6>
			<DAY5>2.75</DAY5>
			<DAY1>3.75</DAY1>
			<TOTAL>13.75</TOTAL>
		</SUBITEM>
		<REFERENCE>9571-EDGDFG-DGSNJE-1837</REFERENCE>
		<GRANDTOTAL>30</GRANDTOTAL>
	</ITEM>
</PURCHASE>

To unmarshall the XML, I created three POJOs to represent the hierarchy of XML elements. The domain objects Purchase, Item and SubItem are involved.  The Purchase  has an Item, that has a collection of SubItem objects. My customer XML converter will transform customer’s purchase history from XML into a domain model using the POJOs.

I am not going to describe the full structure of the POJOs here, as I want to concentrate on talking about the XML converter . The source code as Eclipse project is attached to the current article, so you can download it.

I use XStream, which is a simple open-source Java library for serialize objects to and from XML. The following is the unit test case code snippet that show how I register my custom converter that is used for XML unmarshalling:

XStream xstream = new XStream(new DomDriver());
xstream.alias("PURCHASE", Purchase.class);
xstream.registerConverter(new PurchaseConverter());
Purchase purchase = (Purchase) xstream.fromXML(xmlContent);

I created an alias for Purchase that matches XML root element and registered my custom converter. The converter is a specific converter that knows how to handle this particular XML example, so it is not a generic solution. The converter code as follows:

package asia.javabeans.streamreader.util;

import asia.javabeans.streamreader.domain.Purchase;
import asia.javabeans.streamreader.domain.SubItem;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

/**
 * Current class represents converter for a Purchase XML.
 *
 * @author alexander.zagniotov
 *
 */
final public class PurchaseConverter implements Converter {

	private static final int NUM_OF_DAYS = 7;

	public void marshal(Object value, HierarchicalStreamWriter writer,
			MarshallingContext context) {
	}

	public Object unmarshal(HierarchicalStreamReader reader,
			UnmarshallingContext context) {

		Purchase purchase = new Purchase();

                //while there are unread XML element children and the reader has not reached the closing PURCHASE element
		while (!(reader.getNodeName().equals(XmlElements.PURCHASE) && !reader
				.hasMoreChildren())) {

			if (reader.hasMoreChildren()) {
				reader.moveDown(); // Move down to ITEM element

				// Process child SUBITEM elements of the parent ITEM
				if (reader.getNodeName().equals(XmlElements.ITEM)) {
					iterateThroughItemSubitems(reader, XmlElements.ITEM,
							XmlElements.SUBITEM, purchase);
				}
			}
                        //store value of REFERENCE element in a POJO
			if (reader.getNodeName().equals(XmlElements.REFERENCE)) {
				purchase.setReference(reader.getValue());
			}

			reader.moveUp(); // Move back up to PURCHASE element
		}

		return purchase;
	}

	private Purchase iterateThroughItemSubitems(
			HierarchicalStreamReader reader, String parentNameName,
			String childNodeName, Purchase purchase) {
		boolean hasSubitemNodes = true;

		while (reader.getNodeName().equals(parentNameName) && hasSubitemNodes) {
			reader.moveDown(); // Move down to SUBITEM element

			// We have SUBITEM element that we can read
			if (reader.getNodeName().equals(childNodeName)) {
				purchase = iterateThroughSubitemChildren(reader, childNodeName,
						purchase);
			} else { // No more children SUBITEM elements to read
				break;
			}

			reader.moveUp(); // Move back up to parent ITEM element
			continue;
		}

		return purchase;
	}

	private Purchase iterateThroughSubitemChildren(
			HierarchicalStreamReader reader, String nodeName, Purchase purchase) {
		boolean hasChildrenNodes = true;

		SubItem subItem = new SubItem();

		while (reader.getNodeName().equals(nodeName) && hasChildrenNodes) {
			// Move down to the children of current SUBITEM element
			reader.moveDown();

			if (reader.getNodeName().equals(XmlElements.CODE)) {
				String subItemCode = reader.getValue();
				subItem.setCode(subItemCode);
				reader.moveUp(); // Move back up to parent SUBITEM
				continue;
			}

			if (reader.getNodeName().equals(XmlElements.NAME)) {
				String subItemName = reader.getValue();
				subItem.setName(subItemName);
				reader.moveUp(); // Move back up to parent SUBITEM
				continue;
			}

			if (reader.getNodeName().startsWith(XmlElements.DAY)) {

				for (int i = 1; i <= NUM_OF_DAYS; i++) {
					String xmlDay = XmlElements.DAY + i;

					if (reader.getNodeName().equals(xmlDay)) {

						double hours = Double.parseDouble(reader.getValue());
						subItem.addToDailyHours(xmlDay, hours);
						purchase.addToGrandTotal(hours);
						break;
					}
				}

				reader.moveUp(); // Move back up to parent SUBITEM
				continue;
			}

			if (reader.getNodeName().equals(XmlElements.TOTAL)) {
				hasChildrenNodes = false; // This is the last child of parent SUBITEM

				String itemTotalStr = reader.getValue();
				subItem.setItemTotal(Double.parseDouble(itemTotalStr));
				purchase.getItem().addSubItem(subItem);
				reader.moveUp(); // Move back up to parent SUBITEM
				continue;
			}
		}
		return purchase;
	}

	@SuppressWarnings("unchecked")
	public boolean canConvert(Class clazz) {
		return clazz.equals(Purchase.class);
	}

}

As you can see, the key to operate a stream reader is to move it down to a child element for reading and back up to a parent element. Each time I move the reader down, it moves to an element that has not being read yet.

Conclusion

I presented a simple example where I show how to unmarshall XML into Java POJOs using HierarchicalStreamReader and XStream. The source code is attached.

I hope this tutorial was helpful to some of you,
Regards

Right Tool For the Right Job

I wanted to start a discussion what is the better choice for an application server when building an enterprise J2E application? Should one go for a Tomcat + Spring combination which provide light-weight simplified alternative to JEE container or should more heavy weight app server like JBoss be considered?

I have found some resources on Stackoverflow that provided me enough information to think about:

  1. What are benefits of JBoss AS-based application architecture?
  2. When to ditch a J2EE container (i.e. JBoss) for straight Tomcat
  3. Should I go with Tomcat or a full J2EE container?

Installing Ubuntu 10.04.1 on Dell laptop

I got a new Dell Latitude e6410 from work. After trying Windows it for a few days, I decided to get back to Ubuntu, since I really prefer developing on Linux.

Unfortunately, after booting from live CD my screen started showing me colorful snow and flickering. The moment I select the language and choose to “install Ubuntu”, the screen goes “blah”.

After doing some research and trying several solutions suggested on Ubuntu forum, one of them suggested playing with various booting options (nomodeset,vga=771, etc.),  still I had no luck. After some more reading, I saw that some people that complain about similar problem, have the same graphics card as me:  Nvidia NVS 3100M 512MB.

Martin Wildam did an interesting review of Ubuntu 10.04 in his blog post Ubuntu 10.04 Experiences. So it is known that Linux distros can have problems with various GXF cards …

At the moment, I still haven’t resolved the problem, still looking for solutions …