Marshalling java objects to XML using JaxB

Hi guys. It’s been so long since I have posted anything at all on my blog, that I’m actually ashamed to call myself a blogger. I’m probably more of a blogger wanna-be at this point. In my defense, between the last post I wrote and I now, I have created, given birth to and since raised a whole entire human being who is now one (yaaay), walking and chatting and all sorts of stuff, so I’ve been a bit busy.  To ease myself back in to all of this, I have decided to share my experience with JaxB (a software framework that allows Java developers to map Java classes to XML representations, according to Wikipedia). I hope it will be helpful.

 

As an application developer, there’s a high probability that at some point you will have to process XML to achieve some task or another. I recently had to do such a task. Long story short, I had to do stuff, output it into XML, send it to another system that took the XML as input and did some more stuff to it. Make sense? Good. The team that maintains this other system sent me an XSD (schema) that my XML would have to conform to. To those completely new to all of this, in a nutshell, an XML schema has the .xsd extention and it is a little “document” that outlines the rules that your XML should follow, for it to be valid. The XSD tells you which tags are allowed, which are compulsory or optional, what the data types should be used for which tags, etc. For more information about xml and it’s schemas, please visit w3schools. They explain all of it beautifully.

 

At this point, I am assuming we all have an idea of what XML is and what an XSD is and how it works. So for the point of this exercise, I am going to provide a simple little XSD (from w3schools), and we will use it to learn a little jaxB. The schema is as follows:

 

<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="shiporder">
<xs:complexType>
<xs:sequence>
   <xs:element name="orderperson" type="xs:string"/>
   <xs:element name="shipto">
   <xs:complexType>
      <xs:sequence>
         <xs:element name="name" type="xs:string"/>
         <xs:element name="address" type="xs:string"/>
         <xs:element name="city" type="xs:string"/>
         <xs:element name="country" type="xs:string"/>
      </xs:sequence>
   </xs:complexType>
</xs:element>
<xs:element name="item" maxOccurs="unbounded">
<xs:complexType>
   <xs:sequence>
      <xs:element name="title" type="xs:string"/>
      <xs:element name="note" type="xs:string" minOccurs="0"/>
      <xs:element name="quantity" type="xs:positiveInteger"/>
      <xs:element name="price" type="xs:decimal"/>
   </xs:sequence>
</xs:complexType>
</xs:element>
      </xs:sequence>
<xs:attribute name="orderid" type="xs:string" use="required"/>
      </xs:complexType>
      </xs:element>

      </xs:schema>

 

Because this is not an XML tutorial, I am going to assume basic understanding of XML and XSDs. I am not going to go into how you create an XML that can successfully be validated against this schema, I’m just gonna use an online generator to generate a sample XML for this xsd. If anyone would like an actual tutorial on generating an XML from a schema, pop me a comment below and that might be my next post, and no I won’t take an entire year before the next post, I promise. Here’s the XML we’ll be using (basically, we expect our marshalled java output to look like this):

 

<?xml version="1.0" encoding="utf-8"?>
<shiporder orderid="order1234">
    <orderperson>John Doe</orderperson>
    <shipto>
        <name>John Doe</name>
        <address>123 Church Street</address>
        <city>Utopia</city>
        <country>Outta-this-world</country>
    </shipto>
    <item>
        <title>Egg shipment</title>
        <note>Fragile</note>
        <quantity>50</quantity>
        <price>123.45</price>
    </item>
</shiporder>

 

Looking at this xml above, I bet you’re thinking: “These are some pretty expensive eggs”. I know. I have a goose that lays golden eggs, in case anyone was wondering. It’s worth a mention as well, for anyone who wasn’t aware, that you can use your IDE to generate xml from an xsd, and a huge chunk of what I’m about to demonstrate can also be generated from your IDE in a matter of seconds if you have the JaxB plugin. But I’m a firm believer that before you generate anything, you need to know how to do it manually. Generate for convenience, not to avoid having to acquire knowledge. You know what they say about knowledge being power and stuff.

 

I tried to format it properly, I was kind of hoping you can already sort of see the java objects just as you read through the xml. Or at least the JSON representation of it if you had to do it. Your IDE can generate this for you. But for the purpose of this demonstration, I’m gonna do it manually. To represent the xml above, we would end up with 3 java classes, ShipOrder, ShipTo and Item. To map these classes out, we will have to follow the validation rules set out in the xsd. So the classes would look like:

import java.util.List;

public class ShipOrder {

    private String orderPerson;
    private ShipTo shipTo;
    private List<Item> items;  

    public ShipOrder(){  }

    //getters and setters go here
}

FYI, the XSD says maxOccurs of the item element is unbounded, which means there can be many items. Hence we have a list of items as opposed to an item.

public class ShipTo {

    private String name;
    private String address;
    private String city;
    private String country;

    public ShipTo() { }
    
    //getters and setters go here ...
}
public class Item {

    private String title;
    private String note;
    private Integer quantity; 
    private Double price;

    public Item() {
    }

    //getters and setters go here ...
}

You will notice that the data type of “quantity” is Integer. This means that it would accept a negative value, which it shouldn’t because the xsd clearly says that quantity is a positive Integer. If I had time and energy, and this was super serious, I would write a wrapper class around Integer that limits it’s values to positive ints, but because this is only meant to be a demo of JaxB, let’s not sweat the small stuff. I’m gonna leave it as Integer.

 

These 3 classes are all just POJOs. I have added a public, no argument constructor in all 3 classes cause it’s a requirement for JaxB.  Now we need to add JaxB annotations that will help us map our objects more accurately to XML. For instance, if you look at the ShipTo class above, it has “orderId” as a field just like name, address etc. We might have the illusion that all the fields will be child tags in the shipto tag, when in reality, orderId is an attribute. We need to use annotations to separate the tags from the attributes etc. And we need to also ensure that our tags will be appropriately named. What I mean by that is the following: We have named the class ShipTo, using camel case where the S and T are caps. This is to follow proper coding standards. But we need the xml tag that gets generated from this to have all lower caps cause that’s how it has been set out in the XSD. To sort this out, we will need JaxB annotations. I am going to share what the classes look like after adding the annotations, then I will go through each annotation and what it means after that.

import javax.xml.bind.annotation.*;

@XmlRootElement(name = "shiporder")
@XmlAccessorType(XmlAccessType.FIELD)
public class ShipOrder {

    @XmlAttribute(name = "orderid")
    private String orderId;

    @XmlElement(name = "orderperson")
    private String orderPerson;

    @XmlElement(name = "shipto")
    private ShipTo shipTo;

    @XmlElement(name = "item")
    private List<Item> item;

    public ShipOrder(){  }

    //getters and setters go here ...
}

 

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "shipto")
@XmlAccessorType(XmlAccessType.FIELD)
public class ShipTo {

    @XmlElement(name = "name")
    private String name;

    @XmlElement(name = "address")
    private String address;

    @XmlElement(name = "city")
    private String city;

    @XmlElement(name = "country")
    private String country;

    public ShipTo() { } 

    public ShipTo(String name, String address, String city, 
                  String country) {
        this.name = name;
        this.address = address;
        this.city = city;
        this.country = country;
    }

    //getters and setters go here ...
}
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "item")
@XmlAccessorType(XmlAccessType.FIELD)
public class Item {

    @XmlElement(name = "title")
    private String title;

    @XmlElement(name = "note")
    private String note;

    @XmlElement(name = "quantity")
    private Integer quantity;

    @XmlElement(name = "price")
    private Double price;

    public Item() {
    }

    public Item(String title, String note, Integer quantity, Double price){
        this.title = title;
        this.note = note;
        this.quantity = quantity;
        this.price = price;
    }

    //getters and setters go here ...
}

 

@XmlRootElement: This maps a class or an enum type to an XML root element. When a top-level class or an enum type is annotated with the @XmlRootElement annotation, then its value is represented as an XML element in an XML document. In the brackets we have a name attribute. The value of this attribute gets set as the name of the XML tag when the XML gets generated. For example, if your class/field was called myTag, but you annotated it with @XmlRootElement/@XmlElement (for class/ field respectively), and you set the name attribute to yourTag, i,e @XmlRootElement(name=”yourTag”), then on the xml document, the tag would appear as yourTag. If you don’t set the name attribute, then it will appear as myTag. I hope this isn’t confusing.

 

@XmlElement: Maps a field or property to an XML element

@XmlAttribute: Maps a field or property to an XML attribute

To completely break this down to absolute molecular level, the @XmlElement annotation makes your field an xml element, which is the stuff in the angular brackets (<stuff>) and @XmlAttribute annotation makes your field and xml attribute to the root element represented by that class. (<stuff stuffAttribute=”some value”>). I admit, this is a terrible explanation of element and attribute, head on over to w3schools for that part of things my dear friends, my focus is more on how JaxB works.

@XmlAccesorType: Defines the fields and properties of your Java classes that the JAXB engine uses for binding. It has four values: PUBLIC_MEMBERFIELDPROPERTY  and NONE.  I am not going to get into what these mean. There’s amazing javadocs on these however.

 

So now that we have appropriately annotated our POJOs, we can move on to writing the method that creates our xml from the POJOs, a process called Marshalling. (Doing the opposite is unmarshalling). This is where the good stuff is. We’re gonna do it with and without the schema validation. And it looks like this:

private static String jaxbObjectToXML(ShipOrder shipOrder) throws JAXBException, SAXException {
        StringWriter stringWriter = new StringWriter();
        URL url;
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(ShipOrder.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            jaxbMarshaller.marshal(shipOrder, stringWriter);
            return stringWriter.toString();
        } catch (JAXBException e) {
            throw e; //obviously bad code, do better!
        }
    }
public static void main(String[] args){
    List items = new ArrayList<>();
    items.add(new Item("Egg Shipment", "Fragile", 50, 50.00));
    items.add(new Item("Parcel 2", "Handle with care", 2, 85.00));
    ShipTo shipTo = new ShipTo("John Doe", "100 Grayston", "Johannesburg", "south africa");
    String orderId = "order123";
    String orderPerson = "John Doe";
    String outputXml = jaxbObjectToXML(new ShipOrder(orderId, orderPerson, shipTo, items));
    System.out.println(outputXml);
}

 

Running the main method would print the following:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<shiporder orderid="order123">
    <orderperson>John Doe</orderperson>
    <shipto>
        <name>John doe</name>
        <address>100 Grayston</address>
        <city>Johannesburg</city>
        <country>south africa</country>
    </shipto>
    <item>
        <title>Egg Shipment</title>
        <note>Fragile</note>
        <quantity>50</quantity>
        <price>50.0</price>
    </item>
    <item>
        <title>Parcel 2</title>
        <note>Handle with care</note>
        <quantity>2</quantity>
        <price>85.0</price>
    </item>
</shiporder>

 

Pretty freakin’ easy right? Now you don’t have to create your xml from a string builder and do all sorts of freakish gymnastics to manipulate the string to get it to do what you want. You get to work with actual Java objects but still have your output be xml. And remember kids, tests, tests, tests. Write your tests. TDD the crap out of every solution you write then you don’t need to “System.out.print” in the main method to see the output. Write your tests.

 

So with this solution that we have above, it works and does the job. But it’s not enough. It does absolutely no schema validations. That means that, if we gave input that went against the rules set out in the schema, our xml would still get generated without a problem. That might be okay for some use-cases, but best practice is to respect the xsd,  if the validation fails on your end, it’s just gonna go fail with whatever host system you’re sending it to anyway and  I’m guessing you don’t want that to happen. Next we’re gonna tackle how to do that, for those who are interested in that sort of thing.

 

We need to modify the jaxbObjectToXml method as follows:

private static String jaxbObjectToXML(ShipOrder shipOrder) throws JAXBException, SAXException {
    StringWriter stringWriter = new StringWriter();
    URL url;
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(ShipOrder.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        url = Resources.getResource(PATH_TO_XSD); 
        Schema messageSchema = schemaFactory.newSchema(url);
        jaxbMarshaller.setSchema(messageSchema);
        jaxbMarshaller.marshal(shipOrder, stringWriter);
        return stringWriter.toString();
    } catch (JAXBException e) {
        throw e;
    } catch (SAXException e) {
        throw e;
    }
}

Now that we have set the schema, when jaxbMarshaller.marshal(shipOrder, stringWriter) is called, a schema validation will be run, and if the xml generated violates any of the “rules” set out in the schema, then an exception will be thrown. This safeguards against invalid input, missing tags that are supposed to be compulsory, repeating tags where only one occurrence is allowed etc. The exception is actually your friend here. It’s what you want, then you know your xml is invalid before sending it anywhere or doing any further processing on it.

 

Anyway, that’s all folks. I hope you enjoyed this, and that you wrote your tests and dealt with your exceptions properly instead of just rethrowing them. Do as I say, not as I do, okay. And floss. No seriously, dental hygiene is important you guys. Floss, floss, floss, I can not stress this enough 😀

Adios Mi gente!!

 

From one new mommy to another

You have probably already picked up from the title that today’s blog post has nothing to do with tech. But stay with me anyway. Allow me to reintroduce myself. My name is Bophelo, a kick-ass open source developer, tech enthusiast, wife, sister, aunt, friend, (etc, etc), but before all else, as of 2018, I’m a mommy. I’m a mother to the cutest, sweetest little boy I have ever laid my eyes on, and for the past two months, my one and only job (and addiction) has been taking care of this little dude called Lehakoe. As much as I have been enjoying full-time motherhood, I found myself missing my blog, and since I’m a litlte out of touch with coding right now, I haven’t done much of it since baby was born, I couldn’t think of a better topic to write about than motherhood. Scratch that, parenthood.

 

With two months of experience as a mother, I am obviously an expert parent now and you should totally listen to what I have to say, hahah. No seriously, some of what I have to say is a little golden, it was passed down to me by women who have mothered tons and tons of children really well, and some of it I figured out on the job. Here goes:

 

  1. Always take parenting advice with a pinch of salt. The minute you fall pregnant, you’ll notice just how many opinions everybody has, and how everybody thinks they know what’s best for you and your baby. Take it all with a pinch of salt, or ignore it, and in some cases, maybe even punching people in the face might be an appropriate reaction (Not, violence is bad kids). Seriously, you don’t have to listen to everything everyone says, you don’t even have to listen to everything in this post, it’s really just my opinions
  2. Everybody says this, you have heard it a million times already, but it can’t be stressed enough, ENJOY YOUR BABY!. They grow so quick, before you know it your baby grew overnight and you need to cut a vest off of him cause suddenly taking it off is a mission and he’s crying his little lungs out. Of course this never happened to us. It’s a purely hypothetical situation. You can totally see how it could happen right?
  3. Accept help. If it’s not offered, ask for it from your nearest and dearest. I can’t begin to explain to you what a difference having a good support system makes. Right after Hakoe was born, I had an incredible amount of support. My sister picked up our laundry and brought it back washed, my mother made sure that the house was spotless when we woke up, my sister in law was hand washing baby’s laundry, my mother and my sister were making sure there’s always cooked food, my grandmother was folding laundry, my mother ensured that all of the baby’s bottles, nipple shields, breast pumps, milk storage containers etc were washed and sterilized at all times. And so much more. It was incredible. It allowed me and bae to fully immerse ourselves in the taking care of and enjoying the baby. There isn’t a single moment of his life that I missed cause I had to do his laundry and mop the floors, and that’s something that’s really valuable. If you can’t get this from family and friends, hire some help, but have help.
  4. Humidifier. Get a humidifier. It saved our lives. Lehakoe’s nose used to get blocked, without fail, every. single. night. Every night. He would struggle to breath, and we would lose sleep over it. We would spend hours (I’m obviously exaggerating here) with saline spray and nose frida (another amazing invention) trying to clear his nasal passages. But once we got a humidifier, blocked noses were a thing of the past.
  5. Nose Frida. We got this as a gift from my sister. She got us really amazing gifts, she knew just what she needed as a mother of a young child herself. The Nose Frida seems like a disgusting little thing at first. I’m not gonna explain how it works, our good friend google can do that for you, but it honestly turned out to not be as disgusting as I thought it would be. Infants can’t breathe through their mouths, so when their nasal passages are blocked, it’s the saddest thing ever. You can use Nose Frida and a saline solution to suck out the mucous so the baby can breathe again. Even if your baby doesn’t get blocked every night like ours did, they are bound to get blocked at some point, it’s a great thing to have just in case.
  6. Assuming you are planning on breastfeeding (no judgement if you aren’t), join the La Leche League facebook group. “La Leche League International is a non-governmental, nonprofit organization that organizes advocacy, educational, and training related to breastfeeding.”  The group is very helpful and supportive to breastfeeding moms. I have learnt a lot from the group about nursing, pumping, milk storage etc. It’s a great way to also figure out what’s normal and what’s not, cause breastfeeding isn’t as easy and straightforward as one might expect it to be.
  7. While we’re still on breastfeeding, get a good double-sided, hands-free electric pump. Best decision I ever made. I’m actually pumping milk as I’m writing this right now. I’m gonna try to not do any brand recommendations cause I have only ever tried one brand (which I’m absolutely in love with by the way). But feel free to ask if you’d like to know what it is.
  8. Babies make weird noises in their sleep. I wish somebody had told me this. I spent so many sleepless nights wondering if my baby was fine. He made all sorts of weird and wonderful noises. Some cute, some literally shocked me awake cause I thought he wasn’t okay. He was fine. I’m not saying ignore them, by all means pay attention to every sound, you never know if the baby needs your help (from one over protective mommy to another). All I’m saying is, it’s normal. Your baby is normal. I wish someone had told me.
  9. And while we’re on the topic of normal, there’s many other weird things you’re going to encounter that are absolutely normal. Some have landed us in the ER once or twice for absolutely no reason at all (according to the doctors). Babies get rashes, that’s normal. They skin cracks and peels a few days after birth, also normal. Their toenails look like they’re growing into their little skins at first, totally normal. Try not to freak out. But once again, I say run to that emergency room or the GP or whatever if it gives you peace of mind. Have the nurses laugh at you for being overly cautious. Lose a couple grands. Whatever. As long as it helps you sleep at night. Your child’s well-being is worth a lot more than a little lost time and a little lost money.
  10. All babies are different. Try not to lose your mind over the fact that somebody else’s baby sleeps longer than yours, weighs more than yours, reached certain milestones before yours, etc. Babies are people, and we all know people are unique and all wonderful in their own little ways. Don’t put pressure on yourself or your baby because the internet said, or that mommy from the baby development classes said.
  11. Get a baby wrap. And a microwave sterilizer. And swaddle that baby. Honestly. I’m just gonna compound these into one point cause my baby’s been sleeping for two hours and will probably be up for a feed soon. Like I said. I’m a momma first now. Baby wraps are amazing, not only are they cute, but they allow you to go hands free when baby is feeling particularly needy. And the babies love them too. A microwave sterilizer is one of the best gifts we received, also from my beloved sister. Super convenient. And swaddling will help your baby sleep like a baby (horrible metaphor, babies aren’t the best sleepers around). The swaddle contains their startle reflex (Moro’s reflex) and reduces chances of baby startling themselves awake. You need the baby to sleep, they turn into cute little monsters when they are overtired. Swaddle. Swaddle. Swaddle.
  12. More than anything, remember to take it easy and to take care of yourself. You just carried a whole entire human for really long. It’s very tiring. And bringing them into the world is a lot of work too, however way you chose to do it. And even if you didn’t carry your baby, I imagine a lot of work went into preparing for the baby anyway. REST. I’m not gonna tell you to sleep when the baby sleeps like a lot of people told me. I find that to be ridiculous advice cause it’s not like I can shower when the baby showers, or work on my blog when the baby works on his, etc. But honestly, rest. It’s not always possible, but when it is, take the opportunity to rest. Your baby’s father is just as capable a parent as you are. He can hold the fort so you can catch a snooze, or so you can go for a walk, or whatever floats your boat. Your child needs a well rested, alert mommy, more than a super mombie (zombie mom) who won’t accept help and is going through life half asleep. Of course I understand that not everyone will be privileged enough to have help on offer.
  13. My personal favourite, keep in touch with the outside, non-baby related world. It will keep you sane. I read tech blogs in the middle of the night when baby nurses. You may be a mommy first, but you are still a whole entire human next to that. Nurture that human. Easier said than done, I know. I just turned down a milkshake date with friends cause I couldn’t bring myself to leave my child. I’m not exactly taking my own advice here. But one day at a time. One day at a time.

I hope these will be useful to you, whether you’re a new mommy, an expectant mommy or someone who knows one.

Unit Testing in Mockito vs JMockit.

This post is supposed to be about my experiences using both JMockit and Mockito, to sort of pit them against each other, if you may. But I feel it wouldn’t make sense to just dive straight into that discussion without first touching on the basics of unit testing, such as, what exactly is unit testing. It might seem pretty trivial to you, but trust me, a lot of people don’t truly know what a unit test is. So let’s dive straight into it.

According to our good friends over at google, the word unit means “an individual thing or person regarded as single and complete, but which can also form an individual component of a larger or more complex whole”. It should be easy to go from that definition to assuming that a unit test would be a test of an individual thing that could be a component on a larger whole. In software, particularly when we are talking about object-oriented programming, this “individual thing” could be an entire class, or a method within a class. Which one it is, would depend on your design and what your code does, but that’s a blog post for another day. What all this means, is that when you are writing your unit test, you would need for it to test a single method or a single class at the very least. But often times our objects interact with and are made up by a lot of other objects, they are cogs in a much bigger machine which is the whole application.

To unit test these “cogs”, we need to assume that all the other components of the machine have been tested and work just fine, so we isolate the cog, and test that on it’s own, test that it does what we expect it to do. (The machine will have it’s own “unit” test, which will also assume all the cogs work perfectly, and instead, will test that the machine (as an abstract concept) works the way we expect it to. So this would mean that we need to test our class or our method in complete isolation, and assume that all the classes it depends on have been tested and work perfectly fine. If we assume all the other classes work fine and have been tested, we don’t even need to use concrete instances of these classes, mocks suffice and are actually preferable because then our test will execute much faster if they don’t have to interact with real concrete objects, or with the database etc. If you have ever worked on a large, complex system, trust me, you will appreciate your tests running fast.

If you find yourself concerned about not testing your class with the actual concrete instances of the classes it interacts with, that’s okay, and frankly I’m glad you are thinking of that. I am absolutely not suggesting that we don’t test that at all. What you need to be aware of however, is that we don’t need to for unit tests, that’s where integration tests come in. Integration testing is equally as important as a unit testing, and you definitely need both. But in this article, I am going to focus on unit tests, in future I might delve into integration tests. Let’s take an example of a class (in Java) and go through its unit test.

public class MyObject {

private ForeignObject foreignObject;

public MyObject(ForeignObject foreignObject, Boolean alive) {

this.foreignObject = foreignObject;

this.foreignObject.setAlive(alive)

}

public boolean isMyForeignObjectAlive(){

return foreignObject.getAlive();

}

}

Say we had to unit Test MyObject. This class clearly has a dependency on ForeignObject (and Boolean, which we won’t be focusing much on). Following what I stated above, we are going to assume the correctness of ForeignObject, we are going to assume that when the setAlive(Boolean boolean) and getAlive() methods are called on ForeignObject, they will behave as we expect them to. What we want to test instead, is that instances of our class interact in the way we expect them to with instances of ForeignObject. To achieve this, we would mock out ForeignObject and it’s behavior (only the behavior we need, which makes our test run much faster than if we were calling a concrete instance of ForeignObject). The test would go something a little like:

public class TestMyObject {

@Test

public void testThatMyForeignObjectIsAliveIfIInstantiateMyObjectWithTrue() {

ForeignObject foreignObjectMock = mock(ForeignObject.class) ;  //Mockito

   doNothing().when(foreignObjectMock).setAlive(any());

when(foreignObjectMock.getAlive()).thenReturn(true);

MyObject myObject = new MyObject(foreignObjectMock, true);

Assert.assertTrue(myObject.isMyForeignObjectAlive());

}

}

As you can see, we do not use a concrete instance of ForeignObject, but rather a mock. We also mock out the behaviour that we will need from ForeignObject. We do not need to call the actual setAlive method or the getAlive. We assume they have been tested in the ForeignObject unit tests and that they work fine. This method is sufficient and quick, gives you results very quick.

At this point, it should be clear what a unit test is, and how to approach writing one (in Java that is). So we can move on to the Mockito – JMockit comparison. In the example above, I have used Mockito to mock the object and it’s behaviour. I like how simple and easy to read and understand this becomes in Mockito. And it also makes it very easy to follow the “Given, when, then” structure of writing a test. If we had to express the above in that structure, it would be “GIVEN that we have an instance of foreign object (the mock), WHEN we call setAlive with any value, do nothing (cause we are not interested in foreign object, we are assuming it’s correctness), and WHEN we call getAlive,  return true, THEN, myObject.isForeignObjectAlive() should return true. We do the assertion in the the “THEN” part of the test.

Now let’s look at how you would do this is JMockit. The implementation is not very different, also allows for you you to follow the “Given, when, then” structure, but it tends to be a lot more verbose. Below is how we would write the exact same test in JMockit:

public class TestMyObject {

@Test

public void testThatMyForeignObjectIsAliveIfIInstantiateMyObjectWithTrue() {

MockUp foreignObjectMock = new MockUp{

@Mock

public void setAlive(Boolean alive) {   }

@Mock

public Boolean getAlive() {

return true;

}

};

MyObject myObject = new MyObject(foreignObjectMock.getMockInstance(), true);

Assert.asserTrue(myObject.isMyForeignObjectAlive());

}

The above does the exact same thing, our GIVEN and WHEN have sort of been bunched up together as you mock the object and it’s behaviour all at once. That’s okay. But it doesn’t read as easily as it does using Mockito syntax. And it’s quite verbose as well. I believe in tests that are simple, easy to read and understand, so as to not discourage people from maintaining them. But I admit that this doesn’t exactly make JMockit bad or anything, just different. With that said, I am still very new to JMockit, and for that reason I will make a conscious decision to use it over Mockito in the next few months so I can learn it a bit more and have a deeper understanding of how it works, then I can make a call about which I prefer based on something a lot more substantial, like what each one can offer me in terms of functionality etc. For now, I hope I have motivated you to try at least one of them.

Adios!!

Trunk Based vs Feature Branching – A Rant

I recently started working on a project where they use Trunk Based development. I wasn’t familiar with the term, just the term, the practice has been around, has failed and given birth to feature branching, but let me not start my rant just yet. You might not be familiar with one or the other strategies, maybe even both, that’s okay. Let me balance you real quick, just on a high level.

 

In the Trunk Based Strategy, everyone pushes their code directly onto the master branch. With feature branching, for every “feature”, and I use the word feature very loosely here, I would prefer to use “user story” instead, but it’s called feature branching and not user story branching so here we are. With feature branching, for each feature/story/bugfix, you create a new branch, typically you would be branching away from a develop branch, (some teams branch from master). You write your code and commit it to your branch, you then do a pull request to merge your branch into the main branch (develop, master or whatever it is the team chose to call this branch).

 

I’m a fan of feature branching for a number of reasons, I’ll mention a few:

  1. The master branch will never contain broken code. No more worrying about “who broke the code”. aka, no more tears. No more fears.
  2. It makes code reviews easier to accomplish. Honestly, who really wants to go to someone’s desk to review their changes on their machine? Literally not one person, don’t even lie.
  3. I’m a huge fan of agile, and of Jira, of the entire Atlassian Stack really.  (If you travel back in time and peek at my past, I may have said some bad stuff about Jira, I take it all back, I was young and Naive. forgive me universe).  Now where was I, ah yes, Jira and it’s friends. I’ll admit this is a petty little reason but indulge me. Do you know the joy of dragging your story/task, from the backlog and into “in progress”, and hitting one button and Jira creates a corresponding feature branch for you in Bitbucket? Then you finish working on this branch, you push it into remote (you have obviously rebased at this point) and the branch gets run in a pipeline on Bamboo? And you already know if your changes are sound or not, they go through Sonarqube, all the unit and integration tests get run, and all these nice and tasty little things, without any commitment? If your code is going to break the main branch, you already know, without actually you know, breaking the actual main branch? I don’t know about you but that sounds like a sweet deal to me.

With all these said, I’m willing to admit that this is probably just comfort talking. That this is just me resisting change cause I have gotten so used to feature branching that I might reject anything else that isn’t that. I would like to think I am not that person though, I mostly embrace chance pretty readily, but the benefits have to be proven to me. And honestly it doesn’t feel like the benefits of trunk based development have been proven to me. Instead, when talking to its proponents, all I have heard is reasons why they have a problem with feature branching. My personal favourite being:

“Some branches live for too long, I have seen people working on the same branch for like 8 months”.

Uhm, my response to this is, AGILE. Seriously, how does this happen in an agile project? If the branch corresponds to a story, and the story is supposed to have been completed at the end of the sprint, how did that branch not get nuked at the end of the sprint or at the time it got merged into the main branch? It sounds to me like the problem here is not “agiling” properly, it’s not feature branches that are fundamentally at fault.  Another complaint I have heard is that feature branches prevent continuous integration. Once again I say to this, AGILE. You can’t CI in a waterfall project, or in a WAGILE project. (That’s a portmanteau of waterfall and agile incase you missed it). Oh and one last reason against feature branching that I totally disagree with (I literally had to run back and edit after publishing this 🙂 ). Some people claim that it causes tons of merging conflicts. My answer to that is, what’s preventing people from rebasing before doing a pull request? NOTHING. Merging conflicts are still possible in trunk based dev as well surely?

If we don’t fix the actual problem, changing branching strategies is not going to help us with anything as the problems we experienced before will likely just take on new shape or form.  But all this aside, I’m still willing to convert if someone can offer me a convincing, compelling argument. If they can answer questions such as “what safeguards do you have in place to prevent people from breaking the main branch”, and “How do code reviews work, do we review code at all”. Feel free to convince me, please, I’d love to hear your opinions.

How to: Create collapsible/expandable Div using AngularJS for beginners

I’m a little bored today and I haven’t really been giving as much attention to my blog as I would have liked, so now seemed like a great time to throw in a little beginners tutorial to ease my conscience. I have been playing around with AngularJS a lot more despite obviously having a preference for back-end work, so I thought I would share a little something Angular.  Might seem trivial, but I bet you someone out there somewhere might find it useful.  I am assuming the reader already knows how to create an AngularJS Controller, and below I only present the snippet that goes into the view:

Here we go:

1. <button type="button" ng-click="expand=!expand">Press Me</button>
2. 
3. < div ng-show="expand">
4.     <p>I am a collapsible paragraph</p>
5. </div>

Before I fully explain exactly what we have done above, I’m gonna explain ng-click and ng-show, both are Angular directives. I am also assuming knowledge of what angular directives are. According to AngularJS documentation, “the ng-click directive allows you to specify custom behavior when an element is clicked”. In simpler terms, it allows you to specify exactly what should happen when an element, such as the button above, is clicked. You could choose to invoke a function defined in the controller at the click of an element, amongst other things. The ng-show directive on the other hand, takes a boolean value as input, and sets the visibility of your element to the value of the given boolean. You could feed it a boolean value (true or false), you could feed it a variable that contains a boolean or you could also invoke a function defined in the controller, that returns a boolean. i.e:

ng-show=”vm.show()”

where show() is a function defined in the controller, vm, and show() returns a boolean value upon being invoked, or you could also do:

ng-show=”true”     or        ng-show=”bVal”  where bVal = true;  You get the idea;

 

Now that we are all on the same page about what the directives I used do, let’s go back to the above snippet of code, and analyze it line by line. By the way, I am obviously also assuming basic knowledge of HTML, and if you are still learning it, W3Schools is your friend.

In line 1, we create a button with the text “Press me” on it. And we use the ng-click directive on this button, that when it gets clicked, it should just toggle the value of “expand”, a variable in the controller which holds a boolean type. By default, expand is false. So when the page loads for the first time, the value of expand will be false, when the button gets pressed, the value will become true, if the button gets pressed again, the value becomes false, and so on and so forth.

In the third line we create a div that contains a small paragraph. This div has the directive ng-show which has been set to expand. Which means that the visibility of this div, is controlled by the value of expand. As  discussed above, the default value of expand is false, so when the page first loads, the paragraph should be hidden since ng-show = “false”. At the click of the button however, expand becomes true, the ng-show in the div is set to true and therefor, the div should become visible and we should be able to see the paragraph. Clicking the button again, the paragraph should become invisible, and so on. And in this way, in the simplest way possible, we have created a collapsible/expandable div. In the next tutorial, just for the fun of it, we’ll make an actual drop down menu, complete with icons and everything to demonstrate possible uses of what we learnt today.

 

Adios mi gente!!

The Jackson feature that became a quirk, for a second or so…

Disclaimer: This is not a Jackson/JSON tutorial, prior experience with both is being assumed in this article, this is really just me venting, or rather sharing my findings after a session of good venting and no, don’t close the post, this might save you a lot of heartache and googling later on, or at the very least, give you an explanation for previous heartache. Stay tuned!!

 

So I found a weird little quick with the Jackson Object Mapper in spring today. Let me paint you a picture. So I had a Java class, it looked a little something like this:

public class MyClass {

    private String className;
    private boolean isNameSet;

    public boolean isNameSet() {
        return isNameSet;
    }

    //...insert other getters an setters here
}

 

I was then returning an Object of this type from a rest api. Which would mean spring would deploy our good friend Jackson to serialize our Java object to a JSON object when the API was called upon. Great Stuff. Except that it wasn’t so great. In my swagger (check out swagger for api testing, thank me later), the returned JSON object didn’t exactly look like how I had anticipated. I was expecting it to look like this:

{ "className":"some string", "isNameSet":true }

But instead, the output looked a lot like this:

{"className":"some string","nameSet":true}

 

Notice the difference? The field “isNameSet” has been changed to “nameSet”. Perhaps Jackson was trying to tell me to up my variable-naming game, and that the field should probably have been nameSet to begin with, such that it’s accessor method (that’s the getter, peasants, keep up) can be appropriately named as isNameSet(). **shrugs** It might seem I have upset the Jackson variable naming snobs and they took it upon themselves to fix my transgressions. Jokes, proper naming conventions are very important. Jackson expects the class to have proper naming conventions for the fields, mutators and accessors, i.e, for a boolean field named nameSet, it expects a getter named isNameSet, and for a field named isNameSet, it expects a field named isIsnameSet(). So that’s one way of fixing my problem.

The other way, which is really the worst way, but a way nonetheless, is to use the   @JsonProperty annotation to avoid Jackson being snobbish and correcting your field names for you. So you would define your class like so:

public class MyClass {

    private String className;
    private boolean isNameSet;

    @JsonProperty(value="isNameSet")        
    public boolean isNameSet() {
        return isNameSet;
    }

    //insert more code here
}

And voila, bob’s your uncle, you get your json string exactly how you would expect it.

Cool story, right bro? Tune in again next time and I’ll be sure to tell you more.

 

Let’s talk about Dependency Injection

And no, when I talk depency injection, I don’t mean syringes, needles and stuff, thank goodness.

“Drugs are bad, mmmkay” – Mr Mackey

mr mackey

Some might even take Mr Mackey’s advice a little step further and say all dependencies are bad. Unfortunately, as developers, we can not run away from them. AT ALL. But depending on others’ code doesn’t have to cripple you. If you’re not smart about your design, it can. “How?”, you ask.

Well I’m glad you asked. Let’s have a look at the following code snippet:

public void printWebSource(String webAddress) throws Exception {
    URL url = new URL(webAdress);
    InputStream inputStream = url.openStream();
    BufferedReader buffer = new BufferedReader(new InputStreamReader(inputStream, CHARSET))

    int byteRead;
    while ((byteRead = buffer.read()) != -1) {
        System.out.println((char) byteRead);
    }
    buffer.close();
}

 

This Java method takes a web address as a string (e.g https://wordpress.com) and prints the source code that’s rendered at that address. Taking a quick glance at it, it looks pretty straight forward and like it should do the job just fine. The issue with this method, is how tightly coupled it is with it’s dependencies.

It depends on a few Objects, URL, InputStream, InputStreamReader, BufferedReader, etc. Which is fine, in the name of Abstraction and not reinventing the wheel, we will most probably always depend on code that has already been written by others. The problem comes with tight coupling.

Think of it this way. There’s a boy called X. And a girl called Y. X and Y are in a relationship. Y cooks for X. X depends on Y cause X has to eat. One day, Y decides not to cook for X, so X starves to death and becomes Y’s ex. X was clearly stupid. Had he known how to cook for himself like how every adult man (and woman) should, he would still be alive. But I digress.

The problem with X and Y’s relationship, wasn’t the dependency, it was the tight coupling, such that any changes in Y, affected X super badly. You don’t want to write code that dies if another piece of code decides to stop cooking. And in the code snippet above, if whoever wrote the URL class, decides to change the way URL is instantiated, our method, printWebSource will break (read; starve to death). We don’t want that. We want printWebSource to be a self sufficient, non-stupid method that can grow and mature and understand that patriarchy is stupid. And moreover, unit testing is either going to be a nightmare, cause how are we ever going to mock URL, BufferedReader and all other tightly coupled dependencies? or test coverage will be extremely low, which isn’t very helpful.

So how do we fix it? Once again, I’m super stoked you asked. It’s pretty easy.

Step 1: Identify your tightly coupled dependencies

In the above code snippet, that would be URL, BufferedReader, InpuuStreamReader. These are instantiated inside the method. Which means that if we were to mock them in a unit test. upon running our test, there would be zero interaction with those mocks, so we would have very low test coverage, which would really mean we are writing tests for the sake of it. WE DO NOT DO THAT. We write tests to actually verify that our software is still working correctly and we have not introduced any bugs. Additionally, these would also affect our method should the way they get instantiated change.

 

Step 2:

The fun part, we need to find a way to inject our dependencies into our code. Relax Mr    Mackey, it’s only Objects! There’s multiple ways to inject dependencies, some of which include injecting through your container, (such as using EJBs in the Java Bean world),  injecting them through the constructor or through setters. Have a look at this refactored version of printWebSource

public void printWebSource(URL url) throws Exception {
    InputStream inputStream = url.openStream();
    BufferedReader buffer = getBufferedReaderFromInputStream(inputStream);

    int byteRead;
    while ((byteRead = buffer.read()) != -1) {
        System.out.println((char) byteRead);
    }
    buffer.close();
}

 

In this case, the url is injected through the method parameter, and the creation of the bufferedReader has been abstracted out into an auxiliary method called getBufferedReaderFromInputStream.

With how the method signature was before, an invoking class would have called the method like:

String webUrl = http://www.google.com;

printWebSource(webUrl);

 

After the refactor, they would call it as:

printWebSource(new URL(webUrl));

This places the responsibility of instantiating the URL on the invoking class, and this could further improved by creating the URL as a bean and autowiring it into the invoking class, assuming we would always know webUrl upfront. Now we can write a unit test and get a very high test coverage for our method, and also not have to go change our method should any changes in the dependencies arise.

I realize that the refactoring of this method to get Dependency Injection is a little tedious, so why not just use TDD then your code will look like the second snippet from the get-go? Maybe my next post will be  on TDD and how to do it, might even do a tutorial video, watch this space.

 

Thanks for reading, I hope you understand dependency injection now and why we need  it. My next article will cover another method of Inversion of Control.

Java – Mocking an advanced for-loop with Mockito

I was maintaining a class today that used the old java for loop, you know, the:

for(int i = 0; i<list.length; i++){

Object object = list.get(i);

object.doStuff();

}

I cringed a bit. I mean, unless you are still writing code in java 4 and predecessors, why would you do this? This for loop is hard work to maintain (not really, but stay with me here), hard to read, (seriously, nobody wants to read all those list.get(i) and stuff), and just plain outdated, unless you need to have control over the loop, like in a case where you don’t want to iterate over every single element of your list. This wasn’t one of those cases.

So like any sensible developer, in the name of legibility, I called upon the great syntactic sugar powers of the great java 5 and beyond, and I changed the loop into an enhanced for loop, like so:

for(Object object: list){

object.doStuff();

}

It’s simple, easy to read, and you immediately know from just taking a glance, what this for loop does. Great, right? Wrong. The tests broke! It then dawned on me, whoever wrote this code and decided to use the dinosaur loop in 2017, probably did so to avoid having to unit test the enhanced forloop. With the normal loop, all the behavior you have to mock, is what happens when an item is retrieved from a list, which would be something a lot like this:

List list = mock(List.class);

when(list.get(anyInt()).thenReturn(mock(Object.class))

Easy peasy lemon squeezy!!! Right? Wrong. It’s great when your unit tests (read: TDD)  influence your design and force you to do Inversion of Control (Watch out for a future blog post on the topic), but when your tests force you to write horrible looking code cause you aren’t sure how to test good looking code, then you know it’s probably time you head on over to our good friend google and do some research. Lucky for you, I have already done that for the both of us, so you don’t have to. Here’s how you would mock the behaviour of an enhanced for loop. Before I get into the meaty part, it’s probably worth a mention, that the enhanced forloop is really just syntactic sugar, as I already mentioned, for using iterators. So to mock the behaviour, you would need to mock an iterator as well, like so;

Iterator<Object> iterator = mock(Iterator.class);
List<Object> list = mock(List.class);
Object object = mock(Object.class);

when(list.iterator()).thenReturn(iterator);
//this is to mock list with one element, adjust accordingly
when(iterator.hasNext()).thenReturn(true, false); 
when(iterator.next()).thenReturn(object);

And just like that, your tests will be happy and Bob will be your uncle.

And speaking of Bob being your uncle, head on over to Uncle Bob’s clean coder blog. You will love it I promise. Happy Coding!!

 

 

 

Murphy’s Law at work in my life Today

Sometimes I feel like my life is a series of one awkward moment after another. Issa Rae should hand the “Awkward Black Girl” title over to me. Seriously. So I was tasked with recording a tutorial video for new features I had worked on in our application at work recently. Something I wish I didn’t have to do. Nothing more painful than non-dev related tasks for a developer. But iJob-iJob sbali, so we soldier on. What choice is there really.

Anyway, I quickly grabbed my red cape, put an S on my chest, and quietly sat down to record the video (I skipped the step where I put my underwear over my pants, that’s the difference between me and superman, in case anybody was wondering). Back to the video.  I ran the application, started my screen recorder, I clearly remember thinking to myself “I should probably mute the screen recorder”. I even vaguely remember actually muting the said screen recorder. I’m willing to bet most of my hemoglobin that I muted the sound before I started recording. I’m anemic, so this is a pretty serious bet.

As with any other dev task, before I started, I went and compiled a play list to help me drown everything else out so I can completely concentrate on what I’m doing, which is this case, is a super boring, non-dev related task. Few takes and edits  later, I was done, happy with my work, and the video was on it’s way to the Programme Manager of Strategy Enablement the Chief Technology Office and infrastructure Services. I just added the guy’s title fore measure. Imagine the horror on my face when he responds: “Thanks for the video, interesting choice of music I must say”. OMG OMG OMG, can I die right this second?!!! At this point, I’m not even sure which song was playing during the successful take of the video, which was one of umpteen tries. Gasp! I should probably mention that sometimes I have an affinity for the likes of Nicky Minaj, it would be a really great job retention strategy if I were to not send a video with Nicki Minaj’s songs playing in the background to **insert really long really fancy strategy something title over here**.

In a panic, I switched right over to the video, unmuted the video player (why did I ever mute it to begin with) and listened to the video. Mthande by Musa was playing in the background.  Whyyyyyy? Why must my life be this way??? Why was I born to suffer? Whyyyyy???? Now I’m gonna be known as that hopeless romantic that doesn’t know when to stop and doesn’t understand that a technical tutorial is probably no place for Xhosa Love songs. But then again, I guess it could have been worse, it could have been Nicki Minaj playing.