Programming and Stuff - Michael Scharhag's Java development blog Michael Scharhag http://www.mscharhag.com A blog about programming and software development topics, mostly focused on Java technologies including Java EE, Spring and Grails. http://www.mscharhag.com/posts 2018-05-28T17:18:40Z Android Code Quality Grails Groovy Hibernate IntelliJ IDEA Java Java EE JPA JUnit Localization MongoDB MySQL Solr Spring Spring Data Spring Security 2018-05-28T17:18:40Z Java EE MVC: Handling form validation Michael Scharhag http://www.mscharhag.com tag:mscharhag.com,2018-05-27:09bf1aff-87d3-4e80-9417-444b6485f5fc 2018-05-28T17:18:40Z 2018-05-28T17:18:40Z <p>In this post we will have a look on form validation in Java EE MVC.</p> <p>Java EE MVC integrates with the Java Bean Validation API (<a href="http://beanvalidation.org/1.0/spec/">JSR 303</a>) which makes adding validation constraints pretty easy.</p> <h2>Validation using the JAX-RS way</h2> <p>Assume we have a small html form that can be used to send contact messages. To represent the form data we create a small <span class="code">ContactMessage</span> bean containing the form fields and validation constraints:</p> <pre class="brush: java"> public&nbsp;class&nbsp;ContactMessage&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;@FormParam(&quot;message&quot;) &nbsp;&nbsp;&nbsp;&nbsp;@NotBlank &nbsp;&nbsp;&nbsp;&nbsp;@Size(max&nbsp;=&nbsp;1000) &nbsp;&nbsp;&nbsp;&nbsp;private&nbsp;String&nbsp;message; &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;getters&nbsp;/&nbsp;setters } </pre> <p>In our MVC controller we use the <span class="code">@BeanParam</span> annotation to convert the form data to a <span class="code">ContactMessage</span> object:</p> <pre class="brush: java"> @Controller @Path(&quot;/&quot;) public&nbsp;class&nbsp;ContactController&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;@POST &nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;String&nbsp;formSubmit(@Valid&nbsp;@BeanParam&nbsp;ContactMessage&nbsp;message)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;... &nbsp;&nbsp;&nbsp;&nbsp;} } </pre> <p>(For more details about the <span class="code">@BeanParam</span> annotation, have a look at the blog post <a href="https://www.mscharhag.com/java-ee-mvc/bean-parameters">Working with bean parameters</a>)</p> <p>By adding the <span class="code">@Valid</span> annotation to the <span class="code">ContactMessage</span> parameter we enable validation. If a form is submitted and the validation of the <span class="code">ContactMessage</span> object fails, a <span class="code">ConstraintViolationException</span> will be thrown. The controller method will not be called in this case. Instead, the exception can be handled using a generic JAX-RS <span class="code">ExceptionMapper</span> like shown in another post: <a href="https://www.mscharhag.com/java-ee-mvc/global-exception-handling">Global Exception handling in Java EE MVC</a>.</p> <p>This approach is typically fine for standard JAX-RS REST endpoints. Here we often want to return a generic HTTP 400 (Bad request) status code if invalid data has been passed to the server.</p> <p>In an MVC environment we can use this behaviour to render a standard error page to the user, whenever invalid data has been passed. However, this is often not flexible enough. Often we want to return a more specific page that shows an error message to the user.</p> <h2>Validation using <span class="code">@MvcBinding</span> and <span class="code">BindingResult</span></h2> <p>Java EE MVC provides a <span class="code">@MvcBinding</span> annotation that enables an alternative exception handling mechanism. <span class="code">@MvcBinding</span> can be placed on fields and method parameters together with JAX-RS binding annotations (like <span class="code">@FormParam</span>):</p> <pre class="brush: java"> public&nbsp;class&nbsp;ContactMessage&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;@MvcBinding &nbsp;&nbsp;&nbsp;&nbsp;@FormParam(&quot;message&quot;) &nbsp;&nbsp;&nbsp;&nbsp;@NotBlank &nbsp;&nbsp;&nbsp;&nbsp;@Size(max&nbsp;=&nbsp;1000) &nbsp;&nbsp;&nbsp;&nbsp;private&nbsp;String&nbsp;message; &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;getters&nbsp;/&nbsp;setters } </pre> <p><br /> This tells Java EE MVC to call the controller method instead of the generic exception handler if binding of the annotated field fails. To access binding information, we can inject a <span class="code">BindingResult</span> object into our controller class:</p> <pre class="brush: java"> @Controller @Path(&quot;/&quot;) public&nbsp;class&nbsp;ContactController&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;@Inject &nbsp;&nbsp;&nbsp;&nbsp;private&nbsp;Models&nbsp;models; &nbsp;&nbsp;&nbsp;&nbsp;@Inject &nbsp;&nbsp;&nbsp;&nbsp;private&nbsp;BindingResult&nbsp;bindingResult; &nbsp;&nbsp;&nbsp;&nbsp;@POST &nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;String&nbsp;formSubmit(@Valid&nbsp;@BeanParam&nbsp;ContactMessage&nbsp;message)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(bindingResult.isFailed())&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;models.put(&quot;bindingResult&quot;,&nbsp;bindingResult); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;&quot;/WEB-INF/jsp/contact.jsp&quot;; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;&quot;/WEB-INF/jsp/success.jsp&quot;; &nbsp;&nbsp;&nbsp;&nbsp;} } </pre> <p>As the name suggests, we can use the injected <span class="code">BindingResult</span> object to access binding information within a controller method. In this example we simply check if there was a binding problem by calling <span class="code">isFailed()</span>. By adding the <span class="code">bindingResult</span> to the model, we can access it later in the view to show an error message to the user.</p> <p>A simple JSP view that displays all validation errors below the submit button looks like this:</p> <pre class="brush: xml"> &lt;form&nbsp;action=&quot;${mvc.contextPath}/contact&quot;&nbsp;method=&quot;post&quot;&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;label&gt;Message:&lt;/label&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;textarea&nbsp;name=&quot;message&quot;&gt;&lt;/textarea&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;br/&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;input&nbsp;type=&quot;submit&quot;/&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;c:if&nbsp;test=&quot;${bindingResult.isFailed()}&quot;&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;p&gt;Form&nbsp;validation&nbsp;failed.&nbsp;Reasons:&lt;/p&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;ul&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;c:forEach&nbsp;items=&quot;${bindingResult.allValidationErrors}&quot;&nbsp;var=&quot;validationError&quot;&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;li&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;c:out&nbsp;value=&quot;${validationError.paramName}:&nbsp;${validationError.message}&quot;/&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/li&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/c:forEach&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/ul&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;/c:if&gt; &lt;/form&gt; </pre> <h2>Conclusion</h2> <p>Form validation is pretty easy with Java EE MVC. Validation constraints can be added to beans using JSR 303 Bean validation annotations. <span class="code">@MvcBinding</span> allows us to handle validation errors within controller methods instead of using generic ExceptionMappers. <span class="code">BindingResult</span> gives us access to validation information.</p> <p>As always you can find the example code on <a href="https://github.com/mscharhag/java-ee-8-mvc/tree/master/validation">GitHub</a>.</p> 2018-05-28T17:18:40Z Using Java Stream summary statistics Michael Scharhag http://www.mscharhag.com tag:mscharhag.com,2018-05-21:75632d29-6720-4eb9-a16d-0c3834cabd10 2018-05-21T09:19:18Z 2018-05-21T09:19:23Z <p>Streams of primitive types (<span class="code">IntStream</span>, etc.) provide a <span class="code">summaryStatistics()</span> method that can be used to get multiple <em>statistical</em> properties of a stream (minimum value, average value, etc.).</p> <p>Assume we have a list of people. Our goal is to get the minimum and maximum age of the people in the list using streams.</p> <p>The problem here is that the computation of the minimum and maximum values are terminal stream operations. So we need to come up with our own reduction implementation or create a new stream for every computation. A naive implementation might look like this:</p> <pre class="brush: java"> List&lt;Person&gt;&nbsp;list&nbsp;=&nbsp;Arrays.asList( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;new&nbsp;Person(&quot;John&nbsp;Blue&quot;,&nbsp;28), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;new&nbsp;Person(&quot;Anna&nbsp;Brown&quot;,&nbsp;53), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;new&nbsp;Person(&quot;Paul&nbsp;Black&quot;,&nbsp;47) ); int&nbsp;min&nbsp;=&nbsp;list.stream() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.mapToInt(Person::getAge) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.min() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.orElseThrow(NoSuchElementException::new); int&nbsp;max&nbsp;=&nbsp;list.stream() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.mapToInt(Person::getAge) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.max() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.orElseThrow(NoSuchElementException::new); </pre> <p>Luckily Java provides a much simpler way to do this using the <span class="code">summaryStatistics()</span> method:</p> <pre class="brush: java"> IntSummaryStatistics&nbsp;statistics&nbsp;=&nbsp;list.stream() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.mapToInt(Person::getAge) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.summaryStatistics(); int&nbsp;min&nbsp;=&nbsp;statistics.getMin(); int&nbsp;max&nbsp;=&nbsp;statistics.getMax(); </pre> <p><span class="code">IntSummaryStatistics</span> also provides methods to obtain the count and sum of the stream elements.</p> <p>You can find the full example code on <a href="https://github.com/mscharhag/blog-examples/blob/master/streamstatistics/src/main/java/com/mscharhag/streamstatistics/Example.java">GitHub</a>.</p> 2018-05-21T09:19:23Z Templating with Rocker Michael Scharhag http://www.mscharhag.com tag:mscharhag.com,2017-08-09:0938bafb-73b1-43d9-88ea-e11d3f45da09 2018-05-18T16:39:53Z 2018-05-13T16:39:53Z <p>In this post we will have a quick look at <a href="https://github.com/fizzed/rocker">Rocker</a>, a statically typed and fast Java 8 template engine.</p> <h2>Requireded Dependencies</h2> <p>To get started with Rocker we need to add the following dependencies to our project:</p> <pre class="brush: xml"> &lt;dependency&gt; &nbsp;&nbsp;&lt;groupId&gt;com.fizzed&lt;/groupId&gt; &nbsp;&nbsp;&lt;artifactId&gt;rocker-runtime&lt;/artifactId&gt; &nbsp;&nbsp;&lt;version&gt;0.24.0&lt;/version&gt; &lt;/dependency&gt; &lt;!--&nbsp;for&nbsp;hot-reloading&nbsp;support&nbsp;in&nbsp;development&nbsp;--&gt; &lt;dependency&gt; &nbsp;&nbsp;&lt;groupId&gt;com.fizzed&lt;/groupId&gt; &nbsp;&nbsp;&lt;artifactId&gt;rocker-compiler&lt;/artifactId&gt; &nbsp;&nbsp;&lt;version&gt;0.24.0&lt;/version&gt; &lt;/dependency&gt;</pre> <p>We also need the Rocker Maven plugin, which converts Rocker templates to Java code:</p> <pre class="brush: xml"> &lt;build&gt; &nbsp;&nbsp;&lt;plugins&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;plugin&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;groupId&gt;com.fizzed&lt;/groupId&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;artifactId&gt;rocker-maven-plugin&lt;/artifactId&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;version&gt;0.24.0&lt;/version&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;executions&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;execution&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;id&gt;generate-rocker-templates&lt;/id&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;phase&gt;generate-sources&lt;/phase&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;goals&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;goal&gt;generate&lt;/goal&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/goals&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/execution&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/executions&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;/plugin&gt; &nbsp;&nbsp;&lt;/plugins&gt; &lt;/build&gt;</pre> <h2>Creating the first templates</h2> <p>We will start with a simple example containing two Rocker templates and a Java class.</p> <p>In the first template (<em>main.rocker.html</em>) we define the basic page structure:</p> <pre class="brush: xml"> @args&nbsp;(String&nbsp;title,&nbsp;RockerBody&nbsp;content) &lt;html&gt; &nbsp;&nbsp;&lt;head&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;title&gt;@title&lt;/title&gt; &nbsp;&nbsp;&lt;/head&gt; &nbsp;&nbsp;&lt;body&gt; &nbsp;&nbsp;&nbsp;&nbsp;@content &nbsp;&nbsp;&lt;/body&gt; &lt;/html&gt;</pre> <p>This template has two parameters: The page <span class="code">title</span> and a <span class="code">RockerBody</span> element named <span class="code">content</span>. The <span class="code">content</span> parameter is basically a sub template that is added to the <span class="code">&lt;body&gt;</span> tag.</p> <p>Now we create another template (<em>basic.rocker.html</em>) that defines the content that is passed to our first template:</p> <pre class="brush: xml"> @args&nbsp;(String&nbsp;name) @views.main.template(&quot;Basic&nbsp;example&quot;)&nbsp;-&gt;&nbsp;{ &nbsp;&nbsp;&lt;h1&gt;Hello&nbsp;@name!&lt;/h1&gt; }</pre> <p>This template has a single <span class="code">name</span> parameter that is written to a <span class="code">&lt;h1&gt;</span> tag. We reference the first template (<i>main.rocker.html</i>) with <span class="code">@views.main</span> and use the <span class="code">template(..)</span> method to render it. <i>&quot;Basic example&quot;</i> will be passed as <span class="code">title</span> parameter. The <span class="code">content</span> parameter is defined within the curly braces.</p> <h2>Rendering Rocker templates</h2> <p>Rocker templates are converted to Java code. This can be done using the following Maven command:</p> <pre> mvn generate-sources</pre> <p>This generates a Java class for each template in the <em>target/generated-sources/rocker</em> directory.</p> <p>Now we can render our templates using Java code:</p> <pre class="brush: java"> public&nbsp;class&nbsp;Main&nbsp;{ &nbsp;&nbsp;public&nbsp;static&nbsp;void&nbsp;main(String...&nbsp;args)&nbsp;throws&nbsp;Exception&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;The&nbsp;template&nbsp;&quot;basic.rocker.html&quot;&nbsp;got&nbsp;converted&nbsp;to&nbsp;the&nbsp;class&nbsp;named&nbsp;&quot;basic&quot; &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;which&nbsp;is&nbsp;located&nbsp;in&nbsp;the&nbsp;&quot;views&quot;&nbsp;package &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;String&nbsp;result&nbsp;=&nbsp;views.basic.template(&quot;John&quot;) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.render() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.toString(); &nbsp;&nbsp;&nbsp;&nbsp;System.out.println(result); &nbsp;&nbsp;} }</pre> <p>The output we get looks like this:</p> <pre class="brush: xml"> &lt;html&gt; &nbsp;&nbsp;&lt;head&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;title&gt;Basic&nbsp;example&lt;/title&gt; &nbsp;&nbsp;&lt;/head&gt; &nbsp;&nbsp;&lt;body&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;h1&gt;Hello&nbsp;John!&lt;/h1&gt; &nbsp;&nbsp;&lt;/body&gt; &lt;/html&gt;</pre> <p>A bit of a problem with this approach is that you need to run <span class="code">mvn generate-sources</span> everytime you make a change in your template files. Also note, that your Java code might not compile if the code generation fails because you have an issue in one of your templates.</p> <p>Another possible approach is to use hot reloading and reference the templates dynamically via file names.</p> <p>In this case the Java code looks like this:</p> <pre class="brush: java"> public&nbsp;class&nbsp;Main&nbsp;{ &nbsp;&nbsp;public&nbsp;static&nbsp;void&nbsp;main(String...&nbsp;args)&nbsp;throws&nbsp;Exception&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;Enable&nbsp;hot&nbsp;reloading &nbsp;&nbsp;&nbsp;&nbsp;RockerRuntime.getInstance().setReloading(true); &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;Reference&nbsp;via&nbsp;string&nbsp;instead&nbsp;of&nbsp;using&nbsp;generated&nbsp;code &nbsp;&nbsp;&nbsp;&nbsp;String&nbsp;result&nbsp;=&nbsp;Rocker.template(&quot;views/basic.rocker.html&quot;) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.bind(&quot;name&quot;,&nbsp;&quot;John&quot;) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.render() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.toString(); &nbsp;&nbsp;&nbsp;&nbsp;System.out.println(result) &nbsp;&nbsp;} }</pre> <p>The output we get is exactly the same.</p> <h2>Expressions</h2> <p>Assume we have a simple User class that contains the methods <span class="code">getFirstName()</span> and <span class="code">getLastName()</span>. In the following example we see how we can work with the <span class="code">User</span> object in a Rocker template:</p> <pre class="brush: xml"> @import&nbsp;com.mscharhag.rockerexample.* @args&nbsp;(User&nbsp;user) @views.main.template(&quot;Expressions&quot;)&nbsp;-&gt;&nbsp;{ &nbsp;&nbsp;&lt;ul&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;!--&nbsp;first&nbsp;name&nbsp;--&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;li&gt;@user.getFirstName()&lt;/li&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;!--&nbsp;first&nbsp;three&nbsp;letters&nbsp;of&nbsp;first&nbsp;name&nbsp;--&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;li&gt;@user.getFirstName().substring(0,&nbsp;3)&lt;/li&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;!--&nbsp;first&nbsp;name&nbsp;and&nbsp;last&nbsp;name&nbsp;--&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;li&gt;@user.getFirstName()&nbsp;@user.getLastName()&lt;/li&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;!--&nbsp;using&nbsp;a&nbsp;variable--&gt; &nbsp;&nbsp;&nbsp;&nbsp;@name&nbsp;=&gt;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@user.getFirstName()&nbsp;@user.getLastName() &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&lt;li&gt;@name&lt;/li&gt; &nbsp;&nbsp;&lt;/ul&gt; }</pre> <h2>Conditions</h2> <p>Rocker supports the standard Java if-else flow structure as the following example shows:</p> <pre class="brush: xml"> @import&nbsp;com.mscharhag.rockerexample.* @args&nbsp;(User&nbsp;user) @views.main.template(&quot;Conditions&quot;)&nbsp;-&gt;&nbsp;{ &nbsp;&nbsp;@if&nbsp;(user.getFirstName().length()&nbsp;&gt;&nbsp;10)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&lt;p&gt;Long&nbsp;first&nbsp;name&lt;/p&gt; &nbsp;&nbsp;}&nbsp;else&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&lt;p&gt;short&nbsp;first&nbsp;name&lt;/p&gt; &nbsp;&nbsp;} }</pre> <h2>Loops</h2> <p>Rocker templates support different forms of loops:</p> <pre class="brush: xml"> @import&nbsp;com.mscharhag.rockerexample.* @import&nbsp;java.util.* @args&nbsp;(List&lt;User&gt;&nbsp;users) @views.main.template(&quot;Loops&quot;)&nbsp;-&gt;&nbsp;{ &nbsp;&nbsp;&lt;ul&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;!--&nbsp;standard&nbsp;for&nbsp;loop&nbsp;--&gt; &nbsp;&nbsp;&nbsp;&nbsp;@for&nbsp;(int&nbsp;i&nbsp;=&nbsp;0;&nbsp;i&nbsp;&lt;&nbsp;users.size();&nbsp;i++)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;li&gt;@users.get(i).getFirstName()&lt;/li&gt; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&lt;!--&nbsp;standard&nbsp;&#39;for&nbsp;each&#39;&nbsp;loop&nbsp;--&gt; &nbsp;&nbsp;&nbsp;&nbsp;@for&nbsp;(User&nbsp;user&nbsp;:&nbsp;users)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;li&gt;@user.getFirstName()&lt;/li&gt; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&lt;!--&nbsp;for&nbsp;each&nbsp;loop&nbsp;with&nbsp;additional&nbsp;loop&nbsp;information &nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;li&gt;0:&nbsp;John,&nbsp;first:&nbsp;true,&nbsp;last:&nbsp;false&lt;/li&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;li&gt;1:&nbsp;Martin,&nbsp;first:&nbsp;false,&nbsp;last:&nbsp;false&lt;/li&gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;li&gt;2:&nbsp;Anna,&nbsp;first:&nbsp;false,&nbsp;last:&nbsp;true&lt;/li&gt; &nbsp;&nbsp;&nbsp;&nbsp;--&gt; &nbsp;&nbsp;&nbsp;&nbsp;@for&nbsp;((i,&nbsp;user)&nbsp;:&nbsp;users)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;li&gt;@i.index():&nbsp;@user.getFirstName(),&nbsp;first:&nbsp;@i.first(),&nbsp;last:&nbsp;@i.last()&lt;/li&gt; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp; &nbsp;&nbsp;&lt;/ul&gt; }</pre> <p>The last loop is a special variation of Java&#39;s for-each loop. A second index parameter (named <span class="code">i</span> in the example) can be used to access current iteration information.</p> <h2>Conclusion</h2> <p>Rocker can be definitively an option if you are looking for a Java template engine. According to the benchmark on the <a href="https://github.com/fizzed/rocker">Rocker GitHub repository</a> Rocker is a lot faster than other Java template engines like Freemarker or Velocity. The comprehensive documentation is another good point to mention.</p> <p>The fact that Rocker compiles to Java and allows you to pass data to views in a typesafe way is quite interesting. On one side this is useful because it helps to reduce bugs. On the other side the same feature annoyed me a bit, while I was writing the examples. Whenever I made code changes that affected Rocker templates (e.g. by changing the name of a method that was called within a Rocker template) the templates stopped compiling. In some situations this again stopped my Java code from compiling (because it was using the classes generated by Rocker). This is expected but it can break my preferred workflow of writing Java code first and fixing the templates later. Referencing templates via file names instead of using the generated classes solved this problem (but also throws away the type checking at compile time).</p> <p>You can find the code for the posted examples on <a href="https://github.com/mscharhag/blog-examples/tree/master/rockerdemo">GitHub</a>.</p> 2018-05-13T16:39:53Z Be aware that bcrypt has a maximum password length Michael Scharhag http://www.mscharhag.com tag:mscharhag.com,2017-03-03:3735b6dd-7a7c-4ba4-9b2f-93283f4b3720 2017-03-05T21:31:42Z 2017-03-05T21:31:47Z <p><a href="https://en.wikipedia.org/wiki/Bcrypt">bcrypt</a> is a popular password hashing function these days. Other than standard hash functions (like SHA-515), bcrypt is designed to be slow and therefore very resistant to brute force attacks.</p> <p>However, when using bcrypt you should be aware that it limits your maximum password length to 50-72 bytes. The exact length depends on the bcrypt implementation you are using (see <a href="http://security.stackexchange.com/questions/39849/does-bcrypt-have-a-maximum-password-length">this stackexchange answer</a>).</p> <p>Passwords that exceed the maximum length will be truncated.</p> <p>The following piece of code shows the password truncation using Spring Securities <span class="code">BCryptPasswordEncoder</span>:</p> <pre class="brush: java"> BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); // 72 characters String password1 = &quot;aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&quot;; // 73 characters String password2 = &quot;aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab&quot;; String encodedPassword1 = passwordEncoder.encode(password1); boolean matches = passwordEncoder.matches(password2, encodedPassword1); System.out.println(&quot;encodedPassword1: &quot; + encodedPassword1); System.out.println(&quot;matches: &quot; + matches); </pre> <p>When running this example, the output might look like this:</p> <pre> encodedPassword1: $2a$10$A5OpVKgjEZzmy6UNsqzkjuG2xGET1wp3b/9ET5dz/tHQ3eRvyXSSO matches: true </pre> <p>According to <span class="code">BCryptPasswordEncoder</span> both passwords match (= are identical) even if they have a different length.</p> 2017-03-05T21:31:47Z Java EE 8 MVC: Global exception handling Michael Scharhag http://www.mscharhag.com tag:mscharhag.com,2016-04-27:f728e4b6-1135-4080-903c-769a1db0c881 2016-04-27T16:10:15Z 2016-04-27T16:10:20Z <p>In the previous previous posts we learned about various ways to access request information (e.g. <a href="http://www.mscharhag.com/java-ee-mvc/query-parameters">query</a> or <a href="http://www.mscharhag.com/java-ee-mvc/path-parameters">path parameters</a>) in Java EE MVC. This post shows how to apply global exception handling to an MVC application.</p> <p>Assume we have a controller method that might throw an <span class="code">IllegalArgumentException</span>:</p> <pre class="brush: java"> @Controller @Path(&quot;illegal-argument&quot;) public&nbsp;class&nbsp;ExceptionController&nbsp;{ &nbsp;&nbsp;@GET &nbsp;&nbsp;public&nbsp;String&nbsp;doWork()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;code&nbsp;that&nbsp;might&nbsp;throw&nbsp;an&nbsp;IllegalArgumentException &nbsp;&nbsp;} } </pre> <p>We could now add a <span class="code">try</span>/<span class="code">catch</span> block to <span class="code">doWork()</span> and wrap the piece of code that might throw the exception. However, this approach becomes tedious if it needs to be applied to multiple methods.</p> <p>In such a case we can register a global exception mapper. To do this, we habe to create a class that implements the generic <span class="code">ExceptionMapper</span> interface.</p> <p>A simple <span class="code">ExceptionMapper</span> for <span class="code">IllegalArgumentExceptions</span> looks like this:</p> <pre class="brush: java"> @Provider public&nbsp;class&nbsp;IllegalArgumentExceptionMapper&nbsp;implements&nbsp;ExceptionMapper&lt;IllegalArgumentException&gt;&nbsp;{ &nbsp;&nbsp;@Inject &nbsp;&nbsp;private&nbsp;Models&nbsp;models; &nbsp;&nbsp;@Override &nbsp;&nbsp;public&nbsp;Response&nbsp;toResponse(IllegalArgumentException&nbsp;exception)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;models.put(&quot;message&quot;,&nbsp;exception.getMessage()); &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;Response.status(Response.Status.BAD_REQUEST) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.entity(&quot;/WEB-INF/jsp/error.jsp&quot;) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.build(); &nbsp;&nbsp;} } </pre> <p>Now, whenever an <span class="code">IllegalArgumentException</span> is thrown from controller methods, <span class="code">IllegalArgumentExceptionMapper</span> will be used to convert the exception to an appropriate response. Here a simple error view (error.jsp) is rendered.</p> <p>If you want a generic <span class="code">ExceptionMapper</span> that handles all types of exceptions, you simply have to implement <span class="code">ExceptionMapper&lt;Exception&gt;</span>. If you have multiple <span class="code">ExceptionMapper</span> implementations that are suitable to handle a thrown exception, the most specific <span class="code">ExceptionMapper</span> is used.</p> <h2>Quick Summary</h2> <p>Adding global exception handling to an Java EE MVC application is quite simple. We only have to create a class that implements the <span class="code">ExceptionMapper</span> interface with the exception type that should be handled.</p> <p>The full example code can be found on <a href="https://github.com/mscharhag/java-ee-8-mvc/tree/master/exceptions">GitHub</a>.</p> 2016-04-27T16:10:20Z Simplifying nested loops with Java 8 Lambdas Michael Scharhag http://www.mscharhag.com tag:mscharhag.com,2016-04-03:1218dbff-91ca-4dd6-a88e-ef47369c9ea6 2016-04-03T17:44:41Z 2016-04-03T17:44:52Z <p>This is just a quick tip for everyone who often has to work with multi dimensional arrays in Java 8 (or newer).</p> <p>In this case you might often end with code similar to this:</p> <pre class="brush: java"> float[][]&nbsp;values&nbsp;=&nbsp;... for&nbsp;(int&nbsp;i&nbsp;=&nbsp;0;&nbsp;i&nbsp;&lt;&nbsp;values.length;&nbsp;i++)&nbsp;{ &nbsp;&nbsp;for&nbsp;(int&nbsp;k&nbsp;=&nbsp;0;&nbsp;k&nbsp;&lt;&nbsp;values[i].length;&nbsp;k++)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;float&nbsp;value&nbsp;=&nbsp;values[i][k]; &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;do&nbsp;something&nbsp;with&nbsp;i,&nbsp;k&nbsp;and&nbsp;value &nbsp;&nbsp;} }</pre> <p>If you are lucky you can replace the loops with for-each loops. However, often the indices are required for computations inside the loop.</p> <p>In such a case you can come up with a simple utility method that looks like this:</p> <pre class="brush: java"> private&nbsp;void&nbsp;loop(float[][]&nbsp;values,&nbsp;BiConsumer&lt;Integer,&nbsp;Integer&gt;&nbsp;consumer)&nbsp;{ &nbsp;&nbsp;for&nbsp;(int&nbsp;i&nbsp;=&nbsp;0;&nbsp;i&nbsp;&lt;&nbsp;values.length;&nbsp;i++)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;for&nbsp;(int&nbsp;k&nbsp;=&nbsp;0;&nbsp;k&nbsp;&lt;&nbsp;values[i].length;&nbsp;k++)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;consumer.accept(i,&nbsp;k); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;} } </pre> <p>We can now loop over array indices like this:</p> <pre class="brush: java"> float[][]&nbsp;values&nbsp;=&nbsp;... loop(values,&nbsp;(i,&nbsp;k)&nbsp;-&gt;&nbsp;{ &nbsp;&nbsp;float&nbsp;value&nbsp;=&nbsp;values[i][k]; &nbsp;&nbsp;//&nbsp;do&nbsp;something&nbsp;with&nbsp;i,&nbsp;k&nbsp;and&nbsp;value }); </pre> <p>This way you can keep the looping code out of your main logic.</p> <p>Of course you should change the shown <span class="code">loop()</span> method so it fits your personal needs.</p> <p>&nbsp;</p> 2016-04-03T17:44:52Z Retry handling with Spring-Retry Michael Scharhag http://www.mscharhag.com tag:mscharhag.com,2016-03-30:e7238680-c480-4083-9ed0-812e29f0e6ea 2016-03-30T20:47:22Z 2016-03-30T20:47:22Z <p>Whenever software components communicate with each other, there is a chance for temporary self-correcting faults. Such faults include the temporary unavailability of a service, momentary loss of network connectivity, or timeouts that arise when a service is busy. In such situations a proper retry handling can reduce the problems these faults might cause.</p> <p>In this post we will see how <a href="https://github.com/spring-projects/spring-retry" title="Spring Retry GitHub project">Spring Retry</a> can be used to add robust retry logic to Spring applications. Spring Retry is probably not that well know because it is not listed on the <a href="http://spring.io/docs/reference" title="Spring reference documentation">Spring documentation overview</a>. However, you can find it on the <a href="http://start.spring.io/" title="Spring Initializr">Spring Initializr page</a>.</p> <h2>Setup</h2> <p>To use Spring Retry we need to add the following dependency to our project:</p> <pre class="brush: xml"> &lt;dependency&gt; &nbsp;&nbsp;&lt;groupid&gt;org.springframework.retry&lt;/groupid&gt; &nbsp;&nbsp;&lt;artifactid&gt;spring-retry&lt;/artifactid&gt; &nbsp;&nbsp;&lt;version&gt;1.1.2.RELEASE&lt;/version&gt; &lt;/dependency&gt;</pre> <p>Spring Retry makes use of AOP, so make sure Spring AOP is available:</p> <pre class="brush: xml"> &lt;dependency&gt; &nbsp;&nbsp;&lt;groupid&gt;org.springframework&lt;/groupid&gt; &nbsp;&nbsp;&lt;artifactid&gt;spring-aop&lt;/artifactid&gt; &nbsp;&nbsp;&lt;version&gt;4.2.5.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &nbsp;&nbsp;&lt;groupId&gt;org.aspectj&lt;/groupId&gt; &nbsp;&nbsp;&lt;artifactId&gt;aspectjweaver&lt;/artifactId&gt; &nbsp;&nbsp;&lt;version&gt;1.8.8&lt;/version&gt; &lt;/dependency&gt; </pre> <p>If you are using <a href="http://projects.spring.io/spring-boot/">Spring Boot</a>, you can use <span class="code">spring-boot-starter-aop</span> instead:</p> <pre class="brush: xml"> &lt;dependency&gt; &nbsp;&nbsp;&lt;groupid&gt;org.springframework.boot&lt;/groupid&gt; &nbsp;&nbsp;&lt;artifactid&gt;spring-boot-starter-aop&lt;/artifactid&gt; &lt;/dependency&gt; </pre> <p>To enable Spring Retry we simply have to add <span class="code">@EnableRetry</span> to our application configuration class:</p> <pre class="brush: java"> @EnableRetry @SpringBootApplication // or @Configuration if you are not using Spring Boot public class RetryExampleApplication { // ... } </pre> <h2>Adding retry handling with Annotations</h2> <p>We are now ready to add retry handling to methods. To do so, we simply have to annotate the appropriate methods with <span class="code">@Retryable</span>:</p> <pre class="brush: java"> @Service public class MyService { @Retryable public void simpleRetry() { // perform operation that is likely to fail } } </pre> <p>Methods annotated with <span class="code">@Retryable</span> can be called like any other methods. However, whenever the execution of a retryable method fails with an exception, Spring will automatically retry to call the method up to three times. By default Spring uses a 1 second delay between method calls. Please note that the calling thread blocks during retry handling.</p> <p>The retry behavior can be customized in various ways. For example:</p> <pre class="brush: java"> @Service public class MyService { @Retryable(value = {FooException.class, BarException.class}, maxAttempts = 5) public void retryWithException() { // perform operation that is likely to fail } @Recover public void recover(FooException exception) { // recover from FooException } } </pre> <p>Here we tell Spring to apply retry handling only if a Exception of type <span class="code">FooException</span> or <span class="code">BarException</span> is thrown. Other exceptions will not cause a retry. <span class="code">maxAttempts = 5</span> tells Spring to retry the method up to 5 times if it fails.</p> <p>With <span class="code">@Recover</span> we define a separate recovery method for <span class="code">FooException</span>. This allows us to run special recovery code when a retryable method fails with <span class="code">FooException</span>.</p> <h2>Adding retry handling with <span class="code">RetryTemplate</span></h2> <p>Besides annotations Spring Retry offers a <span class="code">RetryTemplate</span> that can be used to define retry handling in Java code. Like any other bean, a <span class="code">RetryTemplate</span> can simply be configured in our configuration class:</p> <pre class="brush: java"> @EnableRetry @SpringBootApplication // or @Configuration if you are not using Spring Boot public class RetryExampleApplication { @Bean public RetryTemplate retryTemplate() { SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(); retryPolicy.setMaxAttempts(5); FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy(); backOffPolicy.setBackOffPeriod(1500); // 1.5 seconds RetryTemplate template = new RetryTemplate(); template.setRetryPolicy(retryPolicy); template.setBackOffPolicy(backOffPolicy); return template; } // ... }</pre> <p>A <span class="code">RetryPolicy</span> determines when an operation should be retried. <span class="code">SimpleRetryPolicy</span> is a <span class="code">RetryPolicy</span> implementation that retries a fixed number of times.</p> <p>A <span class="code">BackOffPolicy</span> is a strategy interface to control back off between retry attempts. A <span class="code">FixedBackOffPolicy</span> pauses for a fixed period of time before continuing. Some other default <span class="code">BackOffPolicy</span> implementations are <span class="code">ExponentialBackOffPolicy</span> (increases the back off period for each retry) or <span class="code">NoBackOffPolicy</span> (no delay between retries).</p> <p>We can now inject the <span class="code">RetryTemplate</span> to our service. To run code with retry handling we simply have to call <span class="code">RetryTemplate.execute()</span>:</p> <pre class="brush: java"> @Service public class RetryService { @Autowired private RetryTemplate retryTemplate; public void withTemplate() { retryTemplate.execute(context -&gt; { // perform operation that is likely to fail }); } // ... } </pre> <p><span class="code">RetryTemplate.exeucte()</span> takes a <span class="code">RetryCallback&lt;T, E&gt;</span> as parameter. <span class="code">RetryCallback</span> is a functional interface so it can be implemented using a Java 8 Lambda expression (as shown above).</p> <h2>Summary</h2> <p>Spring retry provides an easy way to add retry handling to spring applications. Retry handling can be added using either annotations (<span class="code">@Retryable</span> and <span class="code">@Recover</span>) or by passing a <span class="code">RetryCallback</span> to a <span class="code">RetryTemplate</span>.</p> <p>You can find the full example source code on <a title="Example source code on GitHub" href="https://github.com/mscharhag/blog-examples/tree/master/spring-retry-demo">GitHub</a>.</p> 2016-03-30T20:47:22Z Java EE 8 MVC: Working with bean parameters Michael Scharhag http://www.mscharhag.com tag:mscharhag.com,2016-03-15:33c556cb-fd6e-4aba-9d83-d26c55257a4f 2016-03-15T17:24:22Z 2016-03-15T17:24:29Z <p>In the last posts we saw how to access <a href="http://www.mscharhag.com/java-ee-mvc/query-parameters" title="Working with query parameters">query</a>, <a href="http://www.mscharhag.com/java-ee-mvc/path-parameters" title="Working with path parameters">path</a> and <a href="http://www.mscharhag.com/java-ee-mvc/form-parameters" title="Working with form parameters">form parameters</a> in MVC Controllers. This post shows how multiple parameters can be mapped to an object using the <span class="code">@BeanParam</span> annotation.</p> <p>Let&#39;s reuse the simple HTML form from the post about <a href="http://www.mscharhag.com/java-ee-mvc/form-parameters" title="Working with form parameters">form parameters</a>:</p> <pre class="brush:xml"> &lt;form&nbsp;action=&quot;submit&quot;&nbsp;method=&quot;post&quot;&gt; &nbsp;&nbsp;&lt;label&gt;ID:&lt;/label&gt; &nbsp;&nbsp;&lt;input&nbsp;type=&quot;text&quot;&nbsp;name=&quot;id&quot;&nbsp;/&gt; &nbsp;&nbsp;&lt;label&gt;Name:&lt;/label&gt; &nbsp;&nbsp;&lt;input&nbsp;type=&quot;text&quot;&nbsp;name=&quot;name&quot;&nbsp;/&gt; &nbsp;&nbsp;&lt;label&gt;Role:&lt;/label&gt; &nbsp;&nbsp;&lt;select&nbsp;name=&quot;role&quot;&gt; &lt;option&nbsp;value=&quot;admin&quot;&gt;Admin&lt;/option&gt; &lt;option&nbsp;value=&quot;reporter&quot;&gt;Reporter&lt;/option&gt; &lt;option&nbsp;value=&quot;accountant&quot;&gt;Accountant&lt;/option&gt; &nbsp;&nbsp;&lt;/select&gt; &nbsp;&nbsp;&lt;input&nbsp;type=&quot;submit&quot;/&gt; &lt;/form&gt;</pre> <p>This defines a simple form containing two text input fields and a select menu with three options.</p> <p>In the previous post about <a href="http://www.mscharhag.com/java-ee-mvc/form-parameters" title="Working with form parameters">form parameters</a>, we learned that we can access these parameters by annotating controller parameters with <span class="code">@FormParam</span>.</p> <p>However, this approach is cumbersome if the form has more than a few parameters. In these situations we typically want to map form parameters to a separate object. <span class="code">@BeanParams</span> helps us with doing exactly this.</p> <p>With <span class="code">@BeanParam</span> we can write:</p> <pre class="brush: java"> @POST @Path(&quot;submit&quot;) @Controller public String submit(@BeanParam User user) { // use user .. }</pre> <p>The <span class="code">User</span> class looks like this:</p> <pre class="brush: java"> public class User { @FormParam(&quot;id&quot;) private long id; @FormParam(&quot;name&quot;) private String name; @FormParam(&quot;role&quot;) private Role role; // getters and setters }</pre> <p><br /> When the controller method is called a new instance of <span class="code">User</span> will automatically be created. The fields of the created object will be filled with the passed form parameters.</p> <h2>@BeanParam and other parameter annotations</h2> <p>Classes used with <span class="code">@BeanParam</span> are not limited to form parameters. All parameter annotations shown in previous blog posts (<a href="http://www.mscharhag.com/java-ee-mvc/query-parameters">@QueryParam</a>, <a href="http://www.mscharhag.com/java-ee-mvc/path-parameters">@PathParam</a>, etc.) can be used inside bean parameters.</p> <p>For example:</p> <pre class="brush: java"> @GET @Path(&quot;/date/{year}/{month}&quot;) public String get(@BeanParam RequestData data) { ... } </pre> <pre class="brush: java"> public class RequestData { @PathParam(&quot;year&quot;) private int year; @PathParam(&quot;month&quot;) private int month; @QueryParam(&quot;name&quot;) private String name; // getters and setters } </pre> <p>If we now send a HTTP GET request to</p> <pre> /date/2016/02?name=john</pre> <p>the values <span class="code">2016</span>, <span class="code">2</span> and <span class="code">john</span> will be injected to the fields <span class="code">year</span>, <span class="code">month</span> and <span class="code">name</span> of <span class="code">RequestData</span>.</p> <h2>Quick Summary</h2> <p>With @BeanParam you can inject request parameters into beans. This is especially useful if you have more than a few parameters. Inside bean parameters all other parameter annotations can be used.</p> <p>You can find the example source code on <a href="https://github.com/mscharhag/java-ee-8-mvc/tree/master/request-data">GitHub</a>.</p> 2016-03-15T17:24:29Z Converting Markdown to PDF or DOCX with Pandoc Michael Scharhag http://www.mscharhag.com tag:mscharhag.com,2016-02-26:b158247e-81a4-4723-9d88-f01a9c004d5a 2016-02-29T17:27:45Z 2016-02-29T17:27:45Z <p>Markdown is a popular text formatting syntax among developers these days. Popular Sites like Github or Bitbucket use Markdown for project documentation and various other types of user generated content. These sites automatically convert markdown syntax to HTML, so it can be displayed in a browser.</p> <p>However, maybe you want to use Markdown as document format without using a platform that does the conversion for you. Or you are in need of an output format other than HTML. In this case you need a tool that can convert markdown to the desired target format. <a href="http://pandoc.org/">Pandoc</a> is is a document conversion tool that can be used for exactly this (and a lot of other things). With Pandoc you can convert Markdown documents to PDF, HTML, Words DOCX or many other formats.</p> <p>After installing Pandoc, you can simply run it from command line.</p> <p>Note: By default, Pandoc uses LaTeX to generate PDF documents. So, if you want to generate PDF documents, you need to install a LaTex processor first (<a href="http://pandoc.org/README.html#creating-a-pdf">list of required LaTeX packages</a>).</p> <p>To convert a <span class="code">doc.md</span> Markdown file into a PDF document, the following command can be used:</p> <pre> pandoc -s -o doc.pdf doc.md</pre> <p>Pandoc is able to merge multiple Markdown files into a single PDF document. To generate a single PDF document out of two Markdown files you can use:</p> <pre> pandoc -s -o doc.pdf part01.md part02.md</pre> <p>By default the page margins in the resulting PDF document are quite large. You can change this by passing a <span class="code">margin</span> parameter:</p> <pre> pandoc -s -V geometry:margin=1in -o documentation.pdf part01.md part02.md</pre> <p>To create HTML or DOCX documents you simply have to change the file extension of the target file:</p> <pre> pandoc -s -o doc.html part01.md part02.md pandoc -s -o doc.docx part01.md part02.md </pre> <p>The resulting documents are well formatted. The following two screenshot show a DOCX and a PDF document created out of two small example markdown files:</p> <p>Resulting DOCX document:</p> <p><a class="img-center" href="/files/2016/pandoc-docx.png"><img alt="Word docx document generated by Pandoc" src="/files/2016/pandoc-docx.png" /> </a></p> <p>Resulting PDF document:</p> <p><a class="img-center" href="/files/2016/pandoc-pdf.png"><img alt="Pdf document generated by Pandoc" src="/files/2016/pandoc-pdf.png" /> </a></p> <p>&nbsp;</p> 2016-02-29T17:27:45Z Java EE 8 MVC: Working with form parameters Michael Scharhag http://www.mscharhag.com tag:mscharhag.com,2016-02-20:546537bf-145e-4b62-ae21-9e485c10921b 2016-02-22T17:23:12Z 2016-02-22T17:23:12Z <p>In the previous two posts we saw how to work with <a href="http://www.mscharhag.com/java-ee-mvc/query-parameters">query</a> and <a href="http://www.mscharhag.com/java-ee-mvc/path-parameters">path parameters</a> in the upcoming Java EE MVC framework. This post focuses on form parameters.</p> <p>When you submit a web form using a post request, the form values are send as part of the request body. The media type (or content type) defines the format that is used to store the values inside the request body. Web forms usually use the media type <span class="code">application/x-www-form-urlencoded</span>. Parameters that are send using this media type can be accessed using the <span class="code">@FormParam</span> annotation.</p> <h2>Using form parameters</h2> <p>Assume we have the following simple HTML form, containing two text input fields and a select menu:</p> <pre class="brush: xml"> &lt;form&nbsp;action=&quot;submit&quot;&nbsp;method=&quot;post&quot;&gt; &nbsp;&nbsp;&lt;label&gt;ID:&lt;/label&gt; &nbsp;&nbsp;&lt;input&nbsp;type=&quot;text&quot;&nbsp;name=&quot;id&quot;&nbsp;/&gt; &nbsp;&nbsp; &nbsp;&nbsp;&lt;label&gt;Name:&lt;/label&gt; &nbsp;&nbsp;&lt;input&nbsp;type=&quot;text&quot;&nbsp;name=&quot;name&quot;&nbsp;/&gt; &nbsp;&nbsp; &nbsp;&nbsp;&lt;label&gt;Role:&lt;/label&gt; &nbsp;&nbsp;&lt;select&nbsp;name=&quot;role&quot;&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;option&nbsp;value=&quot;admin&quot;&gt;Admin&lt;/option&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;option&nbsp;value=&quot;reporter&quot;&gt;Reporter&lt;/option&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;option&nbsp;value=&quot;accountant&quot;&gt;Accountant&lt;/option&gt; &nbsp;&nbsp;&lt;/select&gt; &nbsp;&nbsp; &nbsp;&nbsp;&lt;input&nbsp;type=&quot;submit&quot;&nbsp;/&gt; &lt;/form&gt; </pre> <p>To process the form values we can use the following controller method:</p> <pre class="brush: java"> public enum Role { admin, reporter, accountant } </pre> <pre class="brush: java"> @Controller @Path(&quot;form-params&quot;) public class FormParamsController { @POST @Path(&quot;submit&quot;) public String submitParams( @FormParam(&quot;id&quot;) long id, @FormParam(&quot;name&quot;) String name, @FormParam(&quot;role&quot;) Role role) { ... } } </pre> <p>With <span class="code">@FormParam</span> form parameters can automatically be mapped to method arguments. Form parameters use the same type conversion rules as query or path parameters (described <a href="http://www.mscharhag.com/java-ee-mvc/query-parameters#query-params-type-conversion">here</a>). This makes it easy to convert form parameters to primitives, enums or objects.</p> <h2>Using <span class="code">@FormParam</span> on fields and methods</h2> <p>Like other parameter annotations <span class="code">@FormParam</span> can be used to annotate fields and methods.</p> <p>For example:</p> <pre class="brush: java"> @Controller @Path(&quot;form-params-fields&quot;) public class FormParamsFieldController { @FormParam(&quot;id&quot;) private long id; @FormParam(&quot;role&quot;) private Role role; private String name; @FormParam(&quot;name&quot;) public void setNameField(String name) { this.name = name; } @POST public String submitParams() { // use id, role, name } } </pre> <p>In this example the submitted form parameters are mapped to fields (<span class="code">id</span>, <span class="code">role</span>) and a setter (<span class="code">setNameField()</span>). Inside <span class="code">submitParams()</span> we can then simply access the fields to obtain the form parameters.</p> <h2>Quick Summary</h2> <p>Parameters submitted via HTML forms can be obtained with <span class="code">@FormParam</span>. Like <span class="code">@QueryParam</span> and <span class="code">@PathParam</span> it is possible to annotate fields, methods and method parameters with <span class="code">@FormParam</span>.</p> <p>You can find the source code for all examples on <a href="https://github.com/mscharhag/java-ee-8-mvc/tree/master/request-data">GitHub</a>.</p> 2016-02-22T17:23:12Z Java EE 8 MVC: Working with Path Parameters Michael Scharhag http://www.mscharhag.com tag:mscharhag.com,2016-01-31:6a67fb78-fb80-40c0-9aa2-c27d9002b7a2 2016-01-31T17:04:26Z 2016-01-31T17:04:26Z <p>In the previous post we saw <a href="http://www.mscharhag.com/java-ee-mvc/query-parameters">how to work with query parameters in Java EE MVC</a>. This post continues with a very similar topic: path parameters.</p> <p>Path parameters are a dynamic part of the request path and can be specified with the <span class="code">@Path</span> annotation.</p> <p>For example:</p> <pre class="brush: java"> @Controller @Path(&quot;path-params&quot;) public class PathParamsController { @GET @Path(&quot;/date/{year}/{month}&quot;) public String pathParamDate(@PathParam(&quot;year&quot;) int year, @PathParam(&quot;month&quot;) int month) { ... } } </pre> <p>Paths parameter are surrounded with curly brackets inside the <span class="code">@Path</span> annotation. In this example two path parameters are defined: <span class="code">year</span> and <span class="code">month</span>.</p> <p>With <span class="code">@PathParam</span> path parameters can be mapped to method parameters.</p> <p>We can call this method by sending a request to</p> <pre> /path-params/date/2016/01 </pre> <p>In this case <span class="code">2016</span> and <span class="code">1</span> will be passed as <span class="code">year</span> and <span class="code">month</span> arguments.</p> <h2>Type conversion</h2> <p>Path parameters use the same type conversion rules as query parameters (<a href="http://www.mscharhag.com/java-ee-mvc/query-parameters#query-params-type-conversion">explained in the previous blog post</a>).</p> <p>For example, we can convert a path parameter to an enum value like this:</p> <pre class="brush: java"> public enum Role { admin, reporter, accountant } </pre> <pre class="brush: java"> @Controller @Path(&quot;path-params&quot;) public class PathParamsController { @GET @Path(&quot;/roles/{role}&quot;) public String pathParamUsers(@PathParam(&quot;role&quot;) Role role) { ... } } </pre> <p>If we now send a request to</p> <pre> /path-params/roles/admin </pre> <p>the string <span class="code">admin</span> gets converted to the corresponding enum constant.</p> <h2>Using <span class="code">@PathParam</span> on fields and methods</h2> <p>Like <span class="code">@QueryParam</span> the usage of <span class="code">@PathParam</span> is not limited to method parameters. It is also possible to annotate fields or setters with <span class="code">@PathParam</span>.</p> <p>For example:</p> <pre class="brush: java"> @Controller @Path(&quot;path-params&quot;) public class PathParamsController { @PathParam(&quot;category&quot;) private String category; @GET @Path(&quot;/categories/{category}&quot;) public String findByCategory() { // work with category } }</pre> <h2>Using Path Parameters with Patterns</h2> <p>It is possible to define a more specific pattern for a path variable. Therefore, a regular expression can be added after the name of the path variable.</p> <p>For example:</p> <pre class="brush: java"> @Controller @Path(&quot;path-params&quot;) public class PathParamsController { @GET @Path(&quot;/users/{id : \\d+}&quot;) public String findUserById(@PathParam(&quot;id&quot;) long id) { ... } @GET @Path(&quot;/users/{name : [a-zA-Z]+}&quot;) public String findUserByName(@PathParam(&quot;name&quot;) String name) { ... } } </pre> <p>Here we define two controller methods that listen on <span class="code">/users/{variable}</span>:</p> <ul> <li><span class="code">findUserById()</span> is only called if a numeric id is part of the request path</li> <li><span class="code">findUserByName()</span> is used if the path parameter matches the regular expression <span class="code">[a-zA-Z]+</span>.</li> </ul> <p>So if we send a request to</p> <pre> /path-params/users/123 </pre> <p><span class="code">findUserById()</span> will be called and <span class="code">123</span> is passed as <span class="code">id</span>.</p> <p>Sending a request to</p> <pre> /path-params/users/john </pre> <p>calls <span class="code">findUserByName()</span> and passes <span class="code">john</span> as <span class="code">name</span>.</p> <h2>Quick Summary</h2> <p><span class="code">@PathParam</span> can be used to extract path parameters defined with <span class="code">@Path</span>. Like <span class="code">@QueryParam</span>, <span class="code">@PathParam</span> can be used on method arguments, instance fields and methods.</p> <p>When defining path parameters with <span class="code">@Path</span>, a regular expression can be used to define a specific path pattern.</p> <p>You can find the source code for all shown examples on <a href="https://github.com/mscharhag/java-ee-8-mvc/tree/master/request-data">GitHub</a>.</p> 2016-01-31T17:04:26Z Java EE 8 MVC: Working with query parameters Michael Scharhag http://www.mscharhag.com tag:mscharhag.com,2016-01-14:67f305df-3a73-4103-af1b-9f71489a37ff 2016-01-31T17:01:46Z 2016-01-14T17:01:46Z <p>In the previous post about the new Java EE MVC Framework we had <a href="http://www.mscharhag.com/java-ee-mvc/a-detailed-look-on-mvc-controllers">a detailed look on Controllers</a>. In this and the following posts we will see how to access various types of request data in MVC Controllers.</p> <p>Java EE MVC makes heavy use of JAX-RS and most of the things we will see in this and the next posts are JAX-RS features. So, if you are familiar with JAX-RS you probably will not learn much new in this post.</p> <h2>Query parameters</h2> <p>This post focuses on query parameters. If you read my <a href="http://www.mscharhag.com/java-ee-mvc/ozark-getting-started">Java EE MVC Getting started</a> post you might already know the <span class="code">@QueryParam</span> annotation. The most common use case of&nbsp; <span class="code">@QueryParam</span> is to map a query parameter to a controller method parameter.</p> <p>For example:</p> <pre class="brush: java"> @Controller @Path(&quot;query-params&quot;) public class QueryParamsController { @GET public String queryParams(@QueryParam(&quot;name&quot;) String name) { ... } } </pre> <p>If we now send a HTTP GET request to</p> <pre> /query-params?name=john </pre> <p>the string <span class="code">&quot;john&quot;</span> will be passed as <span class="code">name</span> parameter to the method <span class="code">queryParams()</span>.</p> <h2 id="query-params-type-conversion">Type conversion</h2> <p>With <span class="code">@QueryParam</span> query parameters can automatically be converted to various types.</p> <p>For example:</p> <pre class="brush: java"> public enum Role { admin, reporter, accountant } </pre> <pre class="brush: java"> @Controller @Path(&quot;query-params&quot;) public class QueryParamsController { @GET public String queryParams( @QueryParam(&quot;id&quot;) long id, @QueryParam(&quot;name&quot;) String name, @QueryParam(&quot;role&quot;) Role role) { ... } } </pre> <p>We can now send a request like this:</p> <pre> /query-params?id=42&amp;name=john&amp;role=admin </pre> <p>A query parameter can automatically converted to a type, if the target type matches one of the following rules:</p> <ul> <li>It is a primitive type</li> <li>The type has a constructor that accepts a single <span class="code">String</span> argument</li> <li>The type has a static factory method named <span class="code">valueOf()</span> or <span class="code">fromString()</span> with a single <span class="code">String</span> argument</li> <li>The type is <span class="code">List&lt;T&gt;</span>, <span class="code">Set&lt;T&gt;</span>; or <span class="code">SortedSet&lt;T&gt;</span> where T matches one of the previous rules</li> </ul> <p>In the previous example, the query parameter <span class="code">id</span> is automatically converted to <span class="code">long</span>. If the <span class="code">id</span> parameter is missing or a conversion to <span class="code">long</span> is not possible, an exception will be thrown. It is also possible to use <span class="code">Long</span> instead of <span class="code">long</span>. In this case, we get <span class="code">null</span> passed to the controller method if the <span class="code">id</span> parameter is missing.</p> <p>Enums have a <span class="code">valueOf()</span> method by default. So, the query parameter <span class="code">role</span> can automatically be converted to the corresponding enum value.</p> <h2>Using <span class="code">@QueryParam</span> on fields and methods</h2> <p><span class="code">@QueryParam</span> is not limited to method parameters. It is also possible to map query parameters to fields or methods, like the following example shows:</p> <pre class="brush: java"> @Controller @Path(&quot;query-params-fields&quot;) public class QueryParamsFieldController { @QueryParam(&quot;id&quot;) private Long id; @QueryParam(&quot;role&quot;) private Role role; private String name; @QueryParam(&quot;name&quot;) public void setName(String name) { this.name = name; } @GET public String queryParams() { // use id, role and name } } </pre> <p>If we now send a HTTP GET request to</p> <pre> /query-params-fields?name=john&amp;id=42&amp;role=reporter </pre> <p>the parameters are set to the fields <span class="code">id</span>, <span class="code">role</span> and <span class="code">name</span> (via <span class="code">setName()</span>) before <span class="code">queryParams()</span> is called.</p> <p>Do not forget that a new instance of the class is created for every request, so it is safe to have fields that contain request information.</p> <h2>Quick Summary</h2> <p>The <span class="code">@QueryParam</span> annotation can be used to obtain query parameters. <span class="code">@QueryParam</span> can be used on fields, methods and method parameters. Query parameters can be automatically converted to various types, as long as the target type is a primitive type, contains a <span class="code">String</span> constructor or contains <span class="code">valueOf()</span> or <span class="code">fromString()</span> factory methods.</p> <p>You can find the source code for all the shown examples on <a href="https://github.com/mscharhag/java-ee-8-mvc/tree/master/request-data">GitHub</a>.</p> <p>In the next post we will see how to work with path parameters.</p> 2016-01-14T17:01:46Z Java EE 8 MVC: A detailed look at Controllers Michael Scharhag http://www.mscharhag.com tag:mscharhag.com,2015-10-05:55b2fdb2-e387-48d9-9452-52e15f4752b5 2015-10-05T17:17:06Z 2015-10-04T17:17:06Z <p>Java EE MVC is a new action based MVC framework planned for Java EE 8 and specified in <a href="https://jcp.org/en/jsr/detail?id=371">JSR-371</a>. This is the second post of my Java EE 8 MVC tutorial. The first post covered the basics and shows how to <a href="http://www.mscharhag.com/java-ee-mvc/ozark-getting-started" title="Java EE 8 MVC: Getting started with Ozark">get started with Ozark</a>, the Java EE 8 MVC reference implementation.</p> <p>In this post we will have a more detailed look at MVC Controllers.</p> <h2>MVC Controllers</h2> <p>A controller is responsible for processing incoming requests. It invokes business logic, updates the model and returns the view that should be rendered. An MVC Controller is a JAX-RS resource method annotated with <span class="code">@Controller</span>. If a class is annotated with <span class="code">@Controller</span>, then all resource methods of this class are regarded as controllers.</p> <p>The following example shows a simple Controller that renders a product details page for a given product id:</p> <pre class="brush: java"> @Path(&quot;product&quot;) @Controller public&nbsp;class&nbsp;ProductController&nbsp;{ &nbsp;&nbsp;@Inject &nbsp;&nbsp;private&nbsp;Models&nbsp;models; &nbsp;&nbsp;@Inject &nbsp;&nbsp;private&nbsp;ProductService&nbsp;productService; &nbsp;&nbsp;@GET &nbsp;&nbsp;public&nbsp;String&nbsp;getProductDetailPage(@QueryParam(&quot;id&quot;)&nbsp;long&nbsp;productId)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;Product&nbsp;product&nbsp;=&nbsp;this.productService.getProduct(productId); &nbsp;&nbsp;&nbsp;&nbsp;models.put(&quot;product&quot;,&nbsp;product); &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;&quot;/WEB-INF/jsp/productDetailPage.jsp&quot;; &nbsp;&nbsp;} }</pre> <p>This Controller resolves a product id (passed as <span class="code">id</span> request parameter) to a <span class="code">product</span> using a <span class="code">ProductService</span>. The obtained <span class="code">product</span> is added to the model and a path to a view is returned. The view is then rendered with the information stored in the model.</p> <p>Like in JAX-RS, the <span class="code">@Path</span> annotation is used to define the URL path. This Controller is accessible via a URL that looks like this:</p> <pre> /&lt;application-path&gt;/product?id=42</pre> <p>The following example shows a hybrid class with one MVC controller method and one traditional JAX-RS resource method:</p> <pre class="brush: java"> @Path(&quot;hybrid&quot;) public&nbsp;class&nbsp;HybridController&nbsp;{ &nbsp;&nbsp;@GET &nbsp;&nbsp;@Path(&quot;jaxrs&quot;) &nbsp;&nbsp;public&nbsp;Response&nbsp;jaxrs()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;Response.status(200).build(); &nbsp;&nbsp;} &nbsp;&nbsp;@Path(&quot;mvc&quot;) &nbsp;&nbsp;@GET &nbsp;&nbsp;@Controller &nbsp;&nbsp;public&nbsp;String&nbsp;mvc()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;&quot;/WEB-INF/jsp/hello.jsp&quot;; &nbsp;&nbsp;} }</pre> <p>Controller methods work very similar to JAX-RS resource methods. However, there are two small differences:</p> <ul> <li>A return type of <span class="code">String</span> on Controller methods is interpreted as a view path. With JAX-RS resource methods the returned String is interpreted as text content.</li> <li>The default response media type for Controller methods is <span class="code">text/html</span>. Like in JAX-RS the media type can be changed using the <span class="code">@Produces</span> annotation.</li> </ul> <p>MVC Controller classes and hybrid classes with MVC Controller methods need to be CDI-managed beans. Like JAX-RS resource classes, MVC controller classes are instantiated per request. For every request, a new Controller class instance is created.</p> <p>Like in JAX-RS the supported HTTP verb is defined by annotations. If a controller method should listen for HTTP POST requests, it needs to be annotated with <span class="code">@POST</span> instead of <span class="code">@Get</span>.</p> <p>For example:</p> <pre class="brush: java"> @Controller @Path(&quot;http&quot;) public&nbsp;class&nbsp;PostController&nbsp;{ &nbsp;&nbsp;@POST &nbsp;&nbsp;@Path(&quot;post&quot;) &nbsp;&nbsp;public&nbsp;String&nbsp;post()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;&quot;/WEB-INF/jsp/hello.jsp&quot;; &nbsp;&nbsp;} }</pre> <h2>Controller return types</h2> <p>Four different return types are supported on MVC controller methods:</p> <ul> <li><span class="code">String</span> - The returned string value is interpreted as view path.</li> <li><span class="code">void</span> - In this case the view need to be defined using the <span class="code">@View</span> annotation</li> <li><span class="code">Viewable</span> - An abstraction that includes information about a view, the model and the used view engine.</li> <li><span class="code">Response</span> - A JAX-RS response. The entity type of the response needs to be <span class="code">String</span>, <span class="code">void</span> or <span class="code">Viewable</span>.</li> </ul> <p>The following class defines four controller methods using different return types. All methods return the same response:</p> <pre class="brush: java"> @Controller @Path(&quot;return-types&quot;) public&nbsp;class&nbsp;ReturnTypesController&nbsp;{ &nbsp;&nbsp;@GET &nbsp;&nbsp;@View(&quot;/WEB-INF/jsp/hello.jsp&quot;) &nbsp;&nbsp;@Path(&quot;return-void&quot;) &nbsp;&nbsp;public&nbsp;void&nbsp;returnVoid()&nbsp;{ &nbsp;&nbsp;} &nbsp;&nbsp;@GET &nbsp;&nbsp;@Path(&quot;return-string&quot;) &nbsp;&nbsp;public&nbsp;String&nbsp;returnString()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;&quot;/WEB-INF/jsp/hello.jsp&quot;; &nbsp;&nbsp;} &nbsp;&nbsp;@GET &nbsp;&nbsp;@Path(&quot;return-string&quot;) &nbsp;&nbsp;public&nbsp;Viewable&nbsp;returnViewable()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;new&nbsp;Viewable(&quot;/WEB-INF/jsp/hello.jsp&quot;); &nbsp;&nbsp;} &nbsp;&nbsp;@GET &nbsp;&nbsp;@Path(&quot;return-response&quot;) &nbsp;&nbsp;public&nbsp;Response&nbsp;returnResponse()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;Response.status(Response.Status.OK) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.entity(&quot;/WEB-INF/jsp/hello.jsp&quot;) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.build(); &nbsp;&nbsp;} }</pre> <p>Returning a JAX-RS Response is the most flexible way. This way the JAX-RS Response builder can be used to modify the HTTP status code, response headers and more.</p> <p>If <span class="code">void</span> is used as return type, the view needs to be defined using the <span class="code">@View</span> annotation. <span class="code">@View</span> can be applied to methods (like in the previous example) and classes. If a class is annotated with <span class="code">@View</span>, the view is applied to all controller methods in this class. A class level <span class="code">@View</span> annotation can be overridden by a more specific view definition on method level, like shown in the following example:</p> <pre class="brush: java"> @Controller @Path(&quot;views&quot;) @View(&quot;/WEB-INF/jsp/foo.jsp&quot;) public&nbsp;class&nbsp;ViewController&nbsp;{ &nbsp;&nbsp;@GET &nbsp;&nbsp;@Path(&quot;first&quot;) &nbsp;&nbsp;public&nbsp;void&nbsp;first()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;renders&nbsp;foo.jsp &nbsp;&nbsp;} &nbsp;&nbsp;@GET &nbsp;&nbsp;@Path(&quot;second&quot;) &nbsp;&nbsp;@View(&quot;/WEB-INF/jsp/bar.jsp&quot;) &nbsp;&nbsp;public&nbsp;void&nbsp;second()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;renders&nbsp;bar.jsp &nbsp;&nbsp;} &nbsp;&nbsp;@GET &nbsp;&nbsp;@Path(&quot;third&quot;) &nbsp;&nbsp;public&nbsp;String&nbsp;third()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;renders&nbsp;baz.jsp &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;&quot;/WEB-INF/jsp/baz.jsp&quot;; &nbsp;&nbsp;} }</pre> <h2>Summary</h2> <p>The <span class="code">@Controller</span> annotation can be used on methods and classes. When used on classes, all methods of the class are considered as controllers. Controller methods invoke business logic and determine the view that should be rendered. Classes with Controller methods are CDI managed beans. For every request, a new class instance will be created. Traditional JAX-RS resource methods can be combined with MVC Controller methods in the same class.</p> <p>In the next posts about Java EE 8 MVC we will have a look at parameter binding and validation.</p> <p>You can find the example source code on <a href="https://github.com/mscharhag/java-ee-8-mvc/tree/master/controllers" title="Example source code on GitHub">GitHub</a>.</p> 2015-10-04T17:17:06Z Resource versioning with Spring MVC Michael Scharhag http://www.mscharhag.com tag:mscharhag.com,2015-09-21:6ab2e1bc-bbc4-4b92-afcb-4a6c34193a6f 2015-09-21T08:25:36Z 2015-09-21T08:25:36Z <p>When serving static resources, it is common practice to append some kind of version information to the resource URL. This allows the browser to cache resources for an unlimited time. Whenever the content of the resource is changed, the version information in the URL is changed too. The updated URL forces the client browser to discard the cached resource and reload the latest resource version from the server.</p> <p>With Spring it only takes two simple steps to configure versioned resource URLs. In this post we will see how it works.</p> <h2>Serving versioned URLs</h2> <p>First we need to tell Spring that resources should be accessible via a versioned URL. This is done in the resource handler MVC configuration:</p> <pre class="brush: java"> @Configuration public&nbsp;class&nbsp;MvcApplication&nbsp;extends&nbsp;WebMvcConfigurerAdapter&nbsp;{ &nbsp;&nbsp;@Override &nbsp;&nbsp;public&nbsp;void&nbsp;addResourceHandlers(ResourceHandlerRegistry&nbsp;registry)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;VersionResourceResolver&nbsp;versionResourceResolver&nbsp;=&nbsp;new&nbsp;VersionResourceResolver() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.addVersionStrategy(new&nbsp;ContentVersionStrategy(),&nbsp;&quot;/**&quot;); &nbsp;&nbsp;&nbsp;&nbsp;registry.addResourceHandler(&quot;/javascript/*.js&quot;) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.addResourceLocations(&quot;classpath:/static/&quot;) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.setCachePeriod(60&nbsp;*&nbsp;60&nbsp;*&nbsp;24&nbsp;*&nbsp;365)&nbsp;/*&nbsp;one&nbsp;year&nbsp;*/ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.resourceChain(true) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.addResolver(versionResourceResolver); &nbsp;&nbsp;} &nbsp;&nbsp;... }</pre> <p>Here we create a resource handler for JavaScript files located in folder named <span class="code">static</span> inside the classpath. The cache period for these JavaScript files is set to one year. The important part is the <a href="http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/resource/VersionResourceResolver.html" title="Spring VersionResourceResolver API documentation"><span class="code">VersionResourceResolver</span></a> which supports resource URLs with version information. A <a href="http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/resource/VersionStrategy.html" title="Spring VersionStrategy API documentation"><span class="code">VersionStrategy</span></a> is used to obtain the actual version for a resource.</p> <p>In this example we use a <a href="http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/resource/ContentVersionStrategy.html" title="Spring ContentVersionStrategy API documentation"><span class="code">ContentVersionStrategy</span></a>. This <span class="code">VersionStrategy</span> implementation calculates an MD5 hash from the content of the resource and appends it to the file name.</p> <p>For example: Assume we have a JavaScript file <span class="code">test.js</span> inside the <span class="code">classpath:/static/</span> directory. The MD5 hash for <span class="code">test.js</span> is <span class="code">69ea0cf3b5941340f06ea65583193168</span>.</p> <p>We can now send a request to</p> <pre> /javascript/test-69ea0cf3b5941340f06ea65583193168.js</pre> <p>which will resolve to <span class="code">classpath:/static/test.js</span>.</p> <p>Note that it is still possible to request the resource without the MD5 hash. So this request works too:</p> <pre> /javascript/test.js</pre> <p>An alternative <span class="code">VersionStrategy</span> implementation is <a href="http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/resource/FixedVersionStrategy.html" title="Spring FixedVersionStrategy API documentation"><span class="code">FixedVersionStrategy</span></a>. <span class="code">FixedVersionStrategy</span> uses a fixed version string that added as prefix to the resource path.</p> <p>For example:</p> <pre> /v1.2.3/javascript/test.js</pre> <h2>Generating versioned URLs</h2> <p>Now we need to make sure the application generates resource URLs that contain the MD5 hash.</p> <p>One approach for this is to use a <a href="http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/resource/ResourceUrlProvider.html" title="Spring ResourceUrlProvider API documentation"><span class="code">ResourceUrlProvider</span></a>. With a <span class="code">ResourceUrlProvider</span> a resource URL (e.g. <span class="code">/javascript/test.js</span>) can be converted to a versioned URL (e.g. <span class="code">/javascript/test-69ea0cf3b5941340f06ea65583193168.js</span>). A <span class="code">ResourceUrlProvider</span> bean with the id <span class="code">mvcResourceUrlProvider</span> is automatically declared with the MVC configuration.</p> <p>In case you are using Thymeleaf as template engine, you can access the <span class="code">ResourceUrlProvider</span> bean directly from templates using the <span class="code">@bean</span> syntax.</p> <p>For example:</p> <pre class="brush: xml"> &lt;script&nbsp;type=&quot;application/javascript&quot; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;th:src=&quot;${@mvcResourceUrlProvider.getForLookupPath(&#39;/javascript/test.js&#39;)}&quot;&gt; &lt;/script&gt;</pre> <p>If you are using a template engine which does not give you direct access to Spring beans, you can add the <span class="code">ResourceUrlProvider</span> bean to the model attributes. Using a <a href="http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/ControllerAdvice.html" title="Spring ControllerAdvice API documentation"><span class="code">ControllerAdvice</span></a>, this might look like this:</p> <pre class="brush: java"> @ControllerAdvice public&nbsp;class&nbsp;ResourceUrlAdvice&nbsp;{ &nbsp;&nbsp;@Inject &nbsp;&nbsp;ResourceUrlProvider&nbsp;resourceUrlProvider; &nbsp;&nbsp;@ModelAttribute(&quot;urls&quot;) &nbsp;&nbsp;public&nbsp;ResourceUrlProvider&nbsp;urls()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;this.resourceUrlProvider; &nbsp;&nbsp;} }</pre> <p>Inside the view we can then access the <span class="code">ResourceUrlProvider</span> using the <span class="code">urls</span> model attribute:</p> <pre class="brush: xml"> &lt;script&nbsp;type=&quot;application/javascript&quot;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;th:src=&quot;${urls.getForLookupPath(&#39;/javascript/test.js&#39;)}&quot;&gt; &lt;/script&gt;</pre> <p>This approach should work with all template engines that support method calls.</p> <p>An alternative approach to generate versioned URLs is the use of <a href="http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/resource/ResourceUrlEncodingFilter.html" title="Spring ResourceUrlEncodingFilter API documentation"><span class="code">ResourceUrlEncodingFilter</span></a>. This is a Servlet Filter that overrides the <span class="code">HttpServletResponse.encodeURL()</span> method to generate versioned resource URLs.</p> <p>To make use of the <span class="code">ResourceUrlEncodingFilter</span> we simply have to add an additional bean to our configuration class:</p> <pre class="brush: java"> @SpringBootApplication public&nbsp;class&nbsp;MvcApplication&nbsp;extends&nbsp;WebMvcConfigurerAdapter&nbsp;{ &nbsp;&nbsp;@Override &nbsp;&nbsp;public&nbsp;void&nbsp;addResourceHandlers(ResourceHandlerRegistry&nbsp;registry)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;same&nbsp;as&nbsp;before&nbsp;.. &nbsp;&nbsp;} &nbsp;&nbsp;@Bean &nbsp;&nbsp;public&nbsp;ResourceUrlEncodingFilter&nbsp;resourceUrlEncodingFilter()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;new&nbsp;ResourceUrlEncodingFilter(); &nbsp;&nbsp;} &nbsp;&nbsp;... }</pre> <p>If the template engine you are using calls the response <span class="code">encodeURL()</span> method, the version information will be automatically added to the URL. This will work in JSPs, Thymeleaf, FreeMarker and Velocity.</p> <p>For example: With Thymeleaf we can use the standard <span class="code">@{..}</span> syntax to create URLs:</p> <pre class="brush: xml"> &lt;script&nbsp;type=&quot;application/javascript&quot;&nbsp;th:src=&quot;@{/javascript/test.js}&quot;&gt;&lt;/script&gt;</pre> <p>This will result in:</p> <pre class="brush: xml"> &lt;script&nbsp;type=&quot;application/javascript&quot;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;src=&quot;/javascript/test-69ea0cf3b5941340f06ea65583193168.js&quot;&gt; &lt;/script&gt;</pre> <h2>Summary</h2> <p>Adding version information to resource URLs is a common practice to maximize browser caching. With Spring we just have to define a <span class="code">VersionResourceResolver</span> and a <span class="code">VersionStrategy</span> to serve versioned URLs. The easiest way to generate versioned URLs inside template engines, is the use of an <span class="code">ResourceUrlEncodingFilter</span>.</p> <p>If the standard <span class="code">VersionStrategy</span> implementations do not match your requirements, you can create our own <span class="code">VersionStrategy</span> implementation.</p> <p>You can find the full example source code on <a href="https://github.com/mscharhag/blog-examples/tree/master/spring-resource-versioning" title="Example source code on GitHub">GitHub</a>.</p> 2015-09-21T08:25:36Z Java EE 8 MVC: Getting started with Ozark Michael Scharhag http://www.mscharhag.com tag:mscharhag.com,2015-09-01:260d9b6a-b8e0-4c7f-ace6-eeb5c85f04f5 2015-10-05T17:19:00Z 2015-09-01T17:19:00Z <p>About a year ago a new action based MVC framework, simply called MVC, was <a href="http://www.oracle.com/technetwork/articles/java/mvc-2280472.html">announced for Java EE 8</a>. MVC (specified in <a href="https://jcp.org/en/jsr/detail?id=371">JSR 371</a>) is based on JAX-RS and integrates with Java EE technologies like CDI and Bean Validation. The reference implementation for MVC 1.0 is <a href="https://ozark.java.net/index.html">Ozark</a>.</p> <p>This is the first article of a multi-part tutorial I am planning to write about Java EE MVC. In this post we will see how to get a basic Java EE MVC application running with Ozark. Upcoming articles will provide more details to specific sections.</p> <h2>Getting started with Ozark</h2> <p>Please note that the MVC specification is still an early draft, the final specification is planned to be released in Q3 2016. To have a look at Java EE MVC in this early state, we need a recent nightly build version of GlassFish and the current Ozark milestone release. The Ozark team recommends <a href="http://download.oracle.com/glassfish/4.1/nightly/glassfish-4.1-b13-03_16_2015.zip">GlassFish b13 03-16-2015</a> for the current Ozark version.</p> <p>Besides GlassFish we need the following dependencies to create an MVC application:</p> <pre class="brush: xml"> &lt;dependencies&gt; &nbsp;&nbsp;&lt;dependency&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;groupId&gt;com.oracle.ozark&lt;/groupId&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;artifactId&gt;ozark&lt;/artifactId&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;version&gt;1.0.0-m01&lt;/version&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;scope&gt;compile&lt;/scope&gt; &nbsp;&nbsp;&lt;/dependency&gt; &nbsp;&nbsp;&lt;dependency&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;groupId&gt;javax&lt;/groupId&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;artifactId&gt;javaee-api&lt;/artifactId&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;version&gt;7.0&lt;/version&gt; &nbsp;&nbsp;&lt;/dependency&gt; &lt;/dependencies&gt; </pre> <p>As mentioned above, Java EE MVC is based on JAX-RS. So things might look very familiar to you, if you already know about JAX-RS.</p> <p>To create our MVC application we first need a JAX-RS Application class:</p> <pre class="brush: java"> @ApplicationPath(&quot;getting-started&quot;) public&nbsp;class&nbsp;GettingStartedApplication&nbsp;extends&nbsp;Application&nbsp;{ }</pre> <p>This subclass of <a class="code" href="http://docs.oracle.com/javaee/7/api/javax/ws/rs/core/Application.html">javax.ws.rs.core.Application</a> can be used to define additional JAX-RS components. In this example we do not need any special configuration, so the class can stay empty. With <span class="code">@ApplicationPath</span> we define the base path for our application.</p> <h2>Creating the Controller</h2> <p>A controller is responsible for processing incoming requests. Based on the incoming request it executes business logic, updates the model and returns the view that should be rendered. A simple Java EE MVC Controller looks like this:</p> <pre class="brush: java"> @Controller @Path(&quot;hello&quot;) public&nbsp;class&nbsp;HelloController&nbsp;{ &nbsp;&nbsp;@Inject &nbsp;&nbsp;Models&nbsp;models; &nbsp;&nbsp;@GET &nbsp;&nbsp;public&nbsp;String&nbsp;sayHello(@QueryParam(&quot;name&quot;)&nbsp;String&nbsp;name)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;String&nbsp;message&nbsp;=&nbsp;&quot;Hello&nbsp;&quot;&nbsp;+&nbsp;name; &nbsp;&nbsp;&nbsp;&nbsp;models.put(&quot;message&quot;,&nbsp;message); &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;&quot;/WEB-INF/jsp/hello.jsp&quot;; &nbsp;&nbsp;} }</pre> <p>The Controller class is annotated with <span class="code">@Controller</span> and <span class="code">@Path</span>. This indicates that the class is a Java EE MVC Controller that listens for requests on <span class="code">/getting-started/hello</span>.</p> <p>With CDI an instance of <span class="code">Models</span> is injected to the controller. The <span class="code">Models</span> class represents the MVC model. It is filled with data by the controller and is then passed to the view. <span class="code">Models</span> is basically a <span class="code">Map&lt;String, Object&gt;</span> that can contain arbitrary data.</p> <p>The <span class="code">sayHello()</span> method processes incoming HTTP GET requests (indicated by <span class="code">@GET</span>). With <span class="code">@QueryParam</span> request parameters can be bound to method parameters. Inside <span class="code">sayHello()</span> the request parameter <span class="code">name</span> is used to create a text message, which is then added to the Model. The returned String defines the path to the view that should be rendered.</p> <h2>Creating the View</h2> <p>Views in Java EE MVC applications are typically HTML pages with CSS and JavaScript files. In this example our view is a simple JSP file located at <span class="code">/WEB-INF/jsp/hello.jsp</span></p> <pre class="brush: xml"> &lt;%@page&nbsp;contentType=&quot;text/html&quot;&nbsp;pageEncoding=&quot;UTF-8&quot;%&gt; &lt;!DOCTYPE&nbsp;html&gt; &lt;html&gt; &nbsp;&nbsp;&lt;head&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;meta&nbsp;http-equiv=&quot;Content-Type&quot;&nbsp;content=&quot;text/html;&nbsp;charset=UTF-8&quot;&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;title&gt;Getting&nbsp;started&lt;/title&gt; &nbsp;&nbsp;&lt;/head&gt; &nbsp;&nbsp;&lt;body&gt; &nbsp;&nbsp;&nbsp;&nbsp;&lt;h1&gt;${message}&lt;/h1&gt; &nbsp;&nbsp;&lt;/body&gt; &lt;/html&gt;</pre> <p>Inside JSP files, model properties can be accessed via <a href="https://docs.oracle.com/javaee/6/tutorial/doc/bnahq.html">EL</a>. Here, we use <span class="code">${message}</span> to access the model value with the key <span class="code">message</span>.</p> <p>The Java EE MVC specification defines two standard template engines for views: JSP and Facelets. However, other template engines can easily be integrated. We will have a look at the integration of other view technologies in an upcoming post.</p> <h2>Running the application</h2> <p>Now we are ready to start GlassFish and deploy our new MVC application. After that, we can send a GET request to our controller and see what it returns. Do not forget that the controller expects a <span class="code">name</span> parameter.</p> <p>For example</p> <p class="code">GET /getting-started/hello?name=john</p> <p>will result in a HTML page containing the message <i>Hello John</i></p> <h2>Summary</h2> <p>Java EE MVC is the new upcoming Java MVC web framework. It uses a lot of existing Java technologies like JAX-RS, CDI and JSP. The framework itself is quite simple and easy to understand. The complete MVC 1.0 specification is only around 33 pages long and very easy to read.</p> <p>We can use the current milestone release of the MVC 1.0 reference implementation Ozark to get a feeling for the upcoming Java EE 8 framework.</p> <p>You can find the full source code of the example application on <a href="https://github.com/mscharhag/java-ee-8-mvc/tree/master/getting-started">GitHub</a>.</p> <p>In future blog posts we will have a look at parameter validation, exception handling and other view technologies.</p> 2015-09-01T17:19:00Z Exception Translation with ET Michael Scharhag http://www.mscharhag.com tag:blogger.com,1999:blog-7494919170223503557.post-2612437745520653522 2015-09-05T14:29:45Z 2015-06-04T14:29:45Z <p>Some time ago I wrote a small blog post about <a href="http://www.mscharhag.com/2014/02/java-exception-translation-with-aspectj.html">exception translation with AspectJ</a>. In this blog post we will see how to accomplish the same using <a href="https://github.com/mscharhag/ET">ET</a> and its lighter Java 8 approach.</p> <h2>Motivation</h2> <p>Exception translation (or exception conversion) is the process of converting one type of exception into another. The Java code to translate an exception is quite simple and I think every Java developer writes something like this from time to time:</p> <pre class="brush: java"> try&nbsp;{ &nbsp;&nbsp;//&nbsp;code&nbsp;that&nbsp;can&nbsp;throw&nbsp;FooException }&nbsp;catch(FooException&nbsp;e)&nbsp;{ &nbsp;&nbsp;//&nbsp;convert&nbsp;FooException&nbsp;to&nbsp;BarException &nbsp;&nbsp;throw&nbsp;new&nbsp;BarException(e); }</pre> <p>Exception translation is typically applied if exceptions from third party libraries do not fit into your application. Reasons for this might be:</p> <ul> <li>Exceptions thrown by a library are too low level and/or you do not want to leak implementation details into other parts of your application. For example, you want to use a more generic <span class="code">DataAccessException</span> instead of a lower level <span class="code">SQLException</span>.</li> </ul> <ul> <li>A library is using checked exception while you prefer using only runtime exception in your application.</li> </ul> <h2>Exception Translation with ET</h2> <p><a href="https://github.com/mscharhag/ET">ET</a> is a small and simple library for exception translation. To get started with ET, you just need to add the following dependency to your code:</p> <pre class="brush:xml"> &lt;dependency&gt; &nbsp;&nbsp;&lt;groupId&gt;com.mscharhag&lt;/groupId&gt; &nbsp;&nbsp;&lt;artifactId&gt;et&lt;/artifactId&gt; &nbsp;&nbsp;&lt;version&gt;0.2.0&lt;/version&gt; &lt;/dependency&gt;</pre> <p>ET makes use of Java 8 features, so do not forget to set your compiler Level to Java 8.</p> <p>We start with configuring an <span class="code">ExceptionTranslator</span> instance:</p> <pre class="brush: java"> ExceptionTranslator&nbsp;et&nbsp;=&nbsp;ET.newConfiguration() &nbsp;&nbsp;&nbsp;&nbsp;.translate(IOException.class).to(MyRuntimeException.class)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;.translate(FooException.class,&nbsp;BarException.class).to(BazException.class) &nbsp;&nbsp;&nbsp;&nbsp;.done()</pre> <p>Here we create an <span class="code">ExceptionTranslator</span> that converts <span class="code">IOException</span>, <span class="code">FooException</span> and <span class="code">BarException</span>. <span class="code">IOException</span> will be translated to <span class="code">MyRuntimeException</span> while <span class="code">FooException</span> and <span class="code">BarException</span> are translated to <span class="code">BazException</span>.<br /> <br /> Please note that ET requires the translation target exceptions (here <span class="code">MyRuntimeException</span> and <span class="code">BazException</span>) to be <span class="code">RuntimeExceptions</span>.<br /> <span class="code">ExceptionTranslator</span> instances are thread safe and immutable. It is safe to configure an <span class="code">ExceptionTranslator</span> once and then make it globally available.<br /> <br /> Now we can use our new <span class="code">ExceptionTranslator</span> to wrap the code that can throw exceptions we want to convert.</p> <pre class="brush: java"> et.withTranslation(()&nbsp;-&gt;&nbsp;{ &nbsp;&nbsp;//&nbsp;can&nbsp;throw&nbsp;IOException,&nbsp;FooException&nbsp;and/or&nbsp;BarException &nbsp;&nbsp;myObject.dangerOperation();&nbsp; });</pre> <p>If now an <span class="code">IOException</span> is thrown by <span class="code">dangerOperation()</span> <span class="code">et</span> will catch it. <span class="code">et</span> then throws a new <span class="code">MyRuntimeException</span> from the caught <span class="code">IOException</span>. The original <span class="code">IOException</span> is stored in the <span class="code">cause</span> field of <span class="code">MyRuntimeException</span>.</p> <p>To return a value from a translation block <span class="code">withReturningTranslation()</span> can be used:</p> <pre class="brush: java"> MyResultClass&nbsp;data&nbsp;=&nbsp;et.withReturningTranslation(()&nbsp;-&gt;&nbsp;{ &nbsp;&nbsp;... &nbsp;&nbsp;return&nbsp;myObject.dangerOperation();&nbsp; });</pre> <h2>Summary</h2> <p>ET is a small library that might be useful to you, if you have to do a lot of exception conversion in your code. After configuring your conversion rules once, exceptions can be converted by simply wrapping the code in a lambda expression.</p> <p>Have a look at the <a href="https://github.com/mscharhag/ET/blob/master/README.md">full ET documentation</a> on GitHub.</p> 2015-06-04T14:29:45Z What's new in Grails 3 Michael Scharhag http://www.mscharhag.com tag:blogger.com,1999:blog-7494919170223503557.post-5996412238978476811 2015-09-05T14:39:55Z 2015-04-10T14:39:55Z <p>A few days ago <a href="https://github.com/grails/grails-core/releases/tag/v3.0.1">Grails 3.0 was officially released</a>. Grails is now based on <a href="http://projects.spring.io/spring-boot/">Spring Boot</a>, the build system changed from Gant to <a href="https://gradle.org/">Gradle</a> and significant parts of the framework have been rewritten. In this post we will have a look at all the major changes introduced by Grails 3.</p> <h2>Updated file structure</h2> <p>We will start with a screenshot that shows a fresh Grails 3 project created from the Grails command line using<br /> <br /> <span style="background-color: white;"><span class="code">grails create-app hello</span></span><br /> &nbsp;</p> <p><a class="img-center" href="/files/2015/grails3-project-structure.png"><img alt="grails 3 project structure" src="/files/2015/grails3-project-structure.png" /></a></p> <p>The first two folders (<b><i>build</i></b> and <b><i>gradle</i></b>) are related to Gradle, the new build system in Grails 3. As the name implies, <i>build</i> is the directory where build related files like compiled classes and assembled packages are located. The <i>gradle</i> directory contains the <a href="https://www.gradle.org/docs/current/userguide/gradle_wrapper.html">Gradle Wrapper</a> that allows you to build the project without a local Gradle installation.<br /> <br /> The content of the <b><i>conf</i></b> folder has also been changed. The default format for configuration files is now <a href="http://en.wikipedia.org/wiki/YAML">YAML</a>. If you prefer to write your configuration in Groovy, you can still create a <i>grails-app/conf/application.groovy</i> configuration file manually.<br /> <a href="http://logback.qos.ch/">Logback</a> is now the default logging provider. The logging configuration (previously part of <i>Config.groovy</i>) has been moved to <i>conf/logback.groovy</i>.<br /> Note that the <i>conf</i> folder is not a source directory anymore.<br /> <br /> <i><b>init</b></i> is a new folder in Grails 3. It contains <i>Bootstrap.groovy</i> (same content as in previous Grails versions) and the new Application main class (we will look into this in the Spring Boot section).<br /> <br /> The structure of the <i><b>src</b></i> folder has been changed to match Gradle conventions. Additional Java and Groovy files are now located in:<br /> <i>src/main/java</i><br /> <i>src/main/groovy</i><br /> <i>src/test/java</i><br /> <i>src/test/groovy</i><br /> <br /> <b><i>build.gradle</i></b> and <b><i>gradle.properties</i></b> contain the build configuration. <i>BuildConfig.groovy</i> from previous Grails versions does no longer exist.</p> <h2>Spring 4.1 and Spring Boot</h2> <p>Spring Boot is the new basis for Grails. According to Graeme Rocher Grails 3 <a href="http://grails.io/day/2015/03/31/">is nothing less than a ground up rewrite on top of Spring Boot</a>.</p> <p>Like Spring Boot applications Grails 3 projects come with an <span class="code">Application</span> class that has a standard <span class="code">main()</span> method. This means you can start a Grails 3 application simply by running the main class from your IDE.</p> <p>The default <span class="code">Application</span> class looks like this:</p> <pre class="brush: groovy"> class&nbsp;Application&nbsp;extends&nbsp;GrailsAutoConfiguration&nbsp;{ &nbsp;&nbsp;static&nbsp;void&nbsp;main(String[]&nbsp;args)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;GrailsApp.run(Application) &nbsp;&nbsp;} }</pre> <p>Note that the war file you get when packaging the application can now be executed using the <span class="code">java -jar</span> command:<br /> <br /> <span class="code">java -jar build/libs/myApplication-0.1.war</span><br /> <br /> This runs the main method which starts the application using an embedded Tomcat server. Of course you can still deploy the war file on an application server of your choice like in previous Grails versions.<br /> <br /> The <span class="code">Application</span> class acts as <a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-java">Spring configuration class</a>. So, we can use Spring&#39;s <span class="code">@Bean</span> annotation to define custom beans. Methods like <span class="code">onStartup()</span> or <span class="code">onShutdown()</span> can be overwritten if you want to execute custom code at certain application events.</p> <pre class="brush: groovy"> class&nbsp;Application&nbsp;extends&nbsp;GrailsAutoConfiguration&nbsp;{ &nbsp;&nbsp;... &nbsp;&nbsp;@Bean &nbsp;&nbsp;MyBean&nbsp;myBeanId()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;new&nbsp;MyBeanImpl(); &nbsp;&nbsp;} &nbsp;&nbsp;@Override &nbsp;&nbsp;void&nbsp;onStartup(Map&lt;String,&nbsp;Object&gt;&nbsp;event)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;super.onStartup(event) &nbsp;&nbsp; // custom startup code.. &nbsp; } }&nbsp; </pre> <h2>Grails 3 uses Traits</h2> <p>In Grails components like Controllers or Domain classes always had some <i>magically</i> attached functionality. For example, in Controllers you can use methods like <span class="code">render()</span>, <span class="code">redirect()</span> or <span class="code">getParams()</span> without subclassing another class. In Grails 3 these features have been rewritten to make use of T<a href="http://www.mscharhag.com/2014/04/groovy-23-introduces-traits.html">raits introduced by Groovy 2.3</a>.<br /> Certain Traits are automatically attached to Controllers, Services, Tag libraries and so on to make framework methods available. For example, a Controller automatically gets the following Traits: <a href="http://grails.github.io/grails-doc/3.0.x/api/grails/artefact/gsp/TagLibraryInvoker.html">TagLibraryInvoker</a>, <a href="http://grails.github.io/grails-doc/3.0.x/api/grails/artefact/AsyncController.html">AsyncController</a>, <a href="http://grails.github.io/grails-doc/3.0.x/api/grails/artefact/controller/RestResponder.html">RestResponder</a>, <a href="http://grails.github.io/grails-doc/3.0.x/api/grails/artefact/Controller.html">Controller</a>.<br /> <br /> The cool thing with Traits is that you can easily add them to your own classes.<br /> For example: Assume you want to access the <span class="code">request</span> and <span class="code">params</span> objects outside a Grails Controller. All you have to do now is adding the <span class="code">WebAttributes</span> trait to your class:</p> <pre class="brush: groovy"> class&nbsp;MyCustomComponent&nbsp;implements&nbsp;WebAttributes&nbsp;{ &nbsp;&nbsp;public&nbsp;MyCustomComponent() { &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;make&nbsp;use&nbsp;of&nbsp;WebAttributes&nbsp;methods&nbsp;like&nbsp;getWebRequest()&nbsp;or&nbsp;getParams() &nbsp;&nbsp;&nbsp;&nbsp;println&nbsp;&quot;base&nbsp;url:&nbsp;&quot;&nbsp;+&nbsp;webRequest.baseUrl &nbsp;&nbsp;&nbsp;&nbsp;println&nbsp;&quot;params:&nbsp;&quot;&nbsp;+&nbsp;params &nbsp;&nbsp;&nbsp;&nbsp;... &nbsp;&nbsp;} }</pre> <h2>Interceptors</h2> <p>Grails 3 introduced standalone Interceptors. Interceptors can intercept incoming requests to perform common tasks (e.g. logging, authentication, etc.).</p> <p>A new Interceptor can be created using <span class="code">create-interceptor</span> command:<br /> <span class="code">grails create-interceptor MyInterceptor</span><br /> <br /> A newly created Interceptor looks like this:</p> <pre class="brush: groovy"> class&nbsp;MyInterceptor&nbsp;{ &nbsp;&nbsp;boolean&nbsp;before()&nbsp;{&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;executed&nbsp;before&nbsp;a&nbsp;request&nbsp;is&nbsp;processed&nbsp;by&nbsp;a&nbsp;controller &nbsp;&nbsp;&nbsp;&nbsp;true&nbsp; &nbsp;&nbsp;} &nbsp;&nbsp;boolean&nbsp;after()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;executed&nbsp;after&nbsp;a&nbsp;request&nbsp;is&nbsp;processed&nbsp;by&nbsp;a&nbsp;controller &nbsp;&nbsp;&nbsp;&nbsp;true &nbsp;&nbsp;} &nbsp;&nbsp;void&nbsp;afterView()&nbsp;{&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;executed&nbsp;after&nbsp;the&nbsp;view&nbsp;has&nbsp;been&nbsp;rendered &nbsp;&nbsp;} }</pre> <p>Interceptors replace Filters used by previous Grails versions. Filters still work in Grails 3 for backwards compatibility. However, they are considered deprecated now.<br /> <br /> If you are aware of Spring web MVC, you can easily see the similarities to <a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-handlermapping-interceptor">Springs Handler Interceptor</a>.</p> <h2>Gradle builds</h2> <p>As mentioned before, Grails 3 uses Gradle instead of Gant as build system. Gradle is used for tasks like compilation, running tests and packaging the application.<br /> When a Grails command like <span class="code">grails clean</span> is executed, the job is delegated to the corresponding Gradle task (e.g. <span class="code">gradle clean</span>). The Gradle-Wrapper shipped with Grails 3 is used for this.<br /> If you want to use a local installation of Gradle you can execute the Gradle task directly with your own Gradle version. Gradle 2.2 or newer is recommended.<br /> <br /> The following table shows Grails commands and their corresponding Gradle tasks:</p> <table border="0"> <tbody> <tr> <td>Grails command&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>Gradle Task</td> </tr> <tr> <td><span class="code">clean</span></td> <td><span class="code">clean</span></td> </tr> <tr> <td><span class="code">compile</span></td> <td><span class="code">classes</span></td> </tr> <tr> <td><span class="code">package</span></td> <td><span class="code">assemble</span></td> </tr> <tr> <td><span class="code">run-app</span></td> <td><span class="code">run</span></td> </tr> <tr> <td><span class="code">test-app</span></td> <td><span class="code">test</span></td> </tr> <tr> <td><span class="code">war</span></td> <td><span class="code">assemble</span></td> </tr> </tbody> </table> <p><br /> <i>BuildConfig.groovy</i> from previous Grails versions has been completely replaced by the Gradle configuration (<i>build.gradle</i>). Third party dependencies are now defined in <i>build.gradle</i>:</p> <pre class="brush: groovy"> dependencies&nbsp;{ &nbsp;&nbsp;compile&nbsp;&#39;org.grails.plugins:hibernate&#39;&nbsp; &nbsp;&nbsp;compile&nbsp;&#39;org.grails.plugins:cache&#39;&nbsp; &nbsp;&nbsp;compile&nbsp;&#39;org.hibernate:hibernate-ehcache&#39; &nbsp;&nbsp;runtime&nbsp;&#39;org.grails.plugins:asset-pipeline&#39;&nbsp; &nbsp;&nbsp;runtime&nbsp;&#39;org.grails.plugins:scaffolding&#39; &nbsp;&nbsp;... }</pre> <p>For more details, you can have a look at <a href="http://gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html">Dependency Management Guide</a> in the Gradle documentation.</p> <h2>Grails profiles</h2> <p>Whenever you run the <span class="code">create-app</span> command Grails 3 will use a Profile to create a new app.<br /> A Profile encapsulates project structure, commands, templates and plugins. By default Grails 3 uses the <i>web</i> Profile, which creates an app like shown in the screenshot above.<br /> <br /> To create a project with a different Profile, you can use the <span class="code">--profile</span> parameter:<br /> <br /> <span class="code">grails create-app myapp --profile=web-plugin</span><br /> <br /> Grails 3 comes with three different Profiles:</p> <ul> <li><i>web</i> for standard Grails web applications</li> <li><i>web-plugin</i> for web application plugins</li> <li><i>web-micro</i> a minimal micro service application</li> </ul> <h2>Short summary</h2> <p>Grails 3 comes with major changes. The code basis changed to Spring Boot, Gant was replaced with Gradle, existing features were reimplemented using Traits and new features like Profiles and Interceptors were added.<br /> With all those changes it can become quite challenging to upgrade an existing Grails 2.x application to Grails 3 (all Plugins need to be updated first). If you plan to Upgrade to Grails 3, you should have a look at the <a href="http://grails.github.io/grails-doc/3.0.x/guide/upgrading.html">Grails 3 upgrade guide</a>.</p> 2015-04-10T14:39:55Z Using Java 8 Lambda expressions in Java 7 or older Michael Scharhag http://www.mscharhag.com tag:blogger.com,1999:blog-7494919170223503557.post-7067193452956564398 2015-09-05T14:32:13Z 2015-02-26T15:32:13Z <p>I think nobody declines the usefulness of Lambda expressions, introduced by Java 8. However, many projects are stuck with Java 7 or even older versions. Upgrading can be time consuming and costly. If third party components are incompatible with Java 8 upgrading might not be possible at all.<br /> Besides that, the whole Android platform is stuck on Java 6 and 7. Nevertheless, there is still hope for Lambda expressions!</p> <p><a href="https://github.com/orfjackal/retrolambda">Retrolambda</a> provides a backport of Lambda expressions for Java 5, 6 and 7.</p> <p>From the Retrolambda documentation:<i>&nbsp;</i></p> <blockquote class="tr_bq"><i>Retrolambda lets you run Java 8 code with lambda expressions and method references on Java 7 or lower. It does this by transforming your Java 8 compiled bytecode so that it can run on a Java 7 runtime. After the transformation they are just a bunch of normal .class files, without any additional runtime dependencies.</i></blockquote> <p>To get Retrolambda running, you can use the <a href="https://github.com/orfjackal/retrolambda#maven-plugin">Maven</a> or <a href="https://github.com/evant/gradle-retrolambda">Gradle</a> plugin.</p> <p>If you want to use Lambda expressions on Android, you only have to add the following lines to your gradle build files:<br /> <br /> <span style="font-family: inherit;"><i>&lt;project&gt;/build.gradle</i></span>:</p> <pre class="brush: groovy"> buildscript&nbsp;{ &nbsp;&nbsp;dependencies&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;classpath&nbsp;&#39;me.tatarka:gradle-retrolambda:2.4.0&#39;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;} }</pre> <p><br /> <i>&lt;project&gt;/app/build.gradle</i>:</p> <pre class="brush: groovy"> apply&nbsp;plugin:&nbsp;&#39;com.android.application&#39; //&nbsp;Apply&nbsp;retro&nbsp;lambda&nbsp;plugin&nbsp;after&nbsp;the&nbsp;Android&nbsp;plugin apply&nbsp;plugin:&nbsp;&#39;retrolambda&#39;&nbsp; android&nbsp;{ &nbsp;&nbsp;compileOptions&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;change&nbsp;compatibility&nbsp;to&nbsp;Java&nbsp;8&nbsp;to&nbsp;get&nbsp;Java&nbsp;8&nbsp;IDE&nbsp;support &nbsp;&nbsp;&nbsp;&nbsp;sourceCompatibility&nbsp;JavaVersion.VERSION_1_8 &nbsp;&nbsp;&nbsp;&nbsp;targetCompatibility&nbsp;JavaVersion.VERSION_1_8 &nbsp;&nbsp;} }</pre> 2015-02-26T15:32:13Z Static code analysis with JArchitect Michael Scharhag http://www.mscharhag.com tag:blogger.com,1999:blog-7494919170223503557.post-9131156780793670559 2015-09-05T14:34:40Z 2015-02-23T15:34:40Z <p>A few months ago Dane from JArchitect team was nice enough to offer me a free <a href="http://www.jarchitect.com/">JArchitect</a> 4 Pro license. Over the last days I finally managed to look into JArchitect.</p> <p>JArchitect is a quite powerful static code analyser for JVM languages (besides Java it also supports Scala, Groovy and others). It is available for Windows, Linux and Mac OS X. In this post I want to show you some of JArchitect&#39;s features.</p> <h2>Getting started with JArchitect</h2> <p>As an example I analysed the popular Java Library <a href="https://github.com/junit-team/junit">JUnit</a> using JArchitect. The Screenshots you in this post are all taken from the JUnit analysis result.</p> <p>Importing JUnit into JArchitect was actually quite simple. Note that JArchitect analyses the compiled byte code, source files are not required. So I cloned the JUnit repository and called<span style="background-color: white;"> <span style="background-color: #eeeeee;"><span style="font-family: &quot;Courier New&quot;,Courier,monospace;">mvn compile</span></span></span>. After that, all I had to do was adding JUnit&#39;s <span style="font-family: &quot;Courier New&quot;,Courier,monospace;">pom.xml</span> to a new JArchitect project.</p> <p>After pressing the <i>Run Analysis</i> button JArchitect summarizes common metrics on a dashboard screen:<br /> &nbsp;</p> <p><a class="img-center" href="/files/2015/jarchitect-dashboard.png"><img alt="JArchitect Dashboard" src="/files/2015/jarchitect-dashboard.png" /></a></p> <p><br /> Here we can see the lines of code, method <a href="http://en.wikipedia.org/wiki/Cyclomatic_complexity">complexity</a>, comment rate and various other values. This summary is followed by a couple of trend charts that show how these values changed over time.</p> <p><a class="img-center" href="/files/2015/jarchitect-trend.png"><img alt="JArchitect trend chart" src="/files/2015/jarchitect-trend.png" /></a></p> <p>Of course you can also configure your own charts, if you want to see trends of different values.<b> </b></p> <h2>Analyzing dependencies</h2> <p>Next we will look at the third party dependencies of JUnit. JArchitect provides a nice interactive graph for this.<br /> <br /> <a class="img-center" href="/files/2015/jarchitect-depgraph.png"><img alt="JArchitect dependency graph (1)" src="/files/2015/jarchitect-depgraph.png" /></a><br /> &nbsp;</p> <p>Since JUnit only depends on the Java Runtime (rt) and <a href="http://hamcrest.org/JavaHamcrest/">Hamcrest</a> this graph does not have much to show. I am sure you can imagine that this could be much more complex for a larger project.<br /> <br /> Looking at JUnits package dependencies is a bit more interesting. The following Screen shows a section of JUnits package dependency graph.</p> <p>&nbsp;</p> <p><a class="img-center" href="/files/2015/jarchitect-depgraph2.png"><img alt="JArchitect dependency graph (2)" src="/files/2015/jarchitect-depgraph2.png" /></a></p> <p>&nbsp;</p> <p><br /> I selected the<span style="background-color: white;"> <span style="font-family: &quot;Courier New&quot;,Courier,monospace;">junit.framework</span></span> package to see how this package relates to other packages. The different colored arrows show which packages use <span style="font-family: &quot;Courier New&quot;,Courier,monospace;">junit.framework</span> (green), which other packages are used by <span style="font-family: &quot;Courier New&quot;,Courier,monospace;">junit.framework</span> (blue) and mutually dependent packages (red).<br /> <br /> The dependency matrix is another way to look at project dependencies:</p> <p>&nbsp;</p> <p><a class="img-center" href="/files/2015/jarchitect-depmatrix.png"><img alt="JArchitect dependency matrix (1)" src="/files/2015/jarchitect-depmatrix.png" /></a></p> <p><br /> This matrix style view shows you exactly the dependencies between different components (packages, classes or methods). Here I selected the blue field with the number 10 (where the orange lines cross). This shows that the <span style="font-family: &quot;Courier New&quot;,Courier,monospace;">junit.framework</span> package uses 10 members of the <span style="font-family: &quot;Courier New&quot;,Courier,monospace;">java.lang.reflect</span> package (the dependency direction is shown by the white arrow at the selected field).</p> <p>We can dig deeper, and look at this at class and method level.</p> <p>&nbsp;</p> <p><a class="img-center" href="/files/2015/jarchitect-depmatrix2.png"><img alt="JArchitect dependency matrix(2) " src="/files/2015/jarchitect-depmatrix2.png" /></a></p> <p><br /> So it looks like the class <span style="font-family: &quot;Courier New&quot;,Courier,monospace;">junit.framework.TestCase</span> makes use of the method <span style="font-family: &quot;Courier New&quot;,Courier,monospace;">java.lang.Class.getName()</span>.</p> <h2>Tree maps</h2> <p><a href="http://en.wikipedia.org/wiki/Treemapping">Tree map charts</a> are another way to look into a project with JArchitect. The following chart shows the number of code lines in JUnit packages, classes and methods.</p> <p>&nbsp;</p> <p><a class="img-center" href="/files/2015/jarchitect-metrics.png"><img alt="JArchitect metrics" src="/files/2015/jarchitect-metrics.png" /></a></p> <p>&nbsp;</p> <p>In this example chart we cannot see any overly large rectangle, which is a good sign. This probably means that complex parts are well divided into multiple classes and packages (no <a href="http://en.wikipedia.org/wiki/God_object">god object</a> is present).</p> <p>JArchitect can generate such tree maps for lines of code, cyclomatic complexity, number of variables and various other metrics.</p> <h2>Code queries</h2> <p>To extract various metrics out of a project, JArchitect uses a custom query language call Code Query Linq (CQLinq). As the name suggests this is a query language based on <a href="http://en.wikipedia.org/wiki/Language_Integrated_Query">LINQ</a>.</p> <p>&nbsp;</p> <p><a class="img-center" href="/files/2015/jarchitect-queries2.png"><img alt="JArchitect queries" src="/files/2015/jarchitect-queries2.png" /></a></p> <p>&nbsp;</p> <p>This image shows the query of JArchitect&#39;s <i>Methods with too many parameters</i> rule. It looks for methods with more than 8 parameters and creates a warning if one or more methods are found.</p> <p>You can see (and change) all the standard queries provided by JArchitect. Code queries are actually a very cool feature. You can easily create your own queries to extract project specific data you are interested in.<b>&nbsp;</b></p> <h2>Quick summary</h2> <p>JArchitect is a powerful tool for static code analysis. It can provide a lot of insight into complex code bases. Using custom code queries you are able to build your own rule sets in a very comfortable way.</p> <p>In this example I used the JArchitect user interface (<i>VisualJArchitect</i>) for running the code analysis and viewing the results. It is also possible to integrate JArchitect directly into your build process (using a <a href="http://www.jarchitect.com/Doc_Maven">Maven plugin</a> or <a href="http://www.jarchitect.com/Doc_Gradle">command line tools</a>). This way you are able to automatically create reports in HTML format.</p> 2015-02-23T15:34:40Z Creating Android Apps with Groovy 2.4 Michael Scharhag http://www.mscharhag.com tag:blogger.com,1999:blog-7494919170223503557.post-8106110105403943840 2015-09-05T14:40:08Z 2015-02-06T15:40:08Z <p>A few days ago <a href="http://docs.codehaus.org/display/GROOVY/Groovy+2.4+release+notes" target="_blank">Groovy 2.4 was released</a>. One of the major news is that Groovy now officially supports Android application development. To see how this works I used Groovy to create a small ToDo list example application for Android. In this post I will show which steps are required to create an Android application with Groovy and how Groovy can simplify Android application development.</p> <p>The following screen shows the example application written in Groovy. You can find the full source code on <a href="https://github.com/mscharhag/groovy-android-example" target="_blank">GitHub</a>.<br /> &nbsp;</p> <p><a class="img-center" href="/files/2015/groovy-android-app_s.png"><img alt="Groovy app screenshot" src="/files/2015/groovy-android-app_s.png" /></a></p> <p>&nbsp;</p> <h2>Running Groovy on Android</h2> <p>First we need <a href="http://developer.android.com/sdk/index.html" target="_blank">Android Studio</a> which already contains the latest Version of the Android SDK. Over last year the default Android environment changed from Eclipse and Ant to Android Studio (build on IntelliJ) and Gradle. To run Groovy on Android we will need a Gradle Plugin, so make sure you are not using the old Eclipse/Ant based development tools.</p> <p>We create a new Android project in Android Studio and add the following lines to our build files:</p> <p>Top level build file (<i>&lt;project&gt;/build.gradle</i>):</p> <pre class="brush: groovy"> buildscript&nbsp;{ &nbsp;&nbsp;.. &nbsp;&nbsp;dependencies&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;.. &nbsp;&nbsp;&nbsp;&nbsp;classpath&nbsp;&#39;org.codehaus.groovy:gradle-groovy-android-plugin:0.3.5&#39; &nbsp;&nbsp;} }</pre> <p><br /> App build file (<i>&lt;project&gt;/app/build.gradle</i>):</p> <pre class="brush: groovy"> apply&nbsp;plugin:&nbsp;&#39;com.android.application&#39; //&nbsp;apply&nbsp;Groovy&nbsp;Android&nbsp;plugin&nbsp;after&nbsp;the&nbsp;standard&nbsp;Android&nbsp;plugin apply&nbsp;plugin:&nbsp;&#39;groovyx.grooid.groovy-android&#39; dependencies&nbsp;{ &nbsp;&nbsp;.. &nbsp;&nbsp;compile&nbsp;&#39;org.codehaus.groovy:groovy:2.4.0:grooid&#39; }</pre> <p>Source and documentation of the Groovy Android Gradle Plugin can be found on <a href="https://github.com/groovy/groovy-android-gradle-plugin" target="_blank">GitHub</a>.</p> <p>This is all configuration we need, now we can move straight to Groovy code.</p> <p><b>Please note that Groovy code files need to be placed in <span class="code">src/main/groovy</span> instead of <span class="code">src/main/java</span>. Adding Groovy files to src/main/java will not work!</b></p> <p>Developing Android apps in Groovy works exactly the same way as in Java. Because of Groovy&#39;s&nbsp; Java interoperability, you can use and extend Android classes like you would do in Java.</p> <h2>Improving the Groovy experience in Android Studio</h2> <p>Android Studio already contains the Groovy plugin. So, you get Groovy syntax support out of the box.</p> <p>However, you might miss the option to create new Groovy classes from the context menu. Luckily this can be easily configured in Android Studio. You simply have to create a new File Template (<i>Settings &gt; File and code templates</i>) and add the following template code:</p> <pre class="brush: groovy"> #if&nbsp;(${PACKAGE_NAME}&nbsp;&amp;&amp;&nbsp;${PACKAGE_NAME}&nbsp;!=&nbsp;&quot;&quot;)package&nbsp;${PACKAGE_NAME};#end class&nbsp;${NAME}&nbsp;{ }</pre> <p>&nbsp;</p> <p><a class="img-center" href="/files/2015/groovy-android-file-templates.png"><img alt="androidstudio groovy file template setup (1)" src="/files/2015/groovy-android-file-templates.png" /></a></p> <p><br /> Now you can quickly create new Groovy classes using the context menu:</p> <p><a class="img-center" href="/files/2015/groovy-android-file-template-new.png"><img alt="androidstudio groovy file template setup (2)" src="/files/2015/groovy-android-file-template-new.png" /></a></p> <p><br /> You might also look into <a href="https://plugins.jetbrains.com/plugin/7571?pr=idea" target="_blank">this plugin</a> which fixes the issue that you get no auto completion when overriding super class methods in Groovy. Thanks to <a href="https://twitter.com/arasthel92" target="_blank">@arasthel92</a> who told me about this plugin.</p> <h2>Running Groovy applications</h2> <p>Running Groovy apps is identical to running Java apps. We can simply press the <i>run</i> (or <i>debug</i>) button in Android Studio and deploy the application to a connected (or emulated) device.<br /> The cool thing is that the Groovy debugger works out of the box. We can debug running Groovy applications from Android Studio.</p> <p>&nbsp;</p> <p><a class="img-center" href="/files/2015/groovy-android-debug.png" imageanchor="1"><img alt="androidstudio debug groovy app" src="/files/2015/groovy-android-debug.png" /></a></p> <h2><br /> The great parts</h2> <p>The cool thing about Groovy is that it reduces the lines of code you need to write a lot. Its dynamic nature also lets you get rid of all the type casts that are typically required when working with Android.<br /> <br /> One example of this can be found in <a href="https://github.com/mscharhag/groovy-android-example/blob/master/Groovy-Android/app/src/main/groovy/com/mscharhag/groovytodo/activities/ToDoListActivity.groovy"><span class="code">ToDoListActivity.onResume()</span></a>. In this method the data of an Android <a href="http://developer.android.com/reference/android/widget/ListAdapter.html"><span class="code">ListAdapter</span></a> is modified. With Java this would look like this:</p> <pre class="brush: java"> ArrayAdapter&lt;ToDo&gt;&nbsp;adapter&nbsp;=&nbsp;(ArrayAdapter&lt;ToDo&gt;)&nbsp;getListAdapter(); ToDoApplication&nbsp;application&nbsp;=&nbsp;(ToDoApplication)&nbsp;getApplication() adapter.clear() adapter.addAll(application.getToDos()); adapter.notifyDataSetChanged()</pre> <p>With Groovy we can simply rewrite it like this:</p> <pre class="brush: groovy"> listAdapter.clear() listAdapter.addAll(application.toDos) listAdapter.notifyDataSetChanged()</pre> <p>Groovy&#39;s closures are another feature that comes very handy when working with Android.<br /> <br /> To add a click listener to a button you write something like this in Java</p> <pre class="brush: java"> Button&nbsp;button&nbsp;=&nbsp;(Button)&nbsp;findViewById(R.id.newTodoButton); button.setOnClickListener(new&nbsp;View.OnClickListener()&nbsp;{ &nbsp;&nbsp;@Override &nbsp;&nbsp;void&nbsp;onClick(View&nbsp;v)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;... &nbsp;&nbsp;} });</pre> <p>With Groovy it is just</p> <pre class="brush: groovy"> def&nbsp;button&nbsp;=&nbsp;findViewById(R.id.newTodoButton) button.onClickListener&nbsp;=&nbsp;{ &nbsp;&nbsp;... }</pre> <p>See <span class="code"><a href="https://github.com/mscharhag/groovy-android-example/blob/master/Groovy-Android/app/src/main/groovy/com/mscharhag/groovytodo/activities/CreateNewTodoActivity.groovy">CreateNewTodoActivity</a></span> for a complete example.</p> <h2>Be aware of runtime errors</h2> <p>Dynamic languages typically tend to increase the number of errors you find at runtime. Depending on the app you are building this can be a serious issue. Larger Apps can have a significant deployment time (the app needs to be packaged, copied via USB to the device, installed and started on the device).<br /> Groovy&#39;s <span class="code">@CompileStatic</span> annotation can be used to tackle this issue. It can be used to compile parts of your Groovy code statically to reduce runtime errors:</p> <pre class="brush: java"> @CompileStatic class&nbsp;ToDoListActivity&nbsp;extends&nbsp;ListActivity&nbsp;{ &nbsp;&nbsp;.. }</pre> <p>The downside of <span class="code">@CompileStatic</span> is that you can (obviously) no longer use Groovy&#39;s dynamic features.<b>&nbsp;</b></p> <p class="h2">Quick summary</p> <p>It is very easy to get Groovy running on Android. Because of Groovy&#39;s interoperability with Java it is also very easy to mix Groovy and Java in the same application. The Groovy integration in Android Studio is actually better than I have expected (however, some manual tweaks are still required).</p> 2015-02-06T15:40:08Z