CodeEval Find the highest score

Given the representation of a flattened table of scores where the rows represents artists and columns painting styles, give back a string containing the highest score for each style. This is a minimal description of the CodeEval problem #208, and here I am showing my Python 3 solution.

I converted the provides samples in test cases:
def test_provided_1(self):
    self.assertEqual('100 250 150', solution('72 64 150 | 100 18 33 | 13 250 -6'))

def test_provided_2(self):
    self.assertEqual('13 25 70 44', solution('10 25 -30 44 | 5 16 70 8 | 13 1 31 12'))

def test_provided_3(self):
    self.assertEqual('100 200 300 400 500', solution('100 6 300 20 10 | 5 200 6 9 500 | 1 10 3 400 143'))
Then I divided the problem in for steps.

1) Convert the input line in an integer table of scores, where each row represents an artist and each column a style.
2) Rearrange the table so that it can easily be scanned by style.
3) For each style, get its maximum value.
4) Convert the maximum collection in a string and return it.

Authors table

Let's use a list comprehension:
authors = [[int(score) for score in author.split()] for author in line.split('|')]
If your reaction is "what?!", here is the same thing unwinded:
authors = [] # 1
for author in line.split('|'): # 2
    row = [] # 3
    for score in author.split(): # 4
        row.append(int(score)) # 5
    authors.append(row) # 6
1) Create an empty list. This will be our resulting table.
2) Split the input line, using the pipe as separator, and loop on each resulting element.
3) Create an empty list, the current raw we'll fill with scores and push to the table.
4) Split the current section of the input line using the default blank character as separator, and loop on each element, a string that represents the current score.
5) Convert the current score to an integer and push it in the row.
6) Push the row in the authors table.

In a way or the other now we have our table of scores. Given the first test case, author is this list of lists:
[[72, 64, 150], [100, 18, 33], [13, 250, -6]]

Style table

The point of this step is simplify the next one. We could happly skip it, but it improves so much the resulting code readability that we don't really want to miss it.
Besides, here we have a way to put the handy * (star, asterisk, unpack) list operator and the zip built-in function at work.

We want to traspose our table, so that we have styles in the rows. Done in a jiffy
styles = zip(*authors)
The star operator unpacks the authors list, passing its rows, each of them by requirement is an equally sized list, to the zip function.
Zip packs back (for a formal description of its job, see the online Python documentation) the lists, putting in its first element all the first elements of the input lists, down to the last elements.

The result is that in styles we have something that could be seen in this way
[(72, 100, 13), (64, 18, 250), (150, 33, -6)]
(I avoid the details because here I just want to get the problem solved. Please, check about Python iterators and iterables to have more information on what is really going on here.)
Notice that rows are now represented by tuples and not as lists as in the original table. Not a problem, since we don't want to change them in any way.

Max for style

To perform this step I am going to use the built-in functions max(), that returns the largest value among the passed ones, and map(), works like zip, but applying a function to the input data. Putting them together I get:
result = map(max, styles)
If I print result for the first test case, I should get something like
[100, 250, 150]
That is almost the expected output, I only have to format it in the right way.

Let's say we don't want to transpose the table, as done in the previous step. Maybe we want to solve a more complex problem, where tables could be huge, and we don't want to pay the cost of that job. In that case we can fall back to less readable but more efficient code like this:
size = len(table[0]) # 1
result = [-1000 for score in range(size)] # 2
for row in table: # 3
    for i in range(size): # 4
        if row[i] > result[i]:
            result[i] = row[i]
1. By requirement, all rows have the same size.
2. Another requirement is that the lowest score is -1000, I shouldn't use it as a magic number, I know. However, I initialize result to have each element set to the lowest possible value.
3. Scan all the rows.
4. For each element in the row, compare it against the current result for that style, if bigger store it as candidate result.

It should be clear why we prefer the write the map-max version instead of this one, if we don't really have to.

Formatting the result

Usual stuff, convert the solution to a string of blank separated values. Here there is just a minor tweak:
return ' '.join(map(str, result))
I can't join directly on result, because it contains integers, not strings! So, I map result using the str() function that converts its input to string. Done.

Being CodeEval happy with my solution, I pushed test cases and python function source code to GitHub.

Go to the full post

Spring and Mockito

A modern web application written using Spring would use Dependency Injection to loose coupling among the components in the project. This is good, and help us to write more flexible code, as we have seen in a previous post. However this also mean that we need a way to test code that uses a component that is not actually there. Mock testing its here to help us. We'll see here how to use Mockito to achieve this result.

Say that my Spring Boot Application has a RestController named KnightController. It maps a request for the /quest resource to a call to the method doQuest() on the Knight resource owned by the controller.
@RestController
public class KnightController {
    @Resource
    private Knight knight;

    @RequestMapping("/quest")
    public String quest() {
        return knight.doQuest();
    }
}
Knight is just an interface that declares a single method, doQuest(). The beauty of this approach is that we can send any kind of knight in a quest, the only requirement being he implements this interface. For instance, here is a BraveKnight:
public class BraveKnight implements Knight {
    private Quest quest;

    public BraveKnight(Quest quest) {
        this.quest = quest;
    }

    @Override
    public String doQuest() {
        return quest.embark();
    }
}
This Knight owns a Quest, that is defined at runtime, by Constructor Injection, i.e., the actual quest this knight is going to embark is injected in the knight by use of the ctor. As for the Knight, also Quest is an interface with a single method, embark(). Again, in this way a knight is very flexible, having a way to change by injection which is the quest he would embark.

Even if there is more to say on this architecture, here we are interested in see how we can test if what we have now works as expected. Meaning, I would like to write a test case where I create a Quest, I inject it in a BraveKnight, and when I call his doQuest() method I see if the quest embark() method is called. We can't do that in the real world, since Quest is just an interface. But we can mock it, for instance using Mockito.

I need to add the mokito-core dependency in my pom file for the test scope
And then I can create a JUnit-Mockito test case in the test folder. I named it BraveKnightTest.
Its structure is straighforward, let's spend in any case a few words on the first and last line:
Quest quest = Mockito.mock(Quest.class); // 1
// ...
Mockito.verify(quest, Mockito.times(1)).embark(); // 2
1. Create an instance from a mock class that implements the Quest interface.
2. Verify that the method embark() defined on our mock Quest object has actually been called once, as expected.

I have written this post while reading the first chapter of Spring in Action, Fourth Edition by Craig Walls. While doing it, I have ported the original code to a Maven Spring Boot Web project on the STS IDE, using AspectJ annotations instead of the classic xml configuration.

Full source code is on github in the springInAction folder.

Go to the full post

CodeEval Clean up the words

Given a string containing 'dirty' characters, return its 'clean' version. See the CodeEval problem #205 for a full description. Basically, we want to return only lowercase alphabetic characters and a single blank to replace any number of non-alpha characters in between. I am working on this problem using Python 3 as implementation language.

I have converted the given examples in Python test cases, just adding a garbage-only line:
def test_provided_1(self):
    self.assertEqual('hello world', solution('(--9Hello----World...--)'))

def test_provided_2(self):
    self.assertEqual('can you', solution('Can 0$9 ---you~'))

def test_provided_3(self):
    self.assertEqual('what are you doing', solution('13What213are;11you-123+138doing7'))

def test_garbage(self):
    self.assertEqual('', solution('7/8§§?'))
Given my background, I came up firstly with a solution that looks like a code porting from an existing C-language function:
def solution(line):
    result = []
    alpha = False

    for c in line: # 1
        if c.isalpha():
            alpha = True
            result.append(c.lower())
        elif alpha: # 2
            result.append(' ')
            alpha = False

    if result:
        result.pop() # 3

    return ''.join(result) # 4
1. Loop on all the characters in the string. If the current one is an alpha, push its lowered representation to the result list, and raise the flag to signal that we have detected an alpha.
2. If the current character is not an alpha, and we have just pushed an alpha to the result, it is time to push a blank and reset the flag.
3. Actually, CodeEval is not that strict to require this. However, we can avoid to leave a blank at the end of the string popping it. But only if the list is not empty!
4. Finally, convert the list to a string by joining it elements on an empty string.

Still does not come to me naturally, eventually I came up with a more pythonic solution.
import re


def solution(line):
    return re.sub('[^a-zA-Z]+', ' ', line).lower().strip()
Remove the 'dirty' characters by regular expression substitutions, asking to select all sequences composed by one or more non-alpha characters, and pushing a single blank for each of them. Then make it lowercase, and strip all leading and trailing blanks.

Very elegant indeed. Notice that here I'm saying to Python what I want it to do for me, and not how to do it. This way of thinking leads to code that is much more readable and compact.

CodeEval looks happy about both solutions, so I pushed test cases and my python functions to GitHub.

Go to the full post

CodeEval Strings and Arrows

Find how many arrows, '>>-->' or '<--<<', are in a passed string. Beware of overlapping arrows!
This is CodeEval problem #202, and here I show you my Python 3 solution to it.

A few test cases to clarify the problem:
def test_provided_1(self):
    self.assertEqual(2, solution('<--<<--<<'))

def test_provided_2(self):
    self.assertEqual(4, solution('<<>>--><--<<--<<>>>--><'))

def test_provided_3(self):
    self.assertEqual(0, solution('<-->>'))

def test_empty(self):
    self.assertEqual(0, solution(''))

def test_overlapping_right(self):
    self.assertEqual(3, solution('>>-->>-->>-->'))
The idea to solve the problem is neat and simple, just scan the input string looking for the patterns. Here is my solution:
ARROWS = ['>>-->', '<--<<']
ARROW_SIZE = 5


def solution(line):
    result = 0
    for i in range(len(line)): # 1
        candidate = line[i:i + ARROW_SIZE] # 2
        if candidate in ARROWS: # 3
            result += 1
    return result
1. Worst case scenario, I am going to loop on all the characters in the passed string looking for the patterns. Notice that I am working on indeces, in the next note I explain why.
2. I put in candidate the slice of the input line based on the current index. This is the usual way we create a substring in Python.
3. If the candidate matches an arrow, I increase the result.

For our purposes, that is, passing the CodeEval tests, this code is good enough. However, while I was writing it, I felt a bit sad I couldn't skip the loop counter when I identify a matching. Besides, I didn't get any use of the hint about the possible overlapping of arrows. The fact is we simply can't mess with it in a Python for loop, whatever we do to it, it is going to be reset by the for loop control statement.

In this case it is not a big concern, the performance loss is minimal. Still, if the arrows where much longer strings, it could be worthy using a while loop instead, like this:
def solution(line):
    result = 0
    i = 0
    while i < len(line):
        candidate = line[i:i + ARROW_SIZE]
        if candidate in ARROWS:
            result += 1
            i += ARROW_SIZE - 1 # 1
        else:
            i += 1 # 2
    return result
1. In a while loop I have full control on the looping variable. Here I use this feature to jump over the substring, starting the next check on its last character, for what we said about overlapping above.
2. Otherwise, we just pass to the next position in the string.

Both versions works fine for CodeEval, with about the same performance. First one is more readable, so I'd say it should be the preferred one.
As usual, I have pushed test cases and both solutions to GitHub.

Go to the full post

CodeEval Stepwise Word

Write a function that, given in input a list of words, gives back the longest one, in a stepwise fashion. This is the 202 CodeEval problem. Here I am going to show my Python 3 solution.

Firstly, I have converted their example in unit tests. Having a look at them should be clear what they mean for "stepwise".
def test_provided_1(self):
    result = solution('cat dog hello')
    self.assertEqual('h *e **l ***l ****o', result)

def test_provided_2(self):
    result = solution('stop football play')
    self.assertEqual('f *o **o ***t ****b *****a ******l *******l', result)

def test_provided_3(self):
    result = solution('music is my life')
    self.assertEqual('m *u **s ***i ****c', result)
Then, I have divided the problem in two parts. Finding the longest word, and then converting a word in the weird format required.

The longest word could be found in linear time. It is just a matter of keeping track of the currently found solution, comparing its size against the other candidates until a better solution is found or we reach the end of the list:
def get_longest_word(line):
    words = line.split()
    selected = ''
    for word in words:
        if len(word) > len(selected):
            selected = word
    return selected
I get the "stepwise" format by concatenating a growing number of stars followed by the actual character for each step, and then pushing the result in a temporary list. Finally, I join the list on a blank to get the expected string:
result = []
for i in range(len(word)):
    result.append('*' * i + word[i])
return ' '.join(result)
I submitted successfully my solution to CodeEval, and then I have pushed to GitHub both the unit test and the python3 source file.

Go to the full post

A Python function

In the official Python tutorial as an example of function is showed a piece of code that calculate the Fibonacci series. Among the language features on display there, we can also see the handy way of assigning values to more variables in a single operation. Reading it, I though "Cool. But we don't really need two of them there".

So, just for the fun of it, I refactored the function to get rid of the extra variable.

Here is the original code, as you can find it on the python.org tutorial page:
def fib2(n):
    result = []
    a, b = 0, 1
    while a < n:
      result.append(a)
      a, b = b, a+b
    return result
You see the point. It is nice to initialize and modify a and b in the same line, since they are so strictly connected. However, just a single buffer integer is required, since we can refer to the list we are going to return. Well, at least if can assume that the user won't pass as parameter a value less than one.
def fibonacci(n):
    result = [0]
    candidate = 1
    while candidate < n:
        result.append(candidate)
        candidate += result[-2]
    return result
In comparison with the original function, my version loose the example of comma-assignment functionality. However I use the increase-assign (+=) operator and the negative index support on list. I would say it is a tie.

Go to the full post

CodeEval Fizz Buzz

Do you know the Fizz Buzz game? We take a couple of number, say 2 and 3, call the first one Fizz and the second Buzz. Then we say the numbers as they are in the natural series, uttering "Fizz!" instead of the first number (2 in my case) and all its mutiples, and Buzz for the second and multiples. If a number is a multiples of both of them I should say "FizzBuzz!".

The reason to talk about it here is that Fizz Buzz is the first Codeeval problem, and here I am going to present my Python 3 solution to it.

As usual, I started writing a few test cases. In this case I merely converted the two examples provided by CodeEval in Python Unit Tests:
class TestFizzBuzz(unittest.TestCase):

    def test_provided_1(self):
        result = solution('3 5 10 ')
        self.assertEqual('1 2 F 4 B F 7 8 F B ', result)

    def test_provided_2(self):
        result = solution('2 7 15 ')
        self.assertEqual('1 F 3 F 5 F B F 9 F 11 F 13 FB 15 ', result)
When Fizz is 3, Buzz is 5, and we want to go through the first 10 numbers, I should get what showed in the first test case.
A bit more interesting the second one, where 14, should generate a FizzBuzz result.

Being myself a C/C++ programmer at heart, I came out with a first solution in line with my background:
def solution(line): #1
    result = [] #2
    x, y, n = map(int, line.split()) #3
    for i in range(1, n + 1): # 4
        fb = False # 5
        if i % x == 0: # 6
            fb = True
            result.append('F')
        if i % y == 0:
            fb = True
            result.append('B')
        if not fb: # 7
            result.append(str(i))
        result.append(' ') # 8

    return ''.join(result) # 9
1. The parameter line is supposed to be a character string.
2. I would push each result in a list of strings, and in the end I will convert the list to a single string. This is done for efficiency reasons, being a Python string immutable.
3. Extract the values passed by the user. Notice that no error handling is done here, we boldly assumes we have three blank-separated meaningful numbers in it. For the rules of CodeEval this is our expected way of programming. Don't do that at work. Besides, notica also that I have used the Python built-in map function to convert the strings generated by split() to integers.
4. Loop on the natural series, starting from one up to n, as required by the caller. Since Python use the right-open interval concept, I had to increase n by one to get the expected behavior.
5. The problem has a tiny complication. We need to keep track if a number is either multiple of Fizz or Buzz. To achieve this result I use a boolean variable that I named fb.
6. If the current number is a Fizz (or a Buzz) push its letter to the result list.
7. If it is not a Fizz/Buzz push its actual value to the list. But be careful, we want it as a string, so we have to explicitely convert it to that type.
8. A single blank is added as separator.
9. Finally, we convert the list to a string, by joining it.

This code works fine. However anyone could see that it has been written by a C/C++ programmer. By the way, after writing it, I checked in the blog and I found out I had already written a post on this CodeEval problem, proposing a C++ solution. As you can see, the code looks like a transcription of the same concepts with minimal variations.

I decided to think to a more pythonesque solution, and I came out with this:
def solution(line):
    x, y, n = map(int, line.split())
    result = [
        (((i % x == 0) * 'F' + (i % y == 0) * 'B') or '%d' % i) + ' '
        for i in range(1, n + 1)
    ]
    return ' '.join(result)
Basically, is the same thing. However, I moved the for loop inside the list initialization, and I used the clever trick of multiplying a letter for a boolean, knowing that False means zero and True one. Then using the or operator to check if any Fizz/Buzz has been detected and, if not, pushing in the list the number, converted to string.

On GitHub you can find the full Python 3 source code for the unit test and the actual solutions.

Go to the full post

A more springy Hello World

I am going to modify my Spring Boot Hello World application to let it be a bit more springish. The first version was the bare minimum to check that the STS installation was working fine. The second one was a proper, even if minimal, Web Service. The third one added logging capabilities.

Ensured that all this basic stuff works properly, I can confidently move to something more interesting. Let's say hello using IoC (Inversion of Control) and DI (Dependency Injection).

I create a dedicate package for the logic related stuff for my hello project. Not surprisingly, I name it logic, and I put it under the hello package.
Actually, there's not much logic in this app, I just want to greet users. This suggests me to create an interface, Greeter, that exposes the a single greeting method.
The GreetingController changes accordingly. I remove the logic in it, delegating the work to the actual class that is going to implement the Greeter interface.
Notice how much more cleaner is this way of working. The controller doesn't know anymore about how a greeting is generated. It just knows that exists a Greeter interface, it holds a reference to it that is annotated as a Resource, a javax annotation, and through it, a greeting() method would be called to answer to the user request.

I create a couple of concrete classes implementing Greeter to give a sense to this architecture. There are about identical, in the real world things are usually more complicated. Here is the PlainGreeter, its brother MockGreeter is about the same.
Notice how the relation between the controller and the concrete Greeter is set. Before IoC it was commonly considered a controller task to define a dependency with the Greeter. In a way or another, an instance of the actual Greeter was created and used. Now IoC rules, so we perform an Inversion of Control. Is the Greeter that signal to be available for the controller, and the framework, Spring here, that take care of making it work.

I use annotation to implement the IoC relation, and you can see how in the code.
In the controller I have annotated its Greeter data member as Resource. This javax annotation tells Spring that Dependency Injection should be used here.
Each concrete class implementing the Greeter interface that could be a target for DI should be marked as Component, a springframework stereotype annotation.

Finally, we have to tell Spring which among the available Components should be injected in the controller Resource.

An handy way to do it is combining configuration and annotation. In the Spring configuration file I specify which profile is the active one
spring.profiles.active=prod
Then, I add a springframework context Profile annotation to each component, marking with the active profile only the one I want to be used. Be careful on it. Here is the exception that I get at startup if I mark both my components as "prod":
org.springframework.beans.factory.BeanCreationException:
 Error creating bean with name 'greetingController':
 Injection of resource dependencies failed; nested exception is 
org.springframework.beans.factory.NoUniqueBeanDefinitionException: 
 No qualifying bean of type 'dd.manny.hello.logic.Greeter' available:
 expected single matching bean but found 2:
 mockGreeter,plainGreeter

This Spring Boot project is on github. You could be mainly interested in these files:

Go to the full post

Logging in Spring

Spring has been designed to use the Apache Commons Logging, often called JCL from its previous name, Jakarta Commons Logging. It acts as a wrapper (more technically, bridge) hiding the actual log library used by the application. By default, Logback is assumed.

JCL provides six level of logging, from trace to fatal. To show how it works, I have modified the greeting method from my simple Web Service I am playing with:
private static final Log log = LogFactory.getLog(GreetingController.class);

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";
}
LogFactory is the apache.commons.logging class that acts as a factory to create a log object.

If I consume the service, I get something like this:
I see some logging in the console window generated by my app, with a couple of surprises. I miss trace and debug messages, and the fatal one is showed as a plain error.

The latter is a feature, not a bug. Since Logback has no fatal level, JCL maps a fatal request to the error level.
The first one is the default behaviour common to many loggers. If I don't specify which level of logging I want to display, only messages from info level onward are shown.
Here I want to see the full logging, so I add this line to the Spring application.properties file:
logging.level.dd.manny=trace
I restart my Spring application, consume the service, and I get the expected changes in the log.

Log to file

By default, when I ask Spring to log to file, it sends the messages to a file named spring.log, it is usually a good idea to keep this name, however it make sense to place this file in a specific folder. To do that, I add this line to the Spring properties file:
logging.path=/tmp
Last thing. I want to log _only_ to file. To do that I have to mess a bit with the actual logger (once again, in this case Logbackis assumed) configuration file. I am simply using the default one provided by Spring, specifying FILE as appender in the root element:
<root level="INFO">
 <appender-ref ref="FILE" />
</root>
Only the Spring banner is printed to standard output, the log goes straight to file.

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

Go to the full post

Packaging Spring to a jar or war

This is going to be a boring post, the flip side is that is short. I am working with Spring STS and Maven, I have already written a simple Hello World web service for Spring using Boot, and letting it use the default built-in Tomcat application server.

Let's spend some words on how to actually create the fat jar that could be run from the shell, automagically running the embedded Tomcat and the web services in it, and then how to generate instead a plain old war that could be deployed in a stand alone Tomcat.

Fat jar

The first alternative could be achieved in a click, run the Maven install goal for the project. I can either run it from the project root or, as showed below, from its pom.xml element.

The first time I ran it, I saw an annoying warning message in the log:
[WARNING] The requested profile "pom.xml" 
 could not be activated because it does not exist.
To get rid of it, I removed a spurious Maven profile from the project properties

Warning or not, Maven does its job, and I see a jar generated in the target folder, that I can run from the command line. Something like this:
...\helloSpring\target>java -jar hello-0.0.1-SNAPSHOT.jar
Nice.

Classic war
If I want to get a plain old war to be deployed on an already existing application server, a few changes are required.

Java code changes

My HelloSpringApplication class should extend SpringBootServletInitializer and should override the configure method. Pay attention to the super class package, the old one, in the context.web package is now deprecated for the new web.support one.
package dd.manny.hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;

@SpringBootApplication
public class HelloSpringApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(HelloSpringApplication.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(HelloSpringApplication.class);
    }
}

Configuration changes

In the POM file, the packaging element under project is now set to war, and not anymore as jar:
<packaging>war</packaging>
Then, a new dependency should be added:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>
And the spring-boot-maven-plugin plugin removed.

After these changes, when I run pom.xml as Maven install, I generate a war, slimmer than the original jar, that now I can deploy to my Tomcat server.

Go to the full post

A RESTful Web Service saying hello

Here I am completing the example started in the previous post, aimed at writing a simple Spring application using STS. I have ensured the app framework is working fine, now I write a very simple REST Controller.

I have already pushed the code on GitHub, however the job is so easy I don't mind to redo it from scratch. So, I create a Java class named GreetingController in the package controller under my already existing hello package
I annotate it as RestController and I provide it with a public method that returns a String, annotated as RequestMapping:
@RestController
public class GreetingController {
    @RequestMapping("/greeting")
    public String greeting() {
        return "Hello";
    }
}
And that's it!

Let's see it in action. I go to the Boot Dashboard, and I start my helloSpring application.
Whoopsie daisy, I forgot to set the port of my Tomcat server to something different from the default 8080, that is already taken on this box. The result is a long scroll of complaints in the Console window, starting with an exception dump:
java.net.BindException: Address already in use: bind
Ending with an error description (The Tomcat connector configured to listen on port 8080 failed to start. The port may already be in use or the connector may be misconfigured.) and the action (Verify the connector's configuration, identify and stop any process that's listening on port 8080, or configure this application to listen on another port.) we should take to solve it.
There is a number of ways you could follow to solve this issue. Here I set the server port in the Spring application properties file, defined in the src/main/resources folder
When I restart Tomcat, I see I have a clean log
And now I can check on a browser how it works
Good!

Go to the full post

Hello Spring Boot

I have installed Spring STS on a Windows box, and to check that everything is OK, I am writing the usual Hello World program. I have already did it for a previous version and stored the source code on GitHub.

However, it is more fun to do it again from scratch.

From the menu File, I select the wizard to create a New Spring Starter Project.

Then I fill the required fields to specify the project name and a few extra information. I am going to keep much of the proposed default values.
Next page, I keep the default Spring Boot Version, currently 1.4.3, and I add just one extra dependency, Web.
Clicking on Next, we can check what the wizard is doing for us, using the Spring Initializr web site passing the expected parameters. Otherwise, we can simply Finish, and let STS do the work for us.

A few seconds later, I have my new shiny helloSpring project. I open the project POM (remember that I accepted the default project type, Maven), and I am not surprised to see it reflects the selections I have chosen by the wizard.
In the Spring Elements sections, there is a new bean, whose name is based on the name I gave to the project, in this case HelloSpringApplication. Let's have a look at its source code.
The class is in the dd.manny.hello package, as I asked in the wizard, and has been annotated as @SpringBootApplication. It contains a main() method that calls SpringApplication.run() passing as parameters the class itself and the args passed to the application. We expect that on startup Spring sees this is the booting class, and uses its main to call the SpringApplication run() method.

To run my hello application, I now go to the Spring Boot Dashboard. By default, you should find this view on the bottom left in your STS window. If missing, you could get it back from Window - Show View
In the Boot Dashboard Local list I see my application, I select it, and now I can start the associated process. In the console window I can see the resulting logging.
Among the messages, I see a couple of them issued from my class, dd.manny.hello.HelloSpringApplication:
Starting HelloSpringApplication on a555 with PID 8552 
Started HelloSpringApplication in 1.348 seconds (JVM running for 1.995)
Good. The application worked fine.

Go to the full post