FindBugs warning with Guava’s Predicate interface

When running FindBugs on some code I wrote, I received a  NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE warning:

In class com.wall.steve.HelperMethods$1
In method com.wall.steve.HelperMethods$1.apply(MyItem)
Parameter item
At[line 27]

This was the code I had written:

//com.wall.steve.HelperMethods class
public static final Predicate<MyItem> NON_REJECTED_ITEMS = new Predicate<MyItem>() {
    public boolean apply(final MyItem item)  //This is Line 27
        return !item.isRejected();

The issue was with my implementation of the apply() method.  Guava has the parameter of the apply method marked @Nullable.

//Guava 18.0 - Predicate class 
boolean apply(@Nullable T input);

FindBugs flagged my implementation since it does not allow for the item parameter to be null.  To fix this issue, I used the @Nonnull annotation (from the javax.annotation package):

//com.wall.steve.HelperMethods class
public static final Predicate<MyItem> NON_REJECTED_ITEMS = new Predicate<MyItem>() {
    public boolean apply(@Nonnull final MyItem item)  //Line 27
        return !item.isRejected();

This question on Stack Overflow was very similar and provides some more background in answering “why”.

Posted in Guava, Java | Tagged , | Leave a comment

My Presentation at the Twin Cities Java User Group

This week I gave a presentation titled “What’s New in Java 8” at the November meeting of the Twin Cities Java User Group (TCJUG).

Topics covered include:

  1. Interfaces – static and default methods
  2. Lambdas
  3. Functional Programming
  4. Streams API
  5. New java.time API
  6. Nashorn JavaScript Engine
  7. Other new classes and methods

The code I wrote during the presentation can be found on my GitHub site.

Posted in Java, Java 8 | Tagged , | Leave a comment

Java 8 Streams.max() and Streams.min() example

I have been playing around with the new Stream interface in Java 8 and struggled briefly with the max() and min() methods.  Here is some example code I wrote for how to use the method max() from the Stream class.  The min() method will be very similar.

First, I had a Person class which is just a POJO with two fields and getters/setters:

public class Person {
    String name;
    int age;

    //Constructors and Getters/Setters are omitted for brevity

Finally, here is my example using streams:

 public static void main(String[] args) {
     Person obama = new Person("Barack Obama", 53);
     Person bush2 = new Person("George Bush", 68);
     Person clinton = new Person("Bill Clinton", 68);
     Person bush1 = new Person("George HW Bush", 90);
     Person[] personArray = new Person[] {obama, bush2, clinton, bush1};
     List<Person> personList = Arrays.asList(personArray);

    //Find Oldest Person
    final Comparator<Person> comp = (p1, p2) -> p1.getAge(), p2.getAge());
    Person oldest =

    //Find Youngest Person
    //  -This time instead create the Comparator as the argument to the min() method
    Person youngest =
                                .min((p1, p2) ->, p2.getAge()))
Posted in Java, Java 8 | Tagged , | 3 Comments

Fix for Eclispe generated WAR file not including Ivy libraries

I was using Eclipse to create a relatively simple Dynamic Web Project that used Ivy for dependency mangement.  Also, I wanted to use Eclipse’s export to a WAR feature so I would not need to write a build script.  My WAR file was created, but after deploying my web app to Tomcat and starting I received this error:

SEVERE: Servlet /EntitySandboxWeb threw load() exception
java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet
at org.apache.catalina.loader.WebappClassLoader.loadClass(
at org.apache.catalina.loader.WebappClassLoader.loadClass(
at org.apache.catalina.core.DefaultInstanceManager.loadClass(
at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(
at org.apache.catalina.core.DefaultInstanceManager.newInstance(
at org.apache.catalina.core.StandardWrapper.loadServlet(
at org.apache.catalina.core.StandardWrapper.load(
at org.apache.catalina.core.StandardContext.loadOnStartup(
at org.apache.catalina.core.StandardContext.startInternal(
at org.apache.catalina.util.LifecycleBase.start(
at org.apache.catalina.core.ContainerBase$
at org.apache.catalina.core.ContainerBase$
at Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$ Source)
at Source)

I found this error confusing as I knew Ivy had pulled down the dependent libraries my project needed.  I decided to look at the generated WAR file and discovered those libraries were not in the WEB-INF/lib directory.

The solution was simple.

  1. Under Project Properties,  select “Deployment Assembly”.
  2. Click the “Add…” button
  3. On the first screen of the wizard, choose “Java Build Path Entries” and click “Next”.
  4. On the second screen of the wizard, select “Ivy” and click “Finish”.
  5. You can change the “Deploy Path” if necessary (the default is “WEB-INF/lib”).
  6. Export your project to a WAR file again and the Ivy libraries should be in the WEB-INF/lib directory now.


Posted in Eclipse, Tomcat | Tagged , | Leave a comment

How to mock lazy initialization of objects in C# unit tests using Moq

I was unable to find it clearly documented how to use Moq with objects that are to be lazy initialized, so below are the steps I took to do so.

Here is my class under test:

public class MyClass
  public Lazy<IWorkflowService> WorkflowService { get; set; }

  public Lazy<ISession> Session { get; set; }

  public string MyPublicMethod()
    var someValue = this.WorkflowService.Value.GetSomeValue(this.Session.Value.SessionId);

    //Do something with someValue...
    return someValue;

Notice that the GetSomeValue method requires the SessionId off of the Session object.

I now needed to write a unit test for MyPublicMethod().  The question I had was how to actually use Moq with the Session and WorkflowService instances.  Normally, I would just be able to do this in my test:

var mockSession = new Mock<ISession>();
var mockWorkfowService = new Mock<IWorkflowService>(); 

var myClass = new MyClass(); 
myClass.Session = mockSession.Object;
myClass.WorkflowService = mockWorkfowService.Object; 
//Method under test
var actual = myClass.MyPublicMethod();

But when I run the test, I received this error:

System.NullReferenceException: Object reference not set to an instance of an object.

The lazy initialization meant I needed to take another approach.  I read the MSDN Lazy Initialization  documentation and noticed there is a Lazy class constructor that allows you to specify a Func that should be used to return an instance of the object.  I decided to take advantage of this in my test case and return the mock instances that I had already created:

var mockSession = new Mock<ISession>();
var mockWorkfowService = new Mock<IWorkflowService>();

var myClass = new MyClass();

//Make use of the Lazy<T>(Func<T>()) constructor 
//to return the mock instances
myClass.Session = new Lazy<ISession>( () => mockSession.Object);
myClass.WorkflowService = 
    new Lazy<IWorkflowService>( () => mockWorkfowService.Object); 

//Method under test
var actual = myClass.MyPublicMethod();

Re-ran the test and it passed!


Posted in C#, Moq | Tagged , | 2 Comments

Eclipse Error: project facet java 1.7 is not supported by target runtime apache tomcat v6.0

We are upgrading some Java Projects from Java 6 to Java 7.  We use Eclipse yet still need to use Apache Tomcat 6.0.x.  After downloading and installing the a JDK 7 and changing all the necessary references in Project Preferences to Java 7 (e.g. Java Build Path, Java Compiler, etc.), I was still left with this error:

project facet java 1.7 is not supported by target runtime apache tomcat v6.0

Here is the fix:

  1. Window Menu -> Preferences
  2. On the left, select Server -> Runtime Environments
  3. Highlight “Apache Tomcat v6.0” and select the “Edit…” button
  4. On the “Edit Server Runtime Environment” dialog, change the JRE to be a Java 7 JDK or JRE.
  5. Rebuild your project and the error should go away.


Posted in Java, Tomcat | Tagged , , | 3 Comments

C# – Copying HTTP request parameters in call to RedirectToAction

I have been learning C# over the past year and today I encountered a situation with Controller.RedirectToAction() that I took awhile to find a solution to so I wanted to write down my solution.

In my case, I was in a method in a Controller (accessed from a HTTP GET) and needed to invoke RedirectToAction().  However, as part of the call to RedirectToAction() I needed to send along all the HTTP request parameters.

First of all, this is the method in the class FirstController that handled the initial GET request:

public ActionResult HandleRequest1() 
  // Create a dictionary containing the query string parameters
   var queryStringParams = this.Request.QueryString.AsRouteValueDictionary();
  // Pass the queryStringParams dictionary to RedirectToAction
   return this.RedirectToAction<SecondController>(x => x.HandleRequestTwo(), queryStringParams);

Second, this is the method in the class SecondController that was redirectedTo:

public ActionResult HandleRequestTwo() 
  string urlParamsStr = HttpContext.Request.Params.ToString();
  NameValueCollection queryParams = HttpUtility.ParseQueryString(urlParamsStr);
  string value1= queryParams["paramKey1"];
  return new View("SecondView");

In the end, it was creating a Dictionary that solved the problem.

Posted in C# | Tagged | Leave a comment