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) -> Integer.compare( p1.getAge(), p2.getAge());
    Person oldest = personList.stream()
                              .max(comp)
                              .get();

    //Find Youngest Person
    //  -This time instead create the Comparator as the argument to the min() method
    Person youngest = personList.stream()
                                .min((p1, p2) -> Integer.compare(p1.getAge(), p2.getAge()))
                                .get();
}
Posted in Java, Java 8 | Tagged , | Leave a comment

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(WebappClassLoader.java:1718)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1569)
at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:529)
at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:511)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:139)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1143)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5210)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5493)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown 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.

ProjectPropertiesDeployAssembly

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
{
  [Dependency]
  public Lazy<IWorkflowService> WorkflowService { get; set; }

  [Dependency]
  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 , | Leave a comment

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 Tomcat | Tagged , | Leave a comment

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:

[HttpGet]
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

Unit Test Stubs – Returning different values on consecutive calls

I have been learning C# these past few months.  The other day I had to write a unit test in C# that would return different results on consecutive calls from a mocked method where the inputs were the same.  With my Java background, I was familiar with how to do this with the Java mocking libraries such as JMock and Mockito.

For example, in JMock:

String someInput = "test input";
atLeast(1).of (myMockObject).myMethod(someInput);
  will(onConsecutiveCalls(  
  returnValue("one"),
  returnValue("two"),
  returnValue("three")));

And using Mockito:

String someInput = "test input";
when(myMockObject.myMethod(someInput ))
  .thenReturn("one", "two", "three");

But in C# using Moq, it is not nearly as concise.  A few different steps need to be taken.

  1. Create a variable to track the number of time the method has been invoked.
  2. Create an instance of a Func that will determine what to return each time it is invoked.
  3. In the call to Setup(), hand it the Func instance you just created and then also create a Callback to increment the counter created in step 1.

Here is an example:

var numCalls = 0;
Func<string> determineResponse = () =>
{
  if (numCalls == 0) {
    return "one";
  }  else {
    return "two;
  }
};
string someInput = "test input";
myMockObject.Setup(r => r.myMethod(someInput)).Returns(determineResponse).Callback(() => numCalls++);

Perhaps there is a simpler way in C# and Moq, but I have not found it.

Posted in C#, Moq | Tagged , | Leave a comment

Visual Studio 2010 – error: Unable to open the Web site

I was setting up Visual Studio 2010 to hook up with an existing .NET project that existed in source control.  When I tried to open the solution file in VS 2010, I received the following error (My .sln file exists in D:\data\AppName directory):

D:\data\Static\website : error  : Unable to open the Web site 'D:\data\AppName\website'.  The Web site 'D:\data\AppName\website' does not exist.

In this case, the “website” directory is a project with Javascript, CSS and images.  It is not a .NET project.

After searching and searching, I finally found a suggestion that I needed to delete the .suo file in the same directory as my solution file (.sln file), which I did  Then I re-opened the solution in VS 2010 and the path was resolved correctly to the Web site project.

The error was even more confusing as the path D:\data\Static\website is correct.  I still don’t know why VS 2010 was trying to find it in D:\data\AppName\website.  But deleting the .suo file worked and I am moving forward now!

Posted in Visual Studio | Tagged , | 1 Comment