tag:blogger.com,1999:blog-16459207812514187072024-03-19T13:31:14.970+01:00Biting Code<i>tutorial-like examples and some informal chatting on Java, JavaScript, other programming languages, and more.</i>Mannyhttp://www.blogger.com/profile/07393063644320426727noreply@blogger.comBlogger188125tag:blogger.com,1999:blog-1645920781251418707.post-41214573657569441712016-12-20T20:07:00.002+01:002016-12-20T20:23:50.590+01:00Knapsack without repetitionSimilarly to the <a href="http://bitingcode.blogspot.com/2016/12/knapsack-with-repetitions.html">previous problem</a>, we have a knapsack with a specified capacity, a number of items with different weight and value, and we want to select a subset of them that would fit in the knapsack maximizing its value. The difference is that now we are not allowed to put in the knapsack copies of the same item. For this reason this problem is also known as 0/1 knapsack.<br />
<span class="fullpost"><br />
If we keep a dynamic programming approach, the solution won't be too different to the previous one, however we'll need to store the results for all subproblems in a bidimensional array and the process of generating a new subsolution is going to be a bit more complex.<br />
<br />
The idea is that we have a row for each family of subproblems having up to the actual number of items we can choose from.<br />
<br />
Zeroth row is there just to simplify the algorithm, being quite obvious that a knapsack containing zero or one element chosen from no item is going to always have a weight of zero.<br />
<br />
First row is only marginally more interesting. We check the first item, as soon as its weight matches the capacity of a (sub)knapsack, we assign its value to that subsolution, an then al the other subsolutions on its right would have the same value, since we have no other items available.<br />
<br />
It is from second row that we have a more clear view on the problem complexity, since for a generic position in it we have to ensure the capacity of the current knapsack in the subproblem would be optimally filled by the available items.<br />
<br />
Let's see a test case to help us to figure out how to work it out.<br />
<pre class="brush: java">public void testWithouRepetition() {
int[] weights = new int[] { 2, 3, 4, 6 };
int[] values = new int[] { 9, 14, 16, 30 };
assertThat(Knapsack.withoutRepetition(values, weights, 10), is(46));
}
</pre>The table with all the subsolutions for our problem would be:<br />
<pre>[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[ 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9]
[ 0, 0, 9, 14, 14, 23, 23, 23, 23, 23, 23]
[ 0, 0, 9, 14, 16, 23, 25, 30, 30, 39, 39]
[ 0, 0, 9, 14, 16, 23, 30, 30, 39, 44, 46]
</pre>Notice that, zeroth column is an all-zero because whichever is the number of items available, having zero as capacity of the current sub-knapsack will lead to a no-item-selected solution. First column is again filled with zeroes, but for a different reason, there is no item with a weight 1.<br />
In the first row we use only the first item available, the one with weight 2 and value 9. From the second cell on, we can put its value in it.<br />
In the second row, we can put only {2, 9} in cell (2, 2). Next to the right, (2, 3), we could put {2, 9} or {3, 14}. The latter wins. Since (2, 5) on, we can put both items, so the value stored in these cells is 23.<br />
And so on.<br />
<br />
Here is how I have modified the algorithm seen in the previous post to adapt it to this slightly different problem:<br />
<pre class="brush: java">public static int withoutRepetition(int[] values, int[] weights, int weight) {
assert (values.length == weights.length); // 1
int[][] results = new int[values.length + 1][weight + 1]; // 2
for(int i = 1; i < results.length; ++i) { // 3
for(int j = 1; j < results[i].length; ++j) { // 4
results[i][j] = results[i - 1][j]; // 5
if(weights[i - 1] > j) // 6
continue;
int candidate = results[i - 1][j - weights[i - 1]] + values[i - 1]; // 7
if(candidate > results[i][j])
results[i][j] = candidate;
}
}
return results[values.length][weight];
}
</pre>1. A minimal checking to ensure no funny stuff in input. For each value should be available the correlated weight.<br />
2. Core of the dynamic programming algorithm. A table that is going to contain all the subsolutions is created. The following double for loop will fill it up and in the bottom right cell we'll find the solution.<br />
3. Row 0 is not affected, since we know that it has to contain just a bunch of zeroes.<br />
4. Column 0, for each row, is not affected since, again, we just want a zero in it.<br />
5. The current element is initialized with the value contained in the cell in row above, same column.<br />
6. If the weight of the item associated with the current row is bigger than the capacity for the current subsolution, there is not much to do, just skip to the next iteration.<br />
7. Otherwise, let's check if considering the new element in the knapsack will bring to a better solution. We make room for it in the knapsack, considering the best solution in the row above that has enough room for it, and add its value.<br />
<br />
On GitHub you will see that my <a href="https://github.com/egalli64/bitingcode/blob/master/fun/Knapsack.java">Java class Knapsack</a> now has also the method to calculate the "without repetition" variation of the problem. And a test case for it has been added to the associated <a href="https://github.com/egalli64/bitingcode/blob/master/fun/KnapsackTest.java">JUnit class</a>.<br />
</span>Mannyhttp://www.blogger.com/profile/07393063644320426727noreply@blogger.com0tag:blogger.com,1999:blog-1645920781251418707.post-51564962035965943732016-12-12T14:56:00.004+01:002016-12-12T15:13:16.718+01:00Knapsack with repetitionsWe are given a set of items, each of them having a weight and a value, and a knapsack with a specified capacity. Each item is available in as many elements as we like. We want to fill the knapsack in a way that it contains the higher possible value.<br />
<span class="fullpost"><br />
A JUnit test case should help to clarify the problem:<br />
<pre class="brush: java">public void testWithRepetition() {
int[] weights = new int[] { 2, 3, 4, 6 };
int[] values = new int[] { 9, 14, 16, 30 };
assertThat(Knapsack.withRepetition(values, weights, 10), is(48));
}
</pre>We have for different items. The lighter one has weight 2 and value 9, the heavier 6 and 30. We want to write a static method withRepetition() in the class Knapsack that, given in input values, weight and knapsack capacity (here is 10) it would give back the maximum value storable in that knapsack.<br />
<br />
In our case the expected result is 48, coming from weights 6 + 2 + 2, being the value of this triad 30 + 9 + 9.<br />
<br />
Here is my Dynamic Programming solution, based on the algorithm discussed in chapter 6 of the excellent book Algorithms by S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani, using Java as implementation language:<br />
<pre class="brush: java">public static int withRepetition(int[] values, int[] weights, int weight) {
assert(values.length == weights.length);
int[] results = new int[weight + 1]; // 1
for(int i = 1; i < results.length; ++i) { // 2
for(int j = 0; j < weights.length; ++j) { // 3
if(weights[j] > i) // 4
continue;
int candidate = results[i - weights[j]] + values[j]; // 5
if(candidate > results[i])
results[i] = candidate;
}
}
return results[results.length - 1]; // 6
}
</pre>1. Here I am going to store all the results of the subproblems and, in the last element, the one to the actual problem. Notice that we need an element also for the trivial case, knapsack of size zero, that has the obvious solution of zero.<br />
2. Looping on all the DP subproblems, from the first one, where the capacity is one, to calculate at last the actual problem.<br />
3. For each subproblem I verify which is among all the items available the one that maximize the result.<br />
4. If the current item has a weight bigger than the knapsack capacity, there is nothing to do.<br />
5. Check what happens using the previous solution that allows to use the current item, storing the candidate result in a temporary variable. If it is a better result, store it in the array of subresults.<br />
6. In the last element of the array we have the required value.<br />
<br />
The only test case that I tried, is the one provided by the book that you have already seen above. Anyway, you could <a href="https://github.com/egalli64/bitingcode/blob/master/fun/KnapsackTest.java">find it on GitHub</a>, side by side the source Java code for the <a href="https://github.com/egalli64/bitingcode/blob/master/fun/Knapsack.java">class Knapsack</a>.<br />
</span>Mannyhttp://www.blogger.com/profile/07393063644320426727noreply@blogger.com0tag:blogger.com,1999:blog-1645920781251418707.post-21020913379646873172016-12-09T21:36:00.000+01:002016-12-09T21:52:04.583+01:00Levenshtein distanceGiven two strings, return its Levenshtein distance, i.e. the minimum number of character changes needed to mutate the first string in the second one.<br />
<br />
You can have a look at this <a href="http://www.let.rug.nl/kleiweg/lev/">Levenshtein demo</a> to get a better idea of what is expected. Notice that the demo is more complicated than the required solution. We are interested only in the "plain" string type, and we always use weight 1 for indel (insertion/deletion) and substitution operations. Moreover, we don't consider swap.<br />
<span class="fullpost"><br />
The Levenshtein distance is often used to show how Dynamic Programming works in a more complicated case than the classic <a href="http://bitingcode.blogspot.com/2016/12/minimum-number-of-coins-to-make-change.html">make change</a> problem. Here I present my Java solution based on the Wagner–Fischer algorithm, that asks us to build a bidimensional table generating its values starting from the most basic cases up to the required solution.<br />
<br />
The idea of the algorithm is to put on one table axis the first string and the second one on the other one, paying attention to give an extra position at the beginning of both string. So, for instance, if we want to calculate the distance between "one" and "bone", we'll 4 rows and 5 columns (or the other way round).<br />
<br />
Then we have to populate the tables. The top-left cell is the easiest one, it represent the case I want to pass from an empty string to another empty one. No change is needed, so I put there a zero.<br />
<br />
To understand what I should put in the first row I can think to the case I want to calculate the distance from an empty string to another one size n. Obviously, I would increase by one the value in each cell, representing the cost of inserting a new character.<br />
<br />
Similarly, the first column will follow the same structure. Here the increment would represent the deletion of a character.<br />
<br />
The generic case is a bit more complicated, since we have to evaluate four different cases. Let's think to the cell (1,1). To decide which value assign to it we need to compare the first elements of both string. If it is the same, we don't have to increase the distance, we just keep the value calculate for the top left case, namely cell (0,0). Otherwise, we need to consider all the three possible editing that would let us arrive there, inserting a new character, deleting or substituting the existing one. Since we want to find the minimum distance, we'll choose the smallest among these values.<br />
<br />
Remembering how we filled the first row and column, we should see how to get the value for inserting and deleting, it is just a matter of increasing the value contained on the cell on the left and on the top, respectively. For substitution we have to refer to the top-left cell, as we have done for the equality case.<br />
<br />
Once we have grasped the sense of it, building the table is a piece of cake, and what we have to do is just returning the value in the bottom-right cell.<br />
<br />
For testing purpose, and for let me better understand how things work, instead of implementing the solution with a single static method, I used a class with a constructor, that does all the dirty job, and a couple of public methods, one that returns the calculated Levenshtein distance and another one that checks the table as generated by the constructor. You could see the full <a href="https://github.com/egalli64/bitingcode">Java code on GitHub</a>, both for the <a href="https://github.com/egalli64/bitingcode/blob/master/fun/Levenshtein.java">Levenshtein class</a> and its associated <a href="https://github.com/egalli64/bitingcode/blob/master/fun/LevenshteinTest.java">test cases</a>, here I publish and comment only the ctor:<br />
<pre class="brush: java">private int[][] matrix; // 1
public Levenshtein(String from, String to) { // 2
matrix = new int[from.length() + 1][to.length() + 1]; // 3
for (int i = 1; i < matrix[0].length; ++i) { // 4
matrix[0][i] = i;
}
for (int j = 1; j < matrix.length; ++j) {
matrix[j][0] = j;
}
for (int i = 0; i < from.length(); i++) { // 5
for (int j = 0; j < to.length(); j++) {
if (from.charAt(i) == to.charAt(j)) { // 6
matrix[i + 1][j + 1] = matrix[i][j];
} else { // 7
int insert = matrix[i][j + 1] + 1;
int delete = matrix[i + 1][j] + 1;
int substitute = matrix[i][j] + 1;
matrix[i + 1][j + 1] = Math.min(Math.min(insert, delete), substitute);
}
}
}
}
</pre>1. Here is where I am going to store all the partial solutions and the actual one.<br />
2. I think the first string associated to the rows in matrix, the second one to the columns.<br />
3. The matrix has one row plus one for each character in the first string and a column plus one for each character in the second one.<br />
4. Initialize the zeroth row and column as discussed above. No need to initialize matrix[0][0], the default value 0 is exactly what we want.<br />
5. Loop on all the characters in both strings.<br />
6. It's a match! Put in the relative cell in the matrix the same value stored in the top left cell.<br />
7. Otherwise calculate how much is going to cost to put there the right value by insertion, deletion, substitution, and put there the minimum value among these three ones.<br />
<br />
Once built the matrix, the solution appears on the bottom right cell in the matrix.</span>Mannyhttp://www.blogger.com/profile/07393063644320426727noreply@blogger.com0tag:blogger.com,1999:blog-1645920781251418707.post-64808418346134980092016-12-05T22:48:00.001+01:002016-12-05T23:09:15.509+01:00Minimum number of coins to make changeWe should give a certain amount back, and we want minimize the number of coins involved in the operation, accordingly to the available denominations. So, for instance, we have only copper Euro cents (1, 2, 5) and the change should be 4. In this case the expect result is 2, a couple of 2c coins.<br />
<span class="fullpost"><br />
We could think to use a greedy procedure, and sometimes it works beautifully, as in example I showed above. However it does not work for all possible denominations. As a counterexample think what happens if we have to generate 40 from (1, 5, 10, 20, 25). The greedy solution is 3, 25c + 10c + 5c, while the optimal solution is 2, 20c + 20c.<br />
<br />
Actually, this problem is commonly used to introduce dynamic programming, where the idea is solving all the subproblems originating from the required one, starting from the simplest ones, and using those partial solutions to build up the more complex ones.<br />
<br />
Here is a possible Java solution:<br />
<pre class="brush: java">public static int minNumCoins(int amount, List<Integer> coins) {
assert (amount >= 0); // 1
assert (isConsistent(coins)); // 2
List<Integer> results = new ArrayList<>(amount + 1); // 3
results.add(0); // 4
for(int i = 1; i <= amount; ++i) { // 5
results.add(Integer.MAX_VALUE); // 6
for(int coin : coins) { // 7
if(coin > i)
break;
int tentative = results.get(i - coin) + 1; // 8
if(tentative < results.get(i)) {
results.set(i, tentative);
}
}
}
return results.get(results.size() - 1); // 9
}
</pre>1. I assert that the required amount should be not negative.<br />
2. I have delegate to an helper method the consistency check on the coin list. I assume the requisite are that it should not be empty, it has to start from 1, and to be sorted.<br />
3. I'm going to store in this array-list the results for the subproblems and the problem itself. When a step would required a previously calculated subsolution, it would get the result from this list. This technique is known as memoization.<br />
4. Base case. An amount of zero requires no coin.<br />
5. Let's calculate all the subproblems before generating the result for the actual one.<br />
6. Initialize the current solution to the worst possible value.<br />
7. Check it against all available coins, assuming the list being sorted, see (2), we can stop looping as soon as we see a coin greater than the index of current element in the list.<br />
8. A tentative solution is the number of tentatives for the previous intermediate step plus one. If this try is better than the current tentative solution, let's use it as candidate.<br />
9. Now we just have to return the last item in the result array-list.<br />
<br />
Full Java code is on github. There you will find, beside the code you have already seen above, in the same <a href="https://github.com/egalli64/bitingcode/blob/master/fun/CoinChanger.java">class CoinChanger</a> also a greedy implementation, that is going to fail in some cases. Also a JUnit suite of <a href="https://github.com/egalli64/bitingcode/blob/master/fun/CoinChangerTest.java">test cases</a> is there.<br />
</span>Mannyhttp://www.blogger.com/profile/07393063644320426727noreply@blogger.com0tag:blogger.com,1999:blog-1645920781251418707.post-74718196755943463882016-11-03T18:12:00.002+01:002016-11-03T18:34:03.896+01:00Greatest Common DivisorGiven two integers, find their greatest common divisor.<br />
<span class="fullpost"><br />
If you don't know the Euclid algorithm, you should get to a piece of code like this:<br />
<pre class="brush: java">static public int naive(int a, int b) {
int result = 1;
for (int i = 2; i <= Math.min(a, b); ++i) {
if (a % i == 0 && b % i == 0) {
result = i;
}
}
return result;
}
</pre>This raw idea could be improved considering that it doesn't make any sense to check numbers bigger than the square root of the smaller one (beside itself), as well as the multiple of the already discarded numbers - if 2 is not a good candidate, there is no use in checking any even number.<br />
<br />
However, Euclid devised such an elegant and fast converging algorithm that you should have a really good reason to explore alternatives.<br />
<br />
Knowing that the gcd of a and b is the same as the gcd of a and a % b, we can write:<br />
<pre class="brush: java">public static int euclid(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}</pre><br />
To ensure I didn't make any silly mistake when writing my <a href="https://github.com/egalli64/bitingcode/blob/master/fun/GreatestCommonDivisor.java">Java code</a>, I have written a couple of simple JUnit <a href="https://github.com/egalli64/bitingcode/blob/master/fun/GreatestCommonDivisorTest.java">test cases</a>. Both files are now on GitHub.<br />
</span>Mannyhttp://www.blogger.com/profile/07393063644320426727noreply@blogger.com0tag:blogger.com,1999:blog-1645920781251418707.post-38925533689614557272016-10-30T12:36:00.000+01:002016-11-03T17:48:57.699+01:00Last digit of a Fibonacci numberThe Fibonacci sequence leads rapidly to such huge values that it gets difficult even to think to a monster like Fibonacci of one million. However, let's say that we have a less mind-boggling problem, calculating just the last digit of it, even if for large input, like one hundred million. This is not a big issue, in the worst case it is to spot a linear time complexity solution, and if we check closely the properties of the sequence, we could devise a costant time one.<br />
<span class="fullpost"><br />
Firstly, I write a few test case. I am using JUnit 4, and the assertThat Hamcrest-style assertion:<br />
<pre class="brush: java">public class FibonacciTest {
static final Fibonacci fib = new Fibonacci();
// ...
@Test
public void testLastDigit40() {
assertThat(fib.lastDigitNaive(40), is(5));
}
@Test
public void testLastDigit327305() {
assertThat(fib.lastDigit(327_305), is(5));
}
@Test
public void testLastDigit100mio() {
assertThat(fib.lastDigit(100_000_000), is(5));
}
</pre>It is reasonably easy to calculate Fibonacci(40) = 102_334_155 and, trust me, both Fibonacci(327_305) and Fibonacci(100_000_000) have also a five as their last digit.<br />
<br />
Then I write a first implementation for lastDigit() method in my class Fibonacci:<br />
<pre class="brush: java">public int lastDigit(int n) {
if (n < 2) // 1
return n;
int previous = 0; // 2
int current = 1;
for (int i = 1; i < n; ++i) { // 3
int older = previous;
previous = current;
current = (older + previous) % 10; // 4
}
return current;
}
</pre>1. Accordingly to the modern definition of this sequence, Fibonacci(0) is 0 and Fibonacci(1) is 1.<br />
2. To calculate the current Fibonacci number we need to keep track of the latest two ones.<br />
3. Let's loop until we reach our target. The previous value will be discarded, current one will become previous, and the current one is calculated.<br />
4. We are lucky, we don't need to store the actual Fibonacci number, it's last digit is enough.<br />
<br />
Not a bad solution, however we could do better. We just have to notice that after 60 numbers, the final number in the sequence enter in a loop and repeat the first value. The is an interesting <a href="http://math.stackexchange.com/questions/113536/fibonaccis-final-digits-cycle-every-60-numbers">thread on math stackexchange</a> that gives more details on this curious feature.<br />
<br />
Let's exploit it to get a better solution:<br />
<pre class="brush: java">public int lastDigit(int n) {
int[] fibLast = new int[60]; // 1
fibLast[0] = 0;
fibLast[1] = 1;
for (int i = 2; i < 60; ++i) { // 2
fibLast[i] = (fibLast[i - 1] + fibLast[i - 2]) % 10;
}
return fibLast[n%60]; // 3
}
</pre>1. I am going to do the same job as in the first implementation, however I cache the first sixty values in a raw array.<br />
2. Notice the despicable use of the magic number 60 here and in (1). It should be a well commented constant instead!<br />
3. Thanks to the looping nature of the last cypher in Fibonacci numbers, I just have to apply to modulo operator to extract the correct index in my cached values.<br />
<br />
As an obvious performance improvement we should initialize the cache only the first time the method is called. In any case, I think the point is made, so I commit the <a href="https://github.com/egalli64/bitingcode/blob/master/fun/Fibonacci.java">Fibonacci Java class</a> and its <a href="https://github.com/egalli64/bitingcode/blob/master/fun/FibonacciTest.java">JUnit tester</a> to github.<br />
</span>Mannyhttp://www.blogger.com/profile/07393063644320426727noreply@blogger.com0tag:blogger.com,1999:blog-1645920781251418707.post-44388029397057393692016-10-28T12:53:00.000+02:002020-05-03T18:06:26.823+02:00Add testing to a Maven projectThis post was not so obsolete as the previous two ones, however it referred to JUnit 4, while the most interesting point in the argument, I feel, is in the fact that we should use a recent Surefire Maven plugin if we want the test run on build work with JUnit 5.<br />
<br />
So, again, so long my outdated post. If interested, you could get its new version on my other blog: <a href="https://thisthread.blogspot.com/2020/05/test-on-build-with-maven.html">https://thisthread.blogspot.com/2020/05/test-on-build-with-maven.html</a>.Mannyhttp://www.blogger.com/profile/07393063644320426727noreply@blogger.com0tag:blogger.com,1999:blog-1645920781251418707.post-82533866290942680832016-10-25T15:58:00.000+02:002020-05-03T15:30:05.207+02:00Adding Logback to a Maven ProjectIf you have written a Java project, maybe using Eclipse as IDE, but fundamentally using Maven as build manager, and you ask yourself how to add dependencies to it and, even more importantly, how to tell Maven to include your dependencies in the resulting jar, making it "fat" but also so more easily usable. This post was for you.<br />
<br />
I used Logback as sample library, but the story is the same any dependency you are putting in your app.<br />
<br />
Unfortunately it aged badly, so I had to ditch it.<br />
<br />
Still, I decided to rewrite it and I put the new version in my other blog. Follow the link if interested in it. <a href="https://thisthread.blogspot.com/2020/05/jar-with-dependencies-through-maven.html">https://thisthread.blogspot.com/2020/05/jar-with-dependencies-through-maven.html</a>Mannyhttp://www.blogger.com/profile/07393063644320426727noreply@blogger.com0tag:blogger.com,1999:blog-1645920781251418707.post-83052442966645387892016-10-15T16:08:00.001+02:002020-05-03T11:58:09.957+02:00Simple Maven Eclipse ProjectAs the title hints, this post was about creating a tiny little Java desktop apps on the Eclipse IDE using Maven as building tool.<br />
<br />
I say "was" because, unfortunately, it was too obsolete to survive.<br />
<br />
My first idea was just to clean it a bit and make it more fit for the current time. Then I found out that it was simpler for me, and clearer for the reader, if I rewrote it from scratch. Along the way, I have also refactored the code and rearrange the repository on GitHub.<br />
<br />
Moreover, I moved it to my other blog, this thread, that I plan to keep as the only one active. If interested, please follow the link <a href="https://thisthread.blogspot.com/2020/05/simple-maven-eclipse-project.html">https://thisthread.blogspot.com/2020/05/simple-maven-eclipse-project.html</a>Mannyhttp://www.blogger.com/profile/07393063644320426727noreply@blogger.com0tag:blogger.com,1999:blog-1645920781251418707.post-41125811294892698052016-06-07T21:45:00.001+02:002016-06-07T22:12:29.086+02:00AOP with SpringOur Spring Boot Web Application is starting making sense. As we have seen in the <a href="http://bitingcode.blogspot.com/2016/06/wiring-components-in-spring.html">previous post</a>, the controller is wired to a bean, a Knight, that is wired to another bean, a Quest. When the URI /quest is accessed, the RESTful service's nature of the controller enters in the game and, following all the wiring down to the bottom, what the caller gets is the message generated by the embark() method of the actual Quest objected involved.<br />
<br />
Now we want to introduce a class that follows a different perspective, a Minstrel whose raison d'être is singing when a Knight starts and ends a Quest. It's behavior is orthogonal to "normal" way we look at our code. We think at what a minstrel is interested in, we let it know to Spring, and just rely on it. In Aspect Oriented Programming (AOP) terms, Mistrel becomes an aspect of our application.<br />
<span class="fullpost"><br />
The nice point in AOP is that only the aspect, here Minstrel, has to know about what is going on. Knight could stay in its blissful ignorance on the matter, performing its mission as nothing as changed. Here I have changed the concrete Knight implementation just to add a line of log in its doQuest() method, that would help us in seeing the system at work. I have written more on Spring log in <a href="http://bitingcode.blogspot.com/2016/05/spring-log-only-to-file.html">another post</a>.<br />
<br />
To use AOP in Spring Boot, you have to add a dependency in your application <a href="https://github.com/egalli64/springtime/blob/s1.2/springInAction/pom.xml">POM file</a>. STS helps you not to forget it, anyway, groupId is org.springframework.boot and artifactId spring-boot-starter-aop. Besides, I should give to Spring some way to know which aspects it has to work with. We can do it through a XML file or a Java class configuration AspectJ style. I prefer the second way.<br />
<br />
So I created a <a href="https://github.com/egalli64/springtime/blob/s1.2/springInAction/src/main/java/dd/sia/knights/SpringInActionConfig.java">SpringInActionConfig class</a> where I specified the bean that is actually an aspect:<br />
<pre class="brush: java">@Configuration
@EnableAspectJAutoProxy
public class SpringInActionConfig {
@Bean
public Minstrel minstrel() {
return new Minstrel();
}
}
</pre>Notice the two annotations on the class and the bean annotation on its method that just creates a new Minstrel and returns it.<br />
<br />
I have implemented <a href="https://github.com/egalli64/springtime/blob/s1.2/springInAction/src/main/java/dd/sia/knights/logic/Minstrel.java">Minstrel</a> in this way, again using the Spring AspectJ support:<br />
<pre class="brush: java">@Aspect
public class Minstrel {
private final Log log = LogFactory.getLog(Minstrel.class);
@Before("execution(public String Knight.doQuest())")
public void singBeforeQuest() {
log.info("Fa la la, the knight is so brave!");
}
@After("execution(public String Knight.doQuest())")
public void singAfterQuest() {
log.info("Tee hee hee, the brave knight did embark on a quest!");
}
}
</pre>The class is annotated as Aspect, and it has two annotated method, one that has to be executed before the Knight doQuest() method, the other after.<br />
Notice the AspectJ sintax. It looked a bit weird to me the first time, however it makes sense. I have used a very plain and comprehensible notation, it could get much more cryptic. On the other side, it is quite powerful.<br />
<br />
Now, when we run our application we should not see any change in its behavior, but in its log, that now should have in it something like that:<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiOEsafMt8AJlfqqNE6iJw7M5XFlkzEhL2ImY2BQZ1mCQTSrEXVTMQ2_bdyWjzkNniK2cJWM39-CRNlkPZkxYQjvNJDzyWPXhWn4dkXztl-fvOC2YkWhgaZuqcWE10edYxfpM8gYd4afWvJ/s1600/aop.png" imageanchor="1" ><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiOEsafMt8AJlfqqNE6iJw7M5XFlkzEhL2ImY2BQZ1mCQTSrEXVTMQ2_bdyWjzkNniK2cJWM39-CRNlkPZkxYQjvNJDzyWPXhWn4dkXztl-fvOC2YkWhgaZuqcWE10edYxfpM8gYd4afWvJ/s320/aop.png" /></a><br />
I have written this post while reading the first chapter of <a href="https://www.manning.com/books/spring-in-action-fourth-edition">Spring in Action, Fourth Edition</a> by Craig Walls. 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.<br />
<br />
Full <a href="https://github.com/egalli64/springtime/tree/s1.2/springInAction">code on github</a>.<br />
</span>Mannyhttp://www.blogger.com/profile/07393063644320426727noreply@blogger.com0tag:blogger.com,1999:blog-1645920781251418707.post-64209532156699660512016-06-06T17:23:00.000+02:002016-06-06T17:32:37.553+02:00Wiring components in SpringAfter <a href="http://bitingcode.blogspot.com/2016/06/mock-test-on-spring-resource.html">mock testing</a> the components structure of my Spring Web application, I am ready to create a real Knight - Quest couple and see how to wire them together.<br />
<span class="fullpost"><br />
Firstly, I create a concrete Quest, <a href="https://github.com/egalli64/springtime/blob/s1.1/springInAction/src/main/java/dd/sia/knights/logic/SlayDragonQuest.java">SlayDragonQuest</a>, and I let Spring know, through annotations, that it is a component and it is qualified as quest.<br />
<pre class="brush: java">@Component
@Qualifier("quest")
public class SlayDragonQuest implements Quest {
public String embark() {
return "Embarking on quest to slay the dragon!";
}
}
</pre>Then I modify my <a href="https://github.com/egalli64/springtime/blob/s1.1/springInAction/src/main/java/dd/sia/knights/logic/BraveKnight.java">BraveKnight</a> to let Spring know that it is a component too, named knight, and that it is autowired to the component that is qualified as quest.<br />
<pre class="brush: java">@Component("knight")
public class BraveKnight implements Knight {
// ...
@Autowired
public BraveKnight(@Qualifier("quest") Quest quest) {
this.quest = quest;
}
// ...
}
</pre>Let's have a look to the <a href="https://github.com/egalli64/springtime/blob/s1.1/springInAction/src/main/java/dd/sia/knights/controller/KnightController.java">KnightController</a>.<br />
<pre class="brush: java">@RestController // 1
public class KnightController {
@Resource
private Knight knight; // 2
@RequestMapping("/quest")
public String quest() { // 3
return knight.doQuest();
}
}
</pre>1. It is annotated as a RestController, so Spring would use it as a RESTful service.<br />
2. Its knight field is annotated as resource, so Spring would try to inject in it a component named as its type (but starting with a lowercase letter), meaning, the BraveKnight.<br />
3. Any request to the /quest URI is mapped to this method.<br />
<br />
I only have to run it:<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi4CSDt41CkehGPhk5V_QHuzFTBELuIcgucZHwTVmwPt5kFJoRsZoah7Y9ZM-8s3dubvR2wRnf1NmzUcNdr6BQ9tvyjULMGMaVycYqMrJykAcQu416K5uLNom2LIsAzZaR3-Ty8Mgb3DAYq/s1600/quest.png" imageanchor="1" ><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi4CSDt41CkehGPhk5V_QHuzFTBELuIcgucZHwTVmwPt5kFJoRsZoah7Y9ZM-8s3dubvR2wRnf1NmzUcNdr6BQ9tvyjULMGMaVycYqMrJykAcQu416K5uLNom2LIsAzZaR3-Ty8Mgb3DAYq/s320/quest.png" /></a><br />
If something is not clear on this last step, you may get some hints from the previous <a href="http://bitingcode.blogspot.com/2016/05/hello-spring-boot.html">Hello Spring Boot</a> post.<br />
<br />
I have written this code while reading the first chapter of <a href="https://www.manning.com/books/spring-in-action-fourth-edition">Spring in Action, Fourth Edition</a> by Craig Walls. It diverges a bit from the original version, since I have developed a Maven Spring Boot Web project, and here I have used annotations instead of the classic xml configuration to signal beans to Spring and wire them together.<br />
<br />
Full <a href="https://github.com/egalli64/springtime/tree/s1.1/springInAction">code on github</a>.</span>Mannyhttp://www.blogger.com/profile/07393063644320426727noreply@blogger.com0tag:blogger.com,1999:blog-1645920781251418707.post-61233007456888421172016-06-05T15:26:00.001+02:002016-06-05T15:48:34.595+02:00Mock test on a Spring resourceFollowing the first chapter of <a href="https://www.manning.com/books/spring-in-action-fourth-edition">Spring in Action, Fourth Edition</a> by Craig Walls, I'm about to use the constructor injection (a Dependency Injection technique) to implement a IoC (Inversion of Control) relation between a Knight and its own Quest. No disrespect is meant, however I slightly change the original code to adapt it to a standard Boot Maven STS Spring Starter Project with Web dependency.<br />
<span class="fullpost"><br />
I put my SpringBootApplication in the <a href="https://github.com/egalli64/springtime/tree/s1.0/springInAction/src/main/java/dd/sia/knights">dd.sia.knights</a> package, and I created a couple of sub-packages, <a href="https://github.com/egalli64/springtime/tree/s1.0/springInAction/src/main/java/dd/sia/knights/controller">controller</a> and <a href="https://github.com/egalli64/springtime/tree/s1.0/springInAction/src/main/java/dd/sia/knights/logic">logic</a>. In the first one I have put a RestController, named <a href="https://github.com/egalli64/springtime/blob/s1.0/springInAction/src/main/java/dd/sia/knights/controller/KnightController.java">KnightController</a>, that owns a Resource Knight and performs a RequestMapping between the URI /quest and the method quest():<br />
<pre class="brush: java">@RestController
public class KnightController {
@Resource
private Knight knight;
@RequestMapping("/quest")
public String quest() {
return knight.doQuest();
}
}
</pre>I put all the classes rooted in the <a href="https://github.com/egalli64/springtime/blob/s1.0/springInAction/src/main/java/dd/sia/knights/logic/Knight.java">Knight</a> and <a href="https://github.com/egalli64/springtime/blob/s1.0/springInAction/src/main/java/dd/sia/knights/logic/Quest.java">Quest</a> interfaces in the logic sub-package. They both have a single method, doQuest() and embark(), returning a String.<br />
<br />
<b>Constructor Injection</b><br />
<br />
I created a concrete <a href="https://github.com/egalli64/springtime/blob/s1.0/springInAction/src/main/java/dd/sia/knights/logic/BraveKnight.java">BraveKnight</a> that implements Knight and has as private field a Quest. Which Quest a particular BraveKnight has is decided at runtime, injecting the actual Quest through the constructor:<br />
<pre class="brush: java">public class BraveKnight implements Knight {
private Quest quest;
public BraveKnight(Quest quest) {
this.quest = quest;
}
public String doQuest() {
return quest.embark();
}
}
</pre><br />
<b>Mock Test with Mockito</b><br />
<br />
Now we'd like to check if the class structure we designed works as expected. We can't perform normal unit test with JUnit for the reason that we don't currently have any concrete Quest to inject in our Knight. However we can mock-test it.<br />
<br />
To do that we have to add a mokito dependency in our project POM, <a href="https://github.com/egalli64/springtime/blob/s1.0/springInAction/pom.xml">pom.xml</a>, adding mokito-core from org.mockito for test scope. Then I added a JUnit-Mockito <a href="https://github.com/egalli64/springtime/blob/s1.0/springInAction/src/test/java/dd/sia/knights/logic/BraveKnightTest.java">test case for BraveKnight</a> with a single test function:<br />
<pre class="brush: java">@Test
public void testDoQuest() {
Quest quest = Mockito.mock(Quest.class); // 1
BraveKnight knight = new BraveKnight(quest); // 2
knight.doQuest(); // 3
Mockito.verify(quest, Mockito.times(1)).embark(); // 4
}
</pre>1. A mock Quest is created.<br />
2. Injecting the mock quest in a BraveKnight.<br />
3. Call the knight method.<br />
4. Ensure that the embark() method of my mock quest has been called once in this context.<br />
<br />
Full <a href="https://github.com/egalli64/springtime/releases/tag/s1.0">source code is on github</a> in the <a href="https://github.com/egalli64/springtime/tree/s1.0/springInAction">springInAction folder</a>.</span>Mannyhttp://www.blogger.com/profile/07393063644320426727noreply@blogger.com0tag:blogger.com,1999:blog-1645920781251418707.post-75642838211340202752016-06-02T10:52:00.000+02:002016-06-02T10:52:31.561+02:00Plain MVC Spring projectNowadays, if you create a new Spring project on STS, the most natural option is <a href="http://bitingcode.blogspot.com/2016/05/hello-spring-boot.html">using the Spring Starter Project</a> wizard that is going to push you to use Spring Boost. Say that for some reason you don't want to do that, you could fallback to the pre-boot era, here is how, in a few steps.<br />
<span class="fullpost"><br />
Basically, you just have to call the Spring Legacy Project, from menu File - New. There you just have to choose a project name and select which template you want to use. Usually Spring MVC Project is a good choice.<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhLvDcUKibzcvkhqP8w6J9yY03PpC6PyZ7V4j76HfLDDc2cv1TgYk8XORMf15xg36TNLrVcDr310udDgM0vAMTPYW74V4n28Hd2w4xa7CteZaKDOUQstOy_f1u-DlaTwDL5HFgol7R7EaV5/s1600/legacy.png" imageanchor="1" ><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhLvDcUKibzcvkhqP8w6J9yY03PpC6PyZ7V4j76HfLDDc2cv1TgYk8XORMf15xg36TNLrVcDr310udDgM0vAMTPYW74V4n28Hd2w4xa7CteZaKDOUQstOy_f1u-DlaTwDL5HFgol7R7EaV5/s200/legacy.png" /></a><br />
Next step would be specify the top level package for you application. And then the wizard would do all the job for you.<br />
<br />
Just one thing more, when you get back the control, you'd better update the project through Maven, by right click on the project - Maven - Update Project. After that you should be ready to run the project on server.<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi8AVy7epBoddXRW6OT6Y0nRhOE60KU6nX3eTm-DFcQiX3_pApENhN7W0y-5EGA0KPbZTfCdNGDEVTAtOONwCGoaV21HJDQ8f0p5lGuXDI15rLbBJSHa2N4MHrBI_OqOAuJRLzJxWkNri_r/s1600/greeting.png" imageanchor="1" ><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi8AVy7epBoddXRW6OT6Y0nRhOE60KU6nX3eTm-DFcQiX3_pApENhN7W0y-5EGA0KPbZTfCdNGDEVTAtOONwCGoaV21HJDQ8f0p5lGuXDI15rLbBJSHa2N4MHrBI_OqOAuJRLzJxWkNri_r/s320/greeting.png" /></a><br />
</span>Mannyhttp://www.blogger.com/profile/07393063644320426727noreply@blogger.com0tag:blogger.com,1999:blog-1645920781251418707.post-2076470830897829462016-05-31T19:43:00.000+02:002016-05-31T21:41:22.298+02:00A simple IoC + DI Spring exampleIn the previous posts I have written a puny Spring Boot application example sporting a <a href="http://bitingcode.blogspot.com/2016/05/spring-log-only-to-file.html">trivial RESTful controller</a> Let's spice it up a bit, extracting the business logic from the controller and putting it in a hierarchy of classes. The interesting part of it is that I am going to do it using IoC (Inversion of Control) and DI (Dependency Injection).<br />
<span class="fullpost"><br />
I created a sub-package named control, and in it I put an interface, Greeter, that exposes the only method I really care of:<br />
<pre class="brush: java">public interface Greeter {
String greeting();
}
</pre>Then I refactored my GreetingController to use that interface to do the dirty job. Something like this:<br />
<pre class="brush: java">public class GreetingController {
private Greeter greeter;
public String greeting() {
return greeter.greeting();
}
}
</pre>The reason for doing this should be clear. My controller won't care about the details of how a greeting is generated. It just knows that exists a hierarchy of classes rooted in the Greeter interface, and it would call its greeting() method when it intercepts a user call for this job.<br />
<br />
Then I created a couple of concrete classes implementing Greeter. A mock one, thought to be used just in development, and the actual stuff designed to be used in production.<br />
<pre class="brush: java">public class MockGreeter implements Greeter {
private static final Log log = LogFactory.getLog(MockGreeter.class);
@Override
public String greeting() {
log.debug("Generating mock greeting");
return "mock hello!";
}
}
public class PlainGreeter implements Greeter {
private static final Log log = LogFactory.getLog(PlainGreeter.class);
@Override
public String greeting() {
log.trace("Generating plain greeting");
return "Hello!";
}
}
</pre>I know, it is not easy to spot a difference between them. Let's assume they will grow and diverge to something more useful in the future.<br />
<br />
The interesting stuff here is defining how the controller should know which Greeter to use. In the old pre-IoC days it would be its job to create a dependency with the selected Greeter, creating an object of a concrete type. Nowadays we prefer to do the other way round, we invert the control, and let the concrete Greeter signal its availability to be used by the controller to the framework (in this case Spring). We can do that in a few different ways, being annotation usually considered the preferred one.<br />
<br />
The controller should tell to Spring in some way that a field it owns should be injected with a dependency (here is where DI enters in the game). There are a few ways to do it. I usually prefer to annotate the data member, like this:<br />
<pre class="brush: java">@RestController
public class GreetingController {
@Resource
private Greeter greeter;
// ...
}
</pre>On the other side, each Greeter implementation that could be selected from Spring for the controller should show it up:<br />
<pre class="brush: java">@Component
public class MockGreeter implements Greeter {
// ...
}
</pre>We still have a problem. We have two different implementations of Greeter competing to be injected to the controller. Which one should Spring choose?<br />
<br />
One way of solving it is by configuration. We specify the spring.profiles.active property in the Spring application.properties file giving to it a value that would act as a selector for the appropriate Greeter. In my case, I want to play with two different configurations, dev and prod. When in development (dev) I want the mock greeter to be injected in the controller, while in production (prod) the plain greeter should be used.<br />
<br />
In case of production my Spring configuration file would have this line in it:<br />
<pre>spring.profiles.active=prod</pre>My Greeter classes would be annotated in this way:<br />
<pre class="brush: java">@Component
@Profile("prod")
public class PlainGreeter implements Greeter {
// ...
}
@Component
@Profile("!prod")
public class MockGreeter implements Greeter {
// ...
}
</pre><br />
The complete Spring Boot <a href="https://github.com/egalli64/springtime/tree/v4.0">project is on github</a>. The relevant files are<br />
<ul><li><a href="https://github.com/egalli64/springtime/blob/v4.0/helloSpring/src/main/java/dd/manny/hello/controller/GreetingController.java">GreetingController.java</a>, modified to use a Greeter object annotated as resource;</li>
<li><a href="https://github.com/egalli64/springtime/blob/v4.0/helloSpring/src/main/resources/application.properties">application.properties</a>, in which I added the active profile property;</li>
<li><a href="https://github.com/egalli64/springtime/tree/v4.0/helloSpring/src/main/java/dd/manny/hello/logic">the package logic</a>; containing the <a href="https://github.com/egalli64/springtime/blob/v4.0/helloSpring/src/main/java/dd/manny/hello/logic/Greeter.java">Greeter interface</a> and its two implementations.</li>
</ul></span>Mannyhttp://www.blogger.com/profile/07393063644320426727noreply@blogger.com0tag:blogger.com,1999:blog-1645920781251418707.post-68959012784384551732016-05-30T22:44:00.002+02:002017-01-09T14:27:26.404+01:00Spring log only to fileLogging 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.<br />
<br />
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.<br />
<span class="fullpost"><br />
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.<br />
<br />
Let's modify the function greeting in my <a href="http://bitingcode.blogspot.com/2016/05/a-simple-restful-web-service.html">GreetingController</a> to log some (un)useful comments:<br />
<pre class="brush: java">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!";
}
</pre>Where log is private static final object of type org.apache.commons.logging.Log initialized through the JCL LogFactory.<br />
<br />
This could be enough. Still you should have a mildly surprising output, something like:<br />
<pre>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
</pre>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.<br />
<br />
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:<br />
<pre>logging.level.dd.manny=trace</pre>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:<br />
<pre>logging.path=/tmp</pre>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.<br />
<br />
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.<br />
<br />
The full Spring Boot <a href="https://github.com/egalli64/springtime/tree/v3.0">project is on github</a>. The relevant files are <a href="https://github.com/egalli64/springtime/blob/v3.0/helloSpring/src/main/java/dd/manny/hello/controller/GreetingController.java">GreetingController.java</a>, <a href="https://github.com/egalli64/springtime/blob/v3.0/helloSpring/src/main/resources/application.properties">application.properties</a>, and <a href="https://github.com/egalli64/springtime/blob/v3.0/helloSpring/src/main/resources/logback.xml">logback.xml</a>.</span>Mannyhttp://www.blogger.com/profile/07393063644320426727noreply@blogger.com0tag:blogger.com,1999:blog-1645920781251418707.post-2727361035783407012016-05-27T23:00:00.000+02:002016-05-27T23:11:14.460+02:00A simple RESTful Web ServiceIn the <a href="http://bitingcode.blogspot.com/2016/05/hello-spring-boot.html">previous post</a>, 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.<br />
<span class="fullpost"><br />
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.<br />
<br />
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:<br />
<pre class="brush: java">@RestController
public class GreetingController {
@RequestMapping("/greeting")
public String greeting() {
return "Hello!";
}
}
</pre>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.<br />
<br />
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:<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEir_1JDl_rEmUNQ_ZDc6B-LC0C2rbeGYnHCxUJi0kmwzXls9FnUVY_5E3FJ_QAQts8wyQ-Pkfthm-w6RVggx8McJcYm3fCkOgxUfKwDzMvULbXWO8Re_L4mLXzPjzOR7zv4GHMp4wRCyNK2/s1600/greeting.png" imageanchor="1" style="margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEir_1JDl_rEmUNQ_ZDc6B-LC0C2rbeGYnHCxUJi0kmwzXls9FnUVY_5E3FJ_QAQts8wyQ-Pkfthm-w6RVggx8McJcYm3fCkOgxUfKwDzMvULbXWO8Re_L4mLXzPjzOR7zv4GHMp4wRCyNK2/s1600/greeting.png" /></a></div>If you wonder why and how I'm using a non-standard Tomcat port, please refer to the previous post.<br />
<br />
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.<br />
<br />
Source code is <a href="https://github.com/egalli64/springtime/tree/v2.0">on github</a>. The only relevant change from the previous version is the <a href="https://github.com/egalli64/springtime/blob/v2.0/helloSpring/src/main/java/dd/manny/hello/controller/GreetingController.java">GreetingController</a>.</span>Mannyhttp://www.blogger.com/profile/07393063644320426727noreply@blogger.com0tag:blogger.com,1999:blog-1645920781251418707.post-90869317845020039892016-05-26T22:00:00.000+02:002016-05-27T11:08:24.236+02:00Hello Spring BootCreating 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.<br />
<span class="fullpost"><br />
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 <a href="http://start.spring.io/">start.spring.io</a> 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.<br />
<br />
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.<br />
<br />
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.<br />
<br />
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.<br />
<br />
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).<br />
<br />
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.<br />
<br />
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.<br />
<br />
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.<br />
<br />
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.<br />
<br />
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<br />
<pre>java.net.BindException: Address already in use</pre>You are having the same problem.<br />
<br />
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:<br />
<pre>server.port = 8585</pre>Meaning that I want my Tomcat to use a different port from the standard one.<br />
<br />
Now I can restart my application, and get a smooth startup, as showed by the error-free log in the Console view.<br />
<br />
The full code for the <a href="https://github.com/egalli64/springtime/tree/v1.0">project is on github</a>.</span>Mannyhttp://www.blogger.com/profile/07393063644320426727noreply@blogger.com0tag:blogger.com,1999:blog-1645920781251418707.post-38851923441451011212016-05-09T11:17:00.000+02:002016-05-09T11:17:14.667+02:00JSP servlet init parametersCreating 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.<br />
<span class="fullpost"><br />
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.<br />
<br />
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.<br />
<br />
Here is an example for a servlet element, based on a JSP page named counting.jsp placed in the web app root directory:<br />
<pre><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>
</pre>Notice the jsp-file element, that replaces what in a plain servlet is a servlet-class.<br />
<br />
Then we need a servlet-mapping element, that should look something like this one:<br />
<pre><servlet-mapping>
<servlet-name>Counting</servlet-name>
<url-pattern>/counting.jsp</url-pattern>
</servlet-mapping>
</pre><br />
And that's it. Now we can access that init parameter from our Counting JSP page.<br />
<br />
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:<br />
<pre><%!
public void jspInit() {
log("Config init param: " + getServletConfig().getInitParameter("base"));
}
%>
</pre>If we want to access it from a scriplet, we use the config implicit object:<br />
<pre><%= config.getInitParameter("base") %>
</pre></span>Mannyhttp://www.blogger.com/profile/07393063644320426727noreply@blogger.com0tag:blogger.com,1999:blog-1645920781251418707.post-7344435330679672362015-05-04T15:59:00.000+02:002015-05-06T16:21:31.433+02:00Square root by Newton's methodThis well known method to calculate square roots by successive approximations is one of the first examples that Martin Odersky uses in its <a href="http://www.scala-lang.org/docu/files/ScalaByExample.pdf">Scala by example</a> booklet freely available online. You'll find it in section 4 of chapter 4.<br />
<span class="fullpost"><br />
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.<br />
<br />
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:<br />
<pre class="brush: java">def isGoodEnough(guess: Double, x: Double) = math.abs(guess * guess - x) / x < 0.001
</pre>
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:
<pre class="brush: java">def improve(guess: Double, x: Double) = (guess + x / guess ) / 2
</pre>Now we are ready to write the requested function:
<pre class="brush: java">def sqrtIter(guess: Double, x: Double): Double =
if (isGoodEnough(guess, x)) guess
else sqrtIter(improve(guess, x), x)
</pre>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:
<pre class="brush: java">def sqrt(x: Double) = sqrtIter(1.0, x)
</pre>We can compare the result to call to the Scala library function:
<pre class="brush: java">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))
</pre>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.
<pre class="brush: java">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)
}
</pre>
</span>Mannyhttp://www.blogger.com/profile/07393063644320426727noreply@blogger.com1tag:blogger.com,1999:blog-1645920781251418707.post-89395110307161490312015-05-03T17:16:00.000+02:002015-05-03T17:16:21.765+02:00AND and OR as functionsLet'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 <a href="http://bitingcode.blogspot.com/2015/05/by-value-vs-by-name.html">by-value and by-name</a> parameter evaluation strategy.<br />
<span class="fullpost"><br />
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.<br />
<br />
Let's express our requirements with assertions:<br />
<pre class="brush: java">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))
</pre>Here is how I have implemented the two functions:<br />
<pre class="brush: java">def and(a: Boolean, b: => Boolean) = if(a) b else false
def or(a: Boolean, b: => Boolean) = if(a) a else b
</pre>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.<br />
<br />
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:<br />
<pre class="brush: java">def silly() : Boolean = silly
assert(and(false, silly) == (false && silly))
assert(or(true, silly) == (true || silly))
</pre>The short-circuit logic is implemented also from my functions, so no need of evaluating silly().<br />
<br />
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.</span>Mannyhttp://www.blogger.com/profile/07393063644320426727noreply@blogger.com0tag:blogger.com,1999:blog-1645920781251418707.post-49638398535202871192015-05-02T17:41:00.000+02:002015-05-02T17:41:43.167+02:00By-value vs. by-nameA 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.<br />
<br />
A trivial example should help clarify the difference about the two approaches.<br />
<span class="fullpost"><br />
Let's consider a useless function that gets as parameters a couple of integers and always returns zero.<br />
<pre class="brush: java">def zero(a: Int, b: => Int) = 0
</pre>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.<br />
<br />
Function zero() looks pretty harmless. However, we could have big troubles if we use it in conjunction with something like this:<br />
<pre class="brush: java">def silly() : Int = silly
</pre>Function silly() just resolves in an infinitive loop, that would let our program running forever without giving the user any satisfaction.<br />
<br />
If I pass silly() to zero() as its second parameter, I'll have no problem at all:<br />
<pre class="brush: java">println(zero(42, silly))
</pre>Being passed by-name, and not being actually used in zero(), silly() won't be evaluated.<br />
<br />
On the contrary, you want to avoid this:<br />
<pre class="brush: java">println(zero(silly, 42)) // !!!
</pre>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.<br />
</span>Mannyhttp://www.blogger.com/profile/07393063644320426727noreply@blogger.com0tag:blogger.com,1999:blog-1645920781251418707.post-14561343554110124142015-04-28T00:16:00.001+02:002016-12-09T21:37:39.303+01:00Functional Programming is here to stayMartin Odersky talk at OSCON Java 2011, "Working Hard to Keep It Simple". A nice comparison between imperative and functional programming paradigm, and a very fast introduction to Scala. Even if a bit dated, still very interesting. <br />
<span class="fullpost"><br />
<iframe width="560" height="315" src="https://www.youtube.com/embed/3jg1AheF4n0" frameborder="0" allowfullscreen></iframe><br />
</span>Mannyhttp://www.blogger.com/profile/07393063644320426727noreply@blogger.com0tag:blogger.com,1999:blog-1645920781251418707.post-35063470554474893722013-12-23T13:45:00.000+01:002016-12-22T20:37:38.009+01:00Learning Apache Maven 3I have just finished watching to this <a href="http://bit.ly/1kvveqf">Pack video course about Maven</a>, on youtube there is a <a href="http://bit.ly/19eFCkG">preview that shows</a> what you can expect from it.<br />
<span class="fullpost"><br />
It is designed to follow a Java programmer who knows nothing about Maven from the absolute beginning to writing a multi module project.<br />
<br />
The major emphasis is on Maven for Windows plus Eclipse, just at the beginning it is shown how to install Maven on Linux and Mac, and how to integrate it also in Intellij and NetBeans. This is not a big issue, since we are in the Java world, and the platform differences are usually not too harsh.<br />
<br />
The course is structured in four parts. After the installation/integration done in the introduction, we are guided to write a first "hello world" application. The third block is about creating a Web App by Maven that uses features from Struts2, Hibernate, and Spring. The last part shows how to develop a client/sever multi module project.<br />
<br />
I found the standard price for this course a bit excessive, but in this bargains season, at less than five bucks, I wouldn't see how to complain.<br />
<br />
It works fine as an introduction to the matter, in a couple of hours you can't expect to become a Maven master, but I'd say it succeeds in giving a good overview.<br />
<br />
It has a few weak spots, too. Mainly, the audio comment is not lively at all, and there is a curious alternation in voices that I found distracting. Hear this, for instance, at around 1.30:<br />
<iframe width="560" height="315" src="//www.youtube.com/embed/JGEHY_5B2XI?rel=0" frameborder="0" allowfullscreen></iframe><br />
</span>Mannyhttp://www.blogger.com/profile/07393063644320426727noreply@blogger.com0tag:blogger.com,1999:blog-1645920781251418707.post-67075476277611664872013-12-18T10:50:00.000+01:002013-12-18T10:50:02.397+01:00Maven 3 video courseI have got a pointer to this video course on <a href="http://bit.ly/1kvveqf">Apache Maven 3</a>, you could also find a <a href="http://bit.ly/19eFCkG">preview on YouTube</a> that gives the gist of it.<br />
<span class="fullpost"><br />
It is a couple of hours long, it looks to be designed as an introduction to Maven for a Java developer who has no (or little) previous knowledge of it.<br />
<br />
Since I use Maven in an unstructured way, it would probably good for me to find the way to spend time watching it. I plan to do it in the near future, and writing something more about it. <br />
</span>Mannyhttp://www.blogger.com/profile/07393063644320426727noreply@blogger.com0tag:blogger.com,1999:blog-1645920781251418707.post-25161326066997409972013-08-05T15:55:00.001+02:002013-08-05T15:55:26.202+02:00Hello Android StudioI have <a href="http://bitingcode.blogspot.com/2013/08/setting-up-android-studio.html">installed Android Studio</a>, and I have made a Nexus 7 ready to be used as <a href="http://bitingcode.blogspot.com/2013/08/setting-up-nexus-7.html">target device</a>. Now I am ready to develop a first "Hello world" application.<br />
<br />
Android Studio make it very easy.<br />
<span class="fullpost"><br />
Just select New Project from the file menu (or from the welcome dialog) and specified which properties you want to change from the default schema. I modified just three of them:<br />
<pre>- Application name: Hello Android
- Module name: HelloAndroid
- Package name: dd.HelloAndroid
</pre>Then was just a matter of compiling and, after ensuring the target device was connected and available to my developer unit, ran it.<br />
<br />
After confirming on Nexus that I wanted to debug that app, I saw it appearing. It doesn't say much. It just have the "Hello Android" name on the title bar and, wait a moment, an "Hello world!" message below it? Where does it come from?<br />
<br />
We should remember that among the properties we were asked to confirm to create a new project, there was also something about the layout to be used by the application. Let's check it.<br />
<br />
I opened the Project View, I clicked on my HelloAndroid project, src, main, res, layout, and I finally see it, activity_main.xml.<br />
<br />
In it I see that the TextView property is filled with an @string/hello_world. So I opened the res, values, strings.xml, and I saw that a hello_world string resource was set for me to the value "Hello world!"<br />
<br />
I don't want any message on my app, so I cut that line, went back to activity_main.xml, and remove from the "text" property the reference to that string. Re-launching HelloAndroid I can now enjoy its beautiful emptiness. </span>Mannyhttp://www.blogger.com/profile/07393063644320426727noreply@blogger.com1