Spring log only to file

Logging is one of the most fuzzy area in Java. The standard JUL, java.util.logging, entered the arena late, and it has to compete against well respected libraries like Log4J2, SLF4J and Logback (usually SLF4J with Logback). The Spring guys decided to go for JCL, the Apache Commons Logging, that wraps SLF4J for the actual logging library of your choice, here being Logback.

If you don't have any special requirement, you can happily ignore which actual logger is used, just write your code for the JCL interface, leaving out of your scope any low level dependency.

However, if you want your log going to a file, and not to console, as often is the case, you have to deal with the actual logger. Not a big deal, if Logback is your choice.

Let's modify the function greeting in my GreetingController to log some (un)useful comments:
public String greeting() {
 log.trace("trace hello");
 log.debug("debug hello");
 log.info("info hello");
 log.warn("warn hello");
 log.error("error hello");
 log.fatal("fatal hello");
 return "Hello!";
}
Where log is private static final object of type org.apache.commons.logging.Log initialized through the JCL LogFactory.

This could be enough. Still you should have a mildly surprising output, something like:
2016-05-30 22:14:00.888  INFO (...)  : info hello
2016-05-30 22:14:00.888  WARN (...)  : warn hello
2016-05-30 22:14:00.888 ERROR (...)  : error hello
2016-05-30 22:14:00.888 ERROR (...)  : fatal hello
I edited out details in the middle of the lines, I want to focus on the fact that we miss trace and debug messages, and the fatal one became an error one. If you really want fatal log messages, logback is not your choice, since it does not have this log level, and so they are mapped as simple errors.

The first problem could be easily solved adding an entry in the Spring application.properties file (in source/main/resources). Say that I want to log all messages, from trace up to fatal, generated in my packages rooted in dd.manny. I'll add this line:
logging.level.dd.manny=trace
Good. Now I want Spring to log to a file. By default the file will have name spring.log, and I can decided in which folder to be placed like this:
logging.path=/tmp
Nice and easy. Just one thing. I wanted the log to go exclusively to file. To get this effect I have to configure the actual logger.

For this reason I added a logback configuration file in the src/main/resources folder that is mimic of the default Spring one, but it has no appender for console. The key point is that I keep the log level to INFO and I specify FILE as appender, that is going to be set through the property specified above.

The full Spring Boot project is on github. The relevant files are GreetingController.java, application.properties, and logback.xml.

Go to the full post

A simple RESTful Web Service

In the previous post, I have created a very simple WebApp using Spring Boot. Even if it works fine, it isn't much of a fun, giving no feedback whasoever to the user. Let's add a first basic web service to it.

In the Spring jargon, we want a REST Controller, so I create a new subpackage named controller below the one containing the application class, and in there I put a class, GreetingController, that is going to perform the mapping between the URI and the service, and return the expected resource.

The beauty of the Spring implementation is that I create a plain class, called a Bean, not to be confused with Java Bean nor Enterprise Java Bean, and I just annotate the class as @RestController and the method as @RequestMapping:
@RestController
public class GreetingController {
    @RequestMapping("/greeting")
    public String greeting() {
        return "Hello!";
    }
}
That's it. Springs takes care of all the boring details, and lets Tomcat answer generating a document that contains only "Hello" to a request address to the greeting address.

To test if this is working as expected, we can now start the project from the Boot Dashboard, and then accessing the resource from the internal browser, or from an external one. In any case the result should be something like this:
If you wonder why and how I'm using a non-standard Tomcat port, please refer to the previous post.

Sure you can run the application outside STS. Calling maven on the package target would let it generate a jar named something like hello-0.0.1-SNAPSHOT.jar in the target folder, than you can run it with the java -jar command.

Source code is on github. The only relevant change from the previous version is the GreetingController.

Go to the full post

Hello Spring Boot

Creating a web app with the Spring Framework using Boot is quite easy, assuming you have already installed Spring Tool Suite, the Pivotal IDE based on Eclipse.

Actually, it is just a matter of selecting on the menu File, the item New, and there Spring Starter Project. There you are presented with a bunch of names to give and selection to make, I'd suggest you to check start.spring.io for inspiration, since this STS wizard it is nothing more than a proxy to that web page, that would guide you to the creation of a Spring application.

I named my project helloSpring, and then I kept all the main default settings, like the Maven support, jar generation, Java 1.8 language usage, and I only added one single item in Dependencies: Web.

What it is going to happen is that my Spring project would generate a single huge jar embedding Tomcat and all the required dependencies to let the application work. After confirming, Maven could take some time to get all the required jars. However in the end I'll have a nice project ready to be compiled. Even if it is not to do anything sensible at all.

I'd suggest you to have a look at the generated pom.xml file. You won't be surprise to find out that it shows the information you entered in the wizard.

Then, accessing the Project Explorer, you'll see in the Spring Elements a bean HelloSpringApplication (the prefix is the project name, if you chose a different name for it, you'll see the change reflected here).

Let's have a better look a this bean. I asked to the wizard to put the generated classes in the dd.manny.hello package, so there I'm going to find it.

There is not much to see, apart from that the class has been decorated with the @SpringBootApplication annotation, it contains a main() method that calls SpringApplication.run() passing the class itself. Even without knowing anything about Spring Boot, looks intuitive what is going on here. On startup Spring would see that this is the booting class, and would use its main to call the SpringApplication run() method.

Now I'd like to run this application, even I can't expect to get much feedback from it. The easiest way to do it, it is from the Spring Boot Dashboard. You should see that view in the bottom left of your STS window. If for any reason it is missing, you can get it back from Window - Show View - Spring - Boot Dashboard.

In the Boot Dashboard you should see a collapsed list named local. Open it and you should find your project. My one is there, named helloSpring. Now I can use the menu on the Boot Dashboard view, or right-click menu if I am in the mood for it, to start or restart it.

What I usually I get it now is a fat exception. This is because I have something else running on the 8080 port on my machine and STS is trying to run the embedded Tomcat for my application right on that port. If you get
java.net.BindException: Address already in use
You are having the same problem.

Not a big issue, tough. There is a file in the source/main/resources/ folder named application.properties that, not surprisingly, let us to set properties used by our application. Initially it is empty, I added this line:
server.port = 8585
Meaning that I want my Tomcat to use a different port from the standard one.

Now I can restart my application, and get a smooth startup, as showed by the error-free log in the Console view.

The full code for the project is on github.

Go to the full post

JSP servlet init parameters

Creating init parameters for a servlet is easy, when we need to do that for a JSP page it is only a bit more trickier, and we should remember a couple of details.

We can't use annotations, since the translation from JSP to servlet is not in our control. So we have to fall back to the Deployment Descriptor (DD). So, let's go in our web app WEB-INF directory and modify (maybe create) the web.xml file.

In the web-app element we need to create two elements, a servlet and a servlet-mapping, and in the servlet one we could create any init-param we need, just like we can do for a plain servlet.

Here is an example for a servlet element, based on a JSP page named counting.jsp placed in the web app root directory:
<servlet>
  <servlet-name>Counting</servlet-name>
  <jsp-file>/counting.jsp</jsp-file>
  <init-param>
      <param-name>base</param-name>
      <param-value>42</param-value>
  </init-param>
</servlet>
Notice the jsp-file element, that replaces what in a plain servlet is a servlet-class.

Then we need a servlet-mapping element, that should look something like this one:
<servlet-mapping>
  <servlet-name>Counting</servlet-name>
  <url-pattern>/counting.jsp</url-pattern>
</servlet-mapping>

And that's it. Now we can access that init parameter from our Counting JSP page.

For instance, we could be interested in accessing it when the JSP is initialized. In this case, we would override the jspInit() method and get it through getServletConfig(). Like this:
<%!
public void jspInit() {
    log("Config init param: " + getServletConfig().getInitParameter("base"));
}
%>
If we want to access it from a scriplet, we use the config implicit object:
<%= config.getInitParameter("base") %>

Go to the full post

Square root by Newton's method

This well known method to calculate square roots by successive approximations is one of the first examples that Martin Odersky uses in its Scala by example booklet freely available online. You'll find it in section 4 of chapter 4.

The idea of this method is that we guess what could be the result, and then iteratively improve our guess, until we reach a good enough approximation.

It doesn't matter much which is our initial guess, we could simply default it to one, more interesting is deciding when we should stop to iterate. In some way it should be dependent on the input value itself. Here we are going to consider ourself happy when the difference between our guess squared and the input, divided by the input itself is less than one thousandth:
def isGoodEnough(guess: Double, x: Double) = math.abs(guess * guess - x) / x < 0.001
So, we are going to accept 8.003 as approximation for the 64 square root, but we'll reject 8.004. To improve our guess we'll apply this algorithm:
def improve(guess: Double, x: Double) = (guess + x / guess ) / 2
Now we are ready to write the requested function:
def sqrtIter(guess: Double, x: Double): Double =
  if (isGoodEnough(guess, x)) guess
  else sqrtIter(improve(guess, x), x)
If the guess is good enough, we are done. Otherwise iterate again with an improved guess. Likely we don't want the user having the nuisance of providing an initial guess:
def sqrt(x: Double) = sqrtIter(1.0, x)
We can compare the result to call to the Scala library function:
println(sqrt(2) - math.sqrt(2))
println(sqrt(4) - math.sqrt(4))
println(sqrt(1e-6) - math.sqrt(1e-6))
println(sqrt(1e60) - math.sqrt(1e60))
We can, and usually want to, hide the implementation details, making them local to our function. A side effect is that we don't need anymore to pass around the x value, being that visible to all the local functions, too.
def sqrt(x: Double) = {
  def isGoodEnough(guess: Double) = math.abs(guess * guess - x) / x < 0.001
  def improve(guess: Double) = (guess + x / guess ) / 2
  def sqrtIter(guess: Double): Double =
    if (isGoodEnough(guess)) guess
    else sqrtIter(improve(guess))
  
  sqrtIter(1.0, x)
}

Go to the full post

AND and OR as functions

Let's create a couple of Scala functions that would provide an alternative implementation for the AND and OR logical operators. The point of this exercise is seeing how the well known if-else conditional expression works in Scala, and seeing again the difference between by-value and by-name parameter evaluation strategy.

We want to define two functions, and() and or(), behaving like && and ||. Remember that they are so called short-circuit operators. We don't need to check the && second operand when the first is false. Similarly the for ||, when the first operand is true.

Let's express our requirements with assertions:
assert(and(false, false) == (false && false))
assert(and(false, true) == (false && true))
assert(and(true, false) == (true && false))
assert(and(true, true) == (true && true))

assert(or(false, false) == (false || false))
assert(or(false, true) == (false || true))
assert(or(true, false) == (true || false))
assert(or(true, true) == (true || true))
Here is how I have implemented the two functions:
def and(a: Boolean, b: => Boolean) = if(a) b else false
def or(a: Boolean, b: => Boolean) = if(a) a else b
AND is implemented checking the first parameter. If it is true I need to check the second one, otherwise the resulting value is false. Dually for OR, if the first parameter is true, that is the result, otherwise it depends on the second one.

Notice that in both function I have specified that the second parameter is subject to a by-name evaluation. This follows from the short-circuit property of the logical expressions. We can see how this is useful when the second parameter is expensive to evaluate. Or even an infinite loop, as here below:
def silly() : Boolean = silly

assert(and(false, silly) == (false && silly))
assert(or(true, silly) == (true || silly))
The short-circuit logic is implemented also from my functions, so no need of evaluating silly().

Obviously, if I pass silly() as first parameter to either and() or or(), I enter in an infinite loop, and I should kill my Scala application.

Go to the full post

By-value vs. by-name

A pure functional programming language typically uses a by-need evaluation strategy for the arguments of function calls. Scala is a multi-paradigm programming language that also supports the imperative, in an object-oriented way, paradigm. This rules-out by-need, but would let think that the by-name approach would be followed. Still, reasons of efficiency pushed Martin Odersky to chose a by-value approach by default, and leaving the by-name as an alternative.

A trivial example should help clarify the difference about the two approaches.

Let's consider a useless function that gets as parameters a couple of integers and always returns zero.
def zero(a: Int, b: => Int) = 0
Notice that the first parameter is passed to the function by-value, while the second, as specified by the arrow "=>" notation, is passed by-name.

Function zero() looks pretty harmless. However, we could have big troubles if we use it in conjunction with something like this:
def silly() : Int = silly
Function silly() just resolves in an infinitive loop, that would let our program running forever without giving the user any satisfaction.

If I pass silly() to zero() as its second parameter, I'll have no problem at all:
println(zero(42, silly))
Being passed by-name, and not being actually used in zero(), silly() won't be evaluated.

On the contrary, you want to avoid this:
println(zero(silly, 42)) // !!!
Here silly() is passed by-value, this means that Scala tries to calculate its value to pass it to zero(), even if it has no use at all for it. And this would let the user waiting forever for its feedback.

Go to the full post