I have been spending a lot of time with JBoss Seam, and I must say, I am very excited about what I have seen. My goal in these next few posts is to talk about why I think these features of Seam are game changers and what they are saying about the direction the JEE Spec is going.
Before I dive into the topic for this post, one of my coworkers gave a brief introduction to Seam a few weeks ago. I would recommend reading it first if you are completely unfamiliar with Seam. If you are looking for a more thorough introduction (other than the reference docs), I give my recommendation goes to Seam in Action by Dan Allen. It has been my guide in my own exploration of Seam and, in spite of it’s Seam 2.0/2.1 focus, it is extremely relevant to working with Seam 2.2 today. With that out of the way, let us begin with some background.
I am a big fan of the Spring Framework. The many “glue code” utility classes and the Spring IoC Container have been staples in my applications since I started working with the Java Platform. Spring provided a way to do POJO programming in a world that was under the tyranny of the ugly EJB 2 programming model. They created an alternative to a broken standard that was very welcome. But this post is about Seam, so what’s all the Spring talk for? One of the key features, or rather the key feature, of Seam is what the Seam guys like to call Contextual Components. For those of you with a Spring background like me, a Seam Component is analogous to a Spring Bean. The contextual piece is what makes it interesting.
In Spring, you usually assume that a bean is going to be a singleton and that it is going to be stateless. That is the way of things with Spring. The common case is that everything is constructed at startup and all wired together before your application services it’s first request. You get all that glue code and DI goodness right up front. There is another way to handle your beans that is not as widely used. You can declare the scope of a bean to be Prototype, which means Spring will construct a new instance of that bean for you each time you ask your ApplicationContext for it.
Seam has taken this a step further. Instead of beans being limited to being either Stateless application singletons or construction prototypes, Seam let’s you scope components to rich set of contexts. See here for the complete list. This makes the Seam context not just a repository of pre-built service objects, but a scoped application state manager that is managed as a central concern of the framework (which is a fancy way of saying Seam takes care of the plumbing so you don’t have to). Now, instead of having a DAO object that encapsulates your data access methods, you can have a Data Mediator that not only knows how to get at an entity instance and save changes back to the database, but it also tracks the instance in the proper scope for you, so you only have to read it once from the database, even across multiple http requests. It is extremely powerful.
The other piece that Seam adds is called Outjection. No, that isn’t a typo. As part of an operation invoked on a Seam component, it not only gets all it’s dependencies injected, scoped as appropriate for the context of the components involved, but it also can send new components back to the context to be used by other parts of the application, managing the scope all the way.
What does this mean practically? No more leaky Http Sessions!
Now, if you are wondering if this is relevant to where JEE is going, take a look at JSR 299. CDI, or “Web Beans” as it has been called, is largely based on what I just explained to you. This JSR is part of JEE 6 and will available in the next update to your favorite application server. You can get this functionality now with Seam 2.2, or if you are required to “stick with the specs” when you do things, go ahead and download Weld, the JSR 299 reference implementation. Weld is what JBoss AS 6 is using to implement CDI and what Seam 3.0 will be built on.
In my next post, I’ll talk about the power of the new Conversation Context that Seam and JSR 299 introduce.
Without any working knowledge of the Entity Framework I have decided to dive in and see if it is a viable option for data access. In the past I have used LINQ to SQL and was not really that impressed. I had a hard time making use of the Context object inside of a web environment. I also did an enterprise application with LLBLGEN PRO and found it to be quite easy to use, but always had issues with serialization because of its large entity objects.
I have always preferred iBatis for data access because it was light weight, separated queries and made use of Plain Old CLR Object (POCO)s. Entity Framework (EF) has had several iterations and with this latest release is supporting POCOs without inheriting from any special interfaces.
The ability to separate domain objects completely from any kind of persistance code makes systems much more extensible and maintainable. Testing is made much easier when business logic can be tested separately from storage code. The use of POCOs with the Entity Framework (EF) is definitely a step in the right direction!
In order to get started on my journey I hit up quite a few useful blogs. The most useful is the ADO.NET Blog which gives great information about the current state of EF and plans for future releases.
There are currently two ways to connect POCOs to EF. The main way which is currently supported in the VS 2010 RC is through the use of an Entity Data Model. Even though POCOs are being used, the EDMX is still created and used to create mappings of fields to columns in the database. The designer is still in play, but code generation of each entity is turned off. Custom contexts are then created that return each POCO.
The second way to connect POCOs to EF is still in the preview stage and will not be available in the general release of .net 4. This option is called the ‘Code Only’ approach. The ‘Code Only’ approach removes the need to use the EDMX file and allows manual mapping of columns, relationships and keys. This is currently only in the preview stage. For this blog I will use the first approach and in a following blog will follow the same example using the ‘Code Only’ approach.
All code and examples will be from a small app that I am building to keep score of a Spades card game. Data access is the first step of this application which will eventually make use of RIA Services and Silverlight.
1.) First step is to create a database table. I have created a table called ‘Games’ which will hold a record for each Spades game that is played.

2.) Once the table is made the next step is to create our POCO object. The Game object has a property for each column that is in the database. Any column that allows null in the database will be nullable in the object as well.
public class Game
{
public int GameId { get; set; }
public DateTime StartDate { get; set; }
public DateTime? CompleteDate { get; set; }
public int? CurrentHomeScore { get; set; }
public int? CurrentAwayScore { get; set; }
public int? FinalHomeScore { get; set; }
public int? FinalAwayScore { get; set; }
public int CurrentHandNumber { get; set; }
}
3.) Now that we have our POCO we need to map its properties to the database. To do this we need to create a new project called Spades.DataAccess. The reason we create a new project is to ensure that the POCOs in the domain project have no relationship to any persistence code. This makes our design alot more testable.

4.) Add a Entity Data Model (.edmx) to the Spades.DataAccess project. This model allows us to map fields in the database to the POCO object.

5.) Choose the ‘Generate from Database’ option and select the Spades database. Select the ‘Games’ table and create the entity model.


6.) Once the Entity Model has been created we need to stop the auto generation of the entities. This can be achieved by setting the ‘Custom Tool’ property of the Entity Model to null. In the next step we will manually attach the POCO to the Entity Model.

7.) We now create a class that will be used for accessing data and returning POCO objects. This class inherits from the ObjectContext class. A couple things to note: References to the lines 1-4 need to be added for the code to compile. Line 10 passes in the ConnectionString name for the database. The CreateObjectSet
using System.Data.Entity;
using System.Data.EntityModel;
using SpadesDomain.Entities;
using System.Data.Objects;
namespace Spades.DataAccess
{
public class SpadesContext : ObjectContext
{
public SpadesContext() : base("name=SpadesEntities","SpadesEntities")
{
_games = CreateObjectSet<Game>();
}
private ObjectSet<Game> _games;
public ObjectSet<Game> Games
{
get
{
return _games;
}
}
}
}
8.) Finally a unit test is used to test that we can actually pull some test data out of the database. (Use the SQL Studio Management tool to add in a couple rows into the Games table) The unit test references all other projects in the solution. The unit test uses LINQ to pull out all Games in the system and checks to make sure at least one Game came back.
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Spades.DataAccess;
using SpadesDomain.Entities;
namespace SpadesTests.DataTests
{
[TestClass]
public class SpadesContextTests
{
[TestMethod]
public void GetGamesTest()
{
var db = new SpadesContext();
var games = (from g in db.Games select g).ToList<Game>();
Assert.IsTrue(games.Count > 0);
}
}
}
8.) A successful unit test! Up next will be doing this example with the ‘Code Only’ approach.

I spent most of last year working on a project that has afforded me the opportunity to work with some technologies that I had played with a bit before, but hadn’t actually used them in a full-scale project. Apache Wicket is one of those technologies, that I wrote about previously and the other one is RESTful Web Services using JAX-RS.
There are many other great articles on why you would write a service layer that encapsulates your business rules and keep it separate from the UI, so I’m not going to go over that. I will just tell you that we had the goal of creating reusable services for our project, but we wanted to try something different as we were rather disillusioned with SOAP web services and EJB RMI was out as we need to support cross-platform clients.
First, my grief with SOAP is that it is really just another implementation of remote procedure calls that we have all come to know and loath. I have used remote procedure calls in CORBA, Apache’s XML-RPC, EJB RMI (Remote Session Beans) and WS-*/SOAP web services. I’m going to lump these all together into the remote procedure call bucket and tell you that I have had the same issue with all of them. They are incredibly difficult to reuse if you like to have explicit method signatures. This is problem I have experienced many times on various projects. I will also pick on WS-*/SOAP a bit because they built this monster amount of XML protocol on top of HTTP to get around the limitations of HTTP. It makes for a mighty headache when you are trying to debug.
Now, REST’s goal is to simplify things and to use the HTTP protocol’s full spec to make it easier to express what is going on in your service. REST also shifts the model from a remote procedure call to changing the state of a domain object. When you are working with a RESTful web service, I find that it feels a lot more like working with a database record than calling a remote procedure. I think most developers agree that makes it a lot easier to program because you know what to expect. You get a thing from the DB, change it, and save your changes. This is much more intuitive than “You make a call to get a thing. Then you maybe have to change that thing or get some stuff out of it and assemble a bunch of parameters that may or may not be related to what you are doing, but are there because some other client needs them and then make a call”.
Now, you may have instances where you need to get the equivalent of the procedure call in your RESTful web service. For example, in the security module, we need a way to tell the system to generate a random password and email it to the user. What we came up with was to do a POST to /users/
I really like the programming model that JAX-RS gives you. We have been using the jersey implementation of JAX-RS 1.0 on our project. The API makes it dead simple to map your HTTP methods and URL patterns to java classes. It integrates easily with JAXB (our choice for Java to XML translation). You just put JAXB annotations on the objects you want to return or use xjc (which can be a bit of a pain) to generate java classes from your XSDs. All the major JAX-RS frameworks also have extensions that let you use JSON as the wire format for your JAXB objects instead of XML. The amount of code you have to write is very reasonable for a java framework.
Being that I am a total transaction management nerd, I do need to say one thing about the state of RESTful web services. At this time, the only transaction model you will get with REST (at least that is cross-platform friendly) is idempotency. This is something that most developers are not used to. They are used to either assuming a single data source, or, in the case of something like Remote Session Beans, JTA just handles all the magic for you and ties everything together with a nice pretty XA bow (unless you are the one configuring XA, which can be a difficult task).
I have a Grails application that we’re developing and we’re targeting JBoss 5.1 as the production server. Our CI tool (Atalassian Bamboo) produced a production WAR for me which I tried to deploy. Of course I got numerous exceptions and stack traces because I had a copy of servlet-api.jar and xercesImpl.jar already packaged inside my WAR which conflicted with JBoss’ server libs classpath. If you need to remove any artifacts from the Grails build (i.e. grails war), you can write a closure in the bottom of the conf/BuildConfig.groovy such as
//bottom of conf/BuildConfig.groovy
grails.war.resources = { stagingDir ->
File libDir = new File(stagingDir, 'WEB-INF/lib')
def deleteJars = { jarNameStart ->
libDir.eachFile { file ->
if (file.name.startsWith(jarNameStart)) {
file.delete()
println "deleted jar $file"
}
}
}
deleteJars 'servlet-api' // conflicts with jboss 5.1
deleteJars 'xercesImpl' // conflicts with jboss 5.1
}
You will now have a WAR without servlet-api.jar and xercesImpl.jar packaged in the WEB-INF/lib
Feel free to modify to fit your circumstance and environment.
I have been working with version 5 of Day Software’s CQ WCM platform since it was released. One of the great things about developing on version 5.x is the rich set of frameworks and API’s at your disposal (Sling, JCR, etc.).
Recently, a client handed me requirements to create a CQ component that would allow web users to browse documents and folders in specific locations in the repository. Specifically, the client wanted to be able to expand folders and click on links to documents in an interface similar to windows explorer (The filesystem browser they were familiar with). Basically, we needed to put repository content in a tree, and of course, this is a web based interface, and content authors should be able to place this component on any page. I knew there were likely to be existing services or API’s within CQ to help complete this task. Basically, I had a feeling the right way would be quick and easy and the wrong way would consume lots of hours.
While researching an appropriate design, I came across the JSON Query Servlet, which is exposed in CQ thanks to Sling. There is some real power and flexibility here, since you can easily expose repository content to any client that can consume JSON. Also, you can easily customize your result sets using familiar JCR query syntax.
With the content challenge solved, I turned to YUI’s treeview to provide the tree browsing user interface. One of the things that made YUI’s tree widget a good fit, is that you can set a dynamic load property. This means when a user expands a node, the browser will make an ajax call to fetch the children and render the child nodes appropriately, which would will reduce the initial page load time if folders contain large amounts of documents. Additionally, you can add your own css to make parent nodes appear as folders, and leaf nodes appear as styled links, etc.
All that was left to do at this point is tie everything together. Below is some code of what this might look like in a CQ component’s JSP. This is a simplified version I whipped up to remove the branding and styles from our client.
<%@include file="/libs/wcm/global.jsp"%>
<link type="text/css" rel="stylesheet" href="http://yui.yahooapis.com/2.8.0r4/build/treeview/assets/skins/sam/treeview.css">
<script src="http://yui.yahooapis.com/2.8.0r4/build/yahoo-dom-event/yahoo-dom-event.js" ></script>
<script src="http://yui.yahooapis.com/2.8.0r4/build/animation/animation-min.js" type="text/javascript"></script>
<script src="http://yui.yahooapis.com/2.8.0r4/build/treeview/treeview-min.js" ></script>
<script src="http://yui.yahooapis.com/2.8.0r4/build/yahoo/yahoo-min.js"></script>
<script src="http://yui.yahooapis.com/2.8.0r4/build/event/event-min.js"></script>
<script src="http://yui.yahooapis.com/2.8.0r4/build/connection/connection_core-min.js"></script>
<script src="http://yui.yahooapis.com/2.8.0r4/build/connection/connection-min.js"></script>
<script src="http://yui.yahooapis.com/2.8.0r4/build/json/json-min.js" ></script>
<script type="text/javascript">
function buildTree() {
var tree = new YAHOO.widget.TreeView(”tree”);
tree.setDynamicLoad(loadNodeData);
var root = tree.getRoot();
tree.render();
}
function loadNodeData(node, fnLoadComplete) {
var nodePath = encodeURI(node.data);
var sUrl = “/content.query.json?queryType=xpath&statement=/jcr:root” + nodePath + “/* order by @jcr:name”;
var callback = {
success: function(oResponse) {
var jsonObject = YAHOO.lang.JSON.parse(oResponse.responseText);
for (var i = 0; i < jsonObject.length; i++) {
var tempNode = new YAHOO.widget.TextNode(jsonObject[i].name, node, false);
var path = jsonObject[i]['jcr:path'];
tempNode.data = path;
var type = jsonObject[i]['jcr:primaryType'];
if ( type == ‘dam:Asset’ || type == ‘nt:file’) {
tempNode.href = path;
tempNode.isLeaf = true;
tempNode.target = “_blank”;
}
}
oResponse.argument.fnLoadComplete();
},
failure: function(oResponse) {
oResponse.argument.fnLoadComplete();
},
argument: {
“node”: node,
“fnLoadComplete”: fnLoadComplete
},
timeout: 10000
};
YAHOO.util.Connect.asyncRequest(’GET’, sUrl, callback);
}
YAHOO.util.Event.onDOMReady(buildTree);
</script>
<div class=”yui-skin-sam” id=”tree”>
<ul>
<li class=”expanded” yuiConfig=’{”data”:”<%=properties.get(”rootfolder”,”/content/dam/geometrixx”)%>”}’><%=properties.get(”rootfolderlabel”,”Content Browser”)%></li>
</ul>
</div>
There are a couple interesting things in the code I should point out.
var sUrl = "/content.query.json?queryType=xpath&statement=/jcr:root" + nodePath + "/* order by @jcr:name";
This is the line where we assemble the URL which we will GET to assemble the children of the node that was clicked. As you can see, we can refine the JCR query here to limit the results by node type, order by date, etc.
<li class="expanded" yuiConfig='{"data":"<%=properties.get("rootfolder","/content/dam/geometrixx")%>"}'><%=properties.get("rootfolderlabel","Content Browser")%></li>
This is code which can interact with a CQ authoring dialog to set the starting point in the repository for the root node. I have kept things simple here, and just pointed to Geometrixx’s folder in the DAM. Below is a screenshot of a stylized version of the component. Overall, I was very pleased with how easy it was to leverage existing CQ tools and YUI to create this custom component.

Wicket has been my framework of choice for the past year. There are many reasons for this, but one of the big ones is security. Wicket applications have built in protection against Cross Site Scripting (XSS) and SQL Injection attacks, numbers 1 and 2 respectively on the CWE/SANS top 25 most dangerous programming errors. A developer has to consciously enable this functionality for wicket applications to be susceptible.
Developers that assume input to their applications is well formed are at risk for an XSS attack.
An XSS attack involves typing custom javascript code into a search box. For example, entering the text
<script>alert("You are XSS Susceptible");></script>
into a search window and clicking the search button – in an unprotected website – would popup a browser dialog box saying “You are XSS Susceptible” 
A hacker could have a field day knowing that your application is interpreting javascript commands.
Wicket automagically protects against this by escaping all user input by default. So instead of executing the above code after clicking search, a wicket application will receive it as
<script>alert("You are XSS Susceptible");></script>
This effectively prevents XSS attacks.
SQL Injection attacks are number two on the CWE/SANS list. A SQL Injection attack is when a developer uses the application URL to pass database specific data. For example, suppose there is a PERSON database table, Every person has a unique identifier named ID. When a web application wants to request the web page for a particular person, the URL might look like this:
http://unsecure.website.com/getPerson?id=1
where the parameter id is the value from the database that we are querying. Behind the scenes, the SQL in the application might look like this:
SELECT * from PERSON where ID=request.getParameter("id")
which translates to
SELECT * from PERSON where ID=1
Without proper validation and exception handling, a malicious user could enter the following URL:
http://unsecure.website.com/getPerson?id=1&20;or&20;1=1
which would make an unsecure website execute the following SQL
SELECT * from PERSON where ID=1 or 1=1
You can see how this could be very dangerous as the where clause is now always true.
Wicket’s component based framework protects against this attack by allowing you to pass java objects between pages and encodes the parameters into the user’s session. This prevents URL encoding variable. A typical Wicket URL looks like this:
http://secure.wicket.website.com/?wicket:interface=:1:user:toProfile::ILinkListener::
Again, a developer can override this behavior and pass URL parameters, and there is a time and place for that, but by default, it’s nice to have the built in security.
Finally, since Wicket doesn’t use PHP File Inclusion (#14 on the CWE/SANS list), it gets that built-in security as a freebie!
There are two blog posts I have read over the past few weeks that I think give good summary of how to digest the whole “Oracle-buying-Sun-thing”. The first is from Rich Sharples of Redhat on his personal blog. The second is from Mark Little, also of Redhat.
The main take I want to emphasize is that Java is here to stay and is going to continue to be a great platform for building software. I also think that now is a better time than ever to take a look at JBoss, especially with Oracle choosing to cripple Glassfish by disallowing features like clustering, which JBoss supports out of the box.
Official disclaimer: CITYTECH is a JBoss Partner. With that said, I have been working with JBoss AS for 5 years now, starting with version 3.2.x. Having watch the product grow through the 4.x series and now with 5.1 bringing us JEE5 goodness and 6 reaching it’s first milestone in December, things are looking great. I am totally geeked out about JEE6 and the way that it builds on JEE5. I’ll talk more about that in an upcoming post on Seam.
JBoss also has a bunch of other technologies that are worth getting excited about, some of which I hope to have a couple of posts up on soon. Watch for me to cover Seam and GateIn, as I am building an application with them right now.
Last night, my wife and I were woken at 4AM by what we thought for sure were just high winds. But 20-30 mph winds don’t cause the house to creak and you to feel a small, but real sense of motion. Turns out there was an Earthquake last night in Northwestern Illinois, about 30 miles from where we live. Only a 3.8 on the Richter scale, but I still must say I’d never thought I would experience an earthquake in the Midwest. Wild.
Java mocking tools are notorious for their limitations. Ideally, one would not have to compromise design and code integrity for testability, but the reality is that the restrictions of popular testing frameworks such as jMock, Mockito, and EasyMock cause headaches for many developers. Does this look familiar?
private void methodToTest() {
// something meaningful!
}
public void exposeMethodToTest() {
methodToTest(); // i hate my life
}
When researching these frameworks for testing a recent Day CQ5 project, I discovered JMockit and got (relatively) excited about it’s ability to easily test things like final classes and private methods without modifying existing code. Rather than rehash the excellent documentation on their site, I’ll use a couple examples to demonstrate using JMockit to simulate the interactions between the CQ5, Sling, and JCR APIs.
@RunWith(JMockit.class)
public final class SampleTest extends JMockitTest {
@Test
public void sampleTest(@Mocked final SlingHttpServletRequest request)
throws RepositoryException {
new Expectations() {
Resource resource;
Node node;
{
request.getResource();
returns(resource);
resource.adaptTo(Node.class);
returns(node);
node.hasProperty("somePropertyName");
returns(false);
}
};
final Resource requestResource = request.getResource();
final Node resourceNode = requestResource.adaptTo(Node.class);
assertFalse(resourceNode.hasProperty("somePropertyName"));
}
}
Using JMockit’s Expectations API, it is quite simple to mock the object behaviors required to complete the test without unnecessarily creating full mock objects by implementing the Node or Resource interfaces. The basic pattern here is to record an expected method invocation (e.g. request.getResource()) and follow that with returns(), which specifies the expected return value for that invocation.
Let’s consider a more complex example — testing private methods of a final servlet class.
public final class FormServlet extends SlingAllMethodsServlet {
private static final Set PARAMETERS;
private static final Set REQUIRED_PARAM;
static {
PARAMETERS = new HashSet();
PARAMETERS.add(NodePropertyConstants.FIRST_NAME);
PARAMETERS.add(NodePropertyConstants.LAST_NAME);
PARAMETERS.add(NodePropertyConstants.EMAIL);
PARAMETERS.add(NodePropertyConstants.CONFIRM_EMAIL);
PARAMETERS.add(NodePropertyConstants.PHONE);
PARAMETERS.add(NodePropertyConstants.COMPANY);
REQUIRED_PARAM = new HashSet();
REQUIRED_PARAM.add(NodePropertyConstants.FIRST_NAME);
REQUIRED_PARAM.add(NodePropertyConstants.LAST_NAME);
REQUIRED_PARAM.add(NodePropertyConstants.EMAIL);
REQUIRED_PARAM.add(NodePropertyConstants.CONFIRM_EMAIL);
}
// omitted public methods ...
private Map populateValues(final SlingHttpServletRequest request,
final Map validationErrors) {
final Map values = new HashMap();
final ComponentRequest componentRequest = new ComponentRequest(request);
for (String parameterName : PARAMETERS) {
values.put(parameterName, getValidatedParameter(componentRequest,
parameterName, validationErrors));
}
return values;
}
private String getValidatedParameter(final ComponentRequest componentRequest,
final String parameterName, final Map validationErrors) {
final String value = componentRequest.getRequestParameter(parameterName);
// omitted validation code ...
return value;
}
}
Here is the corresponding test:
@RunWith(JMockit.class)
public final class TestFormServlet extends JMockitTest {
private FormServlet servlet;
@Before
public void setUp() {
servlet = new FormServlet();
}
@Mocked
ComponentRequest componentRequest;
@Test
public void testPopulateValues(@Mocked SlingHttpServletRequest request) {
final Map errors = new HashMap();
new NonStrictExpectations() {
{
componentRequest.getRequestParameter(anyString);
returns ("");
}
};
final Map values = Deencapsulation.invoke(servlet, "populateValues",
request, errors);
final Set parameters = Deencapsulation.getField(RSVPFormHandlerServlet.class,
"REQUIRED_PARAM");
final Set allParams = Deencapsulation.getField(RSVPFormHandlerServlet.class,
"PARAMETERS");
new Verifications() {
{
componentRequest.getRequestParameter(anyString);
times = allParams.size();
}
};
assertEquals(allParams.size(), values.size());
assertFalse(errors.isEmpty());
assertEquals(parameters.size(), errors.size());
}
}
We instantiate our servlet, then use the anyString field in the NonStrictExpectations class to denote that we expect a call to componentRequest.getRequestParameter() with ANY string parameter to return an empty string. The Deencapulation utility allows us to directly access private variables and invoke the private method to be tested. We then use the Verifications block to ensure that componentRequest.getRequestParameter() was called for each parameter, using the times field. Our test is completed with standard JUnit assertions to ensure that the “replay” phase of the test produced the expected results.
The examples above are simplistic, but they illustrate the power and flexibility of JMockit to adapt itself to YOUR code, rather than the other way around. Good tools like JMockit give developers the freedom to write high quality, uncompromised code that functions independently of it’s associated unit tests.
Not quite ready to abandon your favorite testing framework for JMockit? Have a look at this comparison matrix:
http://code.google.com/p/jmockit/wiki/MockingToolkitComparisonMatrix
If the above site is unavailable, consider this alternate representation:
Mock-Knocker in action.
Additionally, JMockit has provided a full set of sample test suites from other toolkits with corresponding JMockit versions (extremely helpful for migrating from EasyMock, Mockito, etc.):
http://jmockit.googlecode.com/svn/trunk/www/samples.html
I would encourage anyone writing Java unit tests to give JMockit a try — it takes very little effort to learn and incorporate it into an existing project, and you’ll soon be exercising coverage over previously “untestable” code.
Once you have an application that is running ‘Out of Browser’, network availability will most likely be your next concern. The good news is Silverlight 3 comes through and gives you a way to check if there is an actual network connection available. An interesting caveat here is that you are checking if a network connection is available, but aren’t checking to see if that network is connected to the internet. In order to check for an internet connection a WCF service can be developed that can ping a common website. Kunal Chowdhury’s Blog does a great job of explaining a possible way to do this.
Knowing whether or not an ‘Out of Browser’ Silverlight application has network access can be very powerful. Having this knowledge allows an application to decide whether or not to call out to its services tier. A common use of this would be for an application that saves data to a database through services. Instead of just putting up an error when network connectivity is lost, the application can save data to a local storage in xml or database form and wait for network connectivity to be restored. At that moment the application can then sync the data that it had stored locally through its service interface.
We are going to look at some simple code that would allow an application to be aware of network availability.
1. First we will add some xaml to a form that will act as an indicator of network connectivity. When there is a live network connection we will indicate it with a green circle and no connection with be indicated with a red circle.
1: <Grid x:Name="InternetConnectionGrid" Background="White" Width="175">
2: <Grid.ColumnDefinitions>
3: <ColumnDefinition Width="165"></ColumnDefinition>
4: <ColumnDefinition Width="10"></ColumnDefinition>
5: </Grid.ColumnDefinitions>
6:
7: <TextBlock Text="Current Internet Connection:" Grid.Column="0"></TextBlock>
8: <Ellipse x:Name="circleDisc" Grid.Column="1" Fill="Red" Width="10" Height="10"/>
9: <Ellipse x:Name="circleConn" Grid.Column="1" Fill="Green" Width="10" Height="10"/>
10: </Grid>
2. Snapshot of a live network connection.
3. Snapshot of a disconnected network connection.
4. Now on to the fun part! We need to add code to actually check the network availability. In the constructor we add two lines. The first line registers the NetworkAddressChanged event. This event fires anytime there is a change in network connectivity. If the IP Address changes because there is a move from ethernet connection to wireless connection this event will fire. If a network cord is unplugged this event will fire.
The second line in the constructor calls out to a method that we have developed that actually checks if there is a connection available. NetworkInterface.GetIsNetworkAvailable() returns true if there is a connection and false if there is not. Our method enables the red circle and if a network connection is found it toggles to the green circle.
Finally, inside the NetworkAddressChanged event we also call out to CheckNetworkConnection() to see if the change resulted in the loss or gain of network availability. This short amount of code allows our Silverlight application to be aware of a network connection while operating outside of the browser.
1: public MainPage()
2: {
3: InitializeComponent();
4:
5: NetworkChange.NetworkAddressChanged += NetworkAddressChanged;
6:
7: CheckInternetConnection();
8: }
9:
10: public void NetworkAddressChanged(object sender,EventArgs e)
11: {
12: CheckNetworkConnection();
13: }
14:
15: private void CheckInternetConnection()
16: {
17: circleDisc.Visibility = Visibility.Visible;
18: circleConn.Visibility = Visibility.Collapsed;
19:
20: if (NetworkInterface.GetIsNetworkAvailable())
21: {
22: circleDisc.Visibility = Visibility.Collapsed;
23: circleConn.Visibility = Visibility.Visible;
24: }
25: }
In some cases when running on a virtual machine, the application is not realizing that the network connection has been disabled and returns some false positives. I will be exploring what is causing this issue. Also be careful to check for other network connections that may be hidden in the operating system. A network connection does not have to be connected to the internet for Silverlight to consider it a valid network connection.