tag:blogger.com,1999:blog-80515938961246418072024-03-14T02:04:41.581-05:00CodelooruCodelooru is a technology blog that covers a variety of topics ranging from languages like Java, Spring, Groovy, databases like Cassandra, Postgresql, cloud services like AWS, Azure, etc.Phee Jayhttp://www.blogger.com/profile/08103990765188490526noreply@blogger.comBlogger25125tag:blogger.com,1999:blog-8051593896124641807.post-40438287595659450262022-12-09T12:09:00.005-06:002022-12-09T12:11:52.537-06:00Okta - PKCE Verification Failed while requesting tokenLet me clear a few concepts before I dive into the resolution for "<i>PKCE Verification Failed</i>"<div><ul style="text-align: left;"><li>"<b>Authorization Code</b>" <a href="https://developer.okta.com/docs/guides/implement-grant-type/authcode/main/#authorization-code-flow">flow</a> is an <b>OAuth 2.0 flow</b>, wherein an authorization code is issued by the <i>Authorization Server</i>. This code is used for requesting access tokens, used for accessing the protected resources. Authorization code is exchanged through the front-channel and is susceptible to interception attacks.</li><a name='more'></a><li><b><a href="https://oauth.net/2/pkce/">PKCE</a></b>, which stands for "<b>Proof Key for Code Exchange</b>", is a way to protect from interception attacks while trying to fetch tokens using authorization codes.</li><li>In PKCE, the client generates a <b>code verifier</b> and a hashed value of it called <b>code challenge</b>. While requesting the authorization code, a <b>code challenge</b> is sent to the server, which the server persists. While requesting the access token, the client sends a <b>code verifier</b>. The server hashes the verifier and compares it with the challenge. Thus ensuring the request came from the client.</li></ul>
<div><br /></div><div>While requesting access token using the authorization endpoint <b><i><a href="https://developer.okta.com/docs/reference/api/oidc/#token">/token</a></i></b>, I received the following response.</div><div><br /></div>
<pre class="brush: javascript">{
"error": "invalid_grant",
"error_description": "PKCE verification failed"
}
</pre>
<div>It turns out that Okta has a bug wherein, not all <b>code verifiers</b> work for access token requests. To get past this error, <b>you need to try it with a different verifier and challenge</b>.</div></div><div><br /></div>Phee Jayhttp://www.blogger.com/profile/08103990765188490526noreply@blogger.com0tag:blogger.com,1999:blog-8051593896124641807.post-38253663331609782762022-12-08T12:27:00.006-06:002022-12-08T12:27:48.436-06:00How to rename an AWS Lambda function?<p> As of writing this article, there is no support in AWS to rename a Lambda function. However, there is an option to set an <b>alias</b>. And you can create multiple of them.</p><p>The actual purpose of an <b>alias</b>, though, is to act as a pointer to a specific version of the lambda function. It can also act as a router to route traffic between two versions of the function with weight assignment e.g. to test it as a canary.</p><p>If alias does not meet your needs, then the only other way is to delete the function and recreate it with the desired name.</p>Phee Jayhttp://www.blogger.com/profile/08103990765188490526noreply@blogger.com0tag:blogger.com,1999:blog-8051593896124641807.post-52863990781816657142019-02-11T10:27:00.002-06:002021-05-29T08:55:42.829-05:00Groovy - What is Memoization?<img border="0" data-original-height="74" data-original-width="150" src="https://2.bp.blogspot.com/-SXid_OR8Yxw/WYQEEZcT7FI/AAAAAAAAAPE/E6QuZVR9mckAQ__nqAL72W0awz0EgBMHQCLcBGAs/s1600/Groovy-logo-150.png" style="display: none;" />
Memoization (a.k.a tabling) is a technique in programming where the result of a function call is stored in cache and when the function is subsequently called with the same parameters, the result is returned from the cache instead of executing the function again.
<br />
<a name='more'></a><br />
It is a special form of caching that applies only to functions and methods. Some programming language may support eviction policies, invalidation, and disk storage that a typical caching solution offers.
<br />
<br />
Common use cases for memoization are dynamic programming problems like Fibonacci sequence and factorial computation. It is commonly used to cache frequent computations that can add up to significant processing time. It is best to avoid memoization where the results of the function call may vary e.g. functions that make database calls may return different results and are not suited for memoization.
<br />
<br />
Let's take a simple example in groovy that defines a function for factorial. Factorial of a positive whole number can be defined as <code>factorial(n) = n * factorial(n-1)</code> . So, it can be defined as a recursive function like so.
<br />
<br />
<pre class="brush: groovy">//Example without memoization
factorial = { n ->
if(n == 0) {
return 1
}
else {
println "-- factorial ("+n+") Invoked --"
return n* factorial(n-1);
}
}
println "Factorial of 1 = " + factorial(1) + "\n"
println "Factorial of 2 = " + factorial(2) + "\n"
println "Factorial of 3 = " + factorial(3) + "\n"
println "Factorial of 4 = " + factorial(4) + "\n"
println "Factorial of 5 = " + factorial(5) + "\n"
</pre>
<br />
Results:
<br />
<pre class="brush: groovy">-- factorial (1) Invoked --
Factorial of 1 = 1
-- factorial (2) Invoked --
-- factorial (1) Invoked --
Factorial of 2 = 2
-- factorial (3) Invoked --
-- factorial (2) Invoked --
-- factorial (1) Invoked --
Factorial of 3 = 6
-- factorial (4) Invoked --
-- factorial (3) Invoked --
-- factorial (2) Invoked --
-- factorial (1) Invoked --
Factorial of 4 = 24
-- factorial (5) Invoked --
-- factorial (4) Invoked --
-- factorial (3) Invoked --
-- factorial (2) Invoked --
-- factorial (1) Invoked --
Factorial of 5 = 120
</pre>
<br />
The program above prints a line every time the function is called. As you see in the results, every call to factorial recurses until it hits factorial(0). You can see a bunch of redundant calls happening for computing factorials for numbers that have already been computed before. This algorithm could be easily improved by caching the value of each invocation and using them in the subsequent invocations. And memoization would help with that.<br />
<br />
Now let's see the same example with the memoized closure function. The line where the memoization is applied is highlighted.<br />
<br />
<pre class="brush: groovy; highlight: [11]">//Example with memoization
factorial = { n ->
if(n == 0) {
return 1
}
else {
println "-- factorial ("+n+") Invoked --"
return n* factorial(n-1);
}
}.memoize()
println "Factorial of 1 = " + factorial(1) + "\n"
println "Factorial of 2 = " + factorial(2) + "\n"
println "Factorial of 3 = " + factorial(3) + "\n"
println "Factorial of 4 = " + factorial(4) + "\n"
println "Factorial of 5 = " + factorial(5) + "\n"
</pre>
Results:
<br />
<pre class="brush: groovy">-- factorial (1) Invoked --
Factorial of 1 = 1
-- factorial (2) Invoked --
Factorial of 2 = 2
-- factorial (3) Invoked --
Factorial of 3 = 6
-- factorial (4) Invoked --
Factorial of 4 = 24
-- factorial (5) Invoked --
Factorial of 5 = 120
</pre>
<br />
With memoization, you can see that the recursion has reduced to just once. The calls are cached and the results are used in the subsequent calls.
<br />
<br />
<h3>
Memoization support in Groovy</h3>
<br />
Groovy, like many other functional languages, supports Memoization as a language feature. It can memoize both closures and methods. What we saw in the example above was closure memoization.
<br />
<br />
<h4>
Closures</h4>
<br />
Groovy supports the following methods on Closures for memoization.
<br />
<br />
<code>closure.memoize()</code> - This caches all the calls to the closure. There are no limits. The cache gets cleared only upon garbage collection.
<br />
<br />
<code>closure.memoizeAtMost(n)</code> - This caches a max of <code>n</code> values. It uses an LRU (Last Recently Used) strategy for eviction. Garbage collection applies here as well and the cache may get cleared.
<br />
<br />
<code>closure.memoizeAtLeast(n)</code> - This caches all calls without limit, just like <code>memoize</code>. The difference is that when the garbage collection happens, it protects <code>n</code> recent calls from being evicted.
<br />
<br />
<code>closure.memoizeBetween(n, m)</code> - This protects <code>n</code> items from garbage collection, but sets a max limit of <code>m</code> values on the cache.
<br />
<br />
Let's check out an example with memoizeAtMost.
<br />
<pre class="brush: groovy; highlight:[11]">//Example with memoizeAtMost
factorial = { n ->
if(n == 0) {
return 1
}
else {
println "-- factorial ("+n+") Invoked --"
return n* factorial(n-1);
}
}.memoizeAtMost(1)
println "Factorial of 1 = " + factorial(1) + "\n"
println "Factorial of 2 = " + factorial(2) + "\n"
println "Factorial of 1 = " + factorial(1) + "\n"
println "Factorial of 2 = " + factorial(2) + "\n"
</pre>
Results:
<br />
<pre class="brush: groovy">-- factorial (1) Invoked --
Factorial of 1 = 1
-- factorial (2) Invoked --
Factorial of 2 = 2
-- factorial (1) Invoked --
Factorial of 1 = 1
-- factorial (2) Invoked --
Factorial of 2 = 2
</pre>
<br />
As you can see from the result, the cache size for factorial is just 1. So, when we call <code>factorial(1)</code> followed by <code>factorial(2)</code>, it evicts the result for 1 and replaces it with 2. If you set the memoizeAtMost to 2, the above example would print like so<br />
<br />
<pre class="brush: groovy">-- factorial (1) Invoked --
Factorial of 1 = 1
-- factorial (2) Invoked --
Factorial of 2 = 2
Factorial of 1 = 1
Factorial of 2 = 2
</pre>
<br />
<h4>
Method memoization</h4>
<br />
Memoization can be applied to class methods by annotating them with <code>@Memoized</code>. By default, the cache size has no limit, but if you wish to set a limit, then you can set the <code>maxCacheSize</code> attribute on the annotation and it would behave just like <code>memoizeAtMost</code>.
<br />
Let's see an example.
<br />
<pre class="brush: groovy; highlight:[7]">//Example with @Memoized
import groovy.transform.Memoized
class MemoizationTest {
@Memoized(maxCacheSize = 2)
def factorial(n) {
if(n == 0) {
return 1L
}
else {
println "-- factorial ("+n+") Invoked --"
return 1L*n* factorial(n-1);
}
}
}
def test = new MemoizationTest()
println test.factorial(1)
println test.factorial(2)
println test.factorial(3)
</pre>
<br />
Results:
<br />
<pre class="brush: groovy">-- factorial (1) Invoked --
1
-- factorial (2) Invoked --
2
-- factorial (3) Invoked --
6
</pre>
<br />
<br />
<h3>
Best Practices</h3>
<br />
Memoization is not a full-fledged caching solution. A cache can be invalidated based on certain triggers and it supports other advanced features. Keep in mind the following
<ul>
<li> Ensure that the function being memoized, will always return the same result for the same input parameters. It should not be used for dynamic data e.g. data that is being fetched from the database and is bound to change.</li>
<li>Keep a check on the max values for Memoization. Keeping it unlimited may shoot up the memory usage and make your application latent instead.</li>
</ul>
<br />
<br />
<h3>
Conclusion</h3>
<br />
As we saw in this post through examples, Memoization is a powerful technique that can be used to cache results and improve the overall performance of a program. Use it wisely, keeping in mind the limitations.
<br />
<br />
<div style="background-color: #e6f4ff; border-radius: 5px; padding-bottom: 15px; padding-left: 10px; padding-top: 15px;">
<h4>
Related Articles:</h4>
<ul>
<li><a href="https://www.codelooru.com/2017/08/how-to-read-files-in-groovy.html">How to Read Files in Groovy?</a></li>
<li><a href="https://www.codelooru.com/2019/02/read-and-write-to-excel-groovy.html">How to read and write to excel sheets with Groovy?</a></li>
<li><a href="https://www.codelooru.com/2017/02/how-spring-cache-works-part-1.html">Spring Cache - Part 1 - Introduction</a></li>
</ul>
</div>
<br />Phee Jayhttp://www.blogger.com/profile/08103990765188490526noreply@blogger.com0tag:blogger.com,1999:blog-8051593896124641807.post-9454284808113208062019-02-01T14:38:00.004-06:002022-12-08T12:43:36.266-06:00Groovy - How to read and write to excel sheets with Groovy?<img border="0" data-original-height="74" data-original-width="150" src="https://2.bp.blogspot.com/-SXid_OR8Yxw/WYQEEZcT7FI/AAAAAAAAAPE/E6QuZVR9mckAQ__nqAL72W0awz0EgBMHQCLcBGAs/s1600/Groovy-logo-150.png" style="display: none;" />
<br />
<div>
<b>Scriptom</b> provides a simple COM library for Groovy. It is a Groovy wrapper around <b>JACOB </b>(Java COM Bridge) which provides access to COM Automation components. Scriptom can be used to work with MS Office tools, Internet Explorer or any other Microsoft Windows COM based components. In this article, you will use Scriptom to read and write to excel files.</div>
<br />
<a name='more'></a><h3>
Dependencies</h3>
<br />
You need to download and add the scriptom jar to the classpath. It is available from the maven repo <a href="https://mvnrepository.com/artifact/org.codehaus.groovy.modules.scriptom/scriptom/1.6.0"><b>here</b></a>.
<br />
<br />
In your groovy script import the ActiveXObject class.
<br />
<pre class="brush: groovy">import org.codehaus.groovy.scriptom.ActiveXObject
</pre>
<br />
<h3>
Usage</h3>
<br />
Next, create an instance of the ActiveXObject for Excel and use it to open the excel file.
<br />
<pre class="brush: groovy"> def excelObj = new ActiveXObject('Excel.Application')
def workBook = excelObj.Workbooks.Open(1c:/codelooru.xlsx1)
</pre>
You can get a reference to the Sheet in the following ways.
<br />
<pre class="brush: groovy">
//codelooru.com
//To get a sheet by index
def sheetByIndex = workBook.Sheets.Item[1]
//To get the active sheet in the workbook
def sheetActive = workBook.ActiveSheet
//To get the sheet by name
def sheetByName = workBook.Sheets('Sheet1')
</pre>
<br />
Now you can access the cell data in the following manner. The first parameter to <code>Cells</code> is the row number and the second parameter is column number.
<br />
<pre class="brush: groovy"> //codelooru.com
def cellValue = sheet.Cells(2,1).Value
</pre>
<br />
To update a cell value :
<br />
<pre class="brush: groovy"> //codelooru.com
sheet.Cells(1,1).Value = 100
</pre>
<br />
If you do not have the file after changes to the cells, you will be prompted with a dialog to save. So, to save the changes in the workbook :
<br />
<pre class="brush: groovy"> //codelooru.com
workBook.save
</pre>
<br />
If you do not wish to save the changes, then set the Saved property to true, like so
<br />
<pre class="brush: groovy"> //codelooru.com
workBook.Saved = true
</pre>
<br />
You can get the row and column count of the sheet, like so
<br />
<pre class="brush: groovy"> //codelooru.com
def rows = sheet.UsedRange.Rows.Count
def cols = sheet.UsedRange.Columns.Count
</pre>
<br />
Remember to close the workbook after the use. Otherwise, you will notice an excel instance in the processes.
<br />
<pre class="brush: groovy"> //codelooru.com
workBook.close()
</pre>
<br />
<h3>
Working Example</h3>
<br />
Here is a sample code that uses all of the above snippets to read the data in an active sheet, increment the value by 1 and save it, assuming that the sheet has integer data.
<br />
<br />
<pre class="brush: groovy">
//codelooru.com
import org.codehaus.groovy.scriptom.ActiveXObject
def excelObj = new ActiveXObject('Excel.Application')
def workBook = excelObj.Workbooks.Open('c:/codelooru.xlsx')
try {
def sheet = workBook.ActiveSheet
def rows = sheet.UsedRange.Rows.Count
def cols = sheet.UsedRange.Columns.Count
//Update the values
1.upto(rows, {row ->
1.upto(cols, {col ->
sheet.Cells(row,col).Value = sheet.Cells(row,col).Value + 1
})
})
//Print the data
1.upto(rows, {row ->
1.upto(cols, {col ->
print sheet.Cells(row,col).Value + '\t'
})
println ''
})
workBook.save
}
finally {
workBook.close()
}
</pre>
<br />
<h3>
Conclusion</h3>
<br />
In this post, you saw how you can work with excel sheets in groovy. The post covered very few capabilities of the Excel COM Object. To explore it further, refer the Excel COM Object model <a href="https://docs.microsoft.com/en-us/office/vba/api/overview/excel/object-model"><b>here</b></a>.
<br />
<br />
<br />
<div style="background-color: #e6f4ff; border-radius: 5px; padding-bottom: 15px; padding-left: 10px; padding-top: 15px;">
<h4>
More Articles on Groovy</h4>
<ul>
<li><a href="https://www.codelooru.com/2017/08/how-to-read-files-in-groovy.html">How to Read Files in Groovy?</a></li>
<li><a href="https://www.codelooru.com/2017/08/how-to-execute-groovy-scripts-in.html">How to Execute Groovy Scripts in Sublime Text?</a></li>
</ul>
</div>
<br />Phee Jayhttp://www.blogger.com/profile/08103990765188490526noreply@blogger.com4tag:blogger.com,1999:blog-8051593896124641807.post-35396631703400440702019-01-28T11:47:00.001-06:002021-02-23T00:16:40.082-06:00Spring MVC - How to handle errors from a controller?<img src="https://4.bp.blogspot.com/-FrtEIxwzQrA/WKFQ8JDEaTI/AAAAAAAAAIQ/0FcKt83eYcoQmPBShBGiFk3Cms_two7iwCLcB/s1600/springlogo.png" style="display: none;" />
In a web application, it is very important to handle errors. Proper error handling would protect the application from several vulnerabilities, including <a href="https://www.owasp.org/index.php/Top_10-2017_A6-Security_Misconfiguration">Security Misconfiguration</a>. In this post, you will see how you can handle exceptions that arise out of a Spring MVC based application.<br />
<a name='more'></a><br />
There are multiple ways to handle exceptions and we will cover them one by one. Let's first create a simple controller like so.<br />
<br />
<pre class="brush: java">@RestController
public class MyController {</pre>
<pre class="brush: java"></pre>
<pre class="brush: java"> private boolean throwError = true;
@GetMapping("/myfirstrequest")
private String myLocalRequestHandler() {
if (throwError) {
throw new MyLocalException("Local exception");
}
else {
return "My Local Response!";
}
}
@GetMapping("/mysecondrequest")
private String mySecondRequestHandler() {
if (throwError) {
throw new MyGlobalException("Global exception");
}
else {
return "My Second Response!";
}
}
@GetMapping("/mythirdrequest")
private String myThirdRequestHandler() {
if (throwError) {
throw new MyOtherException("Other exception");
}
else {
return "My Third Response!";
}
}
}
</pre>
<pre class="brush: java"></pre>
<br />
There are three requests that this controller handles. GET /myfirstrequest, which throws out a MyLocalException, GET /mysecondrequest, which throws out a MyGlobalException and GET /mythirdrequest, which throws out MyOtherException.<br />
<br />
Assume that MyLocalException is thrown only by this controller and MyGlobalException and MyOtherException can be thrown by any controller in the application. Let's see how you can handle these exceptions.<br />
<br />
<h3>
@ExceptionHandler</h3>
<br />
ExceptionHandler annotation can be used to mark a controller method to handle exceptions e.g. in our controller, to handle MyLocalException, we can define an exception handler within the controller as follows.
<br />
<br />
<pre class="brush: java"> @ExceptionHandler({MyLocalException.class})
@ResponseStatus(HttpStatus.I_AM_A_TEAPOT)
private void exceptionHandler(Exception ex, HttpServletRequest request,
HttpServletResponse response) throws IOException {
log.error("Handling My Local Exception : ", ex);
}
</pre>
<br />
Now, when you invoke GET /myfirstrequest, the request handler would throw MyLocalException and framework would invoke the exceptionHandler method. The method accepts multiple optional parameters. The Exception parameter would hold the exception that is being handled. Apart from this, the method can also have parameters for http request, response, session objects, locale and the model itself.
<br />
<br />
If you want to set the HTTP status on the response, then annotate the handler with @ResponseStatus with the status code. The handler method can return ModelAndView, Model, View name or a ResponseBody itself. For a full list of parameter and return types, check the Javadoc for @ExceptionHandler.<br />
<br />
<h3>
@ControllerAdvice</h3>
<br />
ControllerAdvice can be used to handle controller exceptions at a global level. The handlers defined within the ControllerAdvice classes will be invoked for exceptions raised by any controller. ControllerAdvice can also be used to define common binding initializers and ModelAttribute binding. If you want to apply the Advice only on select controllers, then you can set the basePackages and annotations attributes to narrow it down.
You can define a handler with ControllerAdvice as shown below.
<br />
<br />
<pre class="brush: java">@ControllerAdvice(basePackages = {"com.codelooru.web"})
public class ControllerExceptionHandler {
@ExceptionHandler(MyGlobalException.class)
@ResponseStatus(HttpStatus.I_AM_A_TEAPOT)
public void handleGlobalException(Exception ex) {
log.error("Handling My Global Exception : ", ex);
}
}
</pre>
<br />
The handler class above is marked with @ControllerAdvice with a basePackages filtering on "com.codelooru.web". This means it would be applicable only on the classes belonging to "com.codelooru.web" and its sub packages. You would also notice that we still use the same @ExceptionHandler annotation to define the exception handler methods. It behaves exactly the same, except that the scope is broad.<br />
<br />
Now when you invoke GET /mysecondrequest, the request handler would throw MyGlobalException and would be handled by the handleGlobalException method.
<br />
<br />
<h3>
HandlerExceptionResolver</h3>
<br />
HandlerExceptionResolver is an older way of handling global controller exceptions. It exists from the pre-annotations era. Exception handlers should implement the HandlerExceptionResolver interceptor and implement the resolveException method to handle the exceptions. The following is an example of a HandlerExceptionResolver.
<br />
<br />
<pre class="brush: java">@Component
public class MyHandlerExceptionResolver extends AbstractHandlerExceptionResolver {
@Override
protected ModelAndView doResolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
log.error("Handling My Other Exception : ", ex);
return null;
}
}
</pre>
<br />
The class above would handle any exceptions that are thrown out of the controller and not handled by any other exception handler. doResolveException can update the ModelAndView to update the model and route to an error view.<br />
<br />
Now, when you invoke GET /mythirdrequest, the controller would throw the MyOtherException and this would be caught and handled by the MyHandlerExceptionResolver.
<br />
<br />
<div style="background-color: #e6f4ff; border-radius: 5px; padding-bottom: 15px; padding-left: 10px; padding-top: 15px;">
<h4>
More Articles on Spring MVC</h4>
<ul>
<li><a href="http://www.codelooru.com/2017/04/localization-with-spring.html">Localization with Spring</a></li>
<li><a href="http://www.codelooru.com/2015/06/etags-and-browser-cache.html">ETags and Browser Cache</a></li>
<li><a href="http://www.codelooru.com/2010/10/what-does-mvcannotation-driven-do.html">What does mvc:annotation-driven Do?</a></li>
<li><a href="http://www.codelooru.com/2010/10/what-is-sessionattributeatore.html">What Is a SessionAttributeStore? When to Use It?</a></li>
</ul>
</div>
<br />Phee Jayhttp://www.blogger.com/profile/08103990765188490526noreply@blogger.comtag:blogger.com,1999:blog-8051593896124641807.post-56042751106982744542019-01-25T14:20:00.001-06:002019-02-14T16:23:37.326-06:00Java - How to find the IP Address of a host in Java ?In Java, if you are looking to resolve an IP Address from the given hostname, then you can leverage the capabilities provided by <code>InetAddress</code>. It belongs to the <code>"java.net"</code> package and provides various utilities related to resolving addresses and IPs. <br />
<a name='more'></a><br />
The following code e.g. gives you back an IP address for the provided hostname.<br />
<br />
<pre class="brush: java">System.out.println( InetAddress.getByName("myhost").getHostAddress() );
</pre>
<br />
Note that <code>getByName</code> throws an <code>UnknownHostException</code> if it is unable to resolve the host.<br />
<br />
A few other interesting methods available from InetAddress are :<br />
<br />
<code>getCanonicalHostName</code> - This returns the fully qualified hostname, including the domain name.<br />
<code>getHostName</code> - To get the hostname for a given IP address.<br />
<code>getLocalHost</code> - To get the hostname or IP Address of the local machine.<br />
<code>getLoopBackAddress</code> - To get the loopback address of the local machine.<br />
<code>isReachable</code> - To check if the address is reachable within the provided timeout <br />
<br />
The following code snippet shows these methods in use:<br />
<br />
<pre class="brush: java">//Prints the FQN for myhost
System.out.println( InetAddress.getByName("myhost").getCanonicalHostName() );
//Prints the hostname for 11.22.1.38
System.out.println( InetAddress.getByAddress(new byte[]{11, 22, 1, 38}).getHostName() );
//Prints the hostname for the local machine
System.out.println( InetAddress.getLocalHost().getHostName );
//Prints the loopback address of the local machine.
System.out.println( InetAddress.getLoopbackAddress().getHostAddress() );
//Prints true if the machine is reachable.
System.out.println( InetAddress.getByName("myhost").isReachable(10000) );
</pre>
The result would be:
<br />
<pre class="brush: java">myhost.codelooru.com
myhost.codelooru.com
mylocalhost
127.0.0.1
true
</pre>
<pre></pre>
<br />
<br />
<div style="background-color: #e6f4ff; border-radius: 5px; padding-bottom: 15px; padding-left: 10px; padding-top: 15px;">
<h4>
Related Articles</h4>
<ul>
<li><a href="https://www.codelooru.com/2017/08/how-to-create-web-notifications.html">How to Create Web Notifications</a></li>
<li><a href="https://www.codelooru.com/2017/03/deep-copy-java-objects-through.html">Deep Copy Java Objects through Serialization</a></li>
<li><a href="https://www.codelooru.com/2017/02/how-to-timeout-jdbc-queries.html">How to Timeout JDBC Queries</a></li>
<li><a href="https://www.codelooru.com/2017/02/tarlog-eclipse-plugin-for-windows.html">Tarlog - Eclipse Plugin for Windows</a></li>
</ul>
</div>
<br />Phee Jayhttp://www.blogger.com/profile/08103990765188490526noreply@blogger.comtag:blogger.com,1999:blog-8051593896124641807.post-59340323777279329102017-09-02T00:34:00.000-05:002019-02-14T16:24:24.420-06:00Spring - Initializing a Spring Bean<img src="https://4.bp.blogspot.com/-FrtEIxwzQrA/WKFQ8JDEaTI/AAAAAAAAAIQ/0FcKt83eYcoQmPBShBGiFk3Cms_two7iwCLcB/s1600/springlogo.png" style="display: none;" />
It is often required to run some custom code on initialization of a Spring bean. e.g. to check for mandatory properties or establish initial connections. Spring provides a few constructs to initialize the beans after they are injected with the properties.
<br />
<a name='more'></a><br />
<br />
<h3>
@PostConstruct</h3>
<br />
This is a method level annotation, available through the standard Java extensions package. It should be applied to methods that need to be executed after the properties are injected to the beans. Spring supports this annotation for initialization.
<br />
<br />
<pre class="brush: java">import javax.annotation.PostConstruct;
import org.springframework.util.Assert;
public class UserService {
private String userprops;
public String getUserprops() {
return userprops;
}
public void setUserprops(String userprops) {
this.userprops = userprops;
}
@PostConstruct
public void initWithPostConstuctor() {
System.out.println("PostConstruct method called");
Assert.notNull(userprops);
}
}
</pre>
<br />
<br />
<h3>
init-method</h3>
<br />
<code>init-method</code> is used for XML based bean configuration. It can be configured with a zero-parameter method to initialize the bean.
<br />
<br />
<pre class="brush: xml"> <bean class="com.codelooru.pojo.UserService" id="userService" init-method="initWithXMLInitMethod">
<property name="userprops" value="userprops">
</property></bean>
</pre>
<br />
<pre class="brush: java">import org.springframework.util.Assert;
public class UserService {
private String userprops;
public String getUserprops() {
return userprops;
}
public void setUserprops(String userprops) {
this.userprops = userprops;
}
public void initWithXMLInitMethod() {
System.out.println("init-method called");
Assert.notNull(userprops);
}
}
</pre>
<br />
<br />
<h3>
InitializingBean</h3>
<br />
<code>InitializingBean</code> is an interface with one single method viz. <code>afterPropertiesSet</code>. Beans can implement this interface, and the method would be invoked after all the properties are set on the Bean. It is usually the least preferred method of initialization as it strongly couples the class to Spring.
<br />
<br />
<pre class="brush: java">import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
public class UserService implements InitializingBean {
private String userprops;
public String getUserprops() {
return userprops;
}
public void setUserprops(String userprops) {
this.userprops = userprops;
}
public void afterPropertiesSet() throws Exception {
System.out.println("afterPropertiesSet for InitializingBean called");
Assert.notNull(userprops);
}
}
</pre>
<br />
<br />
<h3>
Sample Code</h3>
<br />
In this post, we explored 3 ways to initialize a Spring bean. Check out a working example for initialization in this <a href="https://github.com/codelooru/springmvc/tree/master/SpringInitBean"><b>GitHub project</b></a>.
<br />
<br />
<div style="background-color: #e6f4ff; border-radius: 5px; padding-bottom: 15px; padding-left: 10px; padding-top: 15px;">
<h4>
Related Articles</h4>
<ul>
<li><a href="https://www.codelooru.com/2017/04/spring-custom-namespaces.html">How to Create Custom Namespaces and Handlers in Spring</a></li>
<li><a href="https://www.codelooru.com/2017/04/localization-with-spring.html">Localization with Spring</a></li>
<li><a href="https://www.codelooru.com/2017/03/spring-boot-create-deployable-war.html">Spring Boot - How to Create a Deployable War</a></li>
<li><a href="https://www.codelooru.com/2017/02/overriding-spring-beans-with-aliases.html">Overriding Spring Beans with Aliases</a></li>
</ul>
</div>
<br />Phee Jayhttp://www.blogger.com/profile/08103990765188490526noreply@blogger.com0tag:blogger.com,1999:blog-8051593896124641807.post-3563276418778626382017-08-04T00:29:00.001-05:002019-02-14T16:26:02.728-06:00Groovy - How to Execute Groovy Scripts in Sublime Text?<img border="0" data-original-height="74" data-original-width="150" src="https://2.bp.blogspot.com/-SXid_OR8Yxw/WYQEEZcT7FI/AAAAAAAAAPE/E6QuZVR9mckAQ__nqAL72W0awz0EgBMHQCLcBGAs/s1600/Groovy-logo-150.png" style="display: none;" />
This article covers the steps to setup Sublime Text to execute Groovy scripts. <br />
<a name='more'></a><br />
<br />
<br />
<h4>
Step 1</h4>
<br />
Create a new file viz. <code>groovy.sublime-build</code> and put the following JSON content in there. Replace the path to <code>groovy.bat</code> with the right one on your machine.
<br />
<br />
<pre class="brush: js">{
"cmd": ["C:\\groovy-2.4.12\\bin\\groovy.bat","$file"],
"selector": "source.groovy"
}
</pre>
<br />
<br />
<h4>
Step 2</h4>
<br />
Save this file to the following location. The location may vary based on where Windows is installed and the login id.
<br />
<br />
<code>C:\Users\{{youruserid}}\AppData\Roaming\Sublime Text 3\Packages\User\</code>
<br />
<br />
<h4>
Step 3</h4>
<br />
Close and Reopen Sublime Text.
<br />
<br />
<h4>
Step 4</h4>
<br />
To run the groovy script, open the .groovy file in Sublime Text. While it's in the active view, select <i>[ Tools->Build System->groovy ]</i> or <i>[ Tools->Build System->Automatic ]</i> and press <code>Ctrl+B</code>. This will execute the script and output the results on the Sublime Text console.
<br />
<br />
<h3>
Some explanation for the above:</h3>
<br />
In Sublime Text, <i>Build System</i> can be created for any script by creating a file with <i>.sublime-build</i> extension. This file holds the instructions to execute a script. These instructions are in JSON format. On a restart, the filename will be shown under <i>Tools->Build System</i>.
<br />
<br />
The <code>"selector"</code> in the <i>sublime-build</i>, is required only if you want Sublime Text to identify the Build System in <b>Automatic</b> mode. It indicates the extension of the file for which the current <i>sublime-build</i> should be executed.
<br />
<br />
<br />
<div style="background-color: #e6f4ff; border-radius: 5px; padding-bottom: 15px; padding-left: 10px; padding-top: 15px;">
<h4>
More Articles on Groovy</h4>
<ul>
<li><a href="https://www.codelooru.com/2017/08/how-to-read-files-in-groovy.html">How to Read Files in Groovy?</a></li>
<li><a href="https://www.codelooru.com/2019/02/read-and-write-to-excel-groovy.html">How to read and write to excel sheets with Groovy?</a></li>
</ul>
</div>
<br />Phee Jayhttp://www.blogger.com/profile/08103990765188490526noreply@blogger.com2tag:blogger.com,1999:blog-8051593896124641807.post-41985947928061513702017-08-03T23:16:00.000-05:002019-02-14T16:26:55.691-06:00How to Read Files in Groovy?<img border="0" data-original-height="74" data-original-width="150" src="https://3.bp.blogspot.com/-SXid_OR8Yxw/WYQEEZcT7FI/AAAAAAAAAPE/waRR3slP75E2rQro8q0wHydcHTzWhvHLQCPcBGAYYCw/s1600/Groovy-logo-150.png" style="display: none;" />
This article shows various ways of reading a text file in groovy.<br />
<a name='more'></a><br />
<br />
<h3>
Example 1:</h3>
<br />
This example uses the <code>readLines</code> method of the <code>File</code> class. <i>readLines</i> returns back a list of lines as Strings.
<br />
<pre class="brush: groovy">def myFile = new File("codelooru.txt")
def lines = myFile.readLines()
lines.each {line ->
println line
}
</pre>
<br />
<h3>
Example 2:</h3>
<br />
This example uses the <code>withReader</code> method of the <i>File</i> class. <i>withReader</i> creates a <code>BufferedReader</code> with the File and passes it to the Closure. The reader can be used to read a line or characters. The reader is closed once it exits the Closure.
<br />
<pre class="brush: groovy">def myFile = new File("codelooru.txt")
myFile.withReader {reader ->
println reader.readLine()
}
</pre>
<br />
<h3>
Example 3:</h3>
<br />
This example uses the <code>eachLine</code> method of <i>File</i> class. <i>eachLine</i> reads the file line by line and passes each line to the Closure. Again here, the reader is created implicitly and closed on exiting the Closure.
<br />
<pre class="brush: groovy">def myFile = new File("codelooru.txt")
myFile.eachLine {line ->
println line
}
</pre>
<br />
<h3>
Example 4:</h3>
<br />
This example uses the <code>eachLine</code> method that also takes the line number. The line number starts at 1 and can be used to process the data based on line numbers. In the example below, the first 4 lines of the file are skipped.
<br />
<pre class="brush: groovy">def myFile = new File("codelooru.txt")
myFile.eachLine {line, number ->
if(number <= 4)
return
println line
}
</pre>
<br />
<h3>
Example 5:</h3>
<br />
This example is the simplest of all methods. It uses the <code>getText</code> method of <i>File</i> to read the whole file into a String.
<br />
<pre class="brush: groovy">String fileContent = new File('codelooru.txt').text
println fileContent
</pre>
<br />
<br />
<br />
<div style="background-color: #e6f4ff; border-radius: 5px; padding-bottom: 15px; padding-left: 10px; padding-top: 15px;">
<h4>
More Articles on Groovy</h4>
<ul>
<li><a href="https://www.codelooru.com/2019/02/groovy-what-is-memoization.html">Groovy - What is Memoization?</a></li>
<li><a href="https://www.codelooru.com/2019/02/read-and-write-to-excel-groovy.html">How to read and write to excel sheets with Groovy?</a></li>
<li><a href="https://www.codelooru.com/2017/08/how-to-execute-groovy-scripts-in.html">How to Execute Groovy Scripts in Sublime Text?</a></li>
</ul>
</div>
<br />Phee Jayhttp://www.blogger.com/profile/08103990765188490526noreply@blogger.com0tag:blogger.com,1999:blog-8051593896124641807.post-31964207565482076492017-08-01T00:05:00.000-05:002019-02-14T16:29:58.523-06:00How to Create Web Notifications<img src="https://3.bp.blogspot.com/-xfgA5Z6YS5M/WYABEqIBZwI/AAAAAAAAAOI/NoXlqcPyqGYBOxGAexvBE7uYLJxPk5iGwCLcBGAs/s1600/notifbell.PNG" style="display: none;" />
<b>Web Notifications</b> provide ways for websites to display notifications to users e.g. alerting the user about a business event or success/failure of an asynchronous operation. <br />
<a name='more'></a>They are displayed at the system level, which means that even if you are on a different window or tab or focused out of the browser, you can still see those notifications. Notifications are supported by most of the modern browsers (chrome, firefox, edge, safari, and others).
<br />
<br />
Here is a working <a href="http://www.codelooru.com/p/browser-notification-example.html"><b>example of notifications</b></a>.
<br />
<br />
The W3C specification for this API can be found <b><a href="https://www.w3.org/TR/notifications">here</a></b>.
<br />
<br />
<h3>
requestPermission</h3>
<br />
Notifications can be displayed only if the user grants permission to show notifications. If the user denies it, then the user can't see the notification, even if it is created.
<br />
<br />
To request permissions from the user, invoke the following:
<br />
<br />
<br />
<pre class="brush: js">window.Notification.requestPermission();
</pre>
<br />
<br />
<code>requestPermission</code> returns a <i>promise</i> with the result of the user's selection. The result would be
<br />
<ul>
<li><b>default</b> - if the user has not chosen an option. This would behave the same as denied.</li>
<li><b>denied</b> - if the user has denied permission</li>
<li><b>granted</b> - if the user allows notifications</li>
</ul>
<br />
<br />
Once the user grants/denies the permission, she is not prompted for permissions again. The result would return the choice that was made. The result of the permissions can be accessed in the following way:
<br />
<br />
<pre class="brush: js">window.Notification.requestPermission().then(function(result) {
console.log(result);
//Perform activities based on the permission
}
</pre>
<br />
<br />
<h3>
Create Notification</h3>
<br />
A new notification can be created as below:
<br />
<br />
<pre class="brush: js">notification = new window.Notification('Notification Title',
{
body: 'Notification Body',
icon: 'https://www.codelooru.com/icon.png',
dir: 'ltr' //or rtl
}
);
</pre>
<br />
<br />
The constructor for Notification takes title and options as the parameters.
<br />
<code>title</code> is a mandatory parameter. It is used as the title of the notification message.
<br />
<code>options</code> are optional.
<br />
<ul>
<li>under options, you have <i>body</i> which is used as the body of the notification message.</li>
<li>and then you have <i>icon</i> for displaying an icon on the notification</li>
<li><i>dir</i> is for direction and has values rtl for right-to-left or ltr for left-to-right</li>
</ul>
<br />
<br />
The example above would display the following notification.
<br />
<br />
<img border="1" data-original-height="261" data-original-width="554" src="https://2.bp.blogspot.com/-Ix21Y811JqQ/WYAE7VkGoAI/AAAAAAAAAOY/NoPX7kwlFUQAyiXMyJZGpcFMCVhkcEI-ACLcBGAs/s1600/notificationexample.png" />
<br />
<br />
<h3>
Events on Notification</h3>
<br />
The following events are supported on the notifications
<br />
<ul>
<li><code>onclick</code> - occurs when the user clicks on the notification</li>
<li><code>onshow</code> - occurs when the notification is shown</li>
<li><code>onclose</code> - occurs when the user closes the notification</li>
<li><code>onerror</code> - occurs when there is an error showing the notification to the user</li>
</ul>
<br />
<br />
The following example of an event listener would open a new window on click:
<br />
<br />
<pre class="brush: js">notification.onclick = function(event) {
window.open('http://www.codelooru.com');
this.close();
};
</pre>
<br />
<br />
<h3>
Working Example</h3>
<br />
You would find a working example of notification on the <a href="http://www.codelooru.com/p/browser-notification-example.html"><b>page here</b></a>. View the source of the page for the implementation details.
<br />
<br />Phee Jayhttp://www.blogger.com/profile/08103990765188490526noreply@blogger.com0tag:blogger.com,1999:blog-8051593896124641807.post-36162521514388416892017-07-12T01:27:00.000-05:002019-02-25T11:59:13.635-06:00Spring - Lookup Method or Method Injection<img src="https://4.bp.blogspot.com/-FrtEIxwzQrA/WKFQ8JDEaTI/AAAAAAAAAIQ/0FcKt83eYcoQmPBShBGiFk3Cms_two7iwCLcB/s1600/springlogo.png" style="display: none;" /> Most common injection mechanisms used in Spring are <i>Constructor </i>and <i>Property </i>injections. In both the mechanisms, the injection happens only once during the initialization of the Bean. They also require a concrete method defined, e.g., a constructor method for constructor injections and a setter method for property injection.<br />
<a name='more'></a><br />
What if you would like to inject a prototype bean and get a new instance, every time you invoke the getter. In other words, how do you implement a factory method that would return a new bean instance without explicitly implementing the method (to lookup the ApplicationContext)?<br />
<br />
For such scenarios, Spring provides a third injection mechanism viz. <b>Lookup-Method</b>. It is also known as <b>Method Injection</b>. In this mechanism, you would usually create an abstract method to lookup the data and spring would inject a concrete implementation of the method on bean initialization.<br />
<br />
Let's explore this injection through a few examples.<br />
<br />
<h3>
Example classes</h3>
<br />
User POJO that holds the user details:<br />
<pre class="brush:java">public class User {
private String name;
private String type;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
</pre>
<br />
<br />
The User service class that provides operations for getting the user data:<br />
<pre class="brush:java">public abstract class UserService {
/**
* Initialize a new User instance and return it (always a new instance).
* @return
*/
public abstract User getInitializedUserInstance();
/**
* Return the default Operations User (singleton)
* @return
*/
public abstract User getOperationsUser();
}
</pre>
<br />
<br />
Notice that we have defined an abstract class with two abstract methods for fetching the user data. The Javadoc for the methods explain the intent.<br />
<br />
<h3>
Bean Definitions</h3>
<br />
Now, let's define two beans for the User:<br />
<pre class="brush:xml">
</pre>
<br />
<code>initUserBean</code> is defined as a prototype. So, whenever the ApplicationContext is invoked for this bean, it would return a new instance.<br />
<code>opsUserBean</code> is defined as a singleton (no scope means singleton). The ApplicationContext would always return the same instance when invoked.<br />
<br />
Let's define the <code>userService</code>bean in the following manner:<br />
<pre class="brush:xml">
</pre>
<br />
<br />
When this bean is instantiated, Spring generates a subclass using <b>CGLIB</b> and implements the abstract methods to return the beans as specified in the <code>lookup-method</code>.<br />
Instead of an abstract method, if the service operation was defined as a concrete method, Spring would have overridden the method and still returned the bean value as configured.<br />
<br />
<h3>
Testing the example</h3>
<br />
Let's test the User Service example with the code below:<br />
<br />
<pre class="brush:java"> ClassPathXmlApplicationContext appcontext = new ClassPathXmlApplicationContext("beans.xml");
UserService service = appcontext.getBean("userService", UserService.class);
User newUser1 = service.getInitializedUserInstance();
User newUser2 = service.getInitializedUserInstance();
Assert.isTrue(newUser1.getType().equals("admin"));
Assert.isTrue(newUser1 != newUser2);//scope of prototype should return unique instances
User opsUser1 = service.getOperationsUser();
User opsUser2 = service.getOperationsUser();
Assert.isTrue(opsUser1.getType().equals("operator"));
Assert.isTrue(opsUser1.getName().equals("John"));
Assert.isTrue(opsUser1 == opsUser2);//should return the same instance
appcontext.close();
</pre>
<br />
This test would pass all the Asserts. Notice that <code>getInitializedUserInstance</code> would return a new instance everytime it's called and <code>getOperationsUser</code> would return the same instance.<br />
<br />
<h3>
@Lookup</h3>
<br />
Spring provides the <code>@Lookup</code> annotation for annotation based configuration.<br />
<br />
The User and UserService beans from the example can be defined as below, to achieve the same results. Except, two separate bean instances cannot be defined for User; <b>as @Bean is not supported for Lookup methods</b>.<br />
<br />
<pre class="brush:java">@Component("initUserBean")
@Scope("prototype")
public class User {
private String name;
private String type = "admin";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
</pre>
<br />
<br />
<pre class="brush:java">@Component("userService")
public abstract class UserService {
/**
* Initialize a new User instance and return it (always a new instance).
* @return
*/
@Lookup(value="initUserBean")
public abstract User getInitializedUserInstance();
}
</pre>
<br />
<br />
<h3>
Sample Application</h3>
<br />
In this post, we explored the Lookup Method or Method Injection through a few examples. It may not be as frequently used as the other injection methods, but it definitely provides a good alternative for the AbstractFactory pattern. Check out a working example in this <a href="https://github.com/codelooru/springmvc/tree/master/LookupMethodProject"><b>GitHub project</b></a>.<br />
<br />Phee Jayhttp://www.blogger.com/profile/08103990765188490526noreply@blogger.com0tag:blogger.com,1999:blog-8051593896124641807.post-47805810318298755462017-04-28T00:32:00.000-05:002019-02-14T16:37:04.239-06:00How to Create Custom Namespaces and Handlers in Spring<img src="https://4.bp.blogspot.com/-FrtEIxwzQrA/WKFQ8JDEaTI/AAAAAAAAAIQ/0FcKt83eYcoQmPBShBGiFk3Cms_two7iwCLcB/s1600/springlogo.png" style="display: none;" />
<b>Custom namespaces</b> in spring are a way to replace the complex bean definitions with a more user-friendly configuration.
<br />
<br />
Spring itself provides several namespaces out of the box. e.g. <br />
<a name='more'></a><code><mvc:annotation-driven/></code>. See <b><a href="http://www.codelooru.com/2010/10/what-does-mvcannotation-driven-do.html">this post</a></b> for what <code><mvc:annotation-driven/></code> translates to.
<br />
<br />
Let's take an example scenario and run through the steps for creating a custom namespace and its handler.<br />
<br />
<h3>
Example for the namespace</h3>
<br />
Consider the sample classes.
<br />
<br />
<pre class="brush:java">public class MyDAO {
private List<String> fields;
public List<String> getFields() {
return fields;
}
public void setFields(List<String> fields) {
this.fields = fields;
}
}
</pre>
<br />
<pre class="brush:java">public class MyService {
private String serviceName;
private MyDAO defaultDao;
private Map<String, MyDAO> daoRegistry;
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public MyDAO getDefaultDao() {
return defaultDao;
}
public void setDefaultDao(MyDAO defaultDao) {
this.defaultDao = defaultDao;
}
public Map<String, MyDAO> getDaoRegistry() {
return daoRegistry;
}
public void setDaoRegistry(Map<String, MyDAO> daoRegistry) {
this.daoRegistry = daoRegistry;
}
}
</pre>
<br />
Let's say we use the following set of beans to instantiate these classes.
<br />
<br />
<pre class="brush:xml"> <bean class="com.codelooru.dos.MyService" id="myservice-123">
<property name="defaultDao" ref="mydao-123">
<property name="serviceName" value="myservice">
<property name="daoRegistry">
<map>
<entry key="dao1" value-ref="mydao-123">
</entry></map>
</property>
</property></property></bean>
<bean class="com.codelooru.dos.MyDAO" id="mydao-123">
<property name="fields">
<list>
<value>field1</value>
<value>field2</value>
<value>field3</value>
</list>
</property>
</bean>
</pre>
<br />
<br />
Now, I want to replace these bean definitions with something very simple, like
<br />
<br />
<pre class="brush:xml"><createservice daoid="mydao-123" fields="field1,field2,field3" serviceid="myservice-123">
</createservice></pre>
<br />
<br />
Here are the steps to achieve this
<br />
<br />
<h3>
Step 1: Schema Definition</h3>
<br />
Define an XML schema definition for our custom XML element.<br />
<br />
The schema for <code>createservice</code> element would be the following, with the custom namespace being <code>http://www.codelooru.com/custns</code>
<br />
<br />
<pre class="brush:xml"><xs:schema elementformdefault="qualified" targetnamespace="http://www.codelooru.com/custns" xmlns:tns="http://www.codelooru.com/custns" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="createservice">
<xs:complextype>
<xs:attribute name="serviceId" type="xs:string" use="required">
<xs:attribute name="daoId" type="xs:string" use="required">
<xs:attribute name="fields" type="xs:string" use="required">
</xs:attribute></xs:attribute></xs:attribute></xs:complextype>
</xs:element>
</xs:schema>
</pre>
<br />
<br />
<h3>
Step 2: NameSpaceHandler</h3>
<br />
Create a namespace handler for the above-defined namespace. The custom namespace handlers should implement the <code>org.springframework.beans.factory.xml.NamespaceHandler</code> interface. Spring provides a convenience class <code>org.springframework.beans.factory.xml.NamespaceHandlerSupport</code>, which provides a way to register multiple namespace parsers through a single handler.
<br />
<br />
<pre class="brush:java">public class CustomNamespaceHandler extends NamespaceHandlerSupport {
public void init() {
registerBeanDefinitionParser("createservice", new CreateServiceNamespaceBeanDefinitionParser());
}
}
</pre>
<br />
<br />
The init method should register all bean-definition parsers for the required elements.
<br />
<br />
For the <code>createservice</code> element, we will define a new <code>BeanDefinitionParser</code>, which is covered in step 5 in detail.
<br />
<br />
<h3>
Step 3: spring.handlers</h3>
<br />
Create a file <code>"spring.handlers"</code> under <code>META-INF</code> and register the handler for the namespace.
<br />
<br />
<pre class="brush:java">http\://www.codelooru.com/custns=com.codelooru.custns.CustomNamespaceHandler
</pre>
<br />
Spring would call this handler when it encounters the namespace in a spring bean XML.<br />
<br />
<h3>
Step 4: spring.schemas</h3>
<br />
Create a file <code>"spring.schemas"</code> under <code>META-INF</code> and register the schema definition file for the namespace.<br />
<br />
<pre class="brush:java">http\://www.codelooru.com/custns.xsd=schema.xsd
</pre>
<br />
Spring would validate the elements in the bean XML against the provided schema definition.<br />
<br />
<h3>
Step 5: BeanDefinitionParser</h3>
<br />
Create a custom <code>BeanDefinitionParser</code>, which will parse the <code>createservice</code> element and generate bean definitions. The parser should implement the <code>org.springframework.beans.factory.xml.BeanDefinitionParser</code>.<br />
<br />
<pre class="brush:java">public class CreateServiceNamespaceBeanDefinitionParser implements BeanDefinitionParser {
public BeanDefinition parse(Element element, ParserContext parserContext) {
//parsing <custns:abcd service="myservice" dao="mydao" fields="field1,field2,field3"/>
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(MyDAO.class);
builder.addPropertyValue("fields", Arrays.asList(element.getAttribute("fields").split(",")));
String daoId = element.getAttribute("daoId");
parserContext.getRegistry().registerBeanDefinition(daoId, builder.getBeanDefinition());
ManagedMap<Object, Object> map = new ManagedMap<Object, Object>();
map.put("dao1", new RuntimeBeanReference(daoId));
builder = BeanDefinitionBuilder.genericBeanDefinition(MyService.class);
builder.addPropertyValue("serviceName", "myservice");
builder.addPropertyReference("defaultDao", daoId);
builder.addPropertyValue("daoRegistry", map);
parserContext.getRegistry().registerBeanDefinition(element.getAttribute("serviceId"), builder.getBeanDefinition());
return null;
}
}
</pre>
<br />
<br />
This <code>BeanDefinitionParser</code><br />
<br />
<ul>
<li>Implements the <code>parse</code> method, which provides you with the <code>org.w3c.dom.Element</code> object for the <code>createservice</code> element and the <code>ParserContext</code>. </li>
<li><code>ParserContext</code>provides you access to the <code>BeanDefinitionRegistry</code>, which, we will use to register our beans. </li>
<li><code>BeanDefinitionBuilder.genericBeanDefinition(Someclass)</code>, creates a new bean-definition for the provided class. </li>
<li>You can set the value of a property by using <code>addPropertyValue</code> on the builder. The first param would be the property name and the second param would be the actual value. Values can be of any type. </li>
<li>If you want to set a property to a reference bean, then use <code>RuntimeBeanReference</code>.</li>
<li>If your value is a list that has one or more references, then use <code>org.springframework.beans.factory.support.ManagedList</code> to define the list. </li>
<li>If your value is a map that has one or more references, then use <code>org.springframework.beans.factory.support.ManagedMap</code> to define the map. </li>
<li>You can set the property to reference another bean using <code>addPropertyReference</code>. The first param would be the property name and the second param would be the name of the referenced bean. </li>
<li>Once the bean is defined, it can be registered through the <code>parserContext.getRegistry().registerBeanDefinition</code> method. It takes the <code>id</code> of the bean as the first parameter and <code>BeanDefinition</code> as the second.</li>
</ul>
<br />
<br />
<h3>
Sample Application</h3>
<br />
A working sample is available at this <b><a href="https://github.com/codelooru/springmvc/tree/master/NamespaceHandling">GitHub project</a></b>.
<br />
<br />
<br />
<div style="background-color: #e6f4ff; border-radius: 5px; padding-bottom: 15px; padding-left: 10px; padding-top: 15px;">
<h4>
Related Articles</h4>
<ul>
<li><a href="https://www.codelooru.com/2017/04/localization-with-spring.html">Localization with Spring</a></li>
<li><a href="https://www.codelooru.com/2017/03/spring-boot-create-deployable-war.html">Spring Boot - How to Create a Deployable War</a></li>
<li><a href="https://www.codelooru.com/2017/09/initializing-spring-bean.html">Initializing a Spring Bean</a></li>
<li><a href="https://www.codelooru.com/2017/02/overriding-spring-beans-with-aliases.html">Overriding Spring Beans with Aliases</a></li>
</ul>
</div>
<br />Phee Jayhttp://www.blogger.com/profile/08103990765188490526noreply@blogger.com0tag:blogger.com,1999:blog-8051593896124641807.post-4424125775874670122017-04-13T00:47:00.001-05:002019-02-14T16:40:22.661-06:00Localization with Spring<img src="https://4.bp.blogspot.com/-FrtEIxwzQrA/WKFQ8JDEaTI/AAAAAAAAAIQ/0FcKt83eYcoQmPBShBGiFk3Cms_two7iwCLcB/s1600/springlogo.png" style="display: none;" />
Localization enables applications to cater to users of different locations and languages. Spring, as usual, has support for this aspect as well.
<br />
<br />
Before jumping into what Spring has to offer, let's explore what we get from Java itself.<br />
<a name='more'></a><br />
<h3>
</h3>
<h3>
Locale</h3>
<br />
Java provides a <code>java.util.Locale</code> class to represent a locale. <code>Locale</code> holds both the language and region code.
<br />
<br />
The Locale class can be instantiated using the language/locale
<br />
<pre class="brush:java">new Locale("jp", "JP")
</pre>
<br />
<code>Locale</code> also provides predefined constants for several locales. They can be used if the locale is a known one.
<br />
<br />
<pre class="brush:java">Locale.FRENCH
Locale.SIMPLIFIED_CHINESE
</pre>
<br />
The default locale can be obtained through
<br />
<br />
<pre class="brush:java">Locale.getDefault()
</pre>
<br />
<h3>
Resource bundles</h3>
<br />
Java provides a way to define locale-specific resources through <i>resource bundles</i>. The bundles are nothing but simple properties files with key-values. They follow a simple naming convention, to help applications resolve them based on the locale.
<br />
<br />
e.g.<br />
<code>mypagelabels_ja.properties</code> is used to define a mypagelabels bundle for the Japanese locale.
<code>mypagelabels_en_US.properties</code> is used to define a bundle for the English language of US region.<br />
<br />
The extra country suffix is useful for defining bundles for countries that may have the same language but different spellings, meanings or slangs.
<br />
<br />
When no suffixes are provided (<code>mypagelabels.properties</code>), the bundle is considered to be used for default locale of the system.
<br />
<br />
A few example bundles below
<br />
<br />
<b>mypagelabels_en_US.properties
</b><br />
<pre class="brush:java">greetingtext=Hello Martians
goodbyetext=Have a great day!!
</pre>
<br />
<b>mypagelabels_es_ES.properties
</b><br />
<pre class="brush:java">greetingtext=Hola Marcianos
goodbyetext=Que tengas un gran dÃa
</pre>
<h4>
</h4>
<h4>
Reading resource bundles</h4>
<br />
Using Java's <code>java.util.ResourceBundle</code>, you can read a resource bundle from classpath for a given basename and locale. If there is no separate bundle available for the provided locale, then the default bundle is loaded.
<br />
<br />
<pre class="brush:java"> ResourceBundle resources = ResourceBundle.getBundle("mypagelabels", new Locale("es", "ES"));
System.out.println(resources.getString("greetingtext"));
resources = ResourceBundle.getBundle("mypagelabels", Locale.getDefault());
System.out.println(resources.getString("greetingtext"));
</pre>
<br />
<h3>
Spring ResourceBundleMessageSource</h3>
<code><br /></code>
<code>MessageSource(s)</code> in spring help resolve messages that are parameterized. And, of course, it also supports the localization of those messages.
<br />
<br />
<code>ResourceBundleMessageSource</code> is a <code>MessageSource</code> that resolves messages from the resource bundles.
<br />
<br />
Consider the resource bundle and the following code snippet<br />
<b><br /></b>
<b>mypagelabels_es_ES.properties
</b><br />
<pre class="brush:java">greetingtext=Hola {0}
</pre>
<br />
<br />
<pre class="brush:java">ResourceBundleMessageSource resbundleMsfSrc = new ResourceBundleMessageSource();
resbundleMsfSrc.setBasename("mypagelabels");
System.out.println(resbundleMsfSrc.getMessage("greetingtext", new Object[]{"Mario"}, new Locale("es", "ES")));
</pre>
<br />
The example above would output<br />
<code>"Hola Mario".</code>
<br />
<br />
It would first resolve the "<code>mypagelabels</code>" bundle that corresponds to <code>es_ES</code> locale, then it resolves the message corresponding' to "<code>greetingtext</code>", and then it replaces the parameter placeholders with the provided params, which is "<code>Mario</code>" in our case.
<br />
<br />
Note that the placeholders start with number 0. i.e. <code>{0}, {1}, {2}</code>, etc.<br />
<br />
<code><b>ReloadableResourceBundleMessageSource</b></code> is an alternative to <code>ResourceBundleMessageSource</code>, that can resolve messages from the resource bundles without having to restart the JVM. You can make changes to the resource bundle while the application is running and it would resolve it to the latest change.
<br />
<h3>
</h3>
<h3>
</h3>
<h3>
Locale Resolution for MVC apps</h3>
<br />
Spring MVC provides a few components for resolving the user locale and present her with localized content.
<br />
<br />
To make the application locale aware, you need a <code>LocaleResolver</code> and/or a <code>LocaleChangeInterceptor</code>. And you would register them through the web configuration in the following manner.
<br />
<br />
<pre class="brush:java">@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
@Bean
public LocaleResolver sessionLocaleResolver() {
AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
return localeResolver;
}
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
// This interceptor would intercept every single request and set the
// locale value from the param name provided on the resolver.
//Useful only if the locale value is available through a request parameter.
LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
interceptor.setParamName("mylocale");
return interceptor;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
}
</pre>
<h3>
</h3>
<h3>
</h3>
<h3>
LocaleResolver</h3>
<code><br /></code>
<code>LocaleResolver</code>, as the name suggests, is responsible for resolving the locales. It is used throughout the Spring MVC workflow for fetching the user locale. It is a simple interface with two methods.
<br />
<br />
<pre class="brush:java"> //Returns the locale for the given request
Locale resolveLocale(HttpServletRequest request);
//Method to set a locale value. Depending upon the LocaleResolver,
// the locale can be set on the request, response or on to something else altogether.
void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale);
</pre>
<br />
Spring provides several flavors of <code>LocaleResolvers</code> out of the box.
<br />
<h4>
</h4>
<h4>
</h4>
<h4>
AcceptHeaderLocaleResolver</h4>
<br />
It creates a locale object using the "<code>accept-language</code>" header of the HTTP request and returns it. If the header is not present, then the default locale set on the resolver is used.
<br />
<br />
There are browser extensions available that can be used to set different locales in the request. e.g. <a href="https://chrome.google.com/webstore/detail/quick-language-switcher/pmjbhfmaphnpbehdanbjphdcniaelfie?hl=en">Quick Language Switch extension</a> in chrome.<br />
<h4>
</h4>
<h4>
</h4>
<h4>
SessionLocaleResolver</h4>
<br />
It looks up for an attribute viz. "<code>SessionLocaleResolver.LOCALE</code>" in the HTTP Session and returns the Locale object corresponding to that value. If there is no attribute set on the session, then it would return the default locale that was set on the resolver.
<br />
<br />
You can set the locale attribute based on user preferences, on login. Or you can set the locale in the session when the user switches to the preferred locale. It can be used in many custom ways to set the user locale.
<br />
<h4>
</h4>
<h4>
</h4>
<h4>
FixedLocaleResolver</h4>
<br />
This resolver always returns a fixed locale i.e. the one that was set on the resolver when it was created. I can't think of any good reason for using this resolver, except for test purposes.
<br />
<h3>
</h3>
<h3>
</h3>
<h3>
LocaleChangeInterceptor</h3>
<code><br /></code>
<code>LocaleChangeInterceptor</code> is useful if you would like to send the locale information through HTTP request parameters. It intercepts every single request and if the locale parameter is found, then it sets it on the localeResolver. It can't be used with <code>FixedLocaleResolver</code> or <code>AcceptHeaderLocaleResolver</code>, as they do not support setting of locales.
<br />
<br />
It can be used to set the locale on the SessionLocaleResolver or if you have a custom resolver that's more geared towards request specific locale handling.
<br />
<h3>
</h3>
<h3>
</h3>
<h3>
RequestContextUtils</h3>
<code><br /></code>
<code>org.springframework.web.servlet.support.RequestContextUtils</code> provides utility methods to get locale and localeResolver, in case you need them for your own custom purposes.
<br />
<br />
<pre class="brush:java"> Locale curlocale = RequestContextUtils.getLocale(request);
LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
</pre>
<span style="display: none;">
</span>
<br />
<h3>
</h3>
<h3>
Sample Application</h3>
<br />
Check out the sample application that's configured with LocaleResolvers in this <b><a href="https://github.com/codelooru/springmvc/tree/master/LocaleTestApp">GitHub project</a></b>.
<br />
<br />
<div style="background-color: #e6f4ff; border-radius: 5px; padding-bottom: 15px; padding-left: 10px; padding-top: 15px;">
<h4>
Related Articles</h4>
<ul>
<li><a href="https://www.codelooru.com/2017/04/spring-custom-namespaces.html">How to Create Custom Namespaces and Handlers in Spring</a></li>
<li><a href="https://www.codelooru.com/2017/03/spring-boot-create-deployable-war.html">Spring Boot - How to Create a Deployable War</a></li>
<li><a href="https://www.codelooru.com/2017/09/initializing-spring-bean.html">Initializing a Spring Bean</a></li>
<li><a href="https://www.codelooru.com/2017/02/overriding-spring-beans-with-aliases.html">Overriding Spring Beans with Aliases</a></li>
</ul>
</div>
<br />Phee Jayhttp://www.blogger.com/profile/08103990765188490526noreply@blogger.com0tag:blogger.com,1999:blog-8051593896124641807.post-42846005355225442272017-03-29T06:35:00.002-05:002019-02-14T16:41:39.590-06:00Spring Boot - How to Create a Deployable War<img src="https://4.bp.blogspot.com/-FrtEIxwzQrA/WKFQ8JDEaTI/AAAAAAAAAIQ/0FcKt83eYcoQmPBShBGiFk3Cms_two7iwCLcB/s1600/springlogo.png" style="display: none;" />
<b>Spring boot</b>, by default, enables you to create standalone applications through simple, minimal configurations. And due to its self-contained nature, it naturally enables building microservices.<br />
<br />
<b>Spring starters</b> are poms (if using maven) that <br />
<a name='more'></a>encapsulate all the required dependencies that you need to start building an application. And for web applications, it is <code>spring-boot-starter-web</code>. It not only enables Spring MVC and other web components but also injects an embedded tomcat server by default.<br />
<br />
<pre class="brush:xml"> <dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-web</artifactid>
</dependency>
</pre>
<br />
But, what if you do not want to couple your application to a single container, and instead want to create a distributable war and not a standalone fat jar. The following steps would help.<br />
<br />
First and foremost, change the packaging of the pom to war.<br />
<br />
<pre class="brush:xml; highlight: [4]"> <groupid>com.codelooru</groupid>
<artifactid>MyWebApp</artifactid>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
</pre>
<br />
Next, add the <code>spring-boot-starter-tomcat</code> dependency and set the scope to <code>provided</code>. This would remove the spring-boot-starter-tomcat dependency from the war and decouple the application from tomcat.<br />
<br />
<pre class="brush:xml; highlight: [3]"> <dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-tomcat</artifactid>
<scope>provided</scope>
</dependency>
</pre>
<br />
Then you define a <code>ServletInitializer</code> by extending the <code>SpringBootServletInitializer</code>, as shown below. This would initialize the container's <code>ServletContext</code> with the Servlets and Filters from the Spring application context.<br />
<br />
<pre class="brush:java">import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
public class MyWebAppServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(MyWebAppApplication.class);
}
}
</pre>
<code><br /></code> <code>MyWebAppApplication</code> in the example above is your Spring Boot Application class.<br />
<br />
That's it. Now, when you build the application, you would get a nice deployable war.<br />
<br />
<h3>
An easier way ... </h3>
<br />
<code><a href="https://start.spring.io/">Spring Initializr</a></code> does all of the above when you choose the packaging as war. So, if you are clear from the very onset that you want to generate deployable wars, then use this option instead.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://2.bp.blogspot.com/-CQlnyCsPUG8/WNubRn_oRsI/AAAAAAAAANQ/qB9_MDmd1ZMZ9rsGp_sX-eKxue-5ddcRQCLcB/s1600/SpringInitializr-boot-create-war.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="502" src="https://2.bp.blogspot.com/-CQlnyCsPUG8/WNubRn_oRsI/AAAAAAAAANQ/qB9_MDmd1ZMZ9rsGp_sX-eKxue-5ddcRQCLcB/s640/SpringInitializr-boot-create-war.PNG" width="640" /></a></div>
<br />
<br />
<div style="background-color: #e6f4ff; border-radius: 5px; padding-bottom: 15px; padding-left: 10px; padding-top: 15px;">
<h4>
Related Articles</h4>
<ul>
<li><a href="https://www.codelooru.com/2017/04/spring-custom-namespaces.html">How to Create Custom Namespaces and Handlers in Spring</a></li>
<li><a href="https://www.codelooru.com/2017/04/localization-with-spring.html">Localization with Spring</a></li>
<li><a href="https://www.codelooru.com/2017/09/initializing-spring-bean.html">Initializing a Spring Bean</a></li>
<li><a href="https://www.codelooru.com/2017/02/overriding-spring-beans-with-aliases.html">Overriding Spring Beans with Aliases</a></li>
</ul>
</div>
<br />Phee Jayhttp://www.blogger.com/profile/08103990765188490526noreply@blogger.com0tag:blogger.com,1999:blog-8051593896124641807.post-32246395870859181892017-03-09T00:45:00.000-06:002019-02-14T16:45:01.514-06:00Spring Cache - Part 5 - CacheEvict<img src="https://4.bp.blogspot.com/-FrtEIxwzQrA/WKFQ8JDEaTI/AAAAAAAAAIQ/0FcKt83eYcoQmPBShBGiFk3Cms_two7iwCLcB/s1600/springlogo.png" style="display: none;" />
In the Spring Cache series so far (<b><a href="http://www.codelooru.com/2017/02/how-spring-cache-works-part-1.html">Part1</a></b>, <b><a href="http://www.codelooru.com/2017/02/spring-cache-part-2-cache-keys.html">Part2</a></b>, <b><a href="http://www.codelooru.com/2017/03/spring-cache-part-3-conditional-cache.html">Part3</a></b>, <b><a href="http://www.codelooru.com/2017/03/spring-cache-cacheput.html">Part4</a></b>), we have seen examples where the data is getting added to the cache through the use of <code>@Cacheable</code> and <code>@CachePut</code>. But, what about removing data from cache? Consider a call to delete the record from Service or DB, in which case, we would also want to delete that record from the cache.<br />
<br />
<a name='more'></a><br />
We have <code>@CacheEvict</code> to our rescue. When a method is annotated with <code>@CacheEvict</code>, spring removes the data from the cache for the provided key, on the invocation of the method. <code>@CacheEvict</code> supports all the attributes that <code>@Cacheable</code> does. Plus it has a few more.<br />
<br />
Let's explore eviction through various examples.<br />
<br />
First and foremost, the code we would use for our tests.<br />
<br />
<code>ActorService</code>, that provides the persistence for movie actors.<br />
<br />
<pre class="brush:java">public class ActorService {
@Cacheable(value = "actors", key = "#name")
public Actor getActor(String name) {
//The print that proves the method is executed.
System.out.println("getting actor " + name);
//retrieve the actor from DB and return
return new Actor(name, Gender.MALE);
}
//other methods
}
</pre>
<br />
And the code to run the tests.<br />
<br />
<pre class="brush:java"> AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("com.codelooru.cache");
ActorService service = context.getBean("actorService", ActorService.class);
service.getActors("sean");
service.getActors("meryl");
service.getActors("sean");
service.getActors("meryl");
</pre>
On the initial run, we would see the following output.<br />
<pre class="brush:java"> getting actor sean
getting actor meryl
</pre>
<br />
<h3>
CacheEvict with Key</h3>
<div>
<br /></div>
Let's add a <code>removeActor</code> method to the <code>ActorService</code> as shown below. The method is annotated with <code>@CacheEvict</code> with the <code>value</code> set to the cachename, from which the data needs to be evicted.<br />
<br />
<pre class="brush:java"> @CacheEvict(value = "actors", key = "#name")
public void removeActor(String name) {
System.out.println("--removedActor--");
}
</pre>
<br />
And modify the test code as below and run it<br />
<br />
<pre class="brush:java"> service.getActor("sean");
service.getActor("meryl");
service.getActor("sean");
service.getActor("meryl");
service.removeActor("sean");
service.getActor("sean");
service.getActor("meryl");
</pre>
<br />
This would result in
<br />
<br />
<pre class="brush:java">getting actor sean
getting actor meryl
--removedActor--
getting actor sean
</pre>
<br />
In this example, we called <code>removeActor</code> with <code>key = "sean"</code>, which removed sean from the cache. Therefore, the subsequent call to <code>getActor</code> for sean resulted in the execution of the method, but the call with "meryl" did not.<br />
<br />
<h3>
CacheEvict with conditions</h3>
<br />
Let's add a condition for eviction<br />
<br />
<pre class="brush:java"> @CacheEvict(value = "actors", key = "#name", condition="#name == 'meryl'")
public void removeActor(String name)
</pre>
<br />
Running the test code would result in the following.<br />
<br />
<pre class="brush:java"> getting actor sean
getting actor meryl
--removedActor--
</pre>
<br />
This means that the call to <code>removeActor</code> did not remove the data element from cache, as the condition was checking for the name to match 'meryl'.
Let's change the condition to 'sean'
<br />
<br />
<pre class="brush:java"> @CacheEvict(value = "actors", key = "#name", condition="#name == 'sean'")
public void removeActor(String name)
</pre>
<br />
Running the test code would result in the following
<br />
<br />
<pre class="brush:java">getting actor sean
getting actor meryl
--removedActor--
getting actor sean
</pre>
<br />
Now, we see that the <code>removeActor</code> did remove the data element for 'sean' from the cache.
<br />
<br />
<code>unless</code> works in a similar way, except that its expression evaluated after the execution of the method; thereby allowing you to use the <code>result</code> of the method in the expression. See <b><a href="http://www.codelooru.com/2017/03/spring-cache-part-3-conditional-cache.html">Part3</a></b> for more details on how <code>unless</code> works.
<br />
<br />
<h3>
CacheEvict with allEntries</h3>
<div>
<br /></div>
Let's modify <code>removeActor</code> as shown below.
<br />
<br />
<pre class="brush:java"> @CacheEvict(value = "actors", allEntries = true)
public void removeActor(String name)
</pre>
<br />
Running the test code results in the following output.
<br />
<br />
<pre class="brush:java">getting actor sean
getting actor meryl
--removedActor--
getting actor sean
getting actor meryl
</pre>
<br />
As you see, setting the <code>allEntries</code> attribute to true, removed all the data elements from the "actors" cache. Therefore, the subsequent calls with both sean and meryl result in the execution of the methods.
<br />
<br />
<h3>
Final Notes</h3>
<br />
<br />
<ul>
<li>Either <code>key</code> or <code>allEntries</code> attribute should be present for cache eviction.</li>
<li>Do not use both <code>@Cacheable</code> and <code>@CacheEvict</code> on a method. It does not solve any purpose.</li>
<li><code>@CacheEvict</code> does not support retention based eviction e.g. evict LeastRecentlyUsed, LeastFrequentlyUsed, etc. For such policies, you will have to rely on 3rd party cache providers like ehCache.</li>
</ul>
<div>
<br /></div>
Phee Jayhttp://www.blogger.com/profile/08103990765188490526noreply@blogger.com0tag:blogger.com,1999:blog-8051593896124641807.post-23219637511557308532017-03-04T00:23:00.001-06:002019-05-22T11:40:38.839-05:00Deep Copy Java Objects through SerializationWhen it comes to deep copy or cloning an object, the first thing that comes to mind is to override the <code>clone()</code> method and set each field manually. This can be pretty cumbersome to implement for complex objects or if you have to do this for a lot of them.<br />
<a name='more'></a>
<a href="https://www.blogger.com/null" name="more"></a><br />
<b>A simpler way to deep copy an object is to serialize it and then deserialize to get a new instance</b>.
<br />
Let's check out a few examples.
<br />
<br />
<h4>
Deep Copy using Spring's SerializationUtils</h4>
<br />
<pre class="brush:java">//import org.springframework.util.SerializationUtils;
byte[] sourceInBytes = SerializationUtils.serialize(sourceInstance);
Object newInstance = SerializationUtils.deserialize(sourceInBytes);
</pre>
<br />
Since we are using java serialization here, the Class needs to implement <code>Serializable</code>.
<br />
<h4>
Deep Copy using Apache Commons Lang SerializationUtils</h4>
<pre class="brush:java">//import org.apache.commons.lang.SerializationUtils
Object newInstance = SerializationUtils.clone(sourceInstance);
</pre>
<br />
Just like above example, this one needs the POJO to implement <code>Serializable</code>.<br />
<br />
<h4>
Deep Copy through JSON serialization</h4>
<pre class="brush:java">//import org.codehaus.jackson.map.ObjectMapper;
//import org.codehaus.jackson.map.ObjectMapper.DefaultTyping;
ObjectMapper mapper = new ObjectMapper();
mapper.enableDefaultTyping(DefaultTyping.NON_FINAL);
String jsonSource = mapper.writeValueAsString(sourceInstance);
MyClass newInstance = mapper.readValue(jsonSource, MyClass.class);
</pre>
<br />
The advantage with JSON is that the Class need not implement a Serializable interface. It just needs to be a POJO with a public no-arg constructor and getters/setters for the properties. enableDefaultTyping here ensures that the Polymorphic Type Handling is taken care of.
Phee Jayhttp://www.blogger.com/profile/08103990765188490526noreply@blogger.com0tag:blogger.com,1999:blog-8051593896124641807.post-75599264569430529892017-02-23T01:18:00.000-06:002019-02-14T17:08:08.778-06:00Spring Cache - Part 1 - Introduction<div dir="ltr" style="text-align: left;" trbidi="on">
<img src="https://4.bp.blogspot.com/-FrtEIxwzQrA/WKFQ8JDEaTI/AAAAAAAAAIQ/0FcKt83eYcoQmPBShBGiFk3Cms_two7iwCLcB/s1600/springlogo.png" style="display: none;" />
<br />
Caching is an extremely important aspect of applications that care about lower latencies. There are a multitude of rules one has to adhere to while setting up a cache, in order to optimize the performance; but not overdo it. We will not get into those details in this post. Our focus would be on what Spring provides to enable caching in your applications.
<br />
<a name='more'></a><br />
Spring cache was introduced in Spring 3.1. It provides a nice little framework for enabling cache on data access components <b>declaratively</b>. Since then it has gone through several updates and now it supports <b>JSR-107 (a.k.a JCache), which is a specification for in-memory caching</b>.
<br />
<br />
Let's examine through a bunch of examples, how we can leverage Spring cache.<br />
<br />
<h3>
Dependencies
</h3>
<br />
All cache specific spring components are part of the spring-context module. Add the following maven dependency to the pom.xml to pull in spring cache components.<br />
<pre class="brush:xml"><dependency>
<groupid>org.springframework</groupid>
<artifactid>spring-context</artifactid>
<version>4.3.6.RELEASE</version>
</dependency>
</pre>
<br />
<h3>
Sample data retrieval service
</h3>
<br />
The following set of classes are sample classes that help understand the usage of Spring cache. We would use the movie actor database as an example here.<br />
<br />
<b>ActorService </b>is a service class that provides methods for retrieving the movie actor details. <b>Actor</b> is the POJO that holds the actor information.<br />
<br />
<pre class="brush:java">@Component
public class ActorService {
public List<actor> getActors() {
System.out.println("----- Getting movie actors ----");
List<actor> actors = new ArrayList<actor>();
actors.add(new Actor("Sean Connery", Gender.MALE));
actors.add(new Actor("Meryl Streep", Gender.FEMALE));
return actors;
}
}
</pre>
<br />
<span style="font-family: inherit;"><b>ApplicationConfig </b></span>- is the java configuration class for the beans. We will add bean declarations here as we go forward. But currently, it is empty.
<br />
<pre class="brush:java">@Configuration
public class ApplicationConfig {
}
</pre>
<br />
And the following is the code snippet that initializes and loads the spring application context and runs the tests. This routine initializes the <span style="font-family: "courier new" , "courier" , monospace;">AnnotationConfigApplicationContext</span>, that scans for all components defined under <i>"com.codelooru.cache"</i> package and sub-packages. Then it fetches the <span style="font-family: "courier new" , "courier" , monospace;">ActorService </span>from the application context and invokes the <i>getActors()</i> twice on the service. <b>Our goal would be to ensure that the second call does not invoke the method, but rather fetches the data from the cache.
</b><br />
<br />
<pre class="brush:java">AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("com.codelooru.cache");
ActorService service = context.getBean("actorService", ActorService.class);
service.getActors();// called once.
service.getActors();// called twice.
context.close();
</pre>
<br />
Without the cache enabled, when this code is run, we would see the following output on the console.
<br />
<pre class="brush:java">----- Getting movie actors ----
----- Getting movie actors ----
</pre>
<br />
<h3>
Enabling cache with Spring
</h3>
<br />
<h4>
@EnableCaching and CacheManager
</h4>
<br />
To enable cache, we need to first annotate the ApplicationConfig with @EnableCaching and configure a CacheManager bean.
<br />
<br />
<pre class="brush:java">@EnableCaching
@Configuration
public class ApplicationConfig {
@Bean
public CacheManager cacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
Cache actorsCache = new ConcurrentMapCache("actors");
cacheManager.setCaches(Arrays.asList(actorsCache));
return cacheManager;
}
}
</pre>
<br />
<span style="font-family: "courier new" , "courier" , monospace;">@EnableCaching</span> registers and configures all the necessary proxies and interceptors around the cacheable components. These interceptors intercept the method requests and invoke the CacheManagers to fetch the data. This annotation should always be accompanied by a bean definition for the CacheManager.<br />
<span style="font-family: "courier new" , "courier" , monospace;"><br /></span>
<span style="font-family: "courier new" , "courier" , monospace;">CacheManager</span> is responsible for managing the cacheable data. It knows how to store and retrieve the data. Spring provides a few CacheManagers out of the box, <b>but these should not be used for enterprise level applications</b>. They are more suited for tests or simple tools and applications. For enterprise applications, there are better 3rd party components like <b>Ehcache</b>.<br />
<br />
<h4>
Cache
</h4>
<br />
CacheManagers can manage several Caches. A <span style="font-family: "courier new" , "courier" , monospace;">Cache </span>usually has a name and is used for grouping together multiple cacheable data items. It is akin to a map that returns back a value for the given key. Each cache can be configured with its own eviction policies. More about eviction would be covered in later parts of the article.
<br />
<br />
<h4>
Example with cache enabled
</h4>
<br />
In our example, we will use <span style="font-family: "courier new" , "courier" , monospace;">SimpleCacheManager</span>, which is a very basic implementation of cache management with hashmaps. We initialize it with a cache for "actors". The next step is to mark the getActors method as cacheable.<br />
<br />
<pre class="brush:java">@Component
public class ActorService {
@Cacheable("actors")
public List<actor> getActors() {
System.out.println("----- Getting movie actors ----");
List<actor> actors = new ArrayList<actor>();
actors.add(new Actor("Sean Connery", Gender.MALE));
actors.add(new Actor("Meryl Streep", Gender.FEMALE));
return actors;
}
}
</pre>
<br />
<span style="font-family: "courier new" , "courier" , monospace;">@Cacheable</span> annotation is used to mark a Class or method as cacheable. It takes the cache name as the default value. When the getActors() method is first invoked, it would check the "actors" cache for the data and when it does not find it, it would invoke the actual method to get the data. The result is then stored in the cache.
<br />
<br />
With the cache enabled, now the result of the test program would be as below. This means the actual getActors method is invoked only once and the second time, the data is fetched from the cache.<br />
<br />
<pre class="brush:java">----- Getting movie actors ----
</pre>
<br />
In Part 2, we will explore cache keys.</div>
Phee Jayhttp://www.blogger.com/profile/08103990765188490526noreply@blogger.com0tag:blogger.com,1999:blog-8051593896124641807.post-16555917408145211692017-02-17T23:29:00.001-06:002019-02-14T17:08:49.499-06:00JSON Property Name Customization in Jackson using PropertyNamingStrategy<div dir="ltr" style="text-align: left;" trbidi="on">
<img border="0" src="https://4.bp.blogspot.com/-2xNAx1FO5Dg/WLE_l8G-L8I/AAAAAAAAAMk/hvCOOHkR3Tox5GaF2aL8uO4ELmiOyrkCgCLcB/s1600/jsonlogo.png" style="display: none;" />
Jackson is one of the most popular java libraries for serialization/deserialization of POJOs to/from JSON. By default, Jackson derives the JSON element names from the getter/setter method names of the POJO. e.g. <i>getActorName()</i> is translated to <i>actorName</i> in the resulting JSON.<br />
<div dir="ltr">
<br />
<a name='more'></a>Let's take the following POJO and serialization function for our examples.<br />
<br />
<pre class="brush:java">//The POJO that needs to be serialized
public class Actor {
private String actorName;
private Gender actorGender;
public Actor() {}
public Actor(String name, Gender gender) {
this.actorName = name; this.actorGender = gender;
}
public String getActorName() {
return actorName;
}
public void setActorName(String actorName) {
this.actorName = actorName;
}
public Gender getActorGender() {
return actorGender;
}
public void setActorGender(Gender actorGender) {
this.actorGender = actorGender;
}
}
</pre>
<br />
<pre class="brush:java">//Code that serializes the actor object to JSON
Actor actor = new Actor("Al Pacino", Gender.MALE);
ObjectMapper mapper = new ObjectMapper();
Writer w = new StringWriter();
mapper.writeValue(w, actor);
System.out.println(w.toString());
</pre>
<br />
<pre class="brush:javascript">//The resulting JSON with default camelcase
{
"actorName":"Al Pacino",
"actorGender":"MALE"
}
</pre>
</div>
<br />
<div dir="ltr">
<h4 style="text-align: left;">
Customizing element names</h4>
<br />
Jackson allows you to change this default behavior through <b><span style="color: #0b5394; font-family: "courier new" , "courier" , monospace;"><u>PropertyNamingStrategy</u></span></b>.<br />
<span style="color: #0b5394; font-family: "courier new" , "courier" , monospace;"><b>PropertyNamingStrategy </b></span>provides a few template methods that can be overridden to derive custom element names from the method names (for serialization) and vice-versa (for deserialization).<br />
<br />
<span style="color: #0b5394;"><b><span style="font-family: "courier new" , "courier" , monospace;">nameForGetterMethod</span> </b></span>resolves the element names for the given getter method during <i>serialization</i>.<br />
<span style="color: #134f5c; font-family: "courier new" , "courier" , monospace;"><b>nameForSetterMethod </b></span>identifies the element names for the given setter method during <i>deserialization</i>.<br />
<br />
This strategy can then be set on the ObjectMapper, before reading or writing to it.<br />
<br />
<pre class="brush:java">mapper.setPropertyNamingStrategy(myStrategyInstance);
</pre>
</div>
<div dir="ltr">
<br /></div>
<div dir="ltr">
<h4 style="text-align: left;">
Jackson Strategies</h4>
<br />
Jackson provides at least two Strategies out of the box.<br />
<i><br /></i><span style="color: #134f5c; font-family: "courier new" , "courier" , monospace;"><b> LowerCaseWithUnderscoresStrategy </b></span>- It converts camel case properties to lowercase element names separated by underscores. It's a private class and can't be used directly. Instead, it can be used in the following manner.<br />
<pre class="brush:java">mapper.setPropertyNamingStrategy(
PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
</pre>
<br />
<pre class="brush:javascript">//The resulting JSON with underscores
{
"actor_name":"Al Pacino",
"actor_gender":"MALE"
}
</pre>
<br />
<span style="color: #0b5394; font-family: "courier new" , "courier" , monospace;"><b>PascalCaseStrategy</b></span><span style="color: #0b5394; font-family: "courier new" , "courier" , monospace;"><b> </b></span>- It converts camel case properties to PascalCase element names.<br />
<pre class="brush:java">mapper.setPropertyNamingStrategy(
PropertyNamingStrategy.PASCAL_CASE_TO_CAMEL_CASE);
</pre>
<br />
<pre class="brush:javascript">//The resulting JSON with PascalCase elements
{
"ActorName":"Al Pacino",
"ActorGender":"MALE"
}
</pre>
<br />
<br /></div>
<div dir="ltr">
<h4 style="text-align: left;">
Custom strategies</h4>
<br />
You can also define a custom strategy of your own. The <span style="color: #0b5394; font-family: "courier new" , "courier" , monospace;"><b>AllLowerCasePropertyNamingStrategy </b></span>defined below converts the property names to lowercase element names. The <i>defaultName</i> here is the element name that the default strategy provides.<br />
<br />
<pre class="brush:java; highlight:[4,10]">public class AllLowerCasePropertyNamingStrategy extends PropertyNamingStrategy {
@Override
public String nameForGetterMethod(MapperConfig config,
AnnotatedMethod method, String defaultName) {
return defaultName.toLowerCase();
}
@Override
public String nameForSetterMethod(MapperConfig config,
AnnotatedMethod method, String defaultName) {
return defaultName.toLowerCase();
}
}
</pre>
<br />
<pre class="brush:java">mapper.setPropertyNamingStrategy(
new AllLowerCasePropertyNamingStrategy());</pre>
<br />
<pre class="brush:javascript">//The resulting JSON with lowercase element names
{
"actorname":"Al Pacino",
"actorgender":"MALE"
}
</pre>
<br />
Another example of a custom strategy, <span style="color: #0b5394; font-family: "courier new" , "courier" , monospace;"><b>StripPrefixPropertyNamingStrategy</b></span>, strips the given prefix from the property names to derive the element names.<br />
<br />
<pre class="brush:java; highlight:[10,15]">private static class StripPrefixPropertyNamingStrategy extends PropertyNamingStrategy {
private String prefix;
public StripPrefixPropertyNamingStrategy(String prefix) {
this.prefix = prefix;
}
@Override
public String nameForGetterMethod(MapperConfig config, AnnotatedMethod method, String defaultName) {
return defaultName.replaceFirst(prefix, "");
}
@Override
public String nameForSetterMethod(MapperConfig config, AnnotatedMethod method, String defaultName) {
return defaultName.replaceFirst(prefix, "");
}
}
</pre>
<br />
<pre class="brush:java">mapper.setPropertyNamingStrategy(
new StripPrefixPropertyNamingStrategy("actor"));
</pre>
<br />
<pre class="brush:javascript">//The resulting JSON without the actor prefix
{
"Name":"Al Pacino",
"Gender":"MALE"
}
</pre>
<br />
<br /></div>
</div>
Phee Jayhttp://www.blogger.com/profile/08103990765188490526noreply@blogger.com1tag:blogger.com,1999:blog-8051593896124641807.post-66086919482432429202017-02-15T22:55:00.000-06:002019-05-22T11:41:08.297-05:00How to Timeout JDBC Queries<div dir="ltr" style="text-align: left;" trbidi="on">
<img src="https://4.bp.blogspot.com/-FrtEIxwzQrA/WKFQ8JDEaTI/AAAAAAAAAIQ/0FcKt83eYcoQmPBShBGiFk3Cms_two7iwCLcB/s1600/springlogo.png" style="display: none;">
JDBC queries by default do not have any timeout, which means that a query can block the thread for an unlimited amount time; of course, depending upon the DB load and the cost of the query. It is a good practice to timeout these queries if they can take longer than a certain amount of time.<br><a name='more'></a>
<br>
<a name="more"></a><h4 style="text-align: left;">
Timeout on individual Queries</h4>
<div>
<br></div>
<div style="text-align: left;">
JDBC statements can be configured for timeouts, <b>in seconds</b>. When timeouts are set, the driver would wait for the given number of seconds for the query to execute (i.e. executeQuery and executeUpdate) and throw an <b>SQLTimeoutException </b>if doesn't respond within that time.</div>
<br>
Here are a couple of examples.<br>
<br>
<pre class="brush:java; toolbar:on; ruler:false; highlight: 2">Statement stmt = connection.prepareStatement("SELECT * FROM BOOKS");
stmt.setQueryTimeout(10);//Timeout of 10 seconds
//This would throw an SQLTimeoutException if it exceeds 10 seconds
ResultSet result = stmt.executeQuery();
</pre>
<br>
<pre class="brush:java; ruler:false; highlight: 4">PreparedStatement stmt = connection.prepareStatement("UPDATE BOOKS SET RETURNED = ? WHERE BID = ?");
stmt.setBoolean(1, true);
stmt.setString(2, "B1234");
stmt.setQueryTimeout(5);//Timeout of 5 seconds
//This would throw an SQLTimeoutException if it exceeds 5 seconds
stmt.executeUpdate();
</pre>
<br>
<h4>
Global Timeout (JDBC Driver Level)</h4>
<div>
<br></div>
If you need to set the same timeout for all query executions, then it can be set directly on the drivers. <b>However, the options would differ from driver to driver.</b></div><div dir="ltr" style="text-align: left;" trbidi="on">
Here is an example of timeouts set on the Oracle Thin Driver<br>
<br>
<pre class="brush:java; ruler:false; highlight: 4">Properties properties = new Properties();
properties.setProperty("user", "scott");
properties.setProperty("password", "tiger");
//This timeout is in milliseconds, but can vary for other drivers
properties.setProperty(OracleConnection.CONNECTION_PROPERTY_THIN_READ_TIMEOUT, "2000");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@host:1521:SID", properties);
</pre>
<br>
<h4>
Spring JDBC timeouts</h4>
<div>
<br></div>
If you are using Spring JDBC, where you do not have direct control over the JDBC statements, JDBCTemplate also provides an option to setQueryTimeOut. If set to -1, it takes the JDBC driver's default setting for timeouts (which is covered above).<br>
<pre class="brush:java; ruler:false; highlight: 1">getJdbcTemplate().setQueryTimeout(5);
getJdbcTemplate().update("UPDATE BOOKS ...", sqlParamSource);
</pre>
<br>
<br>
<br></div>
<br>
<div style="background-color: #e6f4ff; border-radius: 5px; padding-bottom: 15px; padding-left: 10px; padding-top: 15px;">
<h4>
Related Articles</h4>
<ul>
<li><a href="https://www.codelooru.com/2017/08/how-to-create-web-notifications.html">How to Create Web Notifications</a></li>
<li><a href="https://www.codelooru.com/2019/01/how-to-find-ip-address-of-host-in-java.html">How to find the IP Address of a host in Java?</a></li>
<li><a href="https://www.codelooru.com/2017/03/deep-copy-java-objects-through.html">Deep Copy Java Objects through Serialization</a></li>
<li><a href="https://www.codelooru.com/2017/02/tarlog-eclipse-plugin-for-windows.html">Tarlog - Eclipse Plugin for Windows</a></li>
</ul>
</div>
<br>Phee Jayhttp://www.blogger.com/profile/08103990765188490526noreply@blogger.com1tag:blogger.com,1999:blog-8051593896124641807.post-54720575507499587612017-02-12T22:45:00.003-06:002019-02-14T17:11:02.115-06:00Tarlog - Eclipse Plugin for Windows<div dir="ltr" style="text-align: left;" trbidi="on">
<img src="https://3.bp.blogspot.com/-qHMlxI03IXo/WKFW0K5zvxI/AAAAAAAAAJU/ev4dXPWO7-8i9NGjiKjEMxFRdqwWiFv_wCLcB/s1600/eclipselogo.png" style="display: none;" />
Tarlog is a plugin for eclipse that provides some useful features if you are working on a Windows machine. It allows you to Copy Path, Open Shell or Open Explorer on the selected file or folder in the project. It also allows changing the font of the editor through Ctrl++ and Ctrl-- keys.<br />
<a name='more'></a><br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://3.bp.blogspot.com/-rcKDdnKpsxQ/WKE4uNyqdmI/AAAAAAAAAHQ/peYMxUNl0So3Y9CzMb49MUkwcEi9wSQDgCLcB/s1600/tarlog.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="507" src="https://3.bp.blogspot.com/-rcKDdnKpsxQ/WKE4uNyqdmI/AAAAAAAAAHQ/peYMxUNl0So3Y9CzMb49MUkwcEi9wSQDgCLcB/s640/tarlog.png" width="640" /></a></div>
<br />
<br />
<br />
To install the plugin:<br />
<br />
<ul style="text-align: left;">
<li>Download the latest plugins jar from <a href="https://code.google.com/archive/p/tarlog-plugins/downloads">https://code.google.com/archive/p/tarlog-plugins/downloads</a></li>
<li>Copy the jar to the "<i>plugins</i>" folder under the eclipse installation folder.</li>
<li>Restart Eclipse</li>
</ul>
<div>
<br /></div>
<div>
Tarlog works on Spring Tool Suite (STS) too, as it is based on Eclipse</div>
<div>
<br /></div>
<div>
<br /></div>
</div>
<br />
<div style="background-color: #e6f4ff; border-radius: 5px; padding-bottom: 15px; padding-left: 10px; padding-top: 15px;">
<h4>
Related Articles</h4>
<ul>
<li><a href="https://www.codelooru.com/2017/08/how-to-create-web-notifications.html">How to Create Web Notifications</a></li>
<li><a href="https://www.codelooru.com/2019/01/how-to-find-ip-address-of-host-in-java.html">How to find the IP Address of a host in Java?</a></li>
<li><a href="https://www.codelooru.com/2017/03/deep-copy-java-objects-through.html">Deep Copy Java Objects through Serialization</a></li>
<li><a href="https://www.codelooru.com/2017/02/how-to-timeout-jdbc-queries.html">How to Timeout JDBC Queries</a></li>
</ul>
</div>
<br />Phee Jayhttp://www.blogger.com/profile/08103990765188490526noreply@blogger.com0tag:blogger.com,1999:blog-8051593896124641807.post-63818853363493861062017-02-09T22:53:00.002-06:002019-02-14T17:12:12.257-06:00Overriding Spring Beans with Aliases<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
</div>
<img src="https://4.bp.blogspot.com/-FrtEIxwzQrA/WKFQ8JDEaTI/AAAAAAAAAIQ/0FcKt83eYcoQmPBShBGiFk3Cms_two7iwCLcB/s1600/springlogo.png" style="display: none;" />
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
The most common approach followed for overriding a spring bean is to define a new bean, with the same id as the original bean, in a separate XML file. During context initialization, Spring would register the last bean found for the id, and use it for all the injections.<br />
<br />
I dislike this approach for two reasons.<br />
<a name='more'></a><br />
<ol style="text-align: left;">
<li>It needs the bean ids to be same, thereby taking away the flexibility to provide a meaningful id to the new bean.</li>
<li>It demands that the XML with the new bean is loaded last and enforces the developers to define them last in the context location. This can lead to errors if not careful. </li>
</ol>
<br />
There is an alternate approach, which I prefer. <b>Overriding the bean through aliases</b>. The following set of steps explains this approach.<br />
<br />
First, define the bean that needs to be overridden.<br />
<pre class="brush: xml; ruler: true"><bean id="defaultTxnProcessorBean" class="com.thespringthing.TransactionProcessor">
..
</bean></pre>
<br />
Define a property placeholder, for the properties file that would be used to set the overriding bean name.<br />
<pre class="brush: xml"><bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" >
<value>classpath:config.properties</value>
</property>
</bean>
</pre>
<br />
Next, create an alias for the bean, with a configurable name. Default the value of the property to the default bean name, so that Spring does not enforce creation of this properties file or if the property file already exists then defining this property in the file.<br />
<pre class="brush: xml"><alias name="${txnprocessor.name:defaultTxnProcessorBean}" alias="txnProcessorBean"/></pre>
<br />
Inject this bean to other beans, using the alias.<br />
<pre class="brush: xml"><bean id="anyotherbean" class="com.thespringthing.XYZ">
<property name="txnProcessor" ref="txnProcessorBean" />
</bean></pre>
<br />
<br />
Now, let's say you need to override the default txnProcessor bean, then define the new bean.<br />
<pre class="brush: xml"><bean id="newTxnProcessorBean" class="com.thespringthing.NewTxnProcessor">
..
</bean></pre>
<br />
In the <b>config.</b><b>properties</b> set the property to the new bean name.<br />
<pre class="brush: java">txnprocessor.name=newTxnProcessorBean</pre>
<br />
<br />
This would set the alias to the new bean and would use it for injection, thereby overriding the default bean.</div>
<br />
<br />
<div style="background-color: #e6f4ff; border-radius: 5px; padding-bottom: 15px; padding-left: 10px; padding-top: 15px;">
<h4>
Related Articles</h4>
<ul>
<li><a href="https://www.codelooru.com/2017/04/spring-custom-namespaces.html">How to Create Custom Namespaces and Handlers in Spring</a></li>
<li><a href="https://www.codelooru.com/2017/04/localization-with-spring.html">Localization with Spring</a></li>
<li><a href="https://www.codelooru.com/2017/03/spring-boot-create-deployable-war.html">Spring Boot - How to Create a Deployable War</a></li>
<li><a href="https://www.codelooru.com/2017/09/initializing-spring-bean.html">Initializing a Spring Bean</a></li>
</ul>
</div>
<br />Phee Jayhttp://www.blogger.com/profile/08103990765188490526noreply@blogger.com0tag:blogger.com,1999:blog-8051593896124641807.post-1179611108777560722015-06-26T18:42:00.004-05:002019-02-25T11:25:12.089-06:00ETags and Browser Cache<img src="https://4.bp.blogspot.com/-FrtEIxwzQrA/WKFQ8JDEaTI/AAAAAAAAAIQ/0FcKt83eYcoQmPBShBGiFk3Cms_two7iwCLcB/s1600/springlogo.png" style="display: none;" />
<br />
<div style="text-align: left;" trbidi="on">
<div>
Caching resources on the browser is crucial to minimize unnecessary trips to the server and reduce the load on it. This works well for data that is static. But, there are cases where the data changes every once in a while (although less frequently), and you would want the browser to get the latest data without waiting for the cached data to expire. e.g., consider a scenario where a new version of the application is deployed with changes to CSS and javascript, and you want the user to experience these changes without forcing them to refresh their cache manually. One option you might consider is to make these resources non-cacheable and compromise the page performance a bit. <b>Entity tags</b>( or <b>ETags</b> for short) help you cache such resources, without the performance compromise.<br />
<a name='more'></a><br /></div>
<div>
<b>ETag</b> is an identifier that represents the response content of a request. By comparing ETags, you should be able to tell if the response for a request has changed or not, and decide if you need to send the new data back to the client or just use the cached data.</div>
<div>
<br />
HTTP supports <b><code>ETag</code></b><b> response headers</b> which can be used along with <b><code>If-None-Match</code> request headers</b> for conditionally managing the data cache. These headers should be used only for <code>GET</code> and <code>HEAD</code> requests, which are the recommended methods for fetching cacheable resources.</div>
<div>
<br />
The following sequence diagrams illustrate the ETag workflow for an example of a 3-step resource fetch. Each step requests for the same resource.<br />
<br />
<br />
<br /></div>
<div>
<img src="https://4.bp.blogspot.com/-Oj6tyOt8ag0/VY4EkXx2OZI/AAAAAAAAAEI/7UJnCP4Y8OE/s640/etags.png" /></div>
<div>
<br />
<br />
<h4 style="text-align: left;">
Step 1</h4>
<ul style="text-align: left;">
<li>The Browser sends a request for a resource</li>
<li>The Server creates an ETag value for the resource using a hash or other techniques.</li>
<li>The Server sets this value in "ETag" header in the response.</li>
<li>The Server sends the resource along with ETag.</li>
<li>The Client caches the resource and the ETag</li>
</ul>
<div>
<h4 style="text-align: left;">
Step 2</h4>
</div>
<ul style="text-align: left;">
<li>The Client requests for the same resource</li>
<li>The Client sends the ETag value for the resource through the If-None-Match header.</li>
<li>The Server calculates the ETag for the resource.</li>
<li>The Server compares the new ETag with If-None-Match. </li>
<li>If it matches, the server sends a 304 response code.</li>
<li>The Client uses the data from the cache.</li>
</ul>
<div>
<h4 style="text-align: left;">
Step 3</h4>
</div>
<ul style="text-align: left;">
<li>The Client requests for the same resource.</li>
<li>The Client sends the ETag value for the resource through the If-None-Match header.</li>
<li>The Server calculates the ETag for the resource.</li>
<li>The Server compares the new ETag with If-None-Match.</li>
<li>If it does not match, the server sets the ETag response header with the new value.</li>
<li>The Server sends the resource along with ETag.</li>
<li>The Client caches the new resource and the ETag</li>
</ul>
</div>
<div>
<h3 style="text-align: left;">
<b><br /></b></h3>
<h3 style="text-align: left;">
<b>ETag</b><b> generation</b></h3>
<b><br /></b></div>
<div>
ETag generation in itself could add some amount of latency, depending upon the techniques used. The simplest technique to calculate is to generate a hash of the content with an algorithm like MD5. This can add additional latency, especially for large resources.</div>
<br />
<div>
The generated ETag need not necessarily be unique, <b><i>as long as it can indicate the change in the content</i></b>. For example, in one of my projects, I used the content version as the ETag. The version represented a change in the content, and that was good enough for me to refresh the cache.</div>
<br />
<div>
<h3 style="text-align: left;">
<b>Spring support for </b><b>ETags</b></h3>
</div>
<div>
<h4 style="text-align: left;">
<b><br /></b></h4>
<h4 style="text-align: left;">
<b>WebRequest</b></h4>
<b><br /></b></div>
<div>
<code>org.springframework.web.context.request.WebRequest</code> wraps around the HTTP request and response objects and provides convenient utilities to compare ETags.<br />
<br /></div>
<pre class="brush: java">public boolean ServletWebRequest.checkNotModified(String etag)
</pre>
<div>
<br />
This function compares the ETag and If-Not-Match headers and sets the response code or the ETag response header. You can get hold of the <code>WebRequest</code> instance through the Controller handlers.<br />
<br />
Consider the following example for a better understanding.</div>
<br />
<pre class="brush: java">@RequestMapping(value="codelooru/getMyResource.do", method = RequestMethod.GET)
@ResponseBody
public MyResource getMyResource(HttpServletRequest request, WebRequest webRequest)
{
MyResource myResource = myService.getMyResource();
String etag = generateHash(myResource);
boolean notModified = webRequest.checkNotModified(eTag);
if (! notModified) {
//Forces revalidation of cache. Browser would send an If-Not-Match with ETag in the next request.
response.setHeader("Cache-control", "max-age=0");
return myResource;
}
else {
return null;
}
}
</pre>
<br />
<div>
<h4>
<b>ShallowEtagHeaderFilter</b></h4>
</div>
<div>
<br />
With <code>WebRequest</code>, you would be responsible for generating the ETag. If you wish the framework to do that for you automatically, then you can use <code>ShallowEtagHeaderFilter</code>. It generates ETag and also sets the relevant response header values. It uses MD5 to generate the hash and can be setup via <code>web.xml</code>. Of course, you can always sub-class it to implement a custom ETag generation.</div>
<div>
</div>
<pre class="brush: xml"><filter>
<filter-name>shallowEtagHeaderFilter</filter-name>
<filter-class>org.springframework.web.filter.ShallowEtagHeaderFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>shallowEtagHeaderFilter</filter-name>
<url-pattern>/codelooru/*</url-pattern>
</filter-mapping>
</pre>
<br />
<div>
<h3 style="text-align: left;">
<b>Last-Modified and If-Modified-Since</b></h3>
<b><br /></b></div>
<div>
An alternate approach to ETags is using the last modified time to check for data changes. These functions behave the same as ETag and If-Not-Match. <b>Last-Modified</b> is analogous to ETag and <b>If-Modified-Since</b> is to If-Not-Match. Again, it is useful if you can resolve the last modified time easily.<br />
<br />
The following method in <code>WebRequest</code> can be used for this.<br />
<br />
<div>
</div>
<br />
<pre class="brush: java">public boolean checkNotModified(long lastModifiedTimestamp)
</pre>
</div>
<div>
<h3 style="text-align: left;">
<b><br /></b></h3>
<h3 style="text-align: left;">
<b>Final Disclaimer</b></h3>
</div>
<div>
<br />
ETags are based on response content, which means that you cannot avoid a trip to the server to compare the content. What you are saving, however, is some bandwidth on the way back to client.</div>
<br />
<br />
<div style="background-color: #e6f4ff; border-radius: 5px; padding-bottom: 15px; padding-left: 10px; padding-top: 15px;">
<h4>
More Articles in Spring MVC</h4>
<ul>
<li><a href="http://www.codelooru.com/2017/04/localization-with-spring.html">Localization with Spring</a></li>
<li><a href="http://www.codelooru.com/2010/11/how-does-modelattribute-work.html">How does @ModelAttribute Work?</a></li>
<li><a href="http://www.codelooru.com/2010/10/what-does-mvcannotation-driven-do.html">What does mvc:annotation-driven Do?</a></li>
<li><a href="http://www.codelooru.com/2010/10/what-is-sessionattributeatore.html">What Is a SessionAttributeStore ? When to Use It?</a></li>
</ul>
</div>
<br />
<br /></div>
Phee Jayhttp://www.blogger.com/profile/08103990765188490526noreply@blogger.com0Omaha, United States41.240157469700293 -96.184525336399474tag:blogger.com,1999:blog-8051593896124641807.post-35357732871876062882010-11-17T23:32:00.001-06:002019-02-14T17:21:20.331-06:00How does @ModelAttribute Work?<img src="https://4.bp.blogspot.com/-FrtEIxwzQrA/WKFQ8JDEaTI/AAAAAAAAAIQ/0FcKt83eYcoQmPBShBGiFk3Cms_two7iwCLcB/s1600/springlogo.png" style="display: none;" />
<br />
<div dir="ltr" style="text-align: left;" trbidi="on">
<b>@ModelAttribute</b> is a Spring-MVC annotation that is used for preparing the model data. It is also used to define the command object for binding the HTTP request data. The annotation works only if the class is a Controller class (i.e. annotated with <i>@Controller</i>).<br />
<br />
<i>ModelAttribute</i> can be applied to both methods as well as method-parameters. It accepts an optional <i>"value"</i>, which indicates the name of the attribute. If no value is supplied to the annotation, then the value would default to the return type name in case of methods and parameter type name in case of method-parameters.<br />
<br />
The way Spring processes this annotation is,<br />
<a name='more'></a><br />
<ol>
<li>Before invoking the handler method, Spring invokes all the methods that have @ModelAttribute annotation. It adds the data returned by these methods to a temporary <i>Map</i> object. The data from this Map would be added to the final Model after the execution of the handler method.</li>
<li>Then it prepares to invoke the handler method. To invoke this method, it has to resolve the arguments. If the method has a parameter with @ModelAttribute, then it would search in the temporary <i>Map</i> object with the value of @ModelAttribute. If it finds, then the value from the Map is used for the handler method parameter.</li>
<li>It doesn't find it in the Map, then it checks if there is a SessionAttributes annotation applied on the controller with the given value. If the annotation is present, then the object is retrieved from the session and used for the handler method parameter. If the session doesn't contain the object despite the @SessionAttributes, then an error is raised.</li>
<li>If the object is not resolved through Map or @SessionAttribute, then it creates an instance of the parameter-type and passes it as the handler method parameter. <i>Therefore, for it to create the instance, the parameter type should be a concrete-class-type (interfaces or abstract class types would again raise an error).</i></li>
<li>Once the handler is executed, the parameters marked with @ModelAttributes are added to the Model.</li>
</ol>
<br />
Let me explain you further with the help of some examples.<br />
<br />
<br />
<b>Example 1:</b><br />
<pre class="brush: java">@Controller
public class MyController {
@ModelAttribute("myobject")
public MyObject getInitializedMyObject() {
return myService.getInitializedObject();
}
@RequestMapping(value="/handle.htm", method=RequestMethod.GET)
public ModelAndView handleRequest() {
return new ModelAndView("myView");
}
}
</pre>
In this example, the value returned by getInitializedMyObject is added to the Model. The View would be able to retrieve this object using the key "myobject" from the request attributes.<br />
<br />
<b>Example 2 :</b><br />
<pre class="brush: java">@Controller
public class MyController {
@ModelAttribute("myobject")
public MyObject getInitializeMyObject() {
return myService.getInitializedObject();
}
@RequestMapping(value="/handle.htm", method=RequestMethod.GET)
public ModelAndView handleRequest(@ModelAttribute("myobject") MyObject myObject) {
myObject.setValue("test");
return new ModelAndView("myView");
}
}
</pre>
In this case, the getInitializeMyObject is executed first and the result is stored in a temporary map. This value is then passed as a parameter to the handler method. And finally, myObject is added to the model for the views.<br />
<br />
<b>Example 3 :</b><br />
<pre class="brush: java">@Controller
@SessionAttributes("myobject")
public class MyController {
@RequestMapping(value="/handle.htm", method=RequestMethod.GET)
public ModelAndView handleRequest(@ModelAttribute("myobject") MyObject myObject) {
myObject.setValue("test");
return new ModelAndView("myView");
}
}
</pre>
In this case, Spring searches for "myobject" in the session and pass it as the parameter to the handler method. If "myobject" is not found in the session, then HttpSessionRequiredException is raised.<br />
<br />
<br />
<b>Example 4 :</b><br />
<pre class="brush: java">@Controller
public class MyController {
@RequestMapping(value="/handle.htm", method=RequestMethod.GET)
public ModelAndView handleRequest(@ModelAttribute("myobject") MyObject myObject) {
myObject.setValue("test");
return new ModelAndView("myView");
}
}
</pre>
In this case, a new instance of MyObject is created and then passed to the handler method. If MyObject is an interface or an abstract class, then a BeanInstantiationException is raised.
<br />
<br />
<div style="background-color: #e6f4ff; border-radius: 5px; padding-bottom: 15px; padding-left: 10px; padding-top: 15px;">
<h4>
More Articles in Spring MVC</h4>
<ul>
<li><a href="http://www.codelooru.com/2017/04/localization-with-spring.html">Localization with Spring</a></li>
<li><a href="http://www.codelooru.com/2015/06/etags-and-browser-cache.html">ETags and Browser Cache</a></li>
<li><a href="https://www.codelooru.com/2019/01/error-handling-in-spring-mvc.html">Error handling in Spring MVC</a></li>
<li><a href="http://www.codelooru.com/2010/10/what-does-mvcannotation-driven-do.html">What does mvc:annotation-driven Do?</a></li>
<li><a href="http://www.codelooru.com/2010/10/what-is-sessionattributeatore.html">What Is a SessionAttributeStore? When to Use It?</a></li>
</ul>
</div>
<br />
<br /></div>
Phee Jayhttp://www.blogger.com/profile/08103990765188490526noreply@blogger.com11tag:blogger.com,1999:blog-8051593896124641807.post-63237063065650279712010-10-18T11:31:00.000-05:002019-02-18T10:52:42.232-06:00What Is a SessionAttributeStore? When to Use It?<div dir="ltr" style="text-align: left;" trbidi="on">
<img src="https://4.bp.blogspot.com/-FrtEIxwzQrA/WKFQ8JDEaTI/AAAAAAAAAIQ/0FcKt83eYcoQmPBShBGiFk3Cms_two7iwCLcB/s1600/springlogo.png" style="display: none;" />
<br />
<div dir="ltr" style="text-align: left;" trbidi="on">
<div xmlns="http://www.w3.org/1999/xhtml">
In one of my projects, I had an abstract controller class that simulated the form controller of Spring 1.2 for session forms. Annotations do not accept dynamic parameters. They have to be static. So, in the class, the command object name had to be a constant.<br />
<br />
<a name='more'></a><br />
The class looks somewhat like this.<br />
<pre class="brush: java">@SessionAttributes("COMMANDOBJECT")
public abstract class FormController {
@InitBinder("COMMANDOBJECT")
public void initBinder(WebDataBinder binder, WebRequest request) {
.....
}
@RequestMapping(value = "/form.do", method=RequestMethod.GET)
public ModelAndView initForm(WebRequest request) {
....
}
@RequestMapping(value = "/form.do", method=RequestMethod.POST)
public ModelAndView submitForm(@ModelAttribute(value = "COMMANDOBJECT") CommandObject commandObj, BindingResult bindingResult, SessionStatus status, WebRequest request) {
......
}
}
</pre>
<br />
When I have two different controllers extending this class, both of them use the same command object name to store the command object in the session. So far so good. Now, if I have a main form which would pop-up another modal form, that's when the problem starts. Once, the modal form is closed, you would be unable to submit the main form. The command object in the session would be replaced with the modal form backing object.<br />
<br />
Quick troubleshooting revealed the following. Spring (or rather the <code>AnnotationMethodHandlerAdapter</code>) uses <code><b>SessionAttributeStore</b> </code>to store the session attributes. The default implementation for <code>SessionAttributeStore </code>is <b><code>DefaultSessionAttributeStore</code></b>. <code>DefaultSessionAttributeStore </code>uses the value provided in <code>@SessionAttributes </code>to store the command object (when the form view is rendered). And then uses the value provided in the <code>@ModelAttributes </code>to retrieve the command object (during the form submit). Hence, multiple form windows supported by controllers with the same command object name would not work.<br />
<br />
So, for my situation what I would need is a <code>SessionAttributeStore </code>which can store the attribute with a unique key for every form. A <i>custom</i> <code>SessionAttributeStore</code> can be created and injected to the <b><code">AnnotationMethodHandlerAdapter</code></b>.<br />
<br />
Here is a custom <code>SessionAttributeStore</code> which appends the requestURI to the attributeName before storing, retrieving and removing.<br />
<br />
<pre class="brush: java">public class CustomSessionAttributeStore extends DefaultSessionAttributeStore {
@Override
public void storeAttribute(WebRequest request, String attributeName,
Object attributeValue) {
super.storeAttribute(request, getCustomAttributeName(request, attributeName), attributeValue);
}
@Override
public Object retrieveAttribute(WebRequest request, String attributeName) {
return super.retrieveAttribute(request, getCustomAttributeName(request, attributeName));
}
@Override
public void cleanupAttribute(WebRequest request, String attributeName) {
super.cleanupAttribute(request, getCustomAttributeName(request, attributeName));
}
public String getCustomAttributeName(WebRequest request, String attributeName) {
String result;
if(request instanceof ServletWebRequest) {
result = ((HttpServletRequest)((ServletWebRequest)request).getNativeRequest()).getRequestURI() + attributeName;
}
else {
result = attributeName;
}
return result;
}
}
</pre>
<br />
To use this store, it needs to be injected to the <code>HandlerAdapter</code>.<br />
<br />
<pre class="brush: xml"><bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="sessionAttributeStore">
<bean class="com.codelooru.CustomSessionAttributeStore">
</bean>
</property>
<!-- Other properties would be set here -->
</bean>
</pre>
<br />
<br />
Note that this store still will not work for opening two form windows with the same URL.<br />
<br />
<br />
<br /></div>
</div>
</div>
<br />
<div style="background-color: #e6f4ff; border-radius: 5px; padding-bottom: 15px; padding-left: 10px; padding-top: 15px;">
<h4>
More Articles on Spring MVC</h4>
<ul>
<li><a href="https://www.codelooru.com/2010/11/how-does-modelattribute-work.html">How does @ModelAttribute Work?</a></li>
<li><a href="http://www.codelooru.com/2017/04/localization-with-spring.html">Localization with Spring</a></li>
<li><a href="http://www.codelooru.com/2015/06/etags-and-browser-cache.html">ETags and Browser Cache</a></li>
<li><a href="https://www.codelooru.com/2019/01/error-handling-in-spring-mvc.html">Error handling in Spring MVC</a></li>
<li><a href="http://www.codelooru.com/2010/10/what-does-mvcannotation-driven-do.html">What does mvc:annotation-driven Do?</a></li>
</ul>
</div>
<br />
<br />Phee Jayhttp://www.blogger.com/profile/08103990765188490526noreply@blogger.com2tag:blogger.com,1999:blog-8051593896124641807.post-41744833446125781162010-10-18T11:23:00.001-05:002019-05-22T11:41:36.760-05:00Spring MVC - mvc:annotation-driven - What does it do?<img src="https://4.bp.blogspot.com/-FrtEIxwzQrA/WKFQ8JDEaTI/AAAAAAAAAIQ/0FcKt83eYcoQmPBShBGiFk3Cms_two7iwCLcB/s1600/springlogo.png" style="display: none;" />
<br />
<div dir="ltr" style="text-align: left;" trbidi="on">
<div xmlns="http://www.w3.org/1999/xhtml">
The annotations based MVC was introduced to the framework in Spring 2.5. This model enables the developer to reuse any POJO as a controller and is very flexible with the handler signatures. The old controller hierarchy is deprecated as of Spring 3.0. It would be removed completely from the distribution in one of the future releases.<br /><a name='more'></a>
<br />
<a name='more'></a><br />
<<b>mvc:annotation-driven</b>> tag should be added to your Web Application context XML. This tag defaults the basic components required for delegating the requests to your Controllers. <br />
<br />
<pre class="brush: xml"><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:annotation-driven />
</beans></pre>
<br />
<br />
If this tag is not added to the XML, then you will have to manually define the beans for components like HandlerAdapter, HandlerMapping, Binding Initializer, Request Message converters, etc. This tag helps registering the following components.<br />
<br />
<ol>
<li><b>DefaultAnnotationHandlerMapping</b> - This is a HandlerMapping implementation which maps the HTTP requests to the handler methods defined using the @RequestMapping annotation.<br />
</li>
<li><b>AnnotationMethodHandlerAdapter</b> - It is responsible for scanning the controllers to identify methods (and parameters) annotated with @MVC annotations. It scans and caches handler methods annotated with @RequestMapping. Also handles the @RequestParam, @ModelAttribute, @SessionAttributes and @InitBinder annotations.</li>
<li><b>ConfigurableWebBindingInitializer</b> - The initializer for the Web Data Binder. Helps in declaratively configuring the Web Binder with validators, conversion services, property editors, etc.</li>
<li><b>LocalValidatorFactoryBean</b> - Implements the validator interface and enables JSR303 validation. This is injected into ConfigurableWebBindingInitializer.</li>
<li><b>FormattingConversionServiceFactoryBean</b> - A conversion factory that returns conversion services for basic objects like date and numbers. This factory is again injected into ConfigurableWebBindingInitializer.</li>
<li>Message Converters</li>
<ul>
<li><b>ByteArrayHttpMessageConverter</b> - A HTTP request message converter that reads a HTTP message body and returns a byte stream. It can also read a byte stream and construct a response body. Used for receiving and sending documents like PDF, XLS, etc.</li>
<li><b>StringHttpMessageConverter</b> - A HTTP request message converter that reads a plain text request body and binds it to a String object. And vice-versa with response.</li>
<li><b>FormHttpMessageConverter</b> - A HTTP request message converter that reads a form encoded request body and binds it to a form Binding object.</li>
<li><b>SourceHttpMessageConverter</b> - A HTTP request converter that converts a XML message body to/from Binding Object.</li>
</ul>
</ol>
If these beans are defined in the XML instead of using <<b>mvc:annotation-driven</b>>, it would look something like this.<br />
<br />
<pre class="brush: xml"><beans xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="order" value="0">
</property></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="webBindingInitializer">
<bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="validator" ref="validator">
</property></bean>
</property>
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<bean class="org.springframework.http.converter.FormHttpMessageConverter">
<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter">
</bean></bean></bean></bean></list>
</property>
</bean>
<bean class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" id="validator">
<bean class="org.springframework.format.support.FormattingConversionServiceFactoryBean" id="conversion-service">
</bean></bean></beans>
</pre>
<br />
</div>
</div>
<br />
<div style="background-color: #e6f4ff; border-radius: 5px; padding-bottom: 15px; padding-left: 10px; padding-top: 15px;">
<h4>
More Articles on Spring MVC</h4>
<ul>
<li><a href="https://www.codelooru.com/2010/11/how-does-modelattribute-work.html">How does @ModelAttribute Work?</a></li>
<li><a href="http://www.codelooru.com/2017/04/localization-with-spring.html">Localization with Spring</a></li>
<li><a href="http://www.codelooru.com/2015/06/etags-and-browser-cache.html">ETags and Browser Cache</a></li>
<li><a href="https://www.codelooru.com/2019/01/error-handling-in-spring-mvc.html">Error handling in Spring MVC</a></li>
<li><a href="http://www.codelooru.com/2010/10/what-is-sessionattributeatore.html">What Is a SessionAttributeStore? When to Use It?</a></li>
</ul>
</div>
<br />
<br />
Phee Jayhttp://www.blogger.com/profile/08103990765188490526noreply@blogger.com1